JasonWoof Got questions, comments, patches, etc.? Contact Jason Woofenden
75b833f17cc54f01676e40d0b4b75d3e9309722a
[spectrwm.git] / spectrwm.c
1 /*
2  * Copyright (c) 2009-2012 Marco Peereboom <marco@peereboom.us>
3  * Copyright (c) 2009-2011 Ryan McBride <mcbride@countersiege.com>
4  * Copyright (c) 2009 Darrin Chandler <dwchandler@stilyagin.com>
5  * Copyright (c) 2009 Pierre-Yves Ritschard <pyr@spootnik.org>
6  * Copyright (c) 2010 Tuukka Kataja <stuge@xor.fi>
7  * Copyright (c) 2011 Jason L. Wright <jason@thought.net>
8  * Copyright (c) 2011-2012 Reginald Kennedy <rk@rejii.com>
9  * Copyright (c) 2011-2012 Lawrence Teo <lteo@lteo.net>
10  * Copyright (c) 2011-2012 Tiago Cunha <tcunha@gmx.com>
11  * Copyright (c) 2012 David Hill <dhill@mindcry.org>
12  *
13  * Permission to use, copy, modify, and distribute this software for any
14  * purpose with or without fee is hereby granted, provided that the above
15  * copyright notice and this permission notice appear in all copies.
16  *
17  * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
18  * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
19  * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
20  * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
21  * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
22  * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
23  * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
24  */
25 /*
26  * Much code and ideas taken from dwm under the following license:
27  * MIT/X Consortium License
28  *
29  * 2006-2008 Anselm R Garbe <garbeam at gmail dot com>
30  * 2006-2007 Sander van Dijk <a dot h dot vandijk at gmail dot com>
31  * 2006-2007 Jukka Salmi <jukka at salmi dot ch>
32  * 2007 Premysl Hruby <dfenze at gmail dot com>
33  * 2007 Szabolcs Nagy <nszabolcs at gmail dot com>
34  * 2007 Christof Musik <christof at sendfax dot de>
35  * 2007-2008 Enno Gottox Boland <gottox at s01 dot de>
36  * 2007-2008 Peter Hartlich <sgkkr at hartlich dot com>
37  * 2008 Martin Hurton <martin dot hurton at gmail dot com>
38  *
39  * Permission is hereby granted, free of charge, to any person obtaining a
40  * copy of this software and associated documentation files (the "Software"),
41  * to deal in the Software without restriction, including without limitation
42  * the rights to use, copy, modify, merge, publish, distribute, sublicense,
43  * and/or sell copies of the Software, and to permit persons to whom the
44  * Software is furnished to do so, subject to the following conditions:
45  *
46  * The above copyright notice and this permission notice shall be included in
47  * all copies or substantial portions of the Software.
48  *
49  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
50  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
51  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
52  * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
53  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
54  * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
55  * DEALINGS IN THE SOFTWARE.
56  */
57
58 /* kernel includes */
59 #include <sys/types.h>
60 #include <sys/time.h>
61 #include <sys/stat.h>
62 #include <sys/wait.h>
63 #include <sys/queue.h>
64 #include <sys/param.h>
65 #include <sys/select.h>
66 #if defined(__linux__)
67 #include "tree.h"
68 #elif defined(__OpenBSD__)
69 #include <sys/tree.h>
70 #elif defined(__FreeBSD__)
71 #include <sys/tree.h>
72 #else
73 #include "tree.h"
74 #endif
75
76 /* /usr/includes */
77 #include <ctype.h>
78 #include <err.h>
79 #include <errno.h>
80 #include <fcntl.h>
81 #include <locale.h>
82 #include <paths.h>
83 #include <pwd.h>
84 #include <signal.h>
85 #include <stdio.h>
86 #include <stdlib.h>
87 #include <string.h>
88 #include <time.h>
89 #include <unistd.h>
90 #include <util.h>
91 #include <X11/cursorfont.h>
92 #include <X11/extensions/Xrandr.h>
93 #include <X11/Xft/Xft.h>
94 #include <X11/Xlib-xcb.h>
95 #include <xcb/xcb_atom.h>
96 #include <xcb/xcb_aux.h>
97 #include <xcb/xcb_event.h>
98 #include <xcb/xcb_icccm.h>
99 #include <xcb/xcb_keysyms.h>
100 #include <xcb/xtest.h>
101 #include <xcb/randr.h>
102
103 /* local includes */
104 #include "version.h"
105 #ifdef __OSX__
106 #include <osx.h>
107 #endif
108
109 #ifdef SPECTRWM_BUILDSTR
110 static const char       *buildstr = SPECTRWM_BUILDSTR;
111 #else
112 static const char       *buildstr = SPECTRWM_VERSION;
113 #endif
114
115 #if !defined(__CYGWIN__) /* cygwin chokes on xrandr stuff */
116 #  if RANDR_MAJOR < 1
117 #    error XRandR versions less than 1.0 are not supported
118 #endif
119
120 #  if RANDR_MAJOR >= 1
121 #    if RANDR_MINOR >= 2
122 #      define SWM_XRR_HAS_CRTC
123 #    endif
124 #  endif
125 #endif /* __CYGWIN__ */
126
127 #ifndef XCB_ICCCM_NUM_WM_HINTS_ELEMENTS
128 #define XCB_ICCCM_SIZE_HINT_P_MIN_SIZE          XCB_SIZE_HINT_P_MIN_SIZE
129 #define XCB_ICCCM_SIZE_HINT_P_MAX_SIZE          XCB_SIZE_HINT_P_MAX_SIZE
130 #define XCB_ICCCM_SIZE_HINT_P_RESIZE_INC        XCB_SIZE_HINT_P_RESIZE_INC
131 #define XCB_ICCCM_WM_HINT_INPUT                 XCB_WM_HINT_INPUT
132 #define XCB_ICCCM_WM_HINT_X_URGENCY             XCB_WM_HINT_X_URGENCY
133 #define XCB_ICCCM_WM_STATE_ICONIC               XCB_WM_STATE_ICONIC
134 #define XCB_ICCCM_WM_STATE_WITHDRAWN            XCB_WM_STATE_WITHDRAWN
135 #define XCB_ICCCM_WM_STATE_NORMAL               XCB_WM_STATE_NORMAL
136 #define xcb_icccm_get_text_property_reply_t     xcb_get_text_property_reply_t
137 #define xcb_icccm_get_text_property_reply_wipe  xcb_get_text_property_reply_wipe
138 #define xcb_icccm_get_wm_class                  xcb_get_wm_class
139 #define xcb_icccm_get_wm_class_reply            xcb_get_wm_class_reply
140 #define xcb_icccm_get_wm_class_reply_t          xcb_get_wm_class_reply_t
141 #define xcb_icccm_get_wm_class_reply_wipe       xcb_get_wm_class_reply_wipe
142 #define xcb_icccm_get_wm_hints                  xcb_get_wm_hints
143 #define xcb_icccm_get_wm_hints_reply            xcb_get_wm_hints_reply
144 #define xcb_icccm_get_wm_name                   xcb_get_wm_name
145 #define xcb_icccm_get_wm_name_reply             xcb_get_wm_name_reply
146 #define xcb_icccm_get_wm_normal_hints           xcb_get_wm_normal_hints
147 #define xcb_icccm_get_wm_normal_hints_reply     xcb_get_wm_normal_hints_reply
148 #define xcb_icccm_get_wm_protocols              xcb_get_wm_protocols
149 #define xcb_icccm_get_wm_protocols_reply        xcb_get_wm_protocols_reply
150 #define xcb_icccm_get_wm_protocols_reply_t      xcb_get_wm_protocols_reply_t
151 #define xcb_icccm_get_wm_protocols_reply_wipe   xcb_get_wm_protocols_reply_wipe
152 #define xcb_icccm_get_wm_transient_for          xcb_get_wm_transient_for
153 #define xcb_icccm_get_wm_transient_for_reply    xcb_get_wm_transient_for_reply
154 #define xcb_icccm_wm_hints_t                    xcb_wm_hints_t
155 #endif
156
157 /*#define SWM_DEBUG*/
158 #ifdef SWM_DEBUG
159 #define DPRINTF(x...) do {                                                      \
160         if (swm_debug)                                                          \
161                 fprintf(stderr, x);                                             \
162 } while (0)
163 #define DNPRINTF(n,x...) do {                                                   \
164         if (swm_debug & n) {                                                    \
165                 fprintf(stderr, "%ld ", (long)(time(NULL) - time_started));     \
166                 fprintf(stderr, x);                                             \
167         }                                                                       \
168 } while (0)
169 #define SWM_D_MISC              0x0001
170 #define SWM_D_EVENT             0x0002
171 #define SWM_D_WS                0x0004
172 #define SWM_D_FOCUS             0x0008
173 #define SWM_D_MOVE              0x0010
174 #define SWM_D_STACK             0x0020
175 #define SWM_D_MOUSE             0x0040
176 #define SWM_D_PROP              0x0080
177 #define SWM_D_CLASS             0x0100
178 #define SWM_D_KEY               0x0200
179 #define SWM_D_QUIRK             0x0400
180 #define SWM_D_SPAWN             0x0800
181 #define SWM_D_EVENTQ            0x1000
182 #define SWM_D_CONF              0x2000
183 #define SWM_D_BAR               0x4000
184 #define SWM_D_INIT              0x8000
185
186 u_int32_t               swm_debug = 0
187                             | SWM_D_MISC
188                             | SWM_D_EVENT
189                             | SWM_D_WS
190                             | SWM_D_FOCUS
191                             | SWM_D_MOVE
192                             | SWM_D_STACK
193                             | SWM_D_MOUSE
194                             | SWM_D_PROP
195                             | SWM_D_CLASS
196                             | SWM_D_KEY
197                             | SWM_D_QUIRK
198                             | SWM_D_SPAWN
199                             | SWM_D_EVENTQ
200                             | SWM_D_CONF
201                             | SWM_D_BAR
202                             | SWM_D_INIT
203                             ;
204 #else
205 #define DPRINTF(x...)
206 #define DNPRINTF(n,x...)
207 #endif
208
209 /* convert 8-bit to 16-bit */
210 #define RGB_8_TO_16(col)        ((col) << 8) + (col)
211
212 #define PIXEL_TO_XRENDERCOLOR(px, xrc)                                  \
213         xrc.red = RGB_8_TO_16((px) >> 16 & 0xff);                       \
214         xrc.green = RGB_8_TO_16((px) >> 8 & 0xff);                      \
215         xrc.blue = RGB_8_TO_16((px) & 0xff);                            \
216         xrc.alpha = 0xffff;
217
218 #define LENGTH(x)               (int)(sizeof (x) / sizeof (x)[0])
219 #define MODKEY                  XCB_MOD_MASK_1
220 #define CLEANMASK(mask)         ((mask) & ~(numlockmask | XCB_MOD_MASK_LOCK))
221 #define BUTTONMASK              (XCB_EVENT_MASK_BUTTON_PRESS |          \
222     XCB_EVENT_MASK_BUTTON_RELEASE)
223 #define MOUSEMASK               (BUTTONMASK|XCB_EVENT_MASK_POINTER_MOTION)
224 #define SWM_PROPLEN             (16)
225 #define SWM_FUNCNAME_LEN        (32)
226 #define SWM_KEYS_LEN            (255)
227 #define SWM_QUIRK_LEN           (64)
228 #define X(r)                    (r)->g.x
229 #define Y(r)                    (r)->g.y
230 #define WIDTH(r)                (r)->g.w
231 #define HEIGHT(r)               (r)->g.h
232 #define BORDER(w)               ((w)->bordered ? border_width : 0)
233 #define MAX_X(r)                ((r)->g.x + (r)->g.w)
234 #define MAX_Y(r)                ((r)->g.y + (r)->g.h)
235 #define SH_MIN(w)               (w)->sh.flags & XCB_ICCCM_SIZE_HINT_P_MIN_SIZE
236 #define SH_MIN_W(w)             (w)->sh.min_width
237 #define SH_MIN_H(w)             (w)->sh.min_height
238 #define SH_MAX(w)               (w)->sh.flags & XCB_ICCCM_SIZE_HINT_P_MAX_SIZE
239 #define SH_MAX_W(w)             (w)->sh.max_width
240 #define SH_MAX_H(w)             (w)->sh.max_height
241 #define SH_INC(w)               (w)->sh.flags & XCB_ICCCM_SIZE_HINT_P_RESIZE_INC
242 #define SH_INC_W(w)             (w)->sh.width_inc
243 #define SH_INC_H(w)             (w)->sh.height_inc
244 #define SWM_MAX_FONT_STEPS      (3)
245 #define WINID(w)                ((w) ? (w)->id : 0)
246 #define YESNO(x)                ((x) ? "yes" : "no")
247
248 #define SWM_FOCUS_DEFAULT       (0)
249 #define SWM_FOCUS_FOLLOW        (1)
250 #define SWM_FOCUS_MANUAL        (2)
251
252 #define SWM_CONF_DEFAULT        (0)
253 #define SWM_CONF_KEYMAPPING     (1)
254
255 #ifndef SWM_LIB
256 #define SWM_LIB                 "/usr/local/lib/libswmhack.so"
257 #endif
258
259 char                    **start_argv;
260 xcb_atom_t              a_state;
261 xcb_atom_t              a_prot;
262 xcb_atom_t              a_delete;
263 xcb_atom_t              a_takefocus;
264 xcb_atom_t              a_wmname;
265 xcb_atom_t              a_netwmname;
266 xcb_atom_t              a_utf8_string;
267 xcb_atom_t              a_string;
268 xcb_atom_t              a_swm_iconic;
269 xcb_atom_t              a_swm_ws;
270 volatile sig_atomic_t   running = 1;
271 volatile sig_atomic_t   restart_wm = 0;
272 xcb_timestamp_t         last_event_time = 0;
273 int                     outputs = 0;
274 int                     other_wm;
275 int                     ss_enabled = 0;
276 int                     xrandr_support;
277 int                     xrandr_eventbase;
278 unsigned int            numlockmask = 0;
279
280 Display                 *display;
281 xcb_connection_t        *conn;
282 xcb_key_symbols_t       *syms;
283
284 int                     cycle_empty = 0;
285 int                     cycle_visible = 0;
286 int                     term_width = 0;
287 int                     font_adjusted = 0;
288 unsigned int            mod_key = MODKEY;
289
290 /* dmenu search */
291 struct swm_region       *search_r;
292 int                     select_list_pipe[2];
293 int                     select_resp_pipe[2];
294 pid_t                   searchpid;
295 volatile sig_atomic_t   search_resp;
296 int                     search_resp_action;
297
298 struct search_window {
299         TAILQ_ENTRY(search_window)      entry;
300         int                             idx;
301         struct ws_win                   *win;
302         xcb_gcontext_t                  gc;
303         xcb_window_t                    indicator;
304 };
305 TAILQ_HEAD(search_winlist, search_window);
306 struct search_winlist                   search_wl;
307
308 /* search actions */
309 enum {
310         SWM_SEARCH_NONE,
311         SWM_SEARCH_UNICONIFY,
312         SWM_SEARCH_NAME_WORKSPACE,
313         SWM_SEARCH_SEARCH_WORKSPACE,
314         SWM_SEARCH_SEARCH_WINDOW
315 };
316
317 #define SWM_STACK_TOP           (0)
318 #define SWM_STACK_BOTTOM        (1)
319 #define SWM_STACK_ABOVE         (2)
320 #define SWM_STACK_BELOW         (3)
321
322 /* dialog windows */
323 double                  dialog_ratio = 0.6;
324 /* status bar */
325 #define SWM_BAR_MAX             (256)
326 #define SWM_BAR_JUSTIFY_LEFT    (0)
327 #define SWM_BAR_JUSTIFY_CENTER  (1)
328 #define SWM_BAR_JUSTIFY_RIGHT   (2)
329 #define SWM_BAR_OFFSET          (4)
330 #define SWM_BAR_FONTS           "-*-terminus-medium-*-*-*-12-*-*-*-*-*-*-*," \
331                                 "-*-profont-*-*-*-*-12-*-*-*-*-*-*-*,"      \
332                                 "-*-times-medium-r-*-*-12-*-*-*-*-*-*-*,"    \
333                                 "-misc-fixed-medium-r-*-*-12-*-*-*-*-*-*-*,"  \
334                                 "-*-*-*-r-*-*-*-*-*-*-*-*-*-*"
335
336 #ifdef X_HAVE_UTF8_STRING
337 #define DRAWSTRING(x...)        Xutf8DrawString(x)
338 #else
339 #define DRAWSTRING(x...)        XmbDrawString(x)
340 #endif
341
342 char            *bar_argv[] = { NULL, NULL };
343 int              bar_pipe[2];
344 unsigned char    bar_ext[SWM_BAR_MAX];
345 char             bar_vertext[SWM_BAR_MAX];
346 int              bar_version = 0;
347 sig_atomic_t     bar_alarm = 0;
348 int              bar_delay = 30;
349 int              bar_enabled = 1;
350 int              bar_border_width = 1;
351 int              bar_at_bottom = 0;
352 int              bar_extra = 1;
353 int              bar_extra_running = 0;
354 int              bar_verbose = 1;
355 int              bar_height = 0;
356 int              bar_justify = SWM_BAR_JUSTIFY_LEFT;
357 char             *bar_format = NULL;
358 int              stack_enabled = 1;
359 int              clock_enabled = 1;
360 int              urgent_enabled = 0;
361 char            *clock_format = NULL;
362 int              title_name_enabled = 0;
363 int              title_class_enabled = 0;
364 int              window_name_enabled = 0;
365 int              focus_mode = SWM_FOCUS_DEFAULT;
366 int              focus_close = SWM_STACK_BELOW;
367 int              focus_close_wrap = 1;
368 int              focus_default = SWM_STACK_TOP;
369 int              spawn_position = SWM_STACK_TOP;
370 int              disable_border = 0;
371 int              border_width = 1;
372 int              verbose_layout = 0;
373 time_t           time_started;
374 pid_t            bar_pid;
375 XFontSet         bar_fs;
376 XFontSetExtents *bar_fs_extents;
377 XftFont         *bar_font;
378 int              bar_font_legacy = 1;
379 char            *bar_fonts;
380 XftColor         bar_font_color;
381 struct passwd   *pwd;
382
383 /* layout manager data */
384 struct swm_geometry {
385         int                     x;
386         int                     y;
387         int                     w;
388         int                     h;
389 };
390
391 struct swm_screen;
392 struct workspace;
393
394 struct swm_bar {
395         xcb_window_t            id;
396         xcb_pixmap_t            buffer;
397         struct swm_geometry     g;
398 };
399
400 /* virtual "screens" */
401 struct swm_region {
402         TAILQ_ENTRY(swm_region) entry;
403         struct swm_geometry     g;
404         struct workspace        *ws;    /* current workspace on this region */
405         struct workspace        *ws_prior; /* prior workspace on this region */
406         struct swm_screen       *s;     /* screen idx */
407         struct swm_bar          *bar;
408 };
409 TAILQ_HEAD(swm_region_list, swm_region);
410
411 struct ws_win {
412         TAILQ_ENTRY(ws_win)     entry;
413         xcb_window_t            id;
414         xcb_window_t            transient;
415         struct ws_win           *focus_child;   /* focus on child transient */
416         struct swm_geometry     g;              /* current geometry */
417         struct swm_geometry     g_float;        /* region coordinates */
418         int                     g_floatvalid;   /* g_float geometry validity */
419         int                     floatmaxed;     /* whether maxed by max_stack */
420         int                     floating;
421         int                     manual;
422         int32_t                 mapped;
423         int32_t                 iconic;
424         int                     bordered;
425         unsigned int            ewmh_flags;
426         int                     font_size_boundary[SWM_MAX_FONT_STEPS];
427         int                     font_steps;
428         int                     last_inc;
429         int                     can_delete;
430         int                     take_focus;
431         int                     java;
432         unsigned long           quirks;
433         struct workspace        *ws;    /* always valid */
434         struct swm_screen       *s;     /* always valid, never changes */
435         xcb_get_geometry_reply_t        *wa;
436         xcb_size_hints_t        sh;
437         xcb_icccm_get_wm_class_reply_t  ch;
438         xcb_icccm_wm_hints_t    hints;
439 };
440 TAILQ_HEAD(ws_win_list, ws_win);
441
442 /* pid goo */
443 struct pid_e {
444         TAILQ_ENTRY(pid_e)      entry;
445         pid_t                   pid;
446         int                     ws;
447 };
448 TAILQ_HEAD(pid_list, pid_e);
449 struct pid_list                 pidlist = TAILQ_HEAD_INITIALIZER(pidlist);
450
451 /* layout handlers */
452 void    stack(void);
453 void    vertical_config(struct workspace *, int);
454 void    vertical_stack(struct workspace *, struct swm_geometry *);
455 void    horizontal_config(struct workspace *, int);
456 void    horizontal_stack(struct workspace *, struct swm_geometry *);
457 void    max_stack(struct workspace *, struct swm_geometry *);
458 void    plain_stacker(struct workspace *);
459 void    fancy_stacker(struct workspace *);
460
461 struct layout {
462         void            (*l_stack)(struct workspace *, struct swm_geometry *);
463         void            (*l_config)(struct workspace *, int);
464         u_int32_t       flags;
465 #define SWM_L_FOCUSPREV         (1<<0)
466 #define SWM_L_MAPONFOCUS        (1<<1)
467         void            (*l_string)(struct workspace *);
468 } layouts[] =  {
469         /* stack,               configure */
470         { vertical_stack,       vertical_config,        0,      plain_stacker },
471         { horizontal_stack,     horizontal_config,      0,      plain_stacker },
472         { max_stack,            NULL,
473           SWM_L_MAPONFOCUS | SWM_L_FOCUSPREV,                   plain_stacker },
474         { NULL,                 NULL,                   0,      NULL  },
475 };
476
477 /* position of max_stack mode in the layouts array, index into layouts! */
478 #define SWM_V_STACK             (0)
479 #define SWM_H_STACK             (1)
480 #define SWM_MAX_STACK           (2)
481
482 #define SWM_H_SLICE             (32)
483 #define SWM_V_SLICE             (32)
484
485 /* define work spaces */
486 struct workspace {
487         int                     idx;            /* workspace index */
488         char                    *name;          /* workspace name */
489         int                     always_raise;   /* raise windows on focus */
490         struct layout           *cur_layout;    /* current layout handlers */
491         struct ws_win           *focus;         /* may be NULL */
492         struct ws_win           *focus_prev;    /* may be NULL */
493         struct ws_win           *focus_pending; /* may be NULL */
494         struct swm_region       *r;             /* may be NULL */
495         struct swm_region       *old_r;         /* may be NULL */
496         struct ws_win_list      winlist;        /* list of windows in ws */
497         struct ws_win_list      unmanagedlist;  /* list of dead windows in ws */
498         char                    stacker[10];    /* display stacker and layout */
499
500         /* stacker state */
501         struct {
502                                 int horizontal_msize;
503                                 int horizontal_mwin;
504                                 int horizontal_stacks;
505                                 int horizontal_flip;
506                                 int vertical_msize;
507                                 int vertical_mwin;
508                                 int vertical_stacks;
509                                 int vertical_flip;
510         } l_state;
511 };
512
513 enum {
514         SWM_S_COLOR_BAR,
515         SWM_S_COLOR_BAR_BORDER,
516         SWM_S_COLOR_BAR_FONT,
517         SWM_S_COLOR_FOCUS,
518         SWM_S_COLOR_UNFOCUS,
519         SWM_S_COLOR_MAX
520 };
521
522 /* physical screen mapping */
523 #define SWM_WS_MAX              (22)    /* hard limit */
524 int             workspace_limit = 10;   /* soft limit */
525
526 struct swm_screen {
527         int                     idx;    /* screen index */
528         struct swm_region_list  rl;     /* list of regions on this screen */
529         struct swm_region_list  orl;    /* list of old regions */
530         xcb_window_t            root;
531         struct workspace        ws[SWM_WS_MAX];
532
533         /* colors */
534         struct {
535                 uint32_t        pixel;
536                 char            *name;
537         } c[SWM_S_COLOR_MAX];
538
539         xcb_gcontext_t          bar_gc;
540         GC                      bar_gc_legacy;
541 };
542 struct swm_screen       *screens;
543
544 /* args to functions */
545 union arg {
546         int                     id;
547 #define SWM_ARG_ID_FOCUSNEXT    (0)
548 #define SWM_ARG_ID_FOCUSPREV    (1)
549 #define SWM_ARG_ID_FOCUSMAIN    (2)
550 #define SWM_ARG_ID_SWAPNEXT     (10)
551 #define SWM_ARG_ID_SWAPPREV     (11)
552 #define SWM_ARG_ID_SWAPMAIN     (12)
553 #define SWM_ARG_ID_MOVELAST     (13)
554 #define SWM_ARG_ID_MASTERSHRINK (20)
555 #define SWM_ARG_ID_MASTERGROW   (21)
556 #define SWM_ARG_ID_MASTERADD    (22)
557 #define SWM_ARG_ID_MASTERDEL    (23)
558 #define SWM_ARG_ID_FLIPLAYOUT   (24)
559 #define SWM_ARG_ID_STACKRESET   (30)
560 #define SWM_ARG_ID_STACKINIT    (31)
561 #define SWM_ARG_ID_CYCLEWS_UP   (40)
562 #define SWM_ARG_ID_CYCLEWS_DOWN (41)
563 #define SWM_ARG_ID_CYCLESC_UP   (42)
564 #define SWM_ARG_ID_CYCLESC_DOWN (43)
565 #define SWM_ARG_ID_CYCLEWS_UP_ALL       (44)
566 #define SWM_ARG_ID_CYCLEWS_DOWN_ALL     (45)
567 #define SWM_ARG_ID_STACKINC     (50)
568 #define SWM_ARG_ID_STACKDEC     (51)
569 #define SWM_ARG_ID_SS_ALL       (60)
570 #define SWM_ARG_ID_SS_WINDOW    (61)
571 #define SWM_ARG_ID_DONTCENTER   (70)
572 #define SWM_ARG_ID_CENTER       (71)
573 #define SWM_ARG_ID_KILLWINDOW   (80)
574 #define SWM_ARG_ID_DELETEWINDOW (81)
575 #define SWM_ARG_ID_WIDTHGROW    (90)
576 #define SWM_ARG_ID_WIDTHSHRINK  (91)
577 #define SWM_ARG_ID_HEIGHTGROW   (92)
578 #define SWM_ARG_ID_HEIGHTSHRINK (93)
579 #define SWM_ARG_ID_MOVEUP       (100)
580 #define SWM_ARG_ID_MOVEDOWN     (101)
581 #define SWM_ARG_ID_MOVELEFT     (102)
582 #define SWM_ARG_ID_MOVERIGHT    (103)
583         char                    **argv;
584 };
585
586 /* quirks */
587 struct quirk {
588         TAILQ_ENTRY(quirk)      entry;
589         char                    *class;
590         char                    *name;
591         unsigned long           quirk;
592 #define SWM_Q_FLOAT             (1<<0)  /* float this window */
593 #define SWM_Q_TRANSSZ           (1<<1)  /* transiend window size too small */
594 #define SWM_Q_ANYWHERE          (1<<2)  /* don't position this window */
595 #define SWM_Q_XTERM_FONTADJ     (1<<3)  /* adjust xterm fonts when resizing */
596 #define SWM_Q_FULLSCREEN        (1<<4)  /* remove border */
597 #define SWM_Q_FOCUSPREV         (1<<5)  /* focus on caller */
598 };
599 TAILQ_HEAD(quirk_list, quirk);
600 struct quirk_list               quirks = TAILQ_HEAD_INITIALIZER(quirks);
601
602 /*
603  * Supported EWMH hints should be added to
604  * both the enum and the ewmh array
605  */
606 enum {
607         _NET_ACTIVE_WINDOW,
608         _NET_CLOSE_WINDOW,
609         _NET_MOVERESIZE_WINDOW,
610         _NET_WM_ACTION_ABOVE,
611         _NET_WM_ACTION_CLOSE,
612         _NET_WM_ACTION_FULLSCREEN,
613         _NET_WM_ACTION_MOVE,
614         _NET_WM_ACTION_RESIZE,
615         _NET_WM_ALLOWED_ACTIONS,
616         _NET_WM_NAME,
617         _NET_WM_STATE,
618         _NET_WM_STATE_ABOVE,
619         _NET_WM_STATE_FULLSCREEN,
620         _NET_WM_STATE_HIDDEN,
621         _NET_WM_STATE_MAXIMIZED_HORZ,
622         _NET_WM_STATE_MAXIMIZED_VERT,
623         _NET_WM_STATE_SKIP_PAGER,
624         _NET_WM_STATE_SKIP_TASKBAR,
625         _NET_WM_WINDOW_TYPE,
626         _NET_WM_WINDOW_TYPE_DIALOG,
627         _NET_WM_WINDOW_TYPE_DOCK,
628         _NET_WM_WINDOW_TYPE_NORMAL,
629         _NET_WM_WINDOW_TYPE_SPLASH,
630         _NET_WM_WINDOW_TYPE_TOOLBAR,
631         _NET_WM_WINDOW_TYPE_UTILITY,
632         _SWM_WM_STATE_MANUAL,
633         SWM_EWMH_HINT_MAX
634 };
635
636 struct ewmh_hint {
637         char            *name;
638         xcb_atom_t      atom;
639 } ewmh[SWM_EWMH_HINT_MAX] =     {
640     /* must be in same order as in the enum */
641     {"_NET_ACTIVE_WINDOW", XCB_ATOM_NONE},
642     {"_NET_CLOSE_WINDOW", XCB_ATOM_NONE},
643     {"_NET_MOVERESIZE_WINDOW", XCB_ATOM_NONE},
644     {"_NET_WM_ACTION_ABOVE", XCB_ATOM_NONE},
645     {"_NET_WM_ACTION_CLOSE", XCB_ATOM_NONE},
646     {"_NET_WM_ACTION_FULLSCREEN", XCB_ATOM_NONE},
647     {"_NET_WM_ACTION_MOVE", XCB_ATOM_NONE},
648     {"_NET_WM_ACTION_RESIZE", XCB_ATOM_NONE},
649     {"_NET_WM_ALLOWED_ACTIONS", XCB_ATOM_NONE},
650     {"_NET_WM_NAME", XCB_ATOM_NONE},
651     {"_NET_WM_STATE", XCB_ATOM_NONE},
652     {"_NET_WM_STATE_ABOVE", XCB_ATOM_NONE},
653     {"_NET_WM_STATE_FULLSCREEN", XCB_ATOM_NONE},
654     {"_NET_WM_STATE_HIDDEN", XCB_ATOM_NONE},
655     {"_NET_WM_STATE_MAXIMIZED_HORZ", XCB_ATOM_NONE},
656     {"_NET_WM_STATE_MAXIMIZED_VERT", XCB_ATOM_NONE},
657     {"_NET_WM_STATE_SKIP_PAGER", XCB_ATOM_NONE},
658     {"_NET_WM_STATE_SKIP_TASKBAR", XCB_ATOM_NONE},
659     {"_NET_WM_WINDOW_TYPE", XCB_ATOM_NONE},
660     {"_NET_WM_WINDOW_TYPE_DIALOG", XCB_ATOM_NONE},
661     {"_NET_WM_WINDOW_TYPE_DOCK", XCB_ATOM_NONE},
662     {"_NET_WM_WINDOW_TYPE_NORMAL", XCB_ATOM_NONE},
663     {"_NET_WM_WINDOW_TYPE_SPLASH", XCB_ATOM_NONE},
664     {"_NET_WM_WINDOW_TYPE_TOOLBAR", XCB_ATOM_NONE},
665     {"_NET_WM_WINDOW_TYPE_UTILITY", XCB_ATOM_NONE},
666     {"_SWM_WM_STATE_MANUAL", XCB_ATOM_NONE},
667 };
668
669 /* function prototypes */
670 void     buttonpress(xcb_button_press_event_t *);
671 void     check_conn(void);
672 void     clientmessage(xcb_client_message_event_t *);
673 int      conf_load(char *, int);
674 void     configurenotify(xcb_configure_notify_event_t *);
675 void     configurerequest(xcb_configure_request_event_t *);
676 void     constrain_window(struct ws_win *, struct swm_region *, int);
677 void     destroynotify(xcb_destroy_notify_event_t *);
678 void     enternotify(xcb_enter_notify_event_t *);
679 void     event_drain(uint8_t);
680 void     event_error(xcb_generic_error_t *);
681 void     event_handle(xcb_generic_event_t *);
682 char    *expand_tilde(char *);
683 void     expose(xcb_expose_event_t *);
684 struct ws_win   *find_window(xcb_window_t);
685 int      floating_toggle_win(struct ws_win *);
686 void     focus(struct swm_region *, union arg *);
687 void     focus_flush(void);
688 struct ws_win   *get_focus_magic(struct ws_win *);
689 struct ws_win   *get_focus_prev(struct ws_win *);
690 void     focus_win(struct ws_win *);
691 #ifdef SWM_DEBUG
692 void     focusin(xcb_focus_in_event_t *);
693 #endif
694 xcb_atom_t get_atom_from_string(const char *);
695 #ifdef SWM_DEBUG
696 char    *get_atom_name(xcb_atom_t);
697 char    *get_notify_detail_label(uint8_t);
698 char    *get_notify_mode_label(uint8_t);
699 #endif
700 struct ws_win   *get_region_focus(struct swm_region *);
701 xcb_screen_t    *get_screen(int);
702 char    *get_win_name(xcb_window_t);
703 uint32_t getstate(xcb_window_t);
704 void     grabbuttons(struct ws_win *);
705 void     keypress(xcb_key_press_event_t *);
706 #ifdef SWM_DEBUG
707 void     leavenotify(xcb_leave_notify_event_t *);
708 #endif
709 void     load_float_geom(struct ws_win *, struct swm_region *);
710 struct ws_win   *manage_window(xcb_window_t, uint16_t);
711 void     map_window(struct ws_win *);
712 void     mapnotify(xcb_map_notify_event_t *);
713 void     mappingnotify(xcb_mapping_notify_event_t *);
714 void     maprequest(xcb_map_request_event_t *);
715 void     new_region(struct swm_screen *, int, int, int, int);
716 int      parse_rgb(const char *, uint16_t *, uint16_t *, uint16_t *);
717 void     propertynotify(xcb_property_notify_event_t *);
718 void     spawn_select(struct swm_region *, union arg *, char *, int *);
719 void     screenchange(xcb_randr_screen_change_notify_event_t *);
720 void     shutdown_cleanup(void);
721 void     store_float_geom(struct ws_win *, struct swm_region *);
722 void     unmanage_window(struct ws_win *);
723 void     unmapnotify(xcb_unmap_notify_event_t *);
724 void     unfocus_win(struct ws_win *);
725 void     update_window(struct ws_win *);
726 /*void   visibilitynotify(xcb_visibility_notify_event_t *);*/
727
728 char *
729 expand_tilde(char *s)
730 {
731         struct passwd           *ppwd;
732         int                     i, max;
733         char                    *user;
734         const char              *sc = s;
735         char                    *result;
736
737         if (s == NULL)
738                 errx(1, "expand_tilde: NULL string.");
739
740         if (s[0] != '~') {
741                 result = strdup(sc);
742                 goto out;
743         }
744
745         ++s;
746
747         if ((max = sysconf(_SC_LOGIN_NAME_MAX)) == -1)
748                 errx(1, "expand_tilde: sysconf");
749
750         if ((user = calloc(1, max + 1)) == NULL)
751                 errx(1, "expand_tilde: calloc");
752
753         for (i = 0; s[i] != '/' && s[i] != '\0'; ++i)
754                 user[i] = s[i];
755         user[i] = '\0';
756         s = &s[i];
757
758         ppwd = strlen(user) == 0 ? getpwuid(getuid()) : getpwnam(user);
759         if (ppwd == NULL)
760                 result = strdup(sc);
761         else
762                 if (asprintf(&result, "%s%s", ppwd->pw_dir, s) == -1)
763                         result = NULL;
764 out:
765         if (result == NULL)
766                 errx(1, "expand_tilde: failed to allocate memory.");
767
768         return result;
769 }
770
771 int
772 parse_rgb(const char *rgb, uint16_t *rr, uint16_t *gg, uint16_t *bb)
773 {
774         unsigned int    tmpr, tmpg, tmpb;
775
776         if (sscanf(rgb, "rgb:%x/%x/%x", &tmpr, &tmpg, &tmpb) != 3)
777                 return (-1);
778
779         *rr = RGB_8_TO_16(tmpr);
780         *gg = RGB_8_TO_16(tmpg);
781         *bb = RGB_8_TO_16(tmpb);
782
783         return (0);
784 }
785
786 xcb_screen_t *
787 get_screen(int screen)
788 {
789         const xcb_setup_t       *r;
790         xcb_screen_iterator_t   iter;
791
792         if ((r = xcb_get_setup(conn)) == NULL) {
793                 DNPRINTF(SWM_D_MISC, "get_screen: xcb_get_setup\n");
794                 check_conn();
795         }
796
797         iter = xcb_setup_roots_iterator(r);
798         for (; iter.rem; --screen, xcb_screen_next(&iter))
799                 if (screen == 0)
800                         return (iter.data);
801
802         return (NULL);
803 }
804
805 void
806 focus_flush(void)
807 {
808         if (focus_mode == SWM_FOCUS_DEFAULT)
809                 event_drain(XCB_ENTER_NOTIFY);
810         else
811                 xcb_flush(conn);
812 }
813
814 xcb_atom_t
815 get_atom_from_string(const char *str)
816 {
817         xcb_intern_atom_cookie_t        c;
818         xcb_intern_atom_reply_t         *r;
819         xcb_atom_t                      atom;
820
821         c = xcb_intern_atom(conn, 0, strlen(str), str);
822         r = xcb_intern_atom_reply(conn, c, NULL);
823         if (r) {
824                 atom = r->atom;
825                 free(r);
826
827                 return (atom);
828         }
829
830         return (XCB_ATOM_NONE);
831 }
832
833 void
834 set_swm_iconic(struct ws_win *win, int newv)
835 {
836         int32_t                         v = newv;
837
838         win->iconic = newv;
839
840         if (newv)
841                 xcb_change_property(conn, XCB_PROP_MODE_REPLACE, win->id,
842                     a_swm_iconic, XCB_ATOM_INTEGER, 32, 1, &v);
843         else
844                 xcb_delete_property(conn, win->id, a_swm_iconic);
845 }
846
847 int32_t
848 get_swm_iconic(struct ws_win *win)
849 {
850         int32_t                         v = 0;
851         xcb_get_property_reply_t        *pr = NULL;
852
853         pr = xcb_get_property_reply(conn,
854             xcb_get_property(conn, 0, win->id, a_swm_iconic,
855             XCB_ATOM_INTEGER, 0, 1), NULL);
856         if (!pr)
857                 goto out;
858         if (pr->type != XCB_ATOM_INTEGER || pr->format != 32)
859                 goto out;
860         v = *((int32_t *)xcb_get_property_value(pr));
861 out:
862         if (pr)
863                 free(pr);
864         return (v);
865 }
866
867 void
868 setup_ewmh(void)
869 {
870         xcb_atom_t                      sup_list;
871         int                             i, j, num_screens;
872
873         sup_list = get_atom_from_string("_NET_SUPPORTED");
874
875         for (i = 0; i < LENGTH(ewmh); i++)
876                 ewmh[i].atom = get_atom_from_string(ewmh[i].name);
877
878         num_screens = xcb_setup_roots_length(xcb_get_setup(conn));
879         for (i = 0; i < num_screens; i++) {
880                 /* Support check window will be created by workaround(). */
881
882                 /* Report supported atoms */
883                 xcb_delete_property(conn, screens[i].root, sup_list);
884                 for (j = 0; j < LENGTH(ewmh); j++)
885                         xcb_change_property(conn, XCB_PROP_MODE_APPEND,
886                             screens[i].root, sup_list, XCB_ATOM_ATOM, 32, 1,
887                             &ewmh[j].atom);
888         }
889 }
890
891 void
892 teardown_ewmh(void)
893 {
894         int                             i, num_screens;
895         xcb_atom_t                      sup_check, sup_list;
896         xcb_window_t                    id;
897         xcb_get_property_cookie_t       pc;
898         xcb_get_property_reply_t        *pr;
899
900         sup_check = get_atom_from_string("_NET_SUPPORTING_WM_CHECK");
901         sup_list = get_atom_from_string("_NET_SUPPORTED");
902         num_screens = xcb_setup_roots_length(xcb_get_setup(conn));
903
904         for (i = 0; i < num_screens; i++) {
905                 /* Get the support check window and destroy it */
906                 pc = xcb_get_property(conn, 0, screens[i].root, sup_check,
907                     XCB_ATOM_WINDOW, 0, 1);
908                 pr = xcb_get_property_reply(conn, pc, NULL);
909                 if (!pr)
910                         continue;
911                 if (pr->format == sup_check) {
912                         id = *((xcb_window_t *)xcb_get_property_value(pr));
913
914                         xcb_destroy_window(conn, id);
915                         xcb_delete_property(conn, screens[i].root, sup_check);
916                         xcb_delete_property(conn, screens[i].root, sup_list);
917                 }
918                 free(pr);
919         }
920 }
921
922 void
923 ewmh_autoquirk(struct ws_win *win)
924 {
925         uint32_t                i, n;
926         xcb_atom_t              *type;
927         xcb_get_property_cookie_t       c;
928         xcb_get_property_reply_t        *r;
929
930         c = xcb_get_property(conn, 0, win->id,
931             ewmh[_NET_WM_WINDOW_TYPE].atom, XCB_ATOM_ATOM, 0, UINT32_MAX);
932         r = xcb_get_property_reply(conn, c, NULL);
933         if (!r)
934                 return;
935
936         n = xcb_get_property_value_length(r);
937         type = xcb_get_property_value(r);
938
939         for (i = 0; i < n; i++) {
940                 if (type[i] == ewmh[_NET_WM_WINDOW_TYPE_NORMAL].atom)
941                         break;
942                 if (type[i] == ewmh[_NET_WM_WINDOW_TYPE_DOCK].atom ||
943                     type[i] == ewmh[_NET_WM_WINDOW_TYPE_TOOLBAR].atom ||
944                     type[i] == ewmh[_NET_WM_WINDOW_TYPE_UTILITY].atom) {
945                         win->floating = 1;
946                         win->quirks = SWM_Q_FLOAT | SWM_Q_ANYWHERE;
947                         break;
948                 }
949                 if (type[i] == ewmh[_NET_WM_WINDOW_TYPE_SPLASH].atom ||
950                     type[i] == ewmh[_NET_WM_WINDOW_TYPE_DIALOG].atom) {
951                         win->floating = 1;
952                         win->quirks = SWM_Q_FLOAT;
953                         break;
954                 }
955         }
956         free(r);
957 }
958
959 #define SWM_EWMH_ACTION_COUNT_MAX       (6)
960 #define EWMH_F_FULLSCREEN               (1<<0)
961 #define EWMH_F_ABOVE                    (1<<1)
962 #define EWMH_F_HIDDEN                   (1<<2)
963 #define EWMH_F_SKIP_PAGER               (1<<3)
964 #define EWMH_F_SKIP_TASKBAR             (1<<4)
965 #define SWM_F_MANUAL                    (1<<5)
966
967 int
968 ewmh_set_win_fullscreen(struct ws_win *win, int fs)
969 {
970         if (!win->ws->r)
971                 return (0);
972
973         if (!win->floating)
974                 return (0);
975
976         DNPRINTF(SWM_D_MISC, "ewmh_set_win_fullscreen: window: 0x%x, "
977             "fullscreen %s\n", win->id, YESNO(fs));
978
979         if (fs) {
980                 if (!win->g_floatvalid)
981                         store_float_geom(win, win->ws->r);
982
983                 win->g = win->ws->r->g;
984                 win->bordered = 0;
985         } else {
986                 load_float_geom(win, win->ws->r);
987         }
988
989         return (1);
990 }
991
992 void
993 ewmh_update_actions(struct ws_win *win)
994 {
995         xcb_atom_t              actions[SWM_EWMH_ACTION_COUNT_MAX];
996         int                     n = 0;
997
998         if (win == NULL)
999                 return;
1000
1001         actions[n++] = ewmh[_NET_WM_ACTION_CLOSE].atom;
1002
1003         if (win->floating) {
1004                 actions[n++] = ewmh[_NET_WM_ACTION_MOVE].atom;
1005                 actions[n++] = ewmh[_NET_WM_ACTION_RESIZE].atom;
1006                 actions[n++] = ewmh[_NET_WM_ACTION_ABOVE].atom;
1007         }
1008
1009         xcb_change_property(conn, XCB_PROP_MODE_REPLACE, win->id,
1010             ewmh[_NET_WM_ALLOWED_ACTIONS].atom, XCB_ATOM_ATOM, 32, 1, actions);
1011 }
1012
1013 #define _NET_WM_STATE_REMOVE    0    /* remove/unset property */
1014 #define _NET_WM_STATE_ADD       1    /* add/set property */
1015 #define _NET_WM_STATE_TOGGLE    2    /* toggle property */
1016
1017 void
1018 ewmh_update_win_state(struct ws_win *win, xcb_atom_t state, long action)
1019 {
1020         unsigned int            mask = 0;
1021         unsigned int            changed = 0;
1022         unsigned int            orig_flags;
1023
1024         if (win == NULL)
1025                 return;
1026
1027         DNPRINTF(SWM_D_PROP, "ewmh_update_win_state: window: 0x%x, state: %ld, "
1028             "action: %ld\n", win->id, (unsigned long)state, action);
1029
1030         if (state == ewmh[_NET_WM_STATE_FULLSCREEN].atom)
1031                 mask = EWMH_F_FULLSCREEN;
1032         else if (state == ewmh[_NET_WM_STATE_ABOVE].atom)
1033                 mask = EWMH_F_ABOVE;
1034         else if (state == ewmh[_SWM_WM_STATE_MANUAL].atom)
1035                 mask = SWM_F_MANUAL;
1036         else if (state == ewmh[_NET_WM_STATE_SKIP_PAGER].atom)
1037                 mask = EWMH_F_SKIP_PAGER;
1038         else if (state == ewmh[_NET_WM_STATE_SKIP_TASKBAR].atom)
1039                 mask = EWMH_F_SKIP_TASKBAR;
1040
1041         orig_flags = win->ewmh_flags;
1042
1043         switch (action) {
1044         case _NET_WM_STATE_REMOVE:
1045                 win->ewmh_flags &= ~mask;
1046                 break;
1047         case _NET_WM_STATE_ADD:
1048                 win->ewmh_flags |= mask;
1049                 break;
1050         case _NET_WM_STATE_TOGGLE:
1051                 win->ewmh_flags ^= mask;
1052                 break;
1053         }
1054
1055         changed = (win->ewmh_flags & mask) ^ (orig_flags & mask) ? 1 : 0;
1056
1057         if (state == ewmh[_NET_WM_STATE_ABOVE].atom) {
1058                 if (changed && !floating_toggle_win(win))
1059                                 win->ewmh_flags = orig_flags; /* revert */
1060         } else if (state == ewmh[_SWM_WM_STATE_MANUAL].atom) {
1061                 if (changed)
1062                         win->manual = (win->ewmh_flags & SWM_F_MANUAL) != 0;
1063         } else if (state == ewmh[_NET_WM_STATE_FULLSCREEN].atom) {
1064                 if (changed && !ewmh_set_win_fullscreen(win,
1065                             win->ewmh_flags & EWMH_F_FULLSCREEN))
1066                                 win->ewmh_flags = orig_flags; /* revert */
1067         }
1068
1069         xcb_delete_property(conn, win->id, ewmh[_NET_WM_STATE].atom);
1070
1071         if (win->ewmh_flags & EWMH_F_FULLSCREEN)
1072                 xcb_change_property(conn, XCB_PROP_MODE_APPEND, win->id,
1073                     ewmh[_NET_WM_STATE].atom, XCB_ATOM_ATOM, 32, 1,
1074                     &ewmh[_NET_WM_STATE_FULLSCREEN].atom);
1075         else if (win->ewmh_flags & EWMH_F_SKIP_PAGER)
1076                 xcb_change_property(conn, XCB_PROP_MODE_APPEND, win->id,
1077                     ewmh[_NET_WM_STATE].atom, XCB_ATOM_ATOM, 32, 1,
1078                     &ewmh[_NET_WM_STATE_SKIP_PAGER].atom);
1079         else if (win->ewmh_flags & EWMH_F_SKIP_TASKBAR)
1080                 xcb_change_property(conn, XCB_PROP_MODE_APPEND, win->id,
1081                     ewmh[_NET_WM_STATE].atom, XCB_ATOM_ATOM, 32, 1,
1082                     &ewmh[_NET_WM_STATE_SKIP_TASKBAR].atom);
1083         else if (win->ewmh_flags & EWMH_F_ABOVE)
1084                 xcb_change_property(conn, XCB_PROP_MODE_APPEND, win->id,
1085                     ewmh[_NET_WM_STATE].atom, XCB_ATOM_ATOM, 32, 1,
1086                     &ewmh[_NET_WM_STATE_ABOVE].atom);
1087         else if (win->ewmh_flags & SWM_F_MANUAL)
1088                 xcb_change_property(conn, XCB_PROP_MODE_APPEND, win->id,
1089                     ewmh[_NET_WM_STATE].atom, XCB_ATOM_ATOM, 32, 1,
1090                     &ewmh[_SWM_WM_STATE_MANUAL].atom);
1091 }
1092
1093 void
1094 ewmh_get_win_state(struct ws_win *win)
1095 {
1096         xcb_atom_t                      *states;
1097         xcb_get_property_cookie_t       c;
1098         xcb_get_property_reply_t        *r;
1099         int                             i, n;
1100
1101         if (win == NULL)
1102                 return;
1103
1104         win->ewmh_flags = 0;
1105         if (win->floating)
1106                 win->ewmh_flags |= EWMH_F_ABOVE;
1107         if (win->manual)
1108                 win->ewmh_flags |= SWM_F_MANUAL;
1109
1110         c = xcb_get_property(conn, 0, win->id, ewmh[_NET_WM_STATE].atom,
1111             XCB_ATOM_ATOM, 0, UINT32_MAX);
1112         r = xcb_get_property_reply(conn, c, NULL);
1113         if (!r)
1114                 return;
1115
1116         states = xcb_get_property_value(r);
1117         n = xcb_get_property_value_length(r);
1118
1119         for (i = 0; i < n; i++)
1120                 ewmh_update_win_state(win, states[i], _NET_WM_STATE_ADD);
1121
1122         free(r);
1123 }
1124
1125 /* events */
1126 #ifdef SWM_DEBUG
1127 void
1128 dumpwins(struct swm_region *r, union arg *args)
1129 {
1130         struct ws_win                           *win;
1131         uint32_t                                state;
1132         xcb_get_window_attributes_cookie_t      c;
1133         xcb_get_window_attributes_reply_t       *wa;
1134
1135         /* suppress unused warning since var is needed */
1136         (void)args;
1137
1138         if (r->ws == NULL) {
1139                 warnx("dumpwins: invalid workspace");
1140                 return;
1141         }
1142
1143         warnx("=== managed window list ws %02d ===", r->ws->idx);
1144         TAILQ_FOREACH(win, &r->ws->winlist, entry) {
1145                 state = getstate(win->id);
1146                 c = xcb_get_window_attributes(conn, win->id);
1147                 wa = xcb_get_window_attributes_reply(conn, c, NULL);
1148                 if (wa) {
1149                         warnx("window: 0x%x, map_state: %d, state: %u, "
1150                             "transient: 0x%x", win->id, wa->map_state,
1151                             state, win->transient);
1152                         free(wa);
1153                 } else
1154                         warnx("window: 0x%x, failed xcb_get_window_attributes",
1155                             win->id);
1156         }
1157
1158         warnx("===== unmanaged window list =====");
1159         TAILQ_FOREACH(win, &r->ws->unmanagedlist, entry) {
1160                 state = getstate(win->id);
1161                 c = xcb_get_window_attributes(conn, win->id);
1162                 wa = xcb_get_window_attributes_reply(conn, c, NULL);
1163                 if (wa) {
1164                         warnx("window: 0x%x, map_state: %d, state: %u, "
1165                             "transient: 0x%x", win->id, wa->map_state,
1166                             state, win->transient);
1167                         free(wa);
1168                 } else
1169                         warnx("window: 0x%x, failed xcb_get_window_attributes",
1170                             win->id);
1171         }
1172
1173         warnx("=================================");
1174 }
1175 #else
1176 void
1177 dumpwins(struct swm_region *r, union arg *s)
1178 {
1179         (void)r;
1180         (void)s;
1181 }
1182 #endif /* SWM_DEBUG */
1183
1184 void
1185 sighdlr(int sig)
1186 {
1187         int                     saved_errno, status;
1188         pid_t                   pid;
1189
1190         saved_errno = errno;
1191
1192         switch (sig) {
1193         case SIGCHLD:
1194                 while ((pid = waitpid(WAIT_ANY, &status, WNOHANG)) != 0) {
1195                         if (pid == -1) {
1196                                 if (errno == EINTR)
1197                                         continue;
1198 #ifdef SWM_DEBUG
1199                                 if (errno != ECHILD)
1200                                         warn("sighdlr: waitpid");
1201 #endif /* SWM_DEBUG */
1202                                 break;
1203                         }
1204                         if (pid == searchpid)
1205                                 search_resp = 1;
1206
1207 #ifdef SWM_DEBUG
1208                         if (WIFEXITED(status)) {
1209                                 if (WEXITSTATUS(status) != 0)
1210                                         warnx("sighdlr: child exit status: %d",
1211                                             WEXITSTATUS(status));
1212                         } else
1213                                 warnx("sighdlr: child is terminated "
1214                                     "abnormally");
1215 #endif /* SWM_DEBUG */
1216                 }
1217                 break;
1218
1219         case SIGHUP:
1220                 restart_wm = 1;
1221                 break;
1222         case SIGINT:
1223         case SIGTERM:
1224         case SIGQUIT:
1225                 running = 0;
1226                 break;
1227         }
1228
1229         errno = saved_errno;
1230 }
1231
1232 struct pid_e *
1233 find_pid(pid_t pid)
1234 {
1235         struct pid_e            *p = NULL;
1236
1237         DNPRINTF(SWM_D_MISC, "find_pid: %d\n", pid);
1238
1239         if (pid == 0)
1240                 return (NULL);
1241
1242         TAILQ_FOREACH(p, &pidlist, entry) {
1243                 if (p->pid == pid)
1244                         return (p);
1245         }
1246
1247         return (NULL);
1248 }
1249
1250 uint32_t
1251 name_to_pixel(const char *colorname)
1252 {
1253         uint32_t                        result = 0;
1254         char                            cname[32] = "#";
1255         xcb_screen_t                    *screen;
1256         xcb_colormap_t                  cmap;
1257         xcb_alloc_color_reply_t         *cr;
1258         xcb_alloc_named_color_reply_t   *nr;
1259         uint16_t                        rr, gg, bb;
1260
1261         screen = xcb_setup_roots_iterator(xcb_get_setup(conn)).data;
1262         cmap = screen->default_colormap;
1263
1264         /* color is in format rgb://rr/gg/bb */
1265         if (strncmp(colorname, "rgb:", 4) == 0) {
1266                 if (parse_rgb(colorname, &rr, &gg, &bb) == -1)
1267                         warnx("could not parse rgb %s", colorname);
1268                 else {
1269                         cr = xcb_alloc_color_reply(conn,
1270                             xcb_alloc_color(conn, cmap, rr, gg, bb),
1271                             NULL);
1272                         if (cr) {
1273                                 result = cr->pixel;
1274                                 free(cr);
1275                         } else
1276                                 warnx("color '%s' not found", colorname);
1277                 }
1278         } else {
1279                 nr = xcb_alloc_named_color_reply(conn,
1280                         xcb_alloc_named_color(conn, cmap, strlen(colorname),
1281                             colorname), NULL);
1282                 if (!nr) {
1283                         strlcat(cname, colorname + 2, sizeof cname - 1);
1284                         nr = xcb_alloc_named_color_reply(conn,
1285                             xcb_alloc_named_color(conn, cmap, strlen(cname),
1286                             cname), NULL);
1287                 }
1288                 if (nr) {
1289                         result = nr->pixel;
1290                         free(nr);
1291                 } else
1292                         warnx("color '%s' not found", colorname);
1293         }
1294
1295         return (result);
1296 }
1297
1298 void
1299 setscreencolor(char *val, int i, int c)
1300 {
1301         int     num_screens;
1302
1303         num_screens = xcb_setup_roots_length(xcb_get_setup(conn));
1304         if (i > 0 && i <= num_screens) {
1305                 screens[i - 1].c[c].pixel = name_to_pixel(val);
1306                 free(screens[i - 1].c[c].name);
1307                 if ((screens[i - 1].c[c].name = strdup(val)) == NULL)
1308                         err(1, "strdup");
1309         } else if (i == -1) {
1310                 for (i = 0; i < num_screens; i++) {
1311                         screens[i].c[c].pixel = name_to_pixel(val);
1312                         free(screens[i].c[c].name);
1313                         if ((screens[i].c[c].name = strdup(val)) == NULL)
1314                                 err(1, "strdup");
1315                 }
1316         } else
1317                 errx(1, "invalid screen index: %d out of bounds (maximum %d)",
1318                     i, num_screens);
1319 }
1320
1321 void
1322 fancy_stacker(struct workspace *ws)
1323 {
1324         strlcpy(ws->stacker, "[   ]", sizeof ws->stacker);
1325         if (ws->cur_layout->l_stack == vertical_stack)
1326                 snprintf(ws->stacker, sizeof ws->stacker,
1327                     ws->l_state.vertical_flip ? "[%d>%d]" : "[%d|%d]",
1328                     ws->l_state.vertical_mwin, ws->l_state.vertical_stacks);
1329         if (ws->cur_layout->l_stack == horizontal_stack)
1330                 snprintf(ws->stacker, sizeof ws->stacker,
1331                     ws->l_state.horizontal_flip ? "[%dv%d]" : "[%d-%d]",
1332                     ws->l_state.horizontal_mwin, ws->l_state.horizontal_stacks);
1333 }
1334
1335 void
1336 plain_stacker(struct workspace *ws)
1337 {
1338         strlcpy(ws->stacker, "[ ]", sizeof ws->stacker);
1339         if (ws->cur_layout->l_stack == vertical_stack)
1340                 strlcpy(ws->stacker, ws->l_state.vertical_flip ? "[>]" : "[|]",
1341                     sizeof ws->stacker);
1342         if (ws->cur_layout->l_stack == horizontal_stack)
1343                 strlcpy(ws->stacker, ws->l_state.horizontal_flip ? "[v]" : "[-]",
1344                     sizeof ws->stacker);
1345 }
1346
1347 void
1348 custom_region(char *val)
1349 {
1350         unsigned int                    x, y, w, h;
1351         int                             sidx, num_screens;
1352         xcb_screen_t                    *screen;
1353
1354         num_screens = xcb_setup_roots_length(xcb_get_setup(conn));
1355         if (sscanf(val, "screen[%d]:%ux%u+%u+%u", &sidx, &w, &h, &x, &y) != 5)
1356                 errx(1, "invalid custom region, "
1357                     "should be 'screen[<n>]:<n>x<n>+<n>+<n>");
1358         if (sidx < 1 || sidx > num_screens)
1359                 errx(1, "invalid screen index: %d out of bounds (maximum %d)",
1360                     sidx, num_screens);
1361         sidx--;
1362
1363         if ((screen = get_screen(sidx)) == NULL)
1364                 errx(1, "ERROR: can't get screen %d.", sidx);
1365
1366         if (w < 1 || h < 1)
1367                 errx(1, "region %ux%u+%u+%u too small", w, h, x, y);
1368
1369         if (x > screen->width_in_pixels ||
1370             y > screen->height_in_pixels ||
1371             w + x > screen->width_in_pixels ||
1372             h + y > screen->height_in_pixels) {
1373                 warnx("ignoring region %ux%u+%u+%u - not within screen "
1374                     "boundaries (%ux%u)", w, h, x, y,
1375                     screen->width_in_pixels, screen->height_in_pixels);
1376                 return;
1377         }
1378
1379         new_region(&screens[sidx], x, y, w, h);
1380 }
1381
1382 void
1383 socket_setnonblock(int fd)
1384 {
1385         int                     flags;
1386
1387         if ((flags = fcntl(fd, F_GETFL, 0)) == -1)
1388                 err(1, "fcntl F_GETFL");
1389         flags |= O_NONBLOCK;
1390         if ((flags = fcntl(fd, F_SETFL, flags)) == -1)
1391                 err(1, "fcntl F_SETFL");
1392 }
1393
1394 void
1395 bar_print_legacy(struct swm_region *r, const char *s)
1396 {
1397         xcb_rectangle_t         rect;
1398         uint32_t                gcv[1];
1399         XGCValues               gcvd;
1400         int                     x = 0;
1401         size_t                  len;
1402         XRectangle              ibox, lbox;
1403         GC                      draw;
1404
1405         len = strlen(s);
1406         XmbTextExtents(bar_fs, s, len, &ibox, &lbox);
1407
1408         switch (bar_justify) {
1409         case SWM_BAR_JUSTIFY_LEFT:
1410                 x = SWM_BAR_OFFSET;
1411                 break;
1412         case SWM_BAR_JUSTIFY_CENTER:
1413                 x = (WIDTH(r) - lbox.width) / 2;
1414                 break;
1415         case SWM_BAR_JUSTIFY_RIGHT:
1416                 x = WIDTH(r) - lbox.width - SWM_BAR_OFFSET;
1417                 break;
1418         }
1419
1420         if (x < SWM_BAR_OFFSET)
1421                 x = SWM_BAR_OFFSET;
1422
1423         rect.x = 0;
1424         rect.y = 0;
1425         rect.width = WIDTH(r->bar);
1426         rect.height = HEIGHT(r->bar);
1427
1428         /* clear back buffer */
1429         gcv[0] = r->s->c[SWM_S_COLOR_BAR].pixel;
1430         xcb_change_gc(conn, r->s->bar_gc, XCB_GC_FOREGROUND, gcv);
1431         xcb_poly_fill_rectangle(conn, r->bar->buffer, r->s->bar_gc, 1, &rect);
1432
1433         /* draw back buffer */
1434         gcvd.graphics_exposures = 0;
1435         draw = XCreateGC(display, r->bar->buffer, GCGraphicsExposures, &gcvd);
1436         XSetForeground(display, draw, r->s->c[SWM_S_COLOR_BAR_FONT].pixel);
1437         DRAWSTRING(display, r->bar->buffer, bar_fs, draw,
1438             x, (bar_fs_extents->max_logical_extent.height - lbox.height) / 2 -
1439             lbox.y, s, len);
1440         XFreeGC(display, draw);
1441
1442         /* blt */
1443         xcb_copy_area(conn, r->bar->buffer, r->bar->id, r->s->bar_gc, 0, 0,
1444             0, 0, WIDTH(r->bar), HEIGHT(r->bar));
1445 }
1446
1447 void
1448 bar_print(struct swm_region *r, const char *s)
1449 {
1450         size_t                          len;
1451         xcb_rectangle_t                 rect;
1452         uint32_t                        gcv[1];
1453         int32_t                         x = 0;
1454         XGlyphInfo                      info;
1455         XftDraw                         *draw;
1456
1457         len = strlen(s);
1458
1459         XftTextExtentsUtf8(display, bar_font, (FcChar8 *)s, len, &info);
1460
1461         switch (bar_justify) {
1462         case SWM_BAR_JUSTIFY_LEFT:
1463                 x = SWM_BAR_OFFSET;
1464                 break;
1465         case SWM_BAR_JUSTIFY_CENTER:
1466                 x = (WIDTH(r) - info.width) / 2;
1467                 break;
1468         case SWM_BAR_JUSTIFY_RIGHT:
1469                 x = WIDTH(r) - info.width - SWM_BAR_OFFSET;
1470                 break;
1471         }
1472
1473         if (x < SWM_BAR_OFFSET)
1474                 x = SWM_BAR_OFFSET;
1475
1476         rect.x = 0;
1477         rect.y = 0;
1478         rect.width = WIDTH(r->bar);
1479         rect.height = HEIGHT(r->bar);
1480
1481         /* clear back buffer */
1482         gcv[0] = r->s->c[SWM_S_COLOR_BAR].pixel;
1483         xcb_change_gc(conn, r->s->bar_gc, XCB_GC_FOREGROUND, gcv);
1484         xcb_poly_fill_rectangle(conn, r->bar->buffer, r->s->bar_gc, 1, &rect);
1485
1486         /* draw back buffer */
1487         draw = XftDrawCreate(display, r->bar->buffer,
1488             DefaultVisual(display, r->s->idx),
1489             DefaultColormap(display, r->s->idx));
1490
1491         XftDrawStringUtf8(draw, &bar_font_color, bar_font, x,
1492             (HEIGHT(r->bar) + bar_font->height) / 2 - bar_font->descent,
1493             (FcChar8 *)s, len);
1494
1495         XftDrawDestroy(draw);
1496
1497         /* blt */
1498         xcb_copy_area(conn, r->bar->buffer, r->bar->id, r->s->bar_gc, 0, 0,
1499             0, 0, WIDTH(r->bar), HEIGHT(r->bar));
1500 }
1501
1502 void
1503 bar_extra_stop(void)
1504 {
1505         if (bar_pipe[0]) {
1506                 close(bar_pipe[0]);
1507                 bzero(bar_pipe, sizeof bar_pipe);
1508         }
1509         if (bar_pid) {
1510                 kill(bar_pid, SIGTERM);
1511                 bar_pid = 0;
1512         }
1513         strlcpy((char *)bar_ext, "", sizeof bar_ext);
1514         bar_extra = 0;
1515 }
1516
1517 void
1518 bar_class_name(char *s, size_t sz, struct swm_region *r)
1519 {
1520         if (r == NULL || r->ws == NULL || r->ws->focus == NULL)
1521                 return;
1522         if (r->ws->focus->ch.class_name != NULL)
1523                 strlcat(s, r->ws->focus->ch.class_name, sz);
1524 }
1525
1526 void
1527 bar_title_name(char *s, size_t sz, struct swm_region *r)
1528 {
1529         if (r == NULL || r->ws == NULL || r->ws->focus == NULL)
1530                 return;
1531         if (r->ws->focus->ch.instance_name != NULL)
1532                 strlcat(s, r->ws->focus->ch.instance_name, sz);
1533 }
1534
1535 void
1536 bar_class_title_name(char *s, size_t sz, struct swm_region *r)
1537 {
1538         if (r == NULL || r->ws == NULL || r->ws->focus == NULL)
1539                 return;
1540
1541         bar_class_name(s, sz, r);
1542         strlcat(s, ":", sz);
1543         bar_title_name(s, sz, r);
1544 }
1545
1546 void
1547 bar_window_float(char *s, size_t sz, struct swm_region *r)
1548 {
1549         if (r == NULL || r ->ws == NULL || r->ws->focus == NULL)
1550                 return;
1551         if (r->ws->focus->floating)
1552                 strlcat(s, "(f)", sz);
1553 }
1554
1555 void
1556 bar_window_name(char *s, size_t sz, struct swm_region *r)
1557 {
1558         char            *title;
1559
1560         if (r == NULL || r->ws == NULL || r->ws->focus == NULL)
1561                 return;
1562         if ((title = get_win_name(r->ws->focus->id)) == NULL)
1563                 return;
1564
1565         strlcat(s, title, sz);
1566         free(title);
1567 }
1568
1569 int             urgent[SWM_WS_MAX];
1570 void
1571 bar_urgent(char *s, size_t sz)
1572 {
1573         struct ws_win           *win;
1574         int                     i, j, num_screens;
1575         char                    b[8];
1576         xcb_get_property_cookie_t       c;
1577         xcb_icccm_wm_hints_t    hints;
1578
1579         for (i = 0; i < workspace_limit; i++)
1580                 urgent[i] = 0;
1581
1582         num_screens = xcb_setup_roots_length(xcb_get_setup(conn));
1583         for (i = 0; i < num_screens; i++)
1584                 for (j = 0; j < workspace_limit; j++)
1585                         TAILQ_FOREACH(win, &screens[i].ws[j].winlist, entry) {
1586                                 c = xcb_icccm_get_wm_hints(conn, win->id);
1587                                 if (xcb_icccm_get_wm_hints_reply(conn, c,
1588                                     &hints, NULL) == 0)
1589                                         continue;
1590                                 if (hints.flags & XCB_ICCCM_WM_HINT_X_URGENCY)
1591                                         urgent[j] = 1;
1592                         }
1593
1594         for (i = 0; i < workspace_limit; i++) {
1595                 if (urgent[i])
1596                         snprintf(b, sizeof b, "%d ", i + 1);
1597                 else
1598                         snprintf(b, sizeof b, "- ");
1599                 strlcat(s, b, sz);
1600         }
1601 }
1602
1603 void
1604 bar_workspace_name(char *s, size_t sz, struct swm_region *r)
1605 {
1606         if (r == NULL || r->ws == NULL)
1607                 return;
1608         if (r->ws->name != NULL)
1609                 strlcat(s, r->ws->name, sz);
1610 }
1611
1612 /* build the default bar format according to the defined enabled options */
1613 void
1614 bar_fmt(const char *fmtexp, char *fmtnew, struct swm_region *r, size_t sz)
1615 {
1616         /* if format provided, just copy the buffers */
1617         if (bar_format != NULL) {
1618                 strlcpy(fmtnew, fmtexp, sz);
1619                 return;
1620         }
1621
1622         /* reset the output buffer */
1623         *fmtnew = '\0';
1624
1625         strlcat(fmtnew, "+N:+I ", sz);
1626         if (stack_enabled)
1627                 strlcat(fmtnew, "+S", sz);
1628         strlcat(fmtnew, " ", sz);
1629
1630         /* only show the workspace name if there's actually one */
1631         if (r != NULL && r->ws != NULL && r->ws->name != NULL)
1632                 strlcat(fmtnew, "<+D>", sz);
1633         strlcat(fmtnew, "+3<", sz);
1634
1635         if (clock_enabled) {
1636                 strlcat(fmtnew, fmtexp, sz);
1637                 strlcat(fmtnew, "+4<", sz);
1638         }
1639
1640         /* bar_urgent already adds the space before the last asterisk */
1641         if (urgent_enabled)
1642                 strlcat(fmtnew, "* +U*+4<", sz);
1643
1644         if (title_class_enabled) {
1645                 strlcat(fmtnew, "+C", sz);
1646                 if (!title_name_enabled)
1647                         strlcat(fmtnew, "+4<", sz);
1648         }
1649
1650         /* checks needed by the colon and floating strlcat(3) calls below */
1651         if (r != NULL && r->ws != NULL && r->ws->focus != NULL) {
1652                 if (title_name_enabled) {
1653                         if (title_class_enabled)
1654                                 strlcat(fmtnew, ":", sz);
1655                         strlcat(fmtnew, "+T+4<", sz);
1656                 }
1657                 if (window_name_enabled) {
1658                         if (r->ws->focus->floating)
1659                                 strlcat(fmtnew, "+F ", sz);
1660                         strlcat(fmtnew, "+64W ", sz);
1661                 }
1662         }
1663
1664         /* finally add the action script output and the version */
1665         strlcat(fmtnew, "+4<+A+4<+V", sz);
1666 }
1667
1668 void
1669 bar_replace_pad(char *tmp, int *limit, size_t sz)
1670 {
1671         /* special case; no limit given, pad one space, instead */
1672         if (*limit == (int)sz - 1)
1673                 *limit = 1;
1674         snprintf(tmp, sz, "%*s", *limit, " ");
1675 }
1676
1677 /* replaces the bar format character sequences (like in tmux(1)) */
1678 char *
1679 bar_replace_seq(char *fmt, char *fmtrep, struct swm_region *r, size_t *offrep,
1680     size_t sz)
1681 {
1682         char                    *ptr;
1683         char                    tmp[SWM_BAR_MAX];
1684         int                     limit, size;
1685         size_t                  len;
1686
1687         /* reset strlcat(3) buffer */
1688         *tmp = '\0';
1689
1690         /* get number, if any */
1691         fmt++;
1692         size = 0;
1693         if (sscanf(fmt, "%d%n", &limit, &size) != 1)
1694                 limit = sizeof tmp - 1;
1695         if (limit <= 0 || limit >= (int)sizeof tmp)
1696                 limit = sizeof tmp - 1;
1697
1698         /* there is nothing to replace (ie EOL) */
1699         fmt += size;
1700         if (*fmt == '\0')
1701                 return (fmt);
1702
1703         switch (*fmt) {
1704         case '<':
1705                 bar_replace_pad(tmp, &limit, sizeof tmp);
1706                 break;
1707         case 'A':
1708                 snprintf(tmp, sizeof tmp, "%s", bar_ext);
1709                 break;
1710         case 'C':
1711                 bar_class_name(tmp, sizeof tmp, r);
1712                 break;
1713         case 'D':
1714                 bar_workspace_name(tmp, sizeof tmp, r);
1715                 break;
1716         case 'F':
1717                 bar_window_float(tmp, sizeof tmp, r);
1718                 break;
1719         case 'I':
1720                 snprintf(tmp, sizeof tmp, "%d", r->ws->idx + 1);
1721                 break;
1722         case 'N':
1723                 snprintf(tmp, sizeof tmp, "%d", r->s->idx + 1);
1724                 break;
1725         case 'P':
1726                 bar_class_title_name(tmp, sizeof tmp, r);
1727                 break;
1728         case 'S':
1729                 snprintf(tmp, sizeof tmp, "%s", r->ws->stacker);
1730                 break;
1731         case 'T':
1732                 bar_title_name(tmp, sizeof tmp, r);
1733                 break;
1734         case 'U':
1735                 bar_urgent(tmp, sizeof tmp);
1736                 break;
1737         case 'V':
1738                 snprintf(tmp, sizeof tmp, "%s", bar_vertext);
1739                 break;
1740         case 'W':
1741                 bar_window_name(tmp, sizeof tmp, r);
1742                 break;
1743         default:
1744                 /* unknown character sequence; copy as-is */
1745                 snprintf(tmp, sizeof tmp, "+%c", *fmt);
1746                 break;
1747         }
1748
1749         len = strlen(tmp);
1750         ptr = tmp;
1751         if ((int)len < limit)
1752                 limit = len;
1753         while (limit-- > 0) {
1754                 if (*offrep >= sz - 1)
1755                         break;
1756                 fmtrep[(*offrep)++] = *ptr++;
1757         }
1758
1759         fmt++;
1760         return (fmt);
1761 }
1762
1763 void
1764 bar_replace(char *fmt, char *fmtrep, struct swm_region *r, size_t sz)
1765 {
1766         size_t                  off;
1767
1768         off = 0;
1769         while (*fmt != '\0') {
1770                 if (*fmt != '+') {
1771                         /* skip ordinary characters */
1772                         if (off >= sz - 1)
1773                                 break;
1774                         fmtrep[off++] = *fmt++;
1775                         continue;
1776                 }
1777
1778                 /* character sequence found; replace it */
1779                 fmt = bar_replace_seq(fmt, fmtrep, r, &off, sz);
1780                 if (off >= sz - 1)
1781                         break;
1782         }
1783
1784         fmtrep[off] = '\0';
1785 }
1786
1787 void
1788 bar_fmt_expand(char *fmtexp, size_t sz)
1789 {
1790         char                    *fmt = NULL;
1791         size_t                  len;
1792         struct tm               tm;
1793         time_t                  tmt;
1794
1795         /* start by grabbing the current time and date */
1796         time(&tmt);
1797         localtime_r(&tmt, &tm);
1798
1799         /* figure out what to expand */
1800         if (bar_format != NULL)
1801                 fmt = bar_format;
1802         else if (bar_format == NULL && clock_enabled)
1803                 fmt = clock_format;
1804         /* if nothing to expand bail out */
1805         if (fmt == NULL) {
1806                 *fmtexp = '\0';
1807                 return;
1808         }
1809
1810         /* copy as-is, just in case the format shouldn't be expanded below */
1811         strlcpy(fmtexp, fmt, sz);
1812         /* finally pass the string through strftime(3) */
1813 #ifndef SWM_DENY_CLOCK_FORMAT
1814         if ((len = strftime(fmtexp, sz, fmt, &tm)) == 0)
1815                 warnx("format too long");
1816         fmtexp[len] = '\0';
1817 #endif
1818 }
1819
1820 void
1821 bar_fmt_print(void)
1822 {
1823         char                    fmtexp[SWM_BAR_MAX], fmtnew[SWM_BAR_MAX];
1824         char                    fmtrep[SWM_BAR_MAX];
1825         int                     i, num_screens;
1826         struct swm_region       *r;
1827
1828         /* expand the format by first passing it through strftime(3) */
1829         bar_fmt_expand(fmtexp, sizeof fmtexp);
1830
1831         num_screens = xcb_setup_roots_length(xcb_get_setup(conn));
1832         for (i = 0; i < num_screens; i++) {
1833                 TAILQ_FOREACH(r, &screens[i].rl, entry) {
1834                         if (r->bar == NULL)
1835                                 continue;
1836                         bar_fmt(fmtexp, fmtnew, r, sizeof fmtnew);
1837                         bar_replace(fmtnew, fmtrep, r, sizeof fmtrep);
1838                         if (bar_font_legacy)
1839                                 bar_print_legacy(r, fmtrep);
1840                         else
1841                                 bar_print(r, fmtrep);
1842                 }
1843         }
1844 }
1845
1846 void
1847 bar_update(void)
1848 {
1849         size_t                  len;
1850         char                    *b;
1851
1852         if (!bar_enabled)
1853                 return;
1854         if (bar_extra && bar_extra_running) {
1855                 /* ignore short reads; it'll correct itself */
1856                 while ((b = fgetln(stdin, &len)) != NULL)
1857                         if (b && b[len - 1] == '\n') {
1858                                 b[len - 1] = '\0';
1859                                 strlcpy((char *)bar_ext, b, sizeof bar_ext);
1860                         }
1861                 if (b == NULL && errno != EAGAIN) {
1862                         warn("bar_update: bar_extra failed");
1863                         bar_extra_stop();
1864                 }
1865         } else
1866                 strlcpy((char *)bar_ext, "", sizeof bar_ext);
1867
1868         bar_fmt_print();
1869         alarm(bar_delay);
1870 }
1871
1872 void
1873 bar_signal(int sig)
1874 {
1875         /* suppress unused warning since var is needed */
1876         (void)sig;
1877
1878         bar_alarm = 1;
1879 }
1880
1881 void
1882 bar_toggle(struct swm_region *r, union arg *args)
1883 {
1884         struct swm_region       *tmpr;
1885         int                     i, num_screens;
1886
1887         /* suppress unused warnings since vars are needed */
1888         (void)r;
1889         (void)args;
1890
1891         DNPRINTF(SWM_D_BAR, "bar_toggle\n");
1892
1893         num_screens = xcb_setup_roots_length(xcb_get_setup(conn));
1894         if (bar_enabled) {
1895                 for (i = 0; i < num_screens; i++)
1896                         TAILQ_FOREACH(tmpr, &screens[i].rl, entry)
1897                                 if (tmpr->bar)
1898                                         xcb_unmap_window(conn, tmpr->bar->id);
1899         } else {
1900                 for (i = 0; i < num_screens; i++)
1901                         TAILQ_FOREACH(tmpr, &screens[i].rl, entry)
1902                                 if (tmpr->bar)
1903                                         xcb_map_window(conn, tmpr->bar->id);
1904         }
1905
1906         bar_enabled = !bar_enabled;
1907
1908         stack();
1909
1910         /* must be after stack */
1911         bar_update();
1912
1913         focus_flush();
1914 }
1915
1916 void
1917 bar_refresh(void)
1918 {
1919         struct swm_region       *r;
1920         uint32_t                wa[2];
1921         int                     i, num_screens;
1922
1923         /* do this here because the conf file is in memory */
1924         if (bar_extra && !bar_extra_running && bar_argv[0]) {
1925                 /* launch external status app */
1926                 bar_extra_running = 1;
1927                 if (pipe(bar_pipe) == -1)
1928                         err(1, "pipe error");
1929                 socket_setnonblock(bar_pipe[0]);
1930                 socket_setnonblock(bar_pipe[1]); /* XXX hmmm, really? */
1931                 if (dup2(bar_pipe[0], 0) == -1)
1932                         err(1, "dup2");
1933                 if (dup2(bar_pipe[1], 1) == -1)
1934                         err(1, "dup2");
1935                 if (signal(SIGPIPE, SIG_IGN) == SIG_ERR)
1936                         err(1, "could not disable SIGPIPE");
1937                 switch (bar_pid = fork()) {
1938                 case -1:
1939                         err(1, "cannot fork");
1940                         break;
1941                 case 0: /* child */
1942                         close(bar_pipe[0]);
1943                         execvp(bar_argv[0], bar_argv);
1944                         err(1, "%s external app failed", bar_argv[0]);
1945                         break;
1946                 default: /* parent */
1947                         close(bar_pipe[1]);
1948                         break;
1949                 }
1950         }
1951
1952         num_screens = xcb_setup_roots_length(xcb_get_setup(conn));
1953         for (i = 0; i < num_screens; i++)
1954                 TAILQ_FOREACH(r, &screens[i].rl, entry) {
1955                         if (r->bar == NULL)
1956                                 continue;
1957                         wa[0] = screens[i].c[SWM_S_COLOR_BAR].pixel;
1958                         wa[1] = screens[i].c[SWM_S_COLOR_BAR_BORDER].pixel;
1959                         xcb_change_window_attributes(conn, r->bar->id,
1960                             XCB_CW_BACK_PIXEL | XCB_CW_BORDER_PIXEL, wa);
1961                 }
1962         bar_update();
1963 }
1964
1965 int
1966 isxlfd(char *s)
1967 {
1968         int      count = 0;
1969
1970         while ((s = index(s, '-'))) {
1971                 ++count;
1972                 ++s;
1973         }
1974
1975         return (count == 14);
1976 }
1977
1978 void
1979 fontset_init()
1980 {
1981         char                    *default_string;
1982         char                    **missing_charsets;
1983         int                     num_missing_charsets = 0;
1984         int                     i;
1985
1986         if (bar_fs) {
1987                 XFreeFontSet(display, bar_fs);
1988                 bar_fs = NULL;
1989         }
1990
1991         DNPRINTF(SWM_D_INIT, "fontset_init: loading bar_fonts: %s\n", bar_fonts);
1992
1993         bar_fs = XCreateFontSet(display, bar_fonts, &missing_charsets,
1994             &num_missing_charsets, &default_string);
1995
1996         if (num_missing_charsets > 0) {
1997                 warnx("Unable to load charset(s):");
1998
1999                 for (i = 0; i < num_missing_charsets; ++i)
2000                         warnx("%s", missing_charsets[i]);
2001
2002                 XFreeStringList(missing_charsets);
2003
2004                 if (strcmp(default_string, ""))
2005                         warnx("Glyphs from those sets will be replaced "
2006                             "by '%s'.", default_string);
2007                 else
2008                         warnx("Glyphs from those sets won't be drawn.");
2009         }
2010
2011         if (bar_fs == NULL)
2012                 errx(1, "Error creating font set structure.");
2013
2014         bar_fs_extents = XExtentsOfFontSet(bar_fs);
2015
2016         bar_height = bar_fs_extents->max_logical_extent.height +
2017             2 * bar_border_width;
2018
2019         if (bar_height < 1)
2020                 bar_height = 1;
2021 }
2022
2023 void
2024 xft_init(struct swm_region *r)
2025 {
2026         char                    *font, *d, *search;
2027         XRenderColor            color;
2028
2029         if (bar_font == NULL) {
2030                 if ((d = strdup(bar_fonts)) == NULL)
2031                         errx(1, "insufficient memory.");
2032                 search = d;
2033                 while ((font = strsep(&search, ",")) != NULL) {
2034                         if (*font == '\0')
2035                                 continue;
2036
2037                         DNPRINTF(SWM_D_INIT, "xft_init: try font %s\n", font);
2038
2039                         if (isxlfd(font)) {
2040                                 bar_font = XftFontOpenXlfd(display, r->s->idx,
2041                                                 font);
2042                         } else {
2043                                 bar_font = XftFontOpenName(display, r->s->idx,
2044                                                 font);
2045                         }
2046
2047                         if (!bar_font) {
2048                                 warnx("unable to load font %s", font);
2049                                 continue;
2050                         } else {
2051                                 DNPRINTF(SWM_D_INIT, "successfully opened "
2052                                     "font %s\n", font);
2053                                 break;
2054                         }
2055                 }
2056                 free(d);
2057         }
2058
2059         if (bar_font == NULL)
2060                 errx(1, "unable to open a font");
2061
2062         PIXEL_TO_XRENDERCOLOR(r->s->c[SWM_S_COLOR_BAR_FONT].pixel, color);
2063
2064         if (!XftColorAllocValue(display, DefaultVisual(display, r->s->idx),
2065             DefaultColormap(display, r->s->idx), &color, &bar_font_color))
2066                 warn("unable to allocate Xft color");
2067
2068         bar_height = bar_font->height + 2 * bar_border_width;
2069
2070         if (bar_height < 1)
2071                 bar_height = 1;
2072 }
2073
2074 void
2075 bar_setup(struct swm_region *r)
2076 {
2077         xcb_screen_t    *screen;
2078         uint32_t         wa[3];
2079
2080         DNPRINTF(SWM_D_BAR, "bar_setup: screen %d.\n",
2081             r->s->idx);
2082
2083         if ((screen = get_screen(r->s->idx)) == NULL)
2084                 errx(1, "ERROR: can't get screen %d.", r->s->idx);
2085
2086         if (r->bar != NULL)
2087                 return;
2088
2089         if ((r->bar = calloc(1, sizeof(struct swm_bar))) == NULL)
2090                 err(1, "bar_setup: calloc: failed to allocate memory.");
2091
2092         if (bar_font_legacy)
2093                 fontset_init();
2094         else
2095                 xft_init(r);
2096
2097         X(r->bar) = X(r);
2098         Y(r->bar) = bar_at_bottom ? (Y(r) + HEIGHT(r) - bar_height) : Y(r);
2099         WIDTH(r->bar) = WIDTH(r) - 2 * bar_border_width;
2100         HEIGHT(r->bar) = bar_height - 2 * bar_border_width;
2101
2102         r->bar->id = xcb_generate_id(conn);
2103         wa[0] = r->s->c[SWM_S_COLOR_BAR].pixel;
2104         wa[1] = r->s->c[SWM_S_COLOR_BAR_BORDER].pixel;
2105         wa[2] = XCB_EVENT_MASK_EXPOSURE;
2106
2107         xcb_create_window(conn, XCB_COPY_FROM_PARENT, r->bar->id, r->s->root,
2108             X(r->bar), Y(r->bar), WIDTH(r->bar), HEIGHT(r->bar),
2109             bar_border_width, XCB_WINDOW_CLASS_INPUT_OUTPUT,
2110             XCB_COPY_FROM_PARENT, XCB_CW_BACK_PIXEL | XCB_CW_BORDER_PIXEL
2111             | XCB_CW_EVENT_MASK, wa);
2112
2113         r->bar->buffer = xcb_generate_id(conn);
2114         xcb_create_pixmap(conn, screen->root_depth, r->bar->buffer, r->bar->id,
2115             WIDTH(r->bar), HEIGHT(r->bar));
2116
2117         if (xrandr_support)
2118                 xcb_randr_select_input(conn, r->bar->id,
2119                     XCB_RANDR_NOTIFY_MASK_OUTPUT_CHANGE);
2120
2121         if (bar_enabled)
2122                 xcb_map_window(conn, r->bar->id);
2123
2124         DNPRINTF(SWM_D_BAR, "bar_setup: window: 0x%x, (x,y) w x h: (%d,%d) "
2125             "%d x %d\n", WINID(r->bar), X(r->bar), Y(r->bar), WIDTH(r->bar),
2126             HEIGHT(r->bar));
2127
2128         if (signal(SIGALRM, bar_signal) == SIG_ERR)
2129                 err(1, "could not install bar_signal");
2130         bar_refresh();
2131 }
2132
2133 void
2134 bar_cleanup(struct swm_region *r)
2135 {
2136         if (r->bar == NULL)
2137                 return;
2138         xcb_destroy_window(conn, r->bar->id);
2139         xcb_free_pixmap(conn, r->bar->buffer);
2140         free(r->bar);
2141         r->bar = NULL;
2142 }
2143
2144 void
2145 set_win_state(struct ws_win *win, uint16_t state)
2146 {
2147         uint16_t                data[2] = { state, XCB_ATOM_NONE };
2148
2149         DNPRINTF(SWM_D_EVENT, "set_win_state: window: 0x%x, state: %u\n",
2150             win->id, state);
2151
2152         if (win == NULL)
2153                 return;
2154
2155         xcb_change_property(conn, XCB_PROP_MODE_REPLACE, win->id, a_state,
2156             a_state, 32, 2, data);
2157 }
2158
2159 uint32_t
2160 getstate(xcb_window_t w)
2161 {
2162         uint32_t                        result = 0;
2163         xcb_get_property_cookie_t       c;
2164         xcb_get_property_reply_t        *r;
2165
2166         c = xcb_get_property(conn, 0, w, a_state, a_state, 0L, 2L);
2167         r = xcb_get_property_reply(conn, c, NULL);
2168
2169         if (r) {
2170                 if (r->type == a_state && r->format == 32 && r->length == 2)
2171                         result = *((uint32_t *)xcb_get_property_value(r));
2172                 free(r);
2173         }
2174
2175         DNPRINTF(SWM_D_MISC, "getstate property: win 0x%x state %u\n", w,
2176             result);
2177         return (result);
2178 }
2179
2180 void
2181 version(struct swm_region *r, union arg *args)
2182 {
2183         /* suppress unused warnings since vars are needed */
2184         (void)r;
2185         (void)args;
2186
2187         bar_version = !bar_version;
2188         if (bar_version)
2189                 snprintf(bar_vertext, sizeof bar_vertext,
2190                     "Version: %s Build: %s", SPECTRWM_VERSION, buildstr);
2191         else
2192                 strlcpy(bar_vertext, "", sizeof bar_vertext);
2193         bar_update();
2194
2195         xcb_flush(conn);
2196 }
2197
2198 void
2199 client_msg(struct ws_win *win, xcb_atom_t a, xcb_timestamp_t t)
2200 {
2201         xcb_client_message_event_t      ev;
2202 #ifdef SWM_DEBUG
2203         char                            *name;
2204 #endif
2205
2206         if (win == NULL)
2207                 return;
2208 #ifdef SWM_DEBUG
2209         name = get_atom_name(a);
2210         DNPRINTF(SWM_D_EVENT, "client_msg: window: 0x%x, atom: %s(%u), "
2211             "time: %#x\n",
2212             win->id, name, a, t);
2213         free(name);
2214 #endif
2215
2216         bzero(&ev, sizeof ev);
2217         ev.response_type = XCB_CLIENT_MESSAGE;
2218         ev.window = win->id;
2219         ev.type = a_prot;
2220         ev.format = 32;
2221         ev.data.data32[0] = a;
2222         ev.data.data32[1] = t;
2223
2224         xcb_send_event(conn, 0, win->id,
2225             XCB_EVENT_MASK_NO_EVENT, (const char *)&ev);
2226 }
2227
2228 /* synthetic response to a ConfigureRequest when not making a change */
2229 void
2230 config_win(struct ws_win *win, xcb_configure_request_event_t *ev)
2231 {
2232         xcb_configure_notify_event_t ce;
2233
2234         if (win == NULL)
2235                 return;
2236
2237         /* send notification of unchanged state. */
2238         bzero(&ce, sizeof(ce));
2239         ce.response_type = XCB_CONFIGURE_NOTIFY;
2240         ce.x = X(win);
2241         ce.y = Y(win);
2242         ce.width = WIDTH(win);
2243         ce.height = HEIGHT(win);
2244         ce.override_redirect = 0;
2245
2246         if (ev == NULL) {
2247                 /* EWMH */
2248                 ce.event = win->id;
2249                 ce.window = win->id;
2250                 ce.border_width = BORDER(win);
2251                 ce.above_sibling = XCB_WINDOW_NONE;
2252         } else {
2253                 /* normal */
2254                 ce.event = ev->window;
2255                 ce.window = ev->window;
2256
2257                 /* make response appear more WM_SIZE_HINTS-compliant */
2258                 if (win->sh.flags) {
2259                         DNPRINTF(SWM_D_MISC, "config_win: hints: window: 0x%x,"
2260                             " sh.flags: %u, min: %d x %d, max: %d x %d, inc: "
2261                             "%d x %d\n", win->id, win->sh.flags, SH_MIN_W(win),
2262                             SH_MIN_H(win), SH_MAX_W(win), SH_MAX_H(win),
2263                             SH_INC_W(win), SH_INC_H(win));
2264                 }
2265
2266                 /* min size */
2267                 if (SH_MIN(win)) {
2268                         /* the hint may be set... to 0! */
2269                         if (SH_MIN_W(win) > 0 && ce.width < SH_MIN_W(win))
2270                                 ce.width = SH_MIN_W(win);
2271                         if (SH_MIN_H(win) > 0 && ce.height < SH_MIN_H(win))
2272                                 ce.height = SH_MIN_H(win);
2273                 }
2274
2275                 /* max size */
2276                 if (SH_MAX(win)) {
2277                         /* may also be advertized as 0 */
2278                         if (SH_MAX_W(win) > 0 && ce.width > SH_MAX_W(win))
2279                                 ce.width = SH_MAX_W(win);
2280                         if (SH_MAX_H(win) > 0 && ce.height > SH_MAX_H(win))
2281                                 ce.height = SH_MAX_H(win);
2282                 }
2283
2284                 /* resize increment. */
2285                 if (SH_INC(win)) {
2286                         if (SH_INC_W(win) > 1 && ce.width > SH_INC_W(win))
2287                                 ce.width -= (ce.width - SH_MIN_W(win)) %
2288                                     SH_INC_W(win);
2289                         if (SH_INC_H(win) > 1 && ce.height > SH_INC_H(win))
2290                                 ce.height -= (ce.height - SH_MIN_H(win)) %
2291                                     SH_INC_H(win);
2292                 }
2293
2294                 /* adjust x and y for requested border_width. */
2295                 ce.x += BORDER(win) - ev->border_width;
2296                 ce.y += BORDER(win) - ev->border_width;
2297                 ce.border_width = ev->border_width;
2298                 ce.above_sibling = ev->sibling;
2299         }
2300
2301         DNPRINTF(SWM_D_MISC, "config_win: ewmh: %s, window: 0x%x, (x,y) w x h: "
2302             "(%d,%d) %d x %d, border: %d\n", YESNO(ev == NULL), win->id, ce.x,
2303             ce.y, ce.width, ce.height, ce.border_width);
2304
2305         xcb_send_event(conn, 0, win->id, XCB_EVENT_MASK_STRUCTURE_NOTIFY,
2306             (char *)&ce);
2307 }
2308
2309 int
2310 count_win(struct workspace *ws, int count_transient)
2311 {
2312         struct ws_win           *win;
2313         int                     count = 0;
2314
2315         TAILQ_FOREACH(win, &ws->winlist, entry) {
2316                 if (!count_transient && win->floating)
2317                         continue;
2318                 if (!count_transient && win->transient)
2319                         continue;
2320                 if (win->iconic)
2321                         continue;
2322                 count++;
2323         }
2324         DNPRINTF(SWM_D_MISC, "count_win: %d\n", count);
2325
2326         return (count);
2327 }
2328
2329 void
2330 quit(struct swm_region *r, union arg *args)
2331 {
2332         /* suppress unused warnings since vars are needed */
2333         (void)r;
2334         (void)args;
2335
2336         DNPRINTF(SWM_D_MISC, "quit\n");
2337         running = 0;
2338 }
2339
2340 void
2341 map_window(struct ws_win *win)
2342 {
2343         uint32_t        val = XCB_STACK_MODE_ABOVE;
2344
2345         if (win == NULL)
2346                 return;
2347
2348         DNPRINTF(SWM_D_EVENT, "map_window: win 0x%x, mapped: %s\n", win->id,
2349             YESNO(win->mapped));
2350
2351         xcb_configure_window(conn, win->id,
2352             XCB_CONFIG_WINDOW_STACK_MODE, &val);
2353
2354         if (win->mapped)
2355                 return;
2356
2357         xcb_map_window(conn, win->id);
2358         set_win_state(win, XCB_ICCCM_WM_STATE_NORMAL);
2359         win->mapped = 1;
2360 }
2361
2362 void
2363 unmap_window(struct ws_win *win)
2364 {
2365         if (win == NULL)
2366                 return;
2367
2368         DNPRINTF(SWM_D_EVENT, "unmap_window: win 0x%x, mapped: %s\n", win->id,
2369             YESNO(win->mapped));
2370
2371         if (!win->mapped)
2372                 return;
2373
2374         xcb_unmap_window(conn, win->id);
2375         set_win_state(win, XCB_ICCCM_WM_STATE_ICONIC);
2376         win->mapped = 0;
2377 }
2378
2379 void
2380 unmap_all(void)
2381 {
2382         struct ws_win           *win;
2383         int                     i, j, num_screens;
2384
2385         num_screens = xcb_setup_roots_length(xcb_get_setup(conn));
2386         for (i = 0; i < num_screens; i++)
2387                 for (j = 0; j < workspace_limit; j++)
2388                         TAILQ_FOREACH(win, &screens[i].ws[j].winlist, entry)
2389                                 unmap_window(win);
2390 }
2391
2392 void
2393 fake_keypress(struct ws_win *win, xcb_keysym_t keysym, uint16_t modifiers)
2394 {
2395         xcb_key_press_event_t   event;
2396         xcb_keycode_t           *keycode;
2397
2398         if (win == NULL)
2399                 return;
2400
2401         keycode = xcb_key_symbols_get_keycode(syms, keysym);
2402
2403         DNPRINTF(SWM_D_MISC, "fake_keypress: win 0x%x keycode %u\n",
2404             win->id, *keycode);
2405
2406         bzero(&event, sizeof(event));
2407         event.event = win->id;
2408         event.root = win->s->root;
2409         event.child = XCB_WINDOW_NONE;
2410         event.time = XCB_CURRENT_TIME;
2411         event.event_x = X(win);
2412         event.event_y = Y(win);
2413         event.root_x = 1;
2414         event.root_y = 1;
2415         event.same_screen = 1;
2416         event.detail = *keycode;
2417         event.state = modifiers;
2418
2419         event.response_type = XCB_KEY_PRESS;
2420         xcb_send_event(conn, 1, win->id,
2421             XCB_EVENT_MASK_KEY_PRESS, (const char *)&event);
2422
2423         event.response_type = XCB_KEY_RELEASE;
2424         xcb_send_event(conn, 1, win->id,
2425             XCB_EVENT_MASK_KEY_RELEASE, (const char *)&event);
2426
2427         free(keycode);
2428 }
2429
2430 void
2431 restart(struct swm_region *r, union arg *args)
2432 {
2433         /* suppress unused warning since var is needed */
2434         (void)r;
2435         (void)args;
2436
2437         DNPRINTF(SWM_D_MISC, "restart: %s\n", start_argv[0]);
2438
2439         shutdown_cleanup();
2440
2441         execvp(start_argv[0], start_argv);
2442         warn("execvp failed");
2443         quit(NULL, NULL);
2444 }
2445
2446 struct swm_region *
2447 root_to_region(xcb_window_t root)
2448 {
2449         struct ws_win                   *cfw;
2450         struct swm_region               *r = NULL;
2451         int                             i, num_screens;
2452         xcb_query_pointer_reply_t       *qpr;
2453         xcb_get_input_focus_reply_t     *gifr;
2454
2455         DNPRINTF(SWM_D_MISC, "root_to_region: window: 0x%x\n", root);
2456
2457         num_screens = xcb_setup_roots_length(xcb_get_setup(conn));
2458         for (i = 0; i < num_screens; i++)
2459                 if (screens[i].root == root)
2460                         break;
2461
2462         /* Try to find an actively focused window */
2463         gifr = xcb_get_input_focus_reply(conn, xcb_get_input_focus(conn), NULL);
2464         if (gifr) {
2465                 cfw = find_window(gifr->focus);
2466                 if (cfw && cfw->ws->r)
2467                         r = cfw->ws->r;
2468
2469                 free(gifr);
2470         }
2471
2472         if (r == NULL) {
2473                 /* No region with an active focus; try to use pointer. */
2474                 qpr = xcb_query_pointer_reply(conn, xcb_query_pointer(conn,
2475                     screens[i].root), NULL);
2476
2477                 if (qpr) {
2478                         DNPRINTF(SWM_D_MISC, "root_to_region: pointer: (%d,%d)\n",
2479                             qpr->root_x, qpr->root_y);
2480                         TAILQ_FOREACH(r, &screens[i].rl, entry)
2481                                 if (X(r) <= qpr->root_x && qpr->root_x < MAX_X(r) &&
2482                                     Y(r) <= qpr->root_y && qpr->root_y < MAX_Y(r))
2483                                         break;
2484                         free(qpr);
2485                 }
2486         }
2487
2488         /* Last resort. */
2489         if (r == NULL)
2490                 r = TAILQ_FIRST(&screens[i].rl);
2491
2492         return (r);
2493 }
2494
2495 struct ws_win *
2496 find_unmanaged_window(xcb_window_t id)
2497 {
2498         struct ws_win           *win;
2499         int                     i, j, num_screens;
2500
2501         num_screens = xcb_setup_roots_length(xcb_get_setup(conn));
2502         for (i = 0; i < num_screens; i++)
2503                 for (j = 0; j < workspace_limit; j++)
2504                         TAILQ_FOREACH(win, &screens[i].ws[j].unmanagedlist,
2505                             entry)
2506                                 if (id == win->id)
2507                                         return (win);
2508         return (NULL);
2509 }
2510
2511 struct ws_win *
2512 find_window(xcb_window_t id)
2513 {
2514         struct ws_win           *win;
2515         int                     i, j, num_screens;
2516         xcb_query_tree_reply_t  *r;
2517
2518         num_screens = xcb_setup_roots_length(xcb_get_setup(conn));
2519         for (i = 0; i < num_screens; i++)
2520                 for (j = 0; j < workspace_limit; j++)
2521                         TAILQ_FOREACH(win, &screens[i].ws[j].winlist, entry)
2522                                 if (id == win->id)
2523                                         return (win);
2524
2525         r = xcb_query_tree_reply(conn, xcb_query_tree(conn, id), NULL);
2526         if (!r)
2527                 return (NULL);
2528
2529         /* if we were looking for the parent return that window instead */
2530         if (r->parent == 0 || r->root == r->parent) {
2531                 free(r);
2532                 return (NULL);
2533         }
2534
2535         /* look for parent */
2536         for (i = 0; i < num_screens; i++)
2537                 for (j = 0; j < workspace_limit; j++)
2538                         TAILQ_FOREACH(win, &screens[i].ws[j].winlist, entry)
2539                                 if (r->parent == win->id) {
2540                                         free(r);
2541                                         return (win);
2542                                 }
2543
2544         free(r);
2545         return (NULL);
2546 }
2547
2548 void
2549 spawn(int ws_idx, union arg *args, int close_fd)
2550 {
2551         int                     fd;
2552         char                    *ret = NULL;
2553
2554         DNPRINTF(SWM_D_MISC, "spawn: %s\n", args->argv[0]);
2555
2556         close(xcb_get_file_descriptor(conn));
2557
2558         setenv("LD_PRELOAD", SWM_LIB, 1);
2559
2560         if (asprintf(&ret, "%d", ws_idx) == -1) {
2561                 warn("spawn: asprintf SWM_WS");
2562                 _exit(1);
2563         }
2564         setenv("_SWM_WS", ret, 1);
2565         free(ret);
2566         ret = NULL;
2567
2568         if (asprintf(&ret, "%d", getpid()) == -1) {
2569                 warn("spawn: asprintf _SWM_PID");
2570                 _exit(1);
2571         }
2572         setenv("_SWM_PID", ret, 1);
2573         free(ret);
2574         ret = NULL;
2575
2576         if (setsid() == -1) {
2577                 warn("spawn: setsid");
2578                 _exit(1);
2579         }
2580
2581         if (close_fd) {
2582                 /*
2583                  * close stdin and stdout to prevent interaction between apps
2584                  * and the baraction script
2585                  * leave stderr open to record errors
2586                 */
2587                 if ((fd = open(_PATH_DEVNULL, O_RDWR, 0)) == -1) {
2588                         warn("spawn: open");
2589                         _exit(1);
2590                 }
2591                 dup2(fd, STDIN_FILENO);
2592                 dup2(fd, STDOUT_FILENO);
2593                 if (fd > 2)
2594                         close(fd);
2595         }
2596
2597         execvp(args->argv[0], args->argv);
2598
2599         warn("spawn: execvp");
2600         _exit(1);
2601 }
2602
2603 void
2604 kill_refs(struct ws_win *win)
2605 {
2606         int                     i, x, num_screens;
2607         struct swm_region       *r;
2608         struct workspace        *ws;
2609
2610         if (win == NULL)
2611                 return;
2612
2613         num_screens = xcb_setup_roots_length(xcb_get_setup(conn));
2614         for (i = 0; i < num_screens; i++)
2615                 TAILQ_FOREACH(r, &screens[i].rl, entry)
2616                         for (x = 0; x < workspace_limit; x++) {
2617                                 ws = &r->s->ws[x];
2618                                 if (win == ws->focus)
2619                                         ws->focus = NULL;
2620                                 if (win == ws->focus_prev)
2621                                         ws->focus_prev = NULL;
2622                         }
2623 }
2624
2625 int
2626 validate_win(struct ws_win *testwin)
2627 {
2628         struct ws_win           *win;
2629         struct workspace        *ws;
2630         struct swm_region       *r;
2631         int                     i, x, num_screens;
2632
2633         if (testwin == NULL)
2634                 return (0);
2635
2636         num_screens = xcb_setup_roots_length(xcb_get_setup(conn));
2637         for (i = 0; i < num_screens; i++)
2638                 TAILQ_FOREACH(r, &screens[i].rl, entry)
2639                         for (x = 0; x < workspace_limit; x++) {
2640                                 ws = &r->s->ws[x];
2641                                 TAILQ_FOREACH(win, &ws->winlist, entry)
2642                                         if (win == testwin)
2643                                                 return (0);
2644                         }
2645         return (1);
2646 }
2647
2648 int
2649 validate_ws(struct workspace *testws)
2650 {
2651         struct swm_region       *r;
2652         struct workspace        *ws;
2653         int                     i, x, num_screens;
2654
2655         /* validate all ws */
2656         num_screens = xcb_setup_roots_length(xcb_get_setup(conn));
2657         for (i = 0; i < num_screens; i++)
2658                 TAILQ_FOREACH(r, &screens[i].rl, entry)
2659                         for (x = 0; x < workspace_limit; x++) {
2660                                 ws = &r->s->ws[x];
2661                                 if (ws == testws)
2662                                         return (0);
2663                         }
2664         return (1);
2665 }
2666
2667 void
2668 unfocus_win(struct ws_win *win)
2669 {
2670         xcb_window_t            none = XCB_WINDOW_NONE;
2671
2672         DNPRINTF(SWM_D_FOCUS, "unfocus_win: window: 0x%x\n", WINID(win));
2673
2674         if (win == NULL)
2675                 return;
2676         if (win->ws == NULL) {
2677                 DNPRINTF(SWM_D_FOCUS, "unfocus_win: NULL ws.\n");
2678                 return;
2679         }
2680
2681         if (validate_ws(win->ws)) {
2682                 DNPRINTF(SWM_D_FOCUS, "unfocus_win: invalid ws.\n");
2683                 return;
2684         }
2685
2686         if (win->ws->r == NULL) {
2687                 DNPRINTF(SWM_D_FOCUS, "unfocus_win: NULL region.\n");
2688                 return;
2689         }
2690
2691         if (validate_win(win)) {
2692                 DNPRINTF(SWM_D_FOCUS, "unfocus_win: invalid win.\n");
2693                 kill_refs(win);
2694                 return;
2695         }
2696
2697         if (win->ws->focus == win) {
2698                 win->ws->focus = NULL;
2699                 win->ws->focus_prev = win;
2700         }
2701
2702         if (validate_win(win->ws->focus)) {
2703                 kill_refs(win->ws->focus);
2704                 win->ws->focus = NULL;
2705         }
2706         if (validate_win(win->ws->focus_prev)) {
2707                 kill_refs(win->ws->focus_prev);
2708                 win->ws->focus_prev = NULL;
2709         }
2710
2711         xcb_change_window_attributes(conn, win->id, XCB_CW_BORDER_PIXEL,
2712             &win->ws->r->s->c[SWM_S_COLOR_UNFOCUS].pixel);
2713
2714         xcb_change_property(conn, XCB_PROP_MODE_REPLACE, win->s->root,
2715             ewmh[_NET_ACTIVE_WINDOW].atom, XCB_ATOM_WINDOW, 32, 1, &none);
2716
2717         DNPRINTF(SWM_D_FOCUS, "unfocus_win: done.\n");
2718 }
2719
2720 void
2721 focus_win(struct ws_win *win)
2722 {
2723         struct ws_win                   *cfw = NULL;
2724         xcb_get_input_focus_reply_t     *r;
2725
2726         DNPRINTF(SWM_D_FOCUS, "focus_win: window: 0x%x\n", WINID(win));
2727
2728         if (win == NULL)
2729                 goto out;
2730
2731         if (win->ws == NULL)
2732                 goto out;
2733
2734         if (validate_ws(win->ws))
2735                 goto out;
2736
2737         if (validate_win(win)) {
2738                 kill_refs(win);
2739                 goto out;
2740         }
2741
2742         r = xcb_get_input_focus_reply(conn, xcb_get_input_focus(conn), NULL);
2743         if (r) {
2744                 cfw = find_window(r->focus);
2745                 if (cfw != win)
2746                         unfocus_win(cfw);
2747                 free(r);
2748         }
2749
2750         if (win->ws->focus != win) {
2751                 if (win->ws->focus && win->ws->focus != cfw)
2752                         unfocus_win(win->ws->focus);
2753                 win->ws->focus = win;
2754         }
2755
2756         if (cfw != win && win->ws->r != NULL) {
2757                 /* Set input focus if no input hint, or indicated by hint. */
2758                 if (!(win->hints.flags & XCB_ICCCM_WM_HINT_INPUT) ||
2759                     (win->hints.flags & XCB_ICCCM_WM_HINT_INPUT &&
2760                      win->hints.input))
2761                         xcb_set_input_focus(conn, XCB_INPUT_FOCUS_PARENT,
2762                                         win->id, last_event_time);
2763
2764                 /* Tell app it can adjust focus to a specific window. */
2765                 if (win->take_focus) {
2766                         /* java is special; always tell parent */
2767                         if (win->transient && win->java)
2768                                 client_msg(find_window(win->transient),
2769                                     a_takefocus, last_event_time);
2770                         else
2771                                 client_msg(win, a_takefocus, last_event_time);
2772                 }
2773
2774                 xcb_change_window_attributes(conn, win->id, XCB_CW_BORDER_PIXEL,
2775                     &win->ws->r->s->c[SWM_S_COLOR_FOCUS].pixel);
2776
2777                 if (win->ws->cur_layout->flags & SWM_L_MAPONFOCUS ||
2778                     win->ws->always_raise)
2779                         map_window(win);
2780
2781                 xcb_change_property(conn, XCB_PROP_MODE_REPLACE, win->s->root,
2782                     ewmh[_NET_ACTIVE_WINDOW].atom, XCB_ATOM_WINDOW, 32, 1,
2783                     &win->id);
2784         }
2785
2786 out:
2787         bar_update();
2788
2789         DNPRINTF(SWM_D_FOCUS, "focus_win: done.\n");
2790 }
2791
2792 /* If a child window should have focus instead, return it. */
2793 struct ws_win *
2794 get_focus_magic(struct ws_win *win)
2795 {
2796         struct ws_win   *parent = NULL;
2797         struct ws_win   *child = NULL;
2798
2799         DNPRINTF(SWM_D_FOCUS, "get_focus_magic: window: 0x%x\n", WINID(win));
2800         if (win == NULL)
2801                 return win;
2802
2803         if (win->transient) {
2804                 parent = find_window(win->transient);
2805
2806                 /* If parent prefers focus elsewhere, then try to do so. */
2807                 if (parent && (child = parent->focus_child)) {
2808                         if (validate_win(child) == 0 && child->mapped)
2809                                 win = child;
2810                         else
2811                                 parent->focus_child = NULL;
2812                 }
2813         }
2814
2815         /* If this window prefers focus elsewhere, then try to do so. */
2816         if ((child = win->focus_child)) {
2817                 if (validate_win(child) == 0 && child->mapped)
2818                         win = child;
2819                 else
2820                         win->focus_child = NULL;
2821         }
2822
2823         return win;
2824 }
2825
2826 void
2827 event_drain(uint8_t rt)
2828 {
2829         xcb_generic_event_t     *evt;
2830
2831         /* ensure all pending requests have been processed before filtering. */
2832         xcb_aux_sync(conn);
2833         while ((evt = xcb_poll_for_event(conn))) {
2834                 if (XCB_EVENT_RESPONSE_TYPE(evt) != rt)
2835                         event_handle(evt);
2836
2837                 free(evt);
2838         }
2839 }
2840
2841 void
2842 switchws(struct swm_region *r, union arg *args)
2843 {
2844         int                     wsid = args->id, unmap_old = 0;
2845         struct swm_region       *this_r, *other_r;
2846         struct ws_win           *win;
2847         struct workspace        *new_ws, *old_ws;
2848
2849         if (!(r && r->s))
2850                 return;
2851
2852         if (wsid >= workspace_limit)
2853                 return;
2854
2855         this_r = r;
2856         old_ws = this_r->ws;
2857         new_ws = &this_r->s->ws[wsid];
2858
2859         DNPRINTF(SWM_D_WS, "switchws: screen[%d]:%dx%d+%d+%d: %d -> %d\n",
2860             r->s->idx, WIDTH(r), HEIGHT(r), X(r), Y(r), old_ws->idx, wsid);
2861
2862         if (new_ws == NULL || old_ws == NULL)
2863                 return;
2864         if (new_ws == old_ws)
2865                 return;
2866
2867         unfocus_win(old_ws->focus);
2868
2869         other_r = new_ws->r;
2870         if (other_r == NULL) {
2871                 /* the other workspace is hidden, hide this one */
2872                 old_ws->r = NULL;
2873                 unmap_old = 1;
2874         } else {
2875                 /* the other ws is visible in another region, exchange them */
2876                 other_r->ws_prior = new_ws;
2877                 other_r->ws = old_ws;
2878                 old_ws->r = other_r;
2879         }
2880         this_r->ws_prior = old_ws;
2881         this_r->ws = new_ws;
2882         new_ws->r = this_r;
2883
2884         stack();
2885
2886         /* unmap old windows */
2887         if (unmap_old)
2888                 TAILQ_FOREACH(win, &old_ws->winlist, entry)
2889                         unmap_window(win);
2890
2891         if (focus_mode != SWM_FOCUS_FOLLOW)
2892                 new_ws->focus_pending = get_region_focus(new_ws->r);
2893
2894         if (new_ws->focus_pending && focus_mode != SWM_FOCUS_FOLLOW) {
2895                 /* if workspaces were swapped, then don't wait to set focus */
2896                 if (old_ws->r)
2897                         focus_win(new_ws->focus_pending);
2898         } else {
2899                 /* make sure bar gets updated if ws is empty */
2900                 bar_update();
2901         }
2902
2903         focus_flush();
2904
2905         DNPRINTF(SWM_D_WS, "switchws: done.\n");
2906 }
2907
2908 void
2909 cyclews(struct swm_region *r, union arg *args)
2910 {
2911         union                   arg a;
2912         struct swm_screen       *s = r->s;
2913         int                     cycle_all = 0;
2914
2915         DNPRINTF(SWM_D_WS, "cyclews: id: %d, screen[%d]:%dx%d+%d+%d, ws: %d\n",
2916             args->id, r->s->idx, WIDTH(r), HEIGHT(r), X(r), Y(r), r->ws->idx);
2917
2918         a.id = r->ws->idx;
2919         do {
2920                 switch (args->id) {
2921                 case SWM_ARG_ID_CYCLEWS_UP_ALL:
2922                         cycle_all = 1;
2923                         /* FALLTHROUGH */
2924                 case SWM_ARG_ID_CYCLEWS_UP:
2925                         if (a.id < workspace_limit - 1)
2926                                 a.id++;
2927                         else
2928                                 a.id = 0;
2929                         break;
2930                 case SWM_ARG_ID_CYCLEWS_DOWN_ALL:
2931                         cycle_all = 1;
2932                         /* FALLTHROUGH */
2933                 case SWM_ARG_ID_CYCLEWS_DOWN:
2934                         if (a.id > 0)
2935                                 a.id--;
2936                         else
2937                                 a.id = workspace_limit - 1;
2938                         break;
2939                 default:
2940                         return;
2941                 };
2942
2943                 if (!cycle_all &&
2944                     (!cycle_empty && TAILQ_EMPTY(&s->ws[a.id].winlist)))
2945                         continue;
2946                 if (!cycle_visible && s->ws[a.id].r != NULL)
2947                         continue;
2948
2949                 switchws(r, &a);
2950         } while (a.id != r->ws->idx);
2951 }
2952
2953 void
2954 priorws(struct swm_region *r, union arg *args)
2955 {
2956         union arg               a;
2957
2958         (void)args;
2959
2960         DNPRINTF(SWM_D_WS, "priorws: id: %d, screen[%d]:%dx%d+%d+%d, ws: %d\n",
2961             args->id, r->s->idx, WIDTH(r), HEIGHT(r), X(r), Y(r), r->ws->idx);
2962
2963         if (r->ws_prior == NULL)
2964                 return;
2965
2966         a.id = r->ws_prior->idx;
2967         switchws(r, &a);
2968 }
2969
2970 void
2971 cyclescr(struct swm_region *r, union arg *args)
2972 {
2973         struct swm_region       *rr = NULL;
2974         int                     i, num_screens;
2975
2976         num_screens = xcb_setup_roots_length(xcb_get_setup(conn));
2977         /* do nothing if we don't have more than one screen */
2978         if (!(num_screens > 1 || outputs > 1))
2979                 return;
2980
2981         i = r->s->idx;
2982         switch (args->id) {
2983         case SWM_ARG_ID_CYCLESC_UP:
2984                 rr = TAILQ_NEXT(r, entry);
2985                 if (rr == NULL)
2986                         rr = TAILQ_FIRST(&screens[i].rl);
2987                 break;
2988         case SWM_ARG_ID_CYCLESC_DOWN:
2989                 rr = TAILQ_PREV(r, swm_region_list, entry);
2990                 if (rr == NULL)
2991                         rr = TAILQ_LAST(&screens[i].rl, swm_region_list);
2992                 break;
2993         default:
2994                 return;
2995         };
2996         if (rr == NULL)
2997                 return;
2998
2999         focus_win(get_region_focus(rr));
3000
3001         focus_flush();
3002 }
3003
3004 void
3005 sort_windows(struct ws_win_list *wl)
3006 {
3007         struct ws_win           *win, *parent, *nxt;
3008
3009         if (wl == NULL)
3010                 return;
3011
3012         for (win = TAILQ_FIRST(wl); win != TAILQ_END(wl); win = nxt) {
3013                 nxt = TAILQ_NEXT(win, entry);
3014                 if (win->transient) {
3015                         parent = find_window(win->transient);
3016                         if (parent == NULL) {
3017                                 warnx("not possible bug");
3018                                 continue;
3019                         }
3020                         TAILQ_REMOVE(wl, win, entry);
3021                         TAILQ_INSERT_AFTER(wl, parent, win, entry);
3022                 }
3023         }
3024
3025 }
3026
3027 void
3028 swapwin(struct swm_region *r, union arg *args)
3029 {
3030         struct ws_win           *target, *source;
3031         struct ws_win           *cur_focus;
3032         struct ws_win_list      *wl;
3033
3034         DNPRINTF(SWM_D_WS, "swapwin: id: %d, screen[%d]:%dx%d+%d+%d, ws: %d\n",
3035             args->id, r->s->idx, WIDTH(r), HEIGHT(r), X(r), Y(r), r->ws->idx);
3036
3037         cur_focus = r->ws->focus;
3038         if (cur_focus == NULL)
3039                 return;
3040
3041         source = cur_focus;
3042         wl = &source->ws->winlist;
3043
3044         switch (args->id) {
3045         case SWM_ARG_ID_SWAPPREV:
3046                 if (source->transient)
3047                         source = find_window(source->transient);
3048                 target = TAILQ_PREV(source, ws_win_list, entry);
3049                 if (target && target->transient)
3050                         target = find_window(target->transient);
3051                 TAILQ_REMOVE(wl, source, entry);
3052                 if (target == NULL)
3053                         TAILQ_INSERT_TAIL(wl, source, entry);
3054                 else
3055                         TAILQ_INSERT_BEFORE(target, source, entry);
3056                 break;
3057         case SWM_ARG_ID_SWAPNEXT:
3058                 target = TAILQ_NEXT(source, entry);
3059                 /* move the parent and let the sort handle the move */
3060                 if (source->transient)
3061                         source = find_window(source->transient);
3062                 TAILQ_REMOVE(wl, source, entry);
3063                 if (target == NULL)
3064                         TAILQ_INSERT_HEAD(wl, source, entry);
3065                 else
3066                         TAILQ_INSERT_AFTER(wl, target, source, entry);
3067                 break;
3068         case SWM_ARG_ID_SWAPMAIN:
3069                 target = TAILQ_FIRST(wl);
3070                 if (target == source) {
3071                         if (source->ws->focus_prev != NULL &&
3072                             source->ws->focus_prev != target)
3073                                 source = source->ws->focus_prev;
3074                         else
3075                                 return;
3076                 }
3077                 if (target == NULL || source == NULL)
3078                         return;
3079                 source->ws->focus_prev = target;
3080                 TAILQ_REMOVE(wl, target, entry);
3081                 TAILQ_INSERT_BEFORE(source, target, entry);
3082                 TAILQ_REMOVE(wl, source, entry);
3083                 TAILQ_INSERT_HEAD(wl, source, entry);
3084                 break;
3085         case SWM_ARG_ID_MOVELAST:
3086                 TAILQ_REMOVE(wl, source, entry);
3087                 TAILQ_INSERT_TAIL(wl, source, entry);
3088                 break;
3089         default:
3090                 DNPRINTF(SWM_D_MOVE, "swapwin: invalid id: %d\n", args->id);
3091                 return;
3092         }
3093
3094         sort_windows(wl);
3095
3096         stack();
3097
3098         focus_flush();
3099 }
3100
3101 struct ws_win *
3102 get_focus_prev(struct ws_win *win)
3103 {
3104         struct ws_win           *winfocus = NULL;
3105         struct ws_win           *cur_focus = NULL;
3106         struct ws_win_list      *wl = NULL;
3107         struct workspace        *ws = NULL;
3108
3109         if (!(win && win->ws))
3110                 return NULL;
3111
3112         ws = win->ws;
3113         wl = &ws->winlist;
3114         cur_focus = ws->focus;
3115
3116         DNPRINTF(SWM_D_FOCUS, "get_focus_prev: window: 0x%x, cur_focus: 0x%x\n",
3117             WINID(win), WINID(cur_focus));
3118
3119         /* pickle, just focus on whatever */
3120         if (cur_focus == NULL) {
3121                 /* use prev_focus if valid */
3122                 if (ws->focus_prev && ws->focus_prev != cur_focus &&
3123                     find_window(WINID(ws->focus_prev)))
3124                         winfocus = ws->focus_prev;
3125                 goto done;
3126         }
3127
3128         /* if transient focus on parent */
3129         if (cur_focus->transient) {
3130                 winfocus = find_window(cur_focus->transient);
3131                 goto done;
3132         }
3133
3134         /* if in max_stack try harder */
3135         if ((win->quirks & SWM_Q_FOCUSPREV) ||
3136             (ws->cur_layout->flags & SWM_L_FOCUSPREV)) {
3137                 if (cur_focus != ws->focus_prev)
3138                         winfocus = ws->focus_prev;
3139                 else
3140                         winfocus = TAILQ_PREV(win, ws_win_list, entry);
3141                 if (winfocus)
3142                         goto done;
3143         }
3144
3145         DNPRINTF(SWM_D_FOCUS, "get_focus_prev: focus_close: %d\n", focus_close);
3146
3147         if (winfocus == NULL || winfocus == win) {
3148                 switch (focus_close) {
3149                 case SWM_STACK_BOTTOM:
3150                         winfocus = TAILQ_FIRST(wl);
3151                         break;
3152                 case SWM_STACK_TOP:
3153                         winfocus = TAILQ_LAST(wl, ws_win_list);
3154                         break;
3155                 case SWM_STACK_ABOVE:
3156                         if ((winfocus = TAILQ_NEXT(cur_focus, entry)) == NULL) {
3157                                 if (focus_close_wrap)
3158                                         winfocus = TAILQ_FIRST(wl);
3159                                 else
3160                                         winfocus = TAILQ_PREV(cur_focus,
3161                                             ws_win_list, entry);
3162                         }
3163                         break;
3164                 case SWM_STACK_BELOW:
3165                         if ((winfocus = TAILQ_PREV(cur_focus, ws_win_list,
3166                             entry)) == NULL) {
3167                                 if (focus_close_wrap)
3168                                         winfocus = TAILQ_LAST(wl, ws_win_list);
3169                                 else
3170                                         winfocus = TAILQ_NEXT(cur_focus, entry);
3171                         }
3172                         break;
3173                 }
3174         }
3175 done:
3176         if (winfocus == NULL) {
3177                 if (focus_default == SWM_STACK_TOP)
3178                         winfocus = TAILQ_LAST(wl, ws_win_list);
3179                 else
3180                         winfocus = TAILQ_FIRST(wl);
3181         }
3182
3183         kill_refs(win);
3184
3185         return get_focus_magic(winfocus);
3186 }
3187
3188 struct ws_win *
3189 get_region_focus(struct swm_region *r)
3190 {
3191         struct ws_win           *winfocus = NULL;
3192
3193         if (!(r && r->ws))
3194                 return NULL;
3195
3196         if (r->ws->focus && !r->ws->focus->iconic)
3197                 winfocus = r->ws->focus;
3198         else if (r->ws->focus_prev && !r->ws->focus_prev->iconic)
3199                 winfocus = r->ws->focus_prev;
3200         else
3201                 TAILQ_FOREACH(winfocus, &r->ws->winlist, entry)
3202                         if (!winfocus->iconic)
3203                                 break;
3204
3205         return get_focus_magic(winfocus);
3206 }
3207
3208 void
3209 focus(struct swm_region *r, union arg *args)
3210 {
3211         struct ws_win           *head, *cur_focus = NULL, *winfocus = NULL;
3212         struct ws_win_list      *wl = NULL;
3213         struct workspace        *ws = NULL;
3214         int                     all_iconics;
3215
3216         if (!(r && r->ws))
3217                 return;
3218
3219         DNPRINTF(SWM_D_FOCUS, "focus: id: %d\n", args->id);
3220
3221         if ((cur_focus = r->ws->focus) == NULL)
3222                 return;
3223         ws = r->ws;
3224         wl = &ws->winlist;
3225         if (TAILQ_EMPTY(wl))
3226                 return;
3227         /* make sure there is at least one uniconified window */
3228         all_iconics = 1;
3229         TAILQ_FOREACH(winfocus, wl, entry)
3230                 if (!winfocus->iconic) {
3231                         all_iconics = 0;
3232                         break;
3233                 }
3234         if (all_iconics)
3235                 return;
3236
3237         switch (args->id) {
3238         case SWM_ARG_ID_FOCUSPREV:
3239                 head = TAILQ_PREV(cur_focus, ws_win_list, entry);
3240                 if (head == NULL)
3241                         head = TAILQ_LAST(wl, ws_win_list);
3242                 winfocus = head;
3243                 if (WINID(winfocus) == cur_focus->transient) {
3244                         head = TAILQ_PREV(winfocus, ws_win_list, entry);
3245                         if (head == NULL)
3246                                 head = TAILQ_LAST(wl, ws_win_list);
3247                         winfocus = head;
3248                 }
3249
3250                 /* skip iconics */
3251                 if (winfocus && winfocus->iconic) {
3252                         while (winfocus != cur_focus) {
3253                                 if (winfocus == NULL)
3254                                         winfocus = TAILQ_LAST(wl, ws_win_list);
3255                                 if (!winfocus->iconic)
3256                                         break;
3257                                 winfocus = TAILQ_PREV(winfocus, ws_win_list,
3258                                     entry);
3259                         }
3260                 }
3261                 break;
3262
3263         case SWM_ARG_ID_FOCUSNEXT:
3264                 head = TAILQ_NEXT(cur_focus, entry);
3265                 if (head == NULL)
3266                         head = TAILQ_FIRST(wl);
3267                 winfocus = head;
3268
3269                 /* skip iconics */
3270                 if (winfocus && winfocus->iconic) {
3271                         while (winfocus != cur_focus) {
3272                                 if (winfocus == NULL)
3273                                         winfocus = TAILQ_FIRST(wl);
3274                                 if (!winfocus->iconic)
3275                                         break;
3276                                 winfocus = TAILQ_NEXT(winfocus, entry);
3277                         }
3278                 }
3279                 break;
3280
3281         case SWM_ARG_ID_FOCUSMAIN:
3282                 winfocus = TAILQ_FIRST(wl);
3283                 if (winfocus == cur_focus)
3284                         winfocus = cur_focus->ws->focus_prev;
3285                 break;
3286
3287         default:
3288                 return;
3289         }
3290
3291         focus_win(get_focus_magic(winfocus));
3292
3293         xcb_flush(conn);
3294 }
3295
3296 void
3297 cycle_layout(struct swm_region *r, union arg *args)
3298 {
3299         struct workspace        *ws = r->ws;
3300
3301         /* suppress unused warning since var is needed */
3302         (void)args;
3303
3304         DNPRINTF(SWM_D_EVENT, "cycle_layout: workspace: %d\n", ws->idx);
3305
3306         ws->cur_layout++;
3307         if (ws->cur_layout->l_stack == NULL)
3308                 ws->cur_layout = &layouts[0];
3309
3310         stack();
3311         bar_update();
3312
3313         focus_win(get_region_focus(r));
3314
3315         focus_flush();
3316 }
3317
3318 void
3319 stack_config(struct swm_region *r, union arg *args)
3320 {
3321         struct workspace        *ws = r->ws;
3322
3323         DNPRINTF(SWM_D_STACK, "stack_config: id: %d workspace: %d\n",
3324             args->id, ws->idx);
3325
3326         if (ws->cur_layout->l_config != NULL)
3327                 ws->cur_layout->l_config(ws, args->id);
3328
3329         if (args->id != SWM_ARG_ID_STACKINIT)
3330                 stack();
3331         bar_update();
3332
3333         focus_flush();
3334 }
3335
3336 void
3337 stack(void) {
3338         struct swm_geometry     g;
3339         struct swm_region       *r;
3340         int                     i, num_screens;
3341 #ifdef SWM_DEBUG
3342         int j;
3343 #endif
3344
3345         DNPRINTF(SWM_D_STACK, "stack: begin\n");
3346
3347         num_screens = xcb_setup_roots_length(xcb_get_setup(conn));
3348         for (i = 0; i < num_screens; i++) {
3349 #ifdef SWM_DEBUG
3350                 j = 0;
3351 #endif
3352                 TAILQ_FOREACH(r, &screens[i].rl, entry) {
3353                         DNPRINTF(SWM_D_STACK, "stack: workspace: %d "
3354                             "(screen: %d, region: %d)\n", r->ws->idx, i, j++);
3355
3356                         /* start with screen geometry, adjust for bar */
3357                         g = r->g;
3358                         g.w -= 2 * border_width;
3359                         g.h -= 2 * border_width;
3360                         if (bar_enabled) {
3361                                 if (!bar_at_bottom)
3362                                         g.y += bar_height;
3363                                 g.h -= bar_height;
3364                         }
3365                         r->ws->cur_layout->l_stack(r->ws, &g);
3366                         r->ws->cur_layout->l_string(r->ws);
3367                         /* save r so we can track region changes */
3368                         r->ws->old_r = r;
3369                 }
3370         }
3371         if (font_adjusted)
3372                 font_adjusted--;
3373
3374         DNPRINTF(SWM_D_STACK, "stack: end\n");
3375 }
3376
3377 void
3378 store_float_geom(struct ws_win *win, struct swm_region *r)
3379 {
3380         if (win == NULL || r == NULL)
3381                 return;
3382
3383         /* retain window geom and region geom */
3384         win->g_float = win->g;
3385         win->g_float.x -= X(r);
3386         win->g_float.y -= Y(r);
3387         win->g_floatvalid = 1;
3388         DNPRINTF(SWM_D_MISC, "store_float_geom: window: 0x%x, g: (%d,%d)"
3389             " %d x %d, g_float: (%d,%d) %d x %d\n", win->id, X(win), Y(win),
3390             WIDTH(win), HEIGHT(win), win->g_float.x, win->g_float.y,
3391             win->g_float.w, win->g_float.h);
3392 }
3393
3394 void
3395 load_float_geom(struct ws_win *win, struct swm_region *r)
3396 {
3397         if (win == NULL || r == NULL)
3398                 return;
3399
3400         if (win->g_floatvalid) {
3401                 win->g = win->g_float;
3402                 X(win) += X(r);
3403                 Y(win) += Y(r);
3404                 DNPRINTF(SWM_D_MISC, "load_float_geom: window: 0x%x, g: (%d,%d)"
3405                     "%d x %d\n", win->id, X(win), Y(win), WIDTH(win),
3406                     HEIGHT(win));
3407         } else {
3408                 DNPRINTF(SWM_D_MISC, "load_float_geom: window: 0x%x, g_float "
3409                     "is not set.\n", win->id);
3410         }
3411 }
3412
3413 void
3414 stack_floater(struct ws_win *win, struct swm_region *r)
3415 {
3416         if (win == NULL)
3417                 return;
3418
3419         DNPRINTF(SWM_D_MISC, "stack_floater: window: 0x%x\n", win->id);
3420
3421         /*
3422          * to allow windows to change their size (e.g. mplayer fs) only retrieve
3423          * geom on ws switches or return from max mode
3424          */
3425         if (win->floatmaxed || (r != r->ws->old_r &&
3426             !(win->ewmh_flags & EWMH_F_FULLSCREEN))) {
3427                 /* update geometry for the new region */
3428                 load_float_geom(win, r);
3429         }
3430
3431         win->floatmaxed = 0;
3432
3433         /*
3434          * if set to fullscreen mode, configure window to maximum size.
3435          */
3436         if (win->ewmh_flags & EWMH_F_FULLSCREEN) {
3437                 if (!win->g_floatvalid)
3438                         store_float_geom(win, win->ws->r);
3439
3440                 win->g = r->g;
3441         }
3442
3443         /*
3444          * remove border on fullscreen floater when in fullscreen mode or when
3445          * the quirk is present.
3446          */
3447         if ((win->ewmh_flags & EWMH_F_FULLSCREEN) ||
3448             ((win->quirks & SWM_Q_FULLSCREEN) &&
3449              (WIDTH(win) >= WIDTH(r)) && (HEIGHT(win) >= HEIGHT(r)))) {
3450                 if (win->bordered) {
3451                         win->bordered = 0;
3452                         X(win) += border_width;
3453                         Y(win) += border_width;
3454                 }
3455         } else if (!win->bordered) {
3456                 win->bordered = 1;
3457                 X(win) -= border_width;
3458                 Y(win) -= border_width;
3459         }
3460
3461         if (win->transient && (win->quirks & SWM_Q_TRANSSZ)) {
3462                 WIDTH(win) = (double)WIDTH(r) * dialog_ratio;
3463                 HEIGHT(win) = (double)HEIGHT(r) * dialog_ratio;
3464         }
3465
3466         if (!win->manual && !(win->ewmh_flags & EWMH_F_FULLSCREEN) &&
3467             !(win->quirks & SWM_Q_ANYWHERE)) {
3468                 /*
3469                  * floaters and transients are auto-centred unless moved,
3470                  * resized or ANYWHERE quirk is set.
3471                  */
3472                 X(win) = X(r) + (WIDTH(r) - WIDTH(win)) /  2 - BORDER(win);
3473                 Y(win) = Y(r) + (HEIGHT(r) - HEIGHT(win)) / 2 - BORDER(win);
3474
3475                 store_float_geom(win, r);
3476         }
3477
3478         /* keep window within region bounds */
3479         constrain_window(win, r, 0);
3480
3481         update_window(win);
3482 }
3483
3484 /*
3485  * Send keystrokes to terminal to decrease/increase the font size as the
3486  * window size changes.
3487  */
3488 void
3489 adjust_font(struct ws_win *win)
3490 {
3491         if (!(win->quirks & SWM_Q_XTERM_FONTADJ) ||
3492             win->floating || win->transient)
3493                 return;
3494
3495         if (win->sh.width_inc && win->last_inc != win->sh.width_inc &&
3496             WIDTH(win) / win->sh.width_inc < term_width &&
3497             win->font_steps < SWM_MAX_FONT_STEPS) {
3498                 win->font_size_boundary[win->font_steps] =
3499                     (win->sh.width_inc * term_width) + win->sh.base_width;
3500                 win->font_steps++;
3501                 font_adjusted++;
3502                 win->last_inc = win->sh.width_inc;
3503                 fake_keypress(win, XK_KP_Subtract, XCB_MOD_MASK_SHIFT);
3504         } else if (win->font_steps && win->last_inc != win->sh.width_inc &&
3505             WIDTH(win) > win->font_size_boundary[win->font_steps - 1]) {
3506                 win->font_steps--;
3507                 font_adjusted++;
3508                 win->last_inc = win->sh.width_inc;
3509                 fake_keypress(win, XK_KP_Add, XCB_MOD_MASK_SHIFT);
3510         }
3511 }
3512
3513 #define SWAPXY(g)       do {                            \
3514         int tmp;                                        \
3515         tmp = (g)->y; (g)->y = (g)->x; (g)->x = tmp;    \
3516         tmp = (g)->h; (g)->h = (g)->w; (g)->w = tmp;    \
3517 } while (0)
3518 void
3519 stack_master(struct workspace *ws, struct swm_geometry *g, int rot, int flip)
3520 {
3521         struct swm_geometry     win_g, r_g = *g;
3522         struct ws_win           *win, *fs_win = NULL;
3523         int                     i, j, s, stacks;
3524         int                     w_inc = 1, h_inc, w_base = 1, h_base;
3525         int                     hrh, extra = 0, h_slice, last_h = 0;
3526         int                     split, colno, winno, mwin, msize, mscale;
3527         int                     remain, missing, v_slice, reconfigure = 0;
3528         int                     bordered = 1;
3529
3530         DNPRINTF(SWM_D_STACK, "stack_master: workspace: %d, rot: %s, "
3531             "flip: %s\n", ws->idx, YESNO(rot), YESNO(flip));
3532
3533         winno = count_win(ws, 0);
3534         if (winno == 0 && count_win(ws, 1) == 0)
3535                 return;
3536
3537         TAILQ_FOREACH(win, &ws->winlist, entry)
3538                 if (!win->transient && !win->floating && !win->iconic)
3539                         break;
3540
3541         if (win == NULL)
3542                 goto notiles;
3543
3544         if (rot) {
3545                 w_inc = win->sh.width_inc;
3546                 w_base = win->sh.base_width;
3547                 mwin = ws->l_state.horizontal_mwin;
3548                 mscale = ws->l_state.horizontal_msize;
3549                 stacks = ws->l_state.horizontal_stacks;
3550                 SWAPXY(&r_g);
3551         } else {
3552                 w_inc = win->sh.height_inc;
3553                 w_base = win->sh.base_height;
3554                 mwin = ws->l_state.vertical_mwin;
3555                 mscale = ws->l_state.vertical_msize;
3556                 stacks = ws->l_state.vertical_stacks;
3557         }
3558         win_g = r_g;
3559
3560         if (stacks > winno - mwin)
3561                 stacks = winno - mwin;
3562         if (stacks < 1)
3563                 stacks = 1;
3564
3565         h_slice = r_g.h / SWM_H_SLICE;
3566         if (mwin && winno > mwin) {
3567                 v_slice = r_g.w / SWM_V_SLICE;
3568
3569                 split = mwin;
3570                 colno = split;
3571                 win_g.w = v_slice * mscale;
3572
3573                 if (w_inc > 1 && w_inc < v_slice) {
3574                         /* adjust for window's requested size increment */
3575                         remain = (win_g.w - w_base) % w_inc;
3576                         win_g.w -= remain;
3577                 }
3578
3579                 msize = win_g.w;
3580                 if (flip)
3581                         win_g.x += r_g.w - msize;
3582         } else {
3583                 msize = -2;
3584                 colno = split = winno / stacks;
3585                 win_g.w = ((r_g.w - (stacks * 2 * border_width) +
3586                     2 * border_width) / stacks);
3587         }
3588         hrh = r_g.h / colno;
3589         extra = r_g.h - (colno * hrh);
3590         win_g.h = hrh - 2 * border_width;
3591
3592         /*  stack all the tiled windows */
3593         i = j = 0, s = stacks;
3594         TAILQ_FOREACH(win, &ws->winlist, entry) {
3595                 if (win->transient || win->floating)
3596                         continue;
3597                 if (win->iconic)
3598                         continue;
3599
3600                 if (win->ewmh_flags & EWMH_F_FULLSCREEN) {
3601                         fs_win = win;
3602                         continue;
3603                 }
3604
3605                 if (split && i == split) {
3606                         colno = (winno - mwin) / stacks;
3607                         if (s <= (winno - mwin) % stacks)
3608                                 colno++;
3609                         split = split + colno;
3610                         hrh = (r_g.h / colno);
3611                         extra = r_g.h - (colno * hrh);
3612                         if (flip)
3613                                 win_g.x = r_g.x;
3614                         else
3615                                 win_g.x += win_g.w + 2 * border_width;
3616                         win_g.w = (r_g.w - msize -
3617                             (stacks * 2 * border_width)) / stacks;
3618                         if (s == 1)
3619                                 win_g.w += (r_g.w - msize -
3620                                     (stacks * 2 * border_width)) % stacks;
3621                         s--;
3622                         j = 0;
3623                 }
3624                 win_g.h = hrh - 2 * border_width;
3625                 if (rot) {
3626                         h_inc = win->sh.width_inc;
3627                         h_base = win->sh.base_width;
3628                 } else {
3629                         h_inc = win->sh.height_inc;
3630                         h_base = win->sh.base_height;
3631                 }
3632                 if (j == colno - 1) {
3633                         win_g.h = hrh + extra;
3634                 } else if (h_inc > 1 && h_inc < h_slice) {
3635                         /* adjust for window's requested size increment */
3636                         remain = (win_g.h - h_base) % h_inc;
3637                         missing = h_inc - remain;
3638
3639                         if (missing <= extra || j == 0) {
3640                                 extra -= missing;
3641                                 win_g.h += missing;
3642                         } else {
3643                                 win_g.h -= remain;
3644                                 extra += remain;
3645                         }
3646                 }
3647
3648                 if (j == 0)
3649                         win_g.y = r_g.y;
3650                 else
3651                         win_g.y += last_h + 2 * border_width;
3652
3653                 if (disable_border && !bar_enabled && winno == 1){
3654                         bordered = 0;
3655                         win_g.w += 2 * border_width;
3656                         win_g.h += 2 * border_width;
3657                 } else {
3658                         bordered = 1;
3659                 }
3660                 if (rot) {
3661                         if (X(win) != win_g.y || Y(win) != win_g.x ||
3662                             WIDTH(win) != win_g.h || HEIGHT(win) != win_g.w) {
3663                                 reconfigure = 1;
3664                                 X(win) = win_g.y;
3665                                 Y(win) = win_g.x;
3666                                 WIDTH(win) = win_g.h;
3667                                 HEIGHT(win) = win_g.w;
3668                         }
3669                 } else {
3670                         if (X(win) != win_g.x || Y(win) != win_g.y ||
3671                             WIDTH(win) != win_g.w || HEIGHT(win) != win_g.h) {
3672                                 reconfigure = 1;
3673                                 X(win) = win_g.x;
3674                                 Y(win) = win_g.y;
3675                                 WIDTH(win) = win_g.w;
3676                                 HEIGHT(win) = win_g.h;
3677                         }
3678                 }
3679
3680                 if (bordered != win->bordered) {
3681                         reconfigure = 1;
3682                         win->bordered = bordered;
3683                 }
3684
3685                 if (reconfigure) {
3686                         adjust_font(win);
3687                         update_window(win);
3688                 }
3689
3690                 map_window(win);
3691
3692                 last_h = win_g.h;
3693                 i++;
3694                 j++;
3695         }
3696
3697 notiles:
3698         /* now, stack all the floaters and transients */
3699         TAILQ_FOREACH(win, &ws->winlist, entry) {
3700                 if (!win->transient && !win->floating)
3701                         continue;
3702                 if (win->iconic)
3703                         continue;
3704                 if (win->ewmh_flags & EWMH_F_FULLSCREEN) {
3705                         fs_win = win;
3706                         continue;
3707                 }
3708
3709                 stack_floater(win, ws->r);
3710                 map_window(win);
3711         }
3712
3713         if (fs_win) {
3714                 stack_floater(fs_win, ws->r);
3715                 map_window(fs_win);
3716         }
3717 }
3718
3719 void
3720 vertical_config(struct workspace *ws, int id)
3721 {
3722         DNPRINTF(SWM_D_STACK, "vertical_config: id: %d, workspace: %d\n",
3723             id, ws->idx);
3724
3725         switch (id) {
3726         case SWM_ARG_ID_STACKRESET:
3727         case SWM_ARG_ID_STACKINIT:
3728                 ws->l_state.vertical_msize = SWM_V_SLICE / 2;
3729                 ws->l_state.vertical_mwin = 1;
3730                 ws->l_state.vertical_stacks = 1;
3731                 break;
3732         case SWM_ARG_ID_MASTERSHRINK:
3733                 if (ws->l_state.vertical_msize > 1)
3734                         ws->l_state.vertical_msize--;
3735                 break;
3736         case SWM_ARG_ID_MASTERGROW:
3737                 if (ws->l_state.vertical_msize < SWM_V_SLICE - 1)
3738                         ws->l_state.vertical_msize++;
3739                 break;
3740         case SWM_ARG_ID_MASTERADD:
3741                 ws->l_state.vertical_mwin++;
3742                 break;
3743         case SWM_ARG_ID_MASTERDEL:
3744                 if (ws->l_state.vertical_mwin > 0)
3745                         ws->l_state.vertical_mwin--;
3746                 break;
3747         case SWM_ARG_ID_STACKINC:
3748                 ws->l_state.vertical_stacks++;
3749                 break;
3750         case SWM_ARG_ID_STACKDEC:
3751                 if (ws->l_state.vertical_stacks > 1)
3752                         ws->l_state.vertical_stacks--;
3753                 break;
3754         case SWM_ARG_ID_FLIPLAYOUT:
3755                 ws->l_state.vertical_flip = !ws->l_state.vertical_flip;
3756                 break;
3757         default:
3758                 return;
3759         }
3760 }
3761
3762 void
3763 vertical_stack(struct workspace *ws, struct swm_geometry *g)
3764 {
3765         DNPRINTF(SWM_D_STACK, "vertical_stack: workspace: %d\n", ws->idx);
3766
3767         stack_master(ws, g, 0, ws->l_state.vertical_flip);
3768 }
3769
3770 void
3771 horizontal_config(struct workspace *ws, int id)
3772 {
3773         DNPRINTF(SWM_D_STACK, "horizontal_config: workspace: %d\n", ws->idx);
3774
3775         switch (id) {
3776         case SWM_ARG_ID_STACKRESET:
3777         case SWM_ARG_ID_STACKINIT:
3778                 ws->l_state.horizontal_mwin = 1;
3779                 ws->l_state.horizontal_msize = SWM_H_SLICE / 2;
3780                 ws->l_state.horizontal_stacks = 1;
3781                 break;
3782         case SWM_ARG_ID_MASTERSHRINK:
3783                 if (ws->l_state.horizontal_msize > 1)
3784                         ws->l_state.horizontal_msize--;
3785                 break;
3786         case SWM_ARG_ID_MASTERGROW:
3787                 if (ws->l_state.horizontal_msize < SWM_H_SLICE - 1)
3788                         ws->l_state.horizontal_msize++;
3789                 break;
3790         case SWM_ARG_ID_MASTERADD:
3791                 ws->l_state.horizontal_mwin++;
3792                 break;
3793         case SWM_ARG_ID_MASTERDEL:
3794                 if (ws->l_state.horizontal_mwin > 0)
3795                         ws->l_state.horizontal_mwin--;
3796                 break;
3797         case SWM_ARG_ID_STACKINC:
3798                 ws->l_state.horizontal_stacks++;
3799                 break;
3800         case SWM_ARG_ID_STACKDEC:
3801                 if (ws->l_state.horizontal_stacks > 1)
3802                         ws->l_state.horizontal_stacks--;
3803                 break;
3804         case SWM_ARG_ID_FLIPLAYOUT:
3805                 ws->l_state.horizontal_flip = !ws->l_state.horizontal_flip;
3806                 break;
3807         default:
3808                 return;
3809         }
3810 }
3811
3812 void
3813 horizontal_stack(struct workspace *ws, struct swm_geometry *g)
3814 {
3815         DNPRINTF(SWM_D_STACK, "horizontal_stack: workspace: %d\n", ws->idx);
3816
3817         stack_master(ws, g, 1, ws->l_state.horizontal_flip);
3818 }
3819
3820 /* fullscreen view */
3821 void
3822 max_stack(struct workspace *ws, struct swm_geometry *g)
3823 {
3824         struct swm_geometry     gg = *g;
3825         struct ws_win           *win, *wintrans = NULL, *parent = NULL;
3826         int                     winno, num_screens;
3827
3828         DNPRINTF(SWM_D_STACK, "max_stack: workspace: %d\n", ws->idx);
3829
3830         if (ws == NULL)
3831                 return;
3832
3833         winno = count_win(ws, 0);
3834         if (winno == 0 && count_win(ws, 1) == 0)
3835                 return;
3836
3837         num_screens = xcb_setup_roots_length(xcb_get_setup(conn));
3838         TAILQ_FOREACH(win, &ws->winlist, entry) {
3839                 if (win->transient) {
3840                         wintrans = win;
3841                         parent = find_window(win->transient);
3842                         continue;
3843                 }
3844
3845                 if (win->floating && !win->floatmaxed ) {
3846                         /*
3847                          * retain geometry for retrieval on exit from
3848                          * max_stack mode
3849                          */
3850                         store_float_geom(win, ws->r);
3851                         win->floatmaxed = 1;
3852                 }
3853
3854                 /* only reconfigure if necessary */
3855                 if (X(win) != gg.x || Y(win) != gg.y || WIDTH(win) != gg.w ||
3856                     HEIGHT(win) != gg.h) {
3857                         win->g = gg;
3858                         if (bar_enabled){
3859                                 win->bordered = 1;
3860                         } else {
3861                                 win->bordered = 0;
3862                                 WIDTH(win) += 2 * border_width;
3863                                 HEIGHT(win) += 2 * border_width;
3864                         }
3865
3866                         update_window(win);
3867                 }
3868                 /* unmap only if we don't have multi screen */
3869                 if (win != ws->focus)
3870                         if (!(num_screens > 1 || outputs > 1))
3871                                 unmap_window(win);
3872         }
3873
3874         /* put the last transient on top */
3875         if (wintrans) {
3876                 if (parent)
3877                         map_window(parent);
3878                 stack_floater(wintrans, ws->r);
3879                 ws->focus = get_focus_magic(wintrans);
3880         }
3881 }
3882
3883 void
3884 send_to_ws(struct swm_region *r, union arg *args)
3885 {
3886         int                     wsid = args->id;
3887         struct ws_win           *win = NULL, *parent;
3888         struct workspace        *ws, *nws, *pws;
3889         char                    ws_idx_str[SWM_PROPLEN];
3890
3891         if (wsid >= workspace_limit)
3892                 return;
3893
3894         if (r && r->ws && r->ws->focus)
3895                 win = r->ws->focus;
3896         else
3897                 return;
3898
3899         if (win->ws->idx == wsid)
3900                 return;
3901
3902         DNPRINTF(SWM_D_MOVE, "send_to_ws: win 0x%x, ws %d -> %d\n", win->id,
3903             win->ws->idx, wsid);
3904
3905         ws = win->ws;
3906         nws = &win->s->ws[wsid];
3907
3908         /* Update the window's workspace property: _SWM_WS */
3909         if (snprintf(ws_idx_str, SWM_PROPLEN, "%d", nws->idx) < SWM_PROPLEN) {
3910                 if (focus_mode != SWM_FOCUS_FOLLOW)
3911                         ws->focus_pending = get_focus_prev(win);
3912
3913                 /* Move the parent if this is a transient window. */
3914                 if (win->transient) {
3915                         parent = find_window(win->transient);
3916                         if (parent) {
3917                                 pws = parent->ws;
3918                                 /* Set new focus in parent's ws if needed. */
3919                                 if (pws->focus == parent) {
3920                                         if (focus_mode != SWM_FOCUS_FOLLOW)
3921                                                 pws->focus_pending =
3922                                                     get_focus_prev(parent);
3923
3924                                         unfocus_win(parent);
3925
3926                                         if (focus_mode != SWM_FOCUS_FOLLOW)
3927                                                 pws->focus = pws->focus_pending;
3928
3929                                         if (focus_mode != SWM_FOCUS_FOLLOW)
3930                                                 pws->focus_pending = NULL;
3931                                 }
3932
3933                                 /* Don't unmap parent if new ws is visible */
3934                                 if (nws->r == NULL)
3935                                         unmap_window(parent);
3936
3937                                 /* Transfer */
3938                                 TAILQ_REMOVE(&ws->winlist, parent, entry);
3939                                 TAILQ_INSERT_TAIL(&nws->winlist, parent, entry);
3940                                 parent->ws = nws;
3941
3942                                 DNPRINTF(SWM_D_PROP, "send_to_ws: set "
3943                                     "property: _SWM_WS: %s\n", ws_idx_str);
3944                                 xcb_change_property(conn, XCB_PROP_MODE_REPLACE,
3945                                     parent->id, a_swm_ws, XCB_ATOM_STRING, 8,
3946                                     strlen(ws_idx_str), ws_idx_str);
3947                         }
3948                 }
3949
3950                 unfocus_win(win);
3951
3952                 /* Don't unmap if new ws is visible */
3953                 if (nws->r == NULL)
3954                         unmap_window(win);
3955
3956                 /* Transfer */
3957                 TAILQ_REMOVE(&ws->winlist, win, entry);
3958                 TAILQ_INSERT_TAIL(&nws->winlist, win, entry);
3959                 win->ws = nws;
3960
3961                 /* Set focus on new ws. */
3962                 unfocus_win(nws->focus);
3963                 nws->focus = win;
3964
3965                 DNPRINTF(SWM_D_PROP, "send_to_ws: set property: _SWM_WS: %s\n",
3966                     ws_idx_str);
3967                 xcb_change_property(conn, XCB_PROP_MODE_REPLACE, win->id,
3968                     a_swm_ws, XCB_ATOM_STRING, 8, strlen(ws_idx_str),
3969                     ws_idx_str);
3970
3971                 /* Restack and set new focus. */
3972                 stack();
3973
3974                 if (focus_mode != SWM_FOCUS_FOLLOW) {
3975                         focus_win(ws->focus_pending);
3976                         ws->focus_pending = NULL;
3977                 }
3978
3979                 focus_flush();
3980         }
3981
3982         DNPRINTF(SWM_D_MOVE, "send_to_ws: done.\n");
3983 }
3984
3985 void
3986 pressbutton(struct swm_region *r, union arg *args)
3987 {
3988         /* suppress unused warning since var is needed */
3989         (void)r;
3990
3991         xcb_test_fake_input(conn, XCB_BUTTON_PRESS, args->id,
3992             XCB_CURRENT_TIME, XCB_WINDOW_NONE, 0, 0, 0);
3993         xcb_test_fake_input(conn, XCB_BUTTON_RELEASE, args->id,
3994             XCB_CURRENT_TIME, XCB_WINDOW_NONE, 0, 0, 0);
3995 }
3996
3997 void
3998 raise_toggle(struct swm_region *r, union arg *args)
3999 {
4000         /* suppress unused warning since var is needed */
4001         (void)args;
4002
4003         if (r == NULL || r->ws == NULL)
4004                 return;
4005
4006         r->ws->always_raise = !r->ws->always_raise;
4007
4008         /* bring floaters back to top */
4009         if (!r->ws->always_raise)
4010                 stack();
4011
4012         focus_flush();
4013 }
4014
4015 void
4016 iconify(struct swm_region *r, union arg *args)
4017 {
4018         /* suppress unused warning since var is needed */
4019         (void)args;
4020
4021         if (r->ws->focus == NULL)
4022                 return;
4023
4024         set_swm_iconic(r->ws->focus, 1);
4025
4026         xcb_flush(conn);
4027 }
4028
4029 char *
4030 get_win_name(xcb_window_t win)
4031 {
4032         char                            *name = NULL;
4033         xcb_get_property_cookie_t       c;
4034         xcb_get_property_reply_t        *r;
4035
4036         /* First try _NET_WM_NAME for UTF-8. */
4037         c = xcb_get_property(conn, 0, win, a_netwmname,
4038             XCB_GET_PROPERTY_TYPE_ANY, 0, UINT_MAX);
4039         r = xcb_get_property_reply(conn, c, NULL);
4040
4041         if (!r || r->type == XCB_NONE) {
4042                 free(r);
4043                 /* Use WM_NAME instead; no UTF-8. */
4044                 c = xcb_get_property(conn, 0, win, XCB_ATOM_WM_NAME,
4045                     XCB_GET_PROPERTY_TYPE_ANY, 0, UINT_MAX);
4046                 r = xcb_get_property_reply(conn, c, NULL);
4047
4048                 if(!r || r->type == XCB_NONE) {
4049                         free(r);
4050                         return NULL;
4051                 }
4052         }
4053
4054         if (r->length > 0)
4055                 name = strndup(xcb_get_property_value(r),
4056                     xcb_get_property_value_length(r));
4057
4058         free(r);
4059         return name;
4060 }
4061
4062 void
4063 uniconify(struct swm_region *r, union arg *args)
4064 {
4065         struct ws_win           *win;
4066         FILE                    *lfile;
4067         char                    *name;
4068         int                     count = 0;
4069
4070         DNPRINTF(SWM_D_MISC, "uniconify\n");
4071
4072         if (r == NULL || r->ws == NULL)
4073                 return;
4074
4075         /* make sure we have anything to uniconify */
4076         TAILQ_FOREACH(win, &r->ws->winlist, entry) {
4077                 if (win->ws == NULL)
4078                         continue; /* should never happen */
4079                 if (!win->iconic)
4080                         continue;
4081                 count++;
4082         }
4083         if (count == 0)
4084                 return;
4085
4086         search_r = r;
4087         search_resp_action = SWM_SEARCH_UNICONIFY;
4088
4089         spawn_select(r, args, "search", &searchpid);
4090
4091         if ((lfile = fdopen(select_list_pipe[1], "w")) == NULL)
4092                 return;
4093
4094         TAILQ_FOREACH(win, &r->ws->winlist, entry) {
4095                 if (win->ws == NULL)
4096                         continue; /* should never happen */
4097                 if (!win->iconic)
4098                         continue;
4099
4100                 name = get_win_name(win->id);
4101                 if (name == NULL)
4102                         continue;
4103                 fprintf(lfile, "%s.%u\n", name, win->id);
4104                 free(name);
4105         }
4106
4107         fclose(lfile);
4108 }
4109
4110 void
4111 name_workspace(struct swm_region *r, union arg *args)
4112 {
4113         FILE                    *lfile;
4114
4115         DNPRINTF(SWM_D_MISC, "name_workspace\n");
4116
4117         if (r == NULL)
4118                 return;
4119
4120         search_r = r;
4121         search_resp_action = SWM_SEARCH_NAME_WORKSPACE;
4122
4123         spawn_select(r, args, "name_workspace", &searchpid);
4124
4125         if ((lfile = fdopen(select_list_pipe[1], "w")) == NULL)
4126                 return;
4127
4128         fprintf(lfile, "%s", "");
4129         fclose(lfile);
4130 }
4131
4132 void
4133 search_workspace(struct swm_region *r, union arg *args)
4134 {
4135         int                     i;
4136         struct workspace        *ws;
4137         FILE                    *lfile;
4138
4139         DNPRINTF(SWM_D_MISC, "search_workspace\n");
4140
4141         if (r == NULL)
4142                 return;
4143
4144         search_r = r;
4145         search_resp_action = SWM_SEARCH_SEARCH_WORKSPACE;
4146
4147         spawn_select(r, args, "search", &searchpid);
4148
4149         if ((lfile = fdopen(select_list_pipe[1], "w")) == NULL)
4150                 return;
4151
4152         for (i = 0; i < workspace_limit; i++) {
4153                 ws = &r->s->ws[i];
4154                 if (ws == NULL)
4155                         continue;
4156                 fprintf(lfile, "%d%s%s\n", ws->idx + 1,
4157                     (ws->name ? ":" : ""), (ws->name ? ws->name : ""));
4158         }
4159
4160         fclose(lfile);
4161 }
4162
4163 void
4164 search_win_cleanup(void)
4165 {
4166         struct search_window    *sw = NULL;
4167
4168         while ((sw = TAILQ_FIRST(&search_wl)) != NULL) {
4169                 xcb_destroy_window(conn, sw->indicator);
4170                 TAILQ_REMOVE(&search_wl, sw, entry);
4171                 free(sw);
4172         }
4173 }
4174
4175 void
4176 search_win(struct swm_region *r, union arg *args)
4177 {
4178         struct ws_win           *win = NULL;
4179         struct search_window    *sw = NULL;
4180         xcb_window_t            w;
4181         uint32_t                wa[2];
4182         int                     i, width, height;
4183         char                    s[8];
4184         FILE                    *lfile;
4185         size_t                  len;
4186         XftDraw                 *draw;
4187         XGlyphInfo              info;
4188         GC                      l_draw;
4189         XGCValues               l_gcv;
4190         XRectangle              l_ibox, l_lbox;
4191
4192         DNPRINTF(SWM_D_MISC, "search_win\n");
4193
4194         search_r = r;
4195         search_resp_action = SWM_SEARCH_SEARCH_WINDOW;
4196
4197         spawn_select(r, args, "search", &searchpid);
4198
4199         if ((lfile = fdopen(select_list_pipe[1], "w")) == NULL)
4200                 return;
4201
4202         TAILQ_INIT(&search_wl);
4203
4204         i = 1;
4205         TAILQ_FOREACH(win, &r->ws->winlist, entry) {
4206                 if (win->iconic)
4207                         continue;
4208
4209                 sw = calloc(1, sizeof(struct search_window));
4210                 if (sw == NULL) {
4211                         warn("search_win: calloc");
4212                         fclose(lfile);
4213                         search_win_cleanup();
4214                         return;
4215                 }
4216                 sw->idx = i;
4217                 sw->win = win;
4218
4219                 snprintf(s, sizeof s, "%d", i);
4220                 len = strlen(s);
4221
4222                 w = xcb_generate_id(conn);
4223                 wa[0] = r->s->c[SWM_S_COLOR_FOCUS].pixel;
4224                 wa[1] = r->s->c[SWM_S_COLOR_UNFOCUS].pixel;
4225
4226                 if (bar_font_legacy) {
4227                         XmbTextExtents(bar_fs, s, len, &l_ibox, &l_lbox);
4228                         width = l_lbox.width + 4;
4229                         height = bar_fs_extents->max_logical_extent.height + 4;
4230                 } else {
4231                         XftTextExtentsUtf8(display, bar_font, (FcChar8 *)s, len,
4232                             &info);
4233                         width = info.width + 4;
4234                         height = bar_font->height + 4;
4235                 }
4236
4237                 xcb_create_window(conn, XCB_COPY_FROM_PARENT, w, win->id, 0, 0,
4238                     width, height, 1, XCB_WINDOW_CLASS_INPUT_OUTPUT,
4239                     XCB_COPY_FROM_PARENT, XCB_CW_BACK_PIXEL |
4240                     XCB_CW_BORDER_PIXEL, wa);
4241
4242                 xcb_map_window(conn, w);
4243
4244                 sw->indicator = w;
4245                 TAILQ_INSERT_TAIL(&search_wl, sw, entry);
4246
4247                 if (bar_font_legacy) {
4248                         l_gcv.graphics_exposures = 0;
4249                         l_draw = XCreateGC(display, w, 0, &l_gcv);
4250
4251                         XSetForeground(display, l_draw,
4252                                 r->s->c[SWM_S_COLOR_BAR].pixel);
4253
4254                         DRAWSTRING(display, w, bar_fs, l_draw, 2,
4255                             (bar_fs_extents->max_logical_extent.height -
4256                             l_lbox.height) / 2 - l_lbox.y, s, len);
4257
4258                         XFreeGC(display, l_draw);
4259                 } else {
4260
4261                         draw = XftDrawCreate(display, w,
4262                             DefaultVisual(display, r->s->idx),
4263                             DefaultColormap(display, r->s->idx));
4264
4265                         XftDrawStringUtf8(draw, &bar_font_color, bar_font, 2,
4266                             (HEIGHT(r->bar) + bar_font->height) / 2 -
4267                             bar_font->descent, (FcChar8 *)s, len);
4268
4269                         XftDrawDestroy(draw);
4270                 }
4271
4272                 DNPRINTF(SWM_D_MISC, "search_win: mapped window: 0x%x\n", w);
4273
4274                 fprintf(lfile, "%d\n", i);
4275                 i++;
4276         }
4277
4278         fclose(lfile);
4279
4280         xcb_flush(conn);
4281 }
4282
4283 void
4284 search_resp_uniconify(char *resp, unsigned long len)
4285 {
4286         char                    *name;
4287         struct ws_win           *win;
4288         char                    *s;
4289
4290         DNPRINTF(SWM_D_MISC, "search_resp_uniconify: resp: %s\n", resp);
4291
4292         TAILQ_FOREACH(win, &search_r->ws->winlist, entry) {
4293                 if (!win->iconic)
4294                         continue;
4295                 name = get_win_name(win->id);
4296                 if (name == NULL)
4297                         continue;
4298                 if (asprintf(&s, "%s.%u", name, win->id) == -1) {
4299                         free(name);
4300                         continue;
4301                 }
4302                 free(name);
4303                 if (strncmp(s, resp, len) == 0) {
4304                         /* XXX this should be a callback to generalize */
4305                         set_swm_iconic(win, 0);
4306                         xcb_flush(conn);
4307                         free(s);
4308                         break;
4309                 }
4310                 free(s);
4311         }
4312 }
4313
4314 void
4315 search_resp_name_workspace(char *resp, unsigned long len)
4316 {
4317         struct workspace        *ws;
4318
4319         DNPRINTF(SWM_D_MISC, "search_resp_name_workspace: resp: %s\n", resp);
4320
4321         if (search_r->ws == NULL)
4322                 return;
4323         ws = search_r->ws;
4324
4325         if (ws->name) {
4326                 free(search_r->ws->name);
4327                 search_r->ws->name = NULL;
4328         }
4329
4330         if (len > 1) {
4331                 ws->name = strdup(resp);
4332                 if (ws->name == NULL) {
4333                         DNPRINTF(SWM_D_MISC, "search_resp_name_workspace: "
4334                             "strdup: %s", strerror(errno));
4335                         return;
4336                 }
4337         }
4338 }
4339
4340 void
4341 search_resp_search_workspace(char *resp)
4342 {
4343         char                    *p, *q;
4344         int                     ws_idx;
4345         const char              *errstr;
4346         union arg               a;
4347
4348         DNPRINTF(SWM_D_MISC, "search_resp_search_workspace: resp: %s\n", resp);
4349
4350         q = strdup(resp);
4351         if (!q) {
4352                 DNPRINTF(SWM_D_MISC, "search_resp_search_workspace: strdup: %s",
4353                     strerror(errno));
4354                 return;
4355         }
4356         p = strchr(q, ':');
4357         if (p != NULL)
4358                 *p = '\0';
4359         ws_idx = (int)strtonum(q, 1, workspace_limit, &errstr);
4360         if (errstr) {
4361                 DNPRINTF(SWM_D_MISC, "workspace idx is %s: %s",
4362                     errstr, q);
4363                 free(q);
4364                 return;
4365         }
4366         free(q);
4367         a.id = ws_idx - 1;
4368         switchws(search_r, &a);
4369 }
4370
4371 void
4372 search_resp_search_window(char *resp)
4373 {
4374         char                    *s;
4375         int                     idx;
4376         const char              *errstr;
4377         struct search_window    *sw;
4378
4379         DNPRINTF(SWM_D_MISC, "search_resp_search_window: resp: %s\n", resp);
4380
4381         s = strdup(resp);
4382         if (!s) {
4383                 DNPRINTF(SWM_D_MISC, "search_resp_search_window: strdup: %s",
4384                     strerror(errno));
4385                 return;
4386         }
4387
4388         idx = (int)strtonum(s, 1, INT_MAX, &errstr);
4389         if (errstr) {
4390                 DNPRINTF(SWM_D_MISC, "window idx is %s: %s",
4391                     errstr, s);
4392                 free(s);
4393                 return;
4394         }
4395         free(s);
4396
4397         TAILQ_FOREACH(sw, &search_wl, entry)
4398                 if (idx == sw->idx) {
4399                         focus_win(sw->win);
4400                         break;
4401                 }
4402 }
4403
4404 #define MAX_RESP_LEN    1024
4405
4406 void
4407 search_do_resp(void)
4408 {
4409         ssize_t                 rbytes;
4410         char                    *resp;
4411         unsigned long           len;
4412
4413         DNPRINTF(SWM_D_MISC, "search_do_resp:\n");
4414
4415         search_resp = 0;
4416         searchpid = 0;
4417
4418         if ((resp = calloc(1, MAX_RESP_LEN + 1)) == NULL) {
4419                 warn("search: calloc");
4420                 goto done;
4421         }
4422
4423         rbytes = read(select_resp_pipe[0], resp, MAX_RESP_LEN);
4424         if (rbytes <= 0) {
4425                 warn("search: read error");
4426                 goto done;
4427         }
4428         resp[rbytes] = '\0';
4429
4430         /* XXX:
4431          * Older versions of dmenu (Atleast pre 4.4.1) do not send a
4432          * newline, so work around that by sanitizing the resp now.
4433          */
4434         resp[strcspn(resp, "\n")] = '\0';
4435         len = strlen(resp);
4436
4437         switch (search_resp_action) {
4438         case SWM_SEARCH_UNICONIFY:
4439                 search_resp_uniconify(resp, len);
4440                 break;
4441         case SWM_SEARCH_NAME_WORKSPACE:
4442                 search_resp_name_workspace(resp, len);
4443                 break;
4444         case SWM_SEARCH_SEARCH_WORKSPACE:
4445                 search_resp_search_workspace(resp);
4446                 break;
4447         case SWM_SEARCH_SEARCH_WINDOW:
4448                 search_resp_search_window(resp);
4449                 break;
4450         }
4451
4452 done:
4453         if (search_resp_action == SWM_SEARCH_SEARCH_WINDOW)
4454                 search_win_cleanup();
4455
4456         search_resp_action = SWM_SEARCH_NONE;
4457         close(select_resp_pipe[0]);
4458         free(resp);
4459
4460         xcb_flush(conn);
4461 }
4462
4463 void
4464 wkill(struct swm_region *r, union arg *args)
4465 {
4466         DNPRINTF(SWM_D_MISC, "wkill: id: %d\n", args->id);
4467
4468         if (r->ws->focus == NULL)
4469                 return;
4470
4471         if (args->id == SWM_ARG_ID_KILLWINDOW)
4472                 xcb_kill_client(conn, r->ws->focus->id);
4473         else
4474                 if (r->ws->focus->can_delete)
4475                         client_msg(r->ws->focus, a_delete, 0);
4476
4477         xcb_flush(conn);
4478 }
4479
4480 int
4481 floating_toggle_win(struct ws_win *win)
4482 {
4483         struct swm_region       *r;
4484
4485         if (win == NULL)
4486                 return (0);
4487
4488         if (!win->ws->r)
4489                 return (0);
4490
4491         r = win->ws->r;
4492
4493         /* reject floating toggles in max stack mode */
4494         if (win->ws->cur_layout == &layouts[SWM_MAX_STACK])
4495                 return (0);
4496
4497         if (win->floating) {
4498                 if (!win->floatmaxed) {
4499                         /* retain position for refloat */
4500                         store_float_geom(win, r);
4501                 }
4502                 win->floating = 0;
4503         } else {
4504                 load_float_geom(win, r);
4505                 win->floating = 1;
4506         }
4507
4508         ewmh_update_actions(win);
4509
4510         return (1);
4511 }
4512
4513 void
4514 floating_toggle(struct swm_region *r, union arg *args)
4515 {
4516         struct ws_win           *win = r->ws->focus;
4517
4518         /* suppress unused warning since var is needed */
4519         (void)args;
4520
4521         if (win == NULL)
4522                 return;
4523
4524         if (win->ewmh_flags & EWMH_F_FULLSCREEN)
4525                 return;
4526
4527         ewmh_update_win_state(win, ewmh[_NET_WM_STATE_ABOVE].atom,
4528             _NET_WM_STATE_TOGGLE);
4529
4530         stack();
4531
4532         if (win == win->ws->focus)
4533                 focus_win(win);
4534
4535         focus_flush();
4536 }
4537
4538 void
4539 constrain_window(struct ws_win *win, struct swm_region *r, int resizable)
4540 {
4541         if (MAX_X(win) + BORDER(win) > MAX_X(r)) {
4542                 if (resizable)
4543                         WIDTH(win) = MAX_X(r) - X(win) - BORDER(win);
4544                 else
4545                         X(win) = MAX_X(r)- WIDTH(win) - BORDER(win);
4546         }
4547
4548         if (X(win) + BORDER(win) < X(r)) {
4549                 if (resizable)
4550                         WIDTH(win) -= X(r) - X(win) - BORDER(win);
4551
4552                 X(win) = X(r) - BORDER(win);
4553         }
4554
4555         if (MAX_Y(win) + BORDER(win) > MAX_Y(r)) {
4556                 if (resizable)
4557                         HEIGHT(win) = MAX_Y(r) - Y(win) - BORDER(win);
4558                 else
4559                         Y(win) = MAX_Y(r) - HEIGHT(win) - BORDER(win);
4560         }
4561
4562         if (Y(win) + BORDER(win) < Y(r)) {
4563                 if (resizable)
4564                         HEIGHT(win) -= Y(r) - Y(win) - BORDER(win);
4565
4566                 Y(win) = Y(r) - BORDER(win);
4567         }
4568
4569         if (resizable) {
4570                 if (WIDTH(win) < 1)
4571                         WIDTH(win) = 1;
4572                 if (HEIGHT(win) < 1)
4573                         HEIGHT(win) = 1;
4574         }
4575 }
4576
4577 void
4578 update_window(struct ws_win *win)
4579 {
4580         uint16_t        mask;
4581         uint32_t        wc[5];
4582
4583         mask = XCB_CONFIG_WINDOW_X | XCB_CONFIG_WINDOW_Y |
4584             XCB_CONFIG_WINDOW_WIDTH | XCB_CONFIG_WINDOW_HEIGHT |
4585             XCB_CONFIG_WINDOW_BORDER_WIDTH;
4586         wc[0] = X(win);
4587         wc[1] = Y(win);
4588         wc[2] = WIDTH(win);
4589         wc[3] = HEIGHT(win);
4590         wc[4] = BORDER(win);
4591
4592         DNPRINTF(SWM_D_EVENT, "update_window: window: 0x%x, (x,y) w x h: "
4593             "(%d,%d) %d x %d, bordered: %s\n", win->id, wc[0], wc[1], wc[2],
4594             wc[3], YESNO(win->bordered));
4595
4596         xcb_configure_window(conn, win->id, mask, wc);
4597 }
4598
4599 #define SWM_RESIZE_STEPS        (50)
4600
4601 void
4602 resize(struct ws_win *win, union arg *args)
4603 {
4604         xcb_timestamp_t         timestamp = 0;
4605         struct swm_region       *r = NULL;
4606         int                     resize_step = 0;
4607         struct swm_geometry     g;
4608         int                     top = 0, left = 0, resizing;
4609         int                     dx, dy;
4610         unsigned int            shape; /* cursor style */
4611         xcb_cursor_t            cursor;
4612         xcb_font_t              cursor_font;
4613         xcb_query_pointer_reply_t       *xpr;
4614         xcb_generic_event_t             *evt;
4615         xcb_motion_notify_event_t       *mne;
4616
4617         if (win == NULL)
4618                 return;
4619         r = win->ws->r;
4620
4621         if (win->ewmh_flags & EWMH_F_FULLSCREEN)
4622                 return;
4623
4624         DNPRINTF(SWM_D_EVENT, "resize: window: 0x%x, floating: %s, "
4625             "transient: 0x%x\n", win->id, YESNO(win->floating),
4626             win->transient);
4627
4628         if (!win->transient && !win->floating)
4629                 return;
4630
4631         /* reject resizes in max mode for floaters (transient ok) */
4632         if (win->floatmaxed)
4633                 return;
4634
4635         win->manual = 1;
4636         ewmh_update_win_state(win, ewmh[_SWM_WM_STATE_MANUAL].atom,
4637             _NET_WM_STATE_ADD);
4638
4639         stack();
4640
4641         focus_flush();
4642
4643         switch (args->id) {
4644         case SWM_ARG_ID_WIDTHSHRINK:
4645                 WIDTH(win) -= SWM_RESIZE_STEPS;
4646                 resize_step = 1;
4647                 break;
4648         case SWM_ARG_ID_WIDTHGROW:
4649                 WIDTH(win) += SWM_RESIZE_STEPS;
4650                 resize_step = 1;
4651                 break;
4652         case SWM_ARG_ID_HEIGHTSHRINK:
4653                 HEIGHT(win) -= SWM_RESIZE_STEPS;
4654                 resize_step = 1;
4655                 break;
4656         case SWM_ARG_ID_HEIGHTGROW:
4657                 HEIGHT(win) += SWM_RESIZE_STEPS;
4658                 resize_step = 1;
4659                 break;
4660         default:
4661                 break;
4662         }
4663         if (resize_step) {
4664                 constrain_window(win, r, 1);
4665                 update_window(win);
4666                 store_float_geom(win,r);
4667                 return;
4668         }
4669
4670         /* get cursor offset from window root */
4671         xpr = xcb_query_pointer_reply(conn, xcb_query_pointer(conn, win->id),
4672             NULL);
4673         if (!xpr)
4674                 return;
4675
4676         g = win->g;
4677
4678         if (xpr->win_x < WIDTH(win) / 2)
4679                 left = 1;
4680
4681         if (xpr->win_y < HEIGHT(win) / 2)
4682                 top = 1;
4683
4684         if (args->id == SWM_ARG_ID_CENTER)
4685                 shape = XC_sizing;
4686         else if (top)
4687                 shape = (left) ? XC_top_left_corner : XC_top_right_corner;
4688         else
4689                 shape = (left) ? XC_bottom_left_corner : XC_bottom_right_corner;
4690
4691         cursor_font = xcb_generate_id(conn);
4692         xcb_open_font(conn, cursor_font, strlen("cursor"), "cursor");
4693
4694         cursor = xcb_generate_id(conn);
4695         xcb_create_glyph_cursor(conn, cursor, cursor_font, cursor_font,
4696             shape, shape + 1, 0, 0, 0, 0xffff, 0xffff, 0xffff);
4697
4698         xcb_grab_pointer(conn, 0, win->id, MOUSEMASK,
4699             XCB_GRAB_MODE_ASYNC, XCB_GRAB_MODE_ASYNC, XCB_WINDOW_NONE, cursor,
4700             XCB_CURRENT_TIME),
4701
4702         xcb_flush(conn);
4703         resizing = 1;
4704         while ((evt = xcb_wait_for_event(conn)) && resizing) {
4705                 switch (XCB_EVENT_RESPONSE_TYPE(evt)) {
4706                 case XCB_BUTTON_RELEASE:
4707                         DNPRINTF(SWM_D_EVENT, "resize: BUTTON_RELEASE\n");
4708                         resizing = 0;
4709                         break;
4710                 case XCB_MOTION_NOTIFY:
4711                         mne = (xcb_motion_notify_event_t *)evt;
4712                         /* cursor offset/delta from start of the operation */
4713                         dx = mne->root_x - xpr->root_x;
4714                         dy = mne->root_y - xpr->root_y;
4715
4716                         /* vertical */
4717                         if (top)
4718                                 dy = -dy;
4719
4720                         if (args->id == SWM_ARG_ID_CENTER) {
4721                                 if (g.h / 2 + dy < 1)
4722                                         dy = 1 - g.h / 2;
4723
4724                                 Y(win) = g.y - dy;
4725                                 HEIGHT(win) = g.h + 2 * dy;
4726                         } else {
4727                                 if (g.h + dy < 1)
4728                                         dy = 1 - g.h;
4729
4730                                 if (top)
4731                                         Y(win) = g.y - dy;
4732
4733                                 HEIGHT(win) = g.h + dy;
4734                         }
4735
4736                         /* horizontal */
4737                         if (left)
4738                                 dx = -dx;
4739
4740                         if (args->id == SWM_ARG_ID_CENTER) {
4741                                 if (g.w / 2 + dx < 1)
4742                                         dx = 1 - g.w / 2;
4743
4744                                 X(win) = g.x - dx;
4745                                 WIDTH(win) = g.w + 2 * dx;
4746                         } else {
4747                                 if (g.w + dx < 1)
4748                                         dx = 1 - g.w;
4749
4750                                 if (left)
4751                                         X(win) = g.x - dx;
4752
4753                                 WIDTH(win) = g.w + dx;
4754                         }
4755
4756                         constrain_window(win, r, 1);
4757
4758                         /* not free, don't sync more than 120 times / second */
4759                         if ((mne->time - timestamp) > (1000 / 120) ) {
4760                                 timestamp = mne->time;
4761                                 update_window(win);
4762                                 xcb_flush(conn);
4763                         }
4764                         break;
4765                 default:
4766                         event_handle(evt);
4767                         break;
4768                 }
4769                 free(evt);
4770         }
4771         if (timestamp) {
4772                 update_window(win);
4773                 xcb_flush(conn);
4774         }
4775         store_float_geom(win,r);
4776
4777         xcb_ungrab_pointer(conn, XCB_CURRENT_TIME);
4778         xcb_free_cursor(conn, cursor);
4779         xcb_close_font(conn, cursor_font);
4780         free(xpr);
4781         DNPRINTF(SWM_D_EVENT, "resize: done.\n");
4782 }
4783
4784 void
4785 resize_step(struct swm_region *r, union arg *args)
4786 {
4787         struct ws_win           *win = NULL;
4788
4789         if (r && r->ws && r->ws->focus)
4790                 win = r->ws->focus;
4791         else
4792                 return;
4793
4794         resize(win, args);
4795 }
4796
4797 #define SWM_MOVE_STEPS  (50)
4798
4799 void
4800 move(struct ws_win *win, union arg *args)
4801 {
4802         xcb_timestamp_t         timestamp = 0;
4803         int                     move_step = 0, moving;
4804         struct swm_region       *r = NULL;
4805         xcb_font_t                      cursor_font;
4806         xcb_cursor_t                    cursor;
4807         xcb_query_pointer_reply_t       *qpr;
4808         xcb_generic_event_t             *evt;
4809         xcb_motion_notify_event_t       *mne;
4810
4811         if (win == NULL)
4812                 return;
4813         r = win->ws->r;
4814
4815         if (win->ewmh_flags & EWMH_F_FULLSCREEN)
4816                 return;
4817
4818         DNPRINTF(SWM_D_EVENT, "move: window: 0x%x, floating: %s, transient: "
4819             "0x%x\n", win->id, YESNO(win->floating), win->transient);
4820
4821         /* in max_stack mode should only move transients */
4822         if (win->ws->cur_layout == &layouts[SWM_MAX_STACK] && !win->transient)
4823                 return;
4824
4825         win->manual = 1;
4826         if (!win->floating && !win->transient) {
4827                 store_float_geom(win, r);
4828                 ewmh_update_win_state(win, ewmh[_NET_WM_STATE_ABOVE].atom,
4829                     _NET_WM_STATE_ADD);
4830         }
4831         ewmh_update_win_state(win, ewmh[_SWM_WM_STATE_MANUAL].atom,
4832             _NET_WM_STATE_ADD);
4833
4834         stack();
4835
4836         focus_flush();
4837
4838         move_step = 0;
4839         switch (args->id) {
4840         case SWM_ARG_ID_MOVELEFT:
4841                 X(win) -= (SWM_MOVE_STEPS - border_width);
4842                 move_step = 1;
4843                 break;
4844         case SWM_ARG_ID_MOVERIGHT:
4845                 X(win) += (SWM_MOVE_STEPS - border_width);
4846                 move_step = 1;
4847                 break;
4848         case SWM_ARG_ID_MOVEUP:
4849                 Y(win) -= (SWM_MOVE_STEPS - border_width);
4850                 move_step = 1;
4851                 break;
4852         case SWM_ARG_ID_MOVEDOWN:
4853                 Y(win) += (SWM_MOVE_STEPS - border_width);
4854                 move_step = 1;
4855                 break;
4856         default:
4857                 break;
4858         }
4859         if (move_step) {
4860                 constrain_window(win, r, 0);
4861                 update_window(win);
4862                 store_float_geom(win, r);
4863                 return;
4864         }
4865
4866         cursor_font = xcb_generate_id(conn);
4867         xcb_open_font(conn, cursor_font, strlen("cursor"), "cursor");
4868
4869         cursor = xcb_generate_id(conn);
4870         xcb_create_glyph_cursor(conn, cursor, cursor_font, cursor_font,
4871                 XC_fleur, XC_fleur + 1, 0, 0, 0, 0xffff, 0xffff, 0xffff);
4872
4873         xcb_grab_pointer(conn, 0, win->id, MOUSEMASK,
4874             XCB_GRAB_MODE_ASYNC, XCB_GRAB_MODE_ASYNC,
4875             XCB_WINDOW_NONE, cursor, XCB_CURRENT_TIME);
4876
4877         /* get cursor offset from window root */
4878         qpr = xcb_query_pointer_reply(conn, xcb_query_pointer(conn, win->id),
4879                 NULL);
4880         if (!qpr) {
4881                 xcb_ungrab_pointer(conn, XCB_CURRENT_TIME);
4882                 xcb_free_cursor(conn, cursor);
4883                 xcb_close_font(conn, cursor_font);
4884                 return;
4885         }
4886
4887         xcb_flush(conn);
4888         moving = 1;
4889         while ((evt = xcb_wait_for_event(conn)) && moving) {
4890                 switch (XCB_EVENT_RESPONSE_TYPE(evt)) {
4891                 case XCB_BUTTON_RELEASE:
4892                         DNPRINTF(SWM_D_EVENT, "move: BUTTON_RELEASE\n");
4893                         moving = 0;
4894                         break;
4895                 case XCB_MOTION_NOTIFY:
4896                         mne = (xcb_motion_notify_event_t *)evt;
4897                         X(win) = mne->root_x - qpr->win_x - border_width;
4898                         Y(win) = mne->root_y - qpr->win_y - border_width;
4899
4900                         constrain_window(win, r, 0);
4901
4902                         /* not free, don't sync more than 120 times / second */
4903                         if ((mne->time - timestamp) > (1000 / 120) ) {
4904                                 timestamp = mne->time;
4905                                 update_window(win);
4906                                 xcb_flush(conn);
4907                         }
4908                         break;
4909                 default:
4910                         event_handle(evt);
4911                         break;
4912                 }
4913                 free(evt);
4914         }
4915         if (timestamp) {
4916                 update_window(win);
4917                 xcb_flush(conn);
4918         }
4919         store_float_geom(win, r);
4920         free(qpr);
4921         xcb_free_cursor(conn, cursor);
4922         xcb_close_font(conn, cursor_font);
4923         xcb_ungrab_pointer(conn, XCB_CURRENT_TIME);
4924         DNPRINTF(SWM_D_EVENT, "move: done.\n");
4925 }
4926
4927 void
4928 move_step(struct swm_region *r, union arg *args)
4929 {
4930         struct ws_win           *win = NULL;
4931
4932         if (r && r->ws && r->ws->focus)
4933                 win = r->ws->focus;
4934         else
4935                 return;
4936
4937         if (!win->transient && !win->floating)
4938                 return;
4939
4940         move(win, args);
4941 }
4942
4943 /* user/key callable function IDs */
4944 enum keyfuncid {
4945         KF_BAR_TOGGLE,
4946         KF_BUTTON2,
4947         KF_CYCLE_LAYOUT,
4948         KF_FLIP_LAYOUT,
4949         KF_FLOAT_TOGGLE,
4950         KF_FOCUS_MAIN,
4951         KF_FOCUS_NEXT,
4952         KF_FOCUS_PREV,
4953         KF_HEIGHT_GROW,
4954         KF_HEIGHT_SHRINK,
4955         KF_ICONIFY,
4956         KF_MASTER_SHRINK,
4957         KF_MASTER_GROW,
4958         KF_MASTER_ADD,
4959         KF_MASTER_DEL,
4960         KF_MOVE_DOWN,
4961         KF_MOVE_LEFT,
4962         KF_MOVE_RIGHT,
4963         KF_MOVE_UP,
4964         KF_MVWS_1,
4965         KF_MVWS_2,
4966         KF_MVWS_3,
4967         KF_MVWS_4,
4968         KF_MVWS_5,
4969         KF_MVWS_6,
4970         KF_MVWS_7,
4971         KF_MVWS_8,
4972         KF_MVWS_9,
4973         KF_MVWS_10,
4974         KF_MVWS_11,
4975         KF_MVWS_12,
4976         KF_MVWS_13,
4977         KF_MVWS_14,
4978         KF_MVWS_15,
4979         KF_MVWS_16,
4980         KF_MVWS_17,
4981         KF_MVWS_18,
4982         KF_MVWS_19,
4983         KF_MVWS_20,
4984         KF_MVWS_21,
4985         KF_MVWS_22,
4986         KF_NAME_WORKSPACE,
4987         KF_QUIT,
4988         KF_RAISE_TOGGLE,
4989         KF_RESTART,
4990         KF_SCREEN_NEXT,
4991         KF_SCREEN_PREV,
4992         KF_SEARCH_WIN,
4993         KF_SEARCH_WORKSPACE,
4994         KF_SPAWN_CUSTOM,
4995         KF_STACK_INC,
4996         KF_STACK_DEC,
4997         KF_STACK_RESET,
4998         KF_SWAP_MAIN,
4999         KF_SWAP_NEXT,
5000         KF_SWAP_PREV,
5001         KF_UNICONIFY,
5002         KF_VERSION,
5003         KF_WIDTH_GROW,
5004         KF_WIDTH_SHRINK,
5005         KF_WIND_DEL,
5006         KF_WIND_KILL,
5007         KF_WS_1,
5008         KF_WS_2,
5009         KF_WS_3,
5010         KF_WS_4,
5011         KF_WS_5,
5012         KF_WS_6,
5013         KF_WS_7,
5014         KF_WS_8,
5015         KF_WS_9,
5016         KF_WS_10,
5017         KF_WS_11,
5018         KF_WS_12,
5019         KF_WS_13,
5020         KF_WS_14,
5021         KF_WS_15,
5022         KF_WS_16,
5023         KF_WS_17,
5024         KF_WS_18,
5025         KF_WS_19,
5026         KF_WS_20,
5027         KF_WS_21,
5028         KF_WS_22,
5029         KF_WS_NEXT,
5030         KF_WS_NEXT_ALL,
5031         KF_WS_PREV,
5032         KF_WS_PREV_ALL,
5033         KF_WS_PRIOR,
5034         KF_DUMPWINS, /* MUST BE LAST */
5035         KF_INVALID
5036 };
5037
5038 /* key definitions */
5039 struct keyfunc {
5040         char                    name[SWM_FUNCNAME_LEN];
5041         void                    (*func)(struct swm_region *r, union arg *);
5042         union arg               args;
5043 } keyfuncs[KF_INVALID + 1] = {
5044         /* name                 function        argument */
5045         { "bar_toggle",         bar_toggle,     {0} },
5046         { "button2",            pressbutton,    {2} },
5047         { "cycle_layout",       cycle_layout,   {0} },
5048         { "flip_layout",        stack_config,   {.id = SWM_ARG_ID_FLIPLAYOUT} },
5049         { "float_toggle",       floating_toggle,{0} },
5050         { "focus_main",         focus,          {.id = SWM_ARG_ID_FOCUSMAIN} },
5051         { "focus_next",         focus,          {.id = SWM_ARG_ID_FOCUSNEXT} },
5052         { "focus_prev",         focus,          {.id = SWM_ARG_ID_FOCUSPREV} },
5053         { "height_grow",        resize_step,    {.id = SWM_ARG_ID_HEIGHTGROW} },
5054         { "height_shrink",      resize_step,    {.id = SWM_ARG_ID_HEIGHTSHRINK} },
5055         { "iconify",            iconify,        {0} },
5056         { "master_shrink",      stack_config,   {.id = SWM_ARG_ID_MASTERSHRINK} },
5057         { "master_grow",        stack_config,   {.id = SWM_ARG_ID_MASTERGROW} },
5058         { "master_add",         stack_config,   {.id = SWM_ARG_ID_MASTERADD} },
5059         { "master_del",         stack_config,   {.id = SWM_ARG_ID_MASTERDEL} },
5060         { "move_down",          move_step,      {.id = SWM_ARG_ID_MOVEDOWN} },
5061         { "move_left",          move_step,      {.id = SWM_ARG_ID_MOVELEFT} },
5062         { "move_right",         move_step,      {.id = SWM_ARG_ID_MOVERIGHT} },
5063         { "move_up",            move_step,      {.id = SWM_ARG_ID_MOVEUP} },
5064         { "mvws_1",             send_to_ws,     {.id = 0} },
5065         { "mvws_2",             send_to_ws,     {.id = 1} },
5066         { "mvws_3",             send_to_ws,     {.id = 2} },
5067         { "mvws_4",             send_to_ws,     {.id = 3} },
5068         { "mvws_5",             send_to_ws,     {.id = 4} },
5069         { "mvws_6",             send_to_ws,     {.id = 5} },
5070         { "mvws_7",             send_to_ws,     {.id = 6} },
5071         { "mvws_8",             send_to_ws,     {.id = 7} },
5072         { "mvws_9",             send_to_ws,     {.id = 8} },
5073         { "mvws_10",            send_to_ws,     {.id = 9} },
5074         { "mvws_11",            send_to_ws,     {.id = 10} },
5075         { "mvws_12",            send_to_ws,     {.id = 11} },
5076         { "mvws_13",            send_to_ws,     {.id = 12} },
5077         { "mvws_14",            send_to_ws,     {.id = 13} },
5078         { "mvws_15",            send_to_ws,     {.id = 14} },
5079         { "mvws_16",            send_to_ws,     {.id = 15} },
5080         { "mvws_17",            send_to_ws,     {.id = 16} },
5081         { "mvws_18",            send_to_ws,     {.id = 17} },
5082         { "mvws_19",            send_to_ws,     {.id = 18} },
5083         { "mvws_20",            send_to_ws,     {.id = 19} },
5084         { "mvws_21",            send_to_ws,     {.id = 20} },
5085         { "mvws_22",            send_to_ws,     {.id = 21} },
5086         { "name_workspace",     name_workspace, {0} },
5087         { "quit",               quit,           {0} },
5088         { "raise_toggle",       raise_toggle,   {0} },
5089         { "restart",            restart,        {0} },
5090         { "screen_next",        cyclescr,       {.id = SWM_ARG_ID_CYCLESC_UP} },
5091         { "screen_prev",        cyclescr,       {.id = SWM_ARG_ID_CYCLESC_DOWN} },
5092         { "search_win",         search_win,     {0} },
5093         { "search_workspace",   search_workspace,       {0} },
5094         { "spawn_custom",       NULL,           {0} },
5095         { "stack_inc",          stack_config,   {.id = SWM_ARG_ID_STACKINC} },
5096         { "stack_dec",          stack_config,   {.id = SWM_ARG_ID_STACKDEC} },
5097         { "stack_reset",        stack_config,   {.id = SWM_ARG_ID_STACKRESET} },
5098         { "swap_main",          swapwin,        {.id = SWM_ARG_ID_SWAPMAIN} },
5099         { "swap_next",          swapwin,        {.id = SWM_ARG_ID_SWAPNEXT} },
5100         { "swap_prev",          swapwin,        {.id = SWM_ARG_ID_SWAPPREV} },
5101         { "uniconify",          uniconify,      {0} },
5102         { "version",            version,        {0} },
5103         { "width_grow",         resize_step,    {.id = SWM_ARG_ID_WIDTHGROW} },
5104         { "width_shrink",       resize_step,    {.id = SWM_ARG_ID_WIDTHSHRINK} },
5105         { "wind_del",           wkill,          {.id = SWM_ARG_ID_DELETEWINDOW} },
5106         { "wind_kill",          wkill,          {.id = SWM_ARG_ID_KILLWINDOW} },
5107         { "ws_1",               switchws,       {.id = 0} },
5108         { "ws_2",               switchws,       {.id = 1} },
5109         { "ws_3",               switchws,       {.id = 2} },
5110         { "ws_4",               switchws,       {.id = 3} },
5111         { "ws_5",               switchws,       {.id = 4} },
5112         { "ws_6",               switchws,       {.id = 5} },
5113         { "ws_7",               switchws,       {.id = 6} },
5114         { "ws_8",               switchws,       {.id = 7} },
5115         { "ws_9",               switchws,       {.id = 8} },
5116         { "ws_10",              switchws,       {.id = 9} },
5117         { "ws_11",              switchws,       {.id = 10} },
5118         { "ws_12",              switchws,       {.id = 11} },
5119         { "ws_13",              switchws,       {.id = 12} },
5120         { "ws_14",              switchws,       {.id = 13} },
5121         { "ws_15",              switchws,       {.id = 14} },
5122         { "ws_16",              switchws,       {.id = 15} },
5123         { "ws_17",              switchws,       {.id = 16} },
5124         { "ws_18",              switchws,       {.id = 17} },
5125         { "ws_19",              switchws,       {.id = 18} },
5126         { "ws_20",              switchws,       {.id = 19} },
5127         { "ws_21",              switchws,       {.id = 20} },
5128         { "ws_22",              switchws,       {.id = 21} },
5129         { "ws_next",            cyclews,        {.id = SWM_ARG_ID_CYCLEWS_UP} },
5130         { "ws_next_all",        cyclews,        {.id = SWM_ARG_ID_CYCLEWS_UP_ALL} },
5131         { "ws_prev",            cyclews,        {.id = SWM_ARG_ID_CYCLEWS_DOWN} },
5132         { "ws_prev_all",        cyclews,        {.id = SWM_ARG_ID_CYCLEWS_DOWN_ALL} },
5133         { "ws_prior",           priorws,        {0} },
5134         { "dumpwins",           dumpwins,       {0} }, /* MUST BE LAST */
5135         { "invalid key func",   NULL,           {0} },
5136 };
5137 struct key {
5138         RB_ENTRY(key)           entry;
5139         unsigned int            mod;
5140         KeySym                  keysym;
5141         enum keyfuncid          funcid;
5142         char                    *spawn_name;
5143 };
5144 RB_HEAD(key_tree, key);
5145
5146 int
5147 key_cmp(struct key *kp1, struct key *kp2)
5148 {
5149         if (kp1->keysym < kp2->keysym)
5150                 return (-1);
5151         if (kp1->keysym > kp2->keysym)
5152                 return (1);
5153
5154         if (kp1->mod < kp2->mod)
5155                 return (-1);
5156         if (kp1->mod > kp2->mod)
5157                 return (1);
5158
5159         return (0);
5160 }
5161
5162 RB_GENERATE(key_tree, key, entry, key_cmp);
5163 struct key_tree                 keys;
5164
5165 /* mouse */
5166 enum { client_click, root_click };
5167 struct button {
5168         unsigned int            action;
5169         unsigned int            mask;
5170         unsigned int            button;
5171         void                    (*func)(struct ws_win *, union arg *);
5172         union arg               args;
5173 } buttons[] = {
5174 #define MODKEY_SHIFT    MODKEY | XCB_MOD_MASK_SHIFT
5175           /* action     key             mouse button    func    args */
5176         { client_click, MODKEY,         XCB_BUTTON_INDEX_3,     resize, {.id = SWM_ARG_ID_DONTCENTER} },
5177         { client_click, MODKEY_SHIFT,   XCB_BUTTON_INDEX_3,     resize, {.id = SWM_ARG_ID_CENTER} },
5178         { client_click, MODKEY,         XCB_BUTTON_INDEX_1,     move,   {0} },
5179 #undef MODKEY_SHIFT
5180 };
5181
5182 void
5183 update_modkey(unsigned int mod)
5184 {
5185         int                     i;
5186         struct key              *kp;
5187
5188         mod_key = mod;
5189         RB_FOREACH(kp, key_tree, &keys)
5190                 if (kp->mod & XCB_MOD_MASK_SHIFT)
5191                         kp->mod = mod | XCB_MOD_MASK_SHIFT;
5192                 else
5193                         kp->mod = mod;
5194
5195         for (i = 0; i < LENGTH(buttons); i++)
5196                 if (buttons[i].mask & XCB_MOD_MASK_SHIFT)
5197                         buttons[i].mask = mod | XCB_MOD_MASK_SHIFT;
5198                 else
5199                         buttons[i].mask = mod;
5200 }
5201
5202 /* spawn */
5203 struct spawn_prog {
5204         TAILQ_ENTRY(spawn_prog) entry;
5205         char                    *name;
5206         int                     argc;
5207         char                    **argv;
5208 };
5209 TAILQ_HEAD(spawn_list, spawn_prog);
5210 struct spawn_list               spawns = TAILQ_HEAD_INITIALIZER(spawns);
5211
5212 int
5213 spawn_expand(struct swm_region *r, union arg *args, char *spawn_name,
5214     char ***ret_args)
5215 {
5216         struct spawn_prog       *prog = NULL;
5217         int                     i;
5218         char                    *ap, **real_args;
5219
5220         /* suppress unused warning since var is needed */
5221         (void)args;
5222
5223         DNPRINTF(SWM_D_SPAWN, "spawn_expand: %s\n", spawn_name);
5224
5225         /* find program */
5226         TAILQ_FOREACH(prog, &spawns, entry) {
5227                 if (!strcasecmp(spawn_name, prog->name))
5228                         break;
5229         }
5230         if (prog == NULL) {
5231                 warnx("spawn_custom: program %s not found", spawn_name);
5232                 return (-1);
5233         }
5234
5235         /* make room for expanded args */
5236         if ((real_args = calloc(prog->argc + 1, sizeof(char *))) == NULL)
5237                 err(1, "spawn_custom: calloc real_args");
5238
5239         /* expand spawn_args into real_args */
5240         for (i = 0; i < prog->argc; i++) {
5241                 ap = prog->argv[i];
5242                 DNPRINTF(SWM_D_SPAWN, "spawn_custom: raw arg: %s\n", ap);
5243                 if (!strcasecmp(ap, "$bar_border")) {
5244                         if ((real_args[i] =
5245                             strdup(r->s->c[SWM_S_COLOR_BAR_BORDER].name))
5246                             == NULL)
5247                                 err(1,  "spawn_custom border color");
5248                 } else if (!strcasecmp(ap, "$bar_color")) {
5249                         if ((real_args[i] =
5250                             strdup(r->s->c[SWM_S_COLOR_BAR].name))
5251                             == NULL)
5252                                 err(1, "spawn_custom bar color");
5253                 } else if (!strcasecmp(ap, "$bar_font")) {
5254                         if ((real_args[i] = strdup(bar_fonts))
5255                             == NULL)
5256                                 err(1, "spawn_custom bar fonts");
5257                 } else if (!strcasecmp(ap, "$bar_font_color")) {
5258                         if ((real_args[i] =
5259                             strdup(r->s->c[SWM_S_COLOR_BAR_FONT].name))
5260                             == NULL)
5261                                 err(1, "spawn_custom color font");
5262                 } else if (!strcasecmp(ap, "$color_focus")) {
5263                         if ((real_args[i] =
5264                             strdup(r->s->c[SWM_S_COLOR_FOCUS].name))
5265                             == NULL)
5266                                 err(1, "spawn_custom color focus");
5267                 } else if (!strcasecmp(ap, "$color_unfocus")) {
5268                         if ((real_args[i] =
5269                             strdup(r->s->c[SWM_S_COLOR_UNFOCUS].name))
5270                             == NULL)
5271                                 err(1, "spawn_custom color unfocus");
5272                 } else {
5273                         /* no match --> copy as is */
5274                         if ((real_args[i] = strdup(ap)) == NULL)
5275                                 err(1, "spawn_custom strdup(ap)");
5276                 }
5277                 DNPRINTF(SWM_D_SPAWN, "spawn_custom: cooked arg: %s\n",
5278                     real_args[i]);
5279         }
5280
5281 #ifdef SWM_DEBUG
5282         DNPRINTF(SWM_D_SPAWN, "spawn_custom: result: ");
5283         for (i = 0; i < prog->argc; i++)
5284                 DNPRINTF(SWM_D_SPAWN, "\"%s\" ", real_args[i]);
5285         DNPRINTF(SWM_D_SPAWN, "\n");
5286 #endif
5287         *ret_args = real_args;
5288         return (prog->argc);
5289 }
5290
5291 void
5292 spawn_custom(struct swm_region *r, union arg *args, char *spawn_name)
5293 {
5294         union arg               a;
5295         char                    **real_args;
5296         int                     spawn_argc, i;
5297
5298         if ((spawn_argc = spawn_expand(r, args, spawn_name, &real_args)) < 0)
5299                 return;
5300         a.argv = real_args;
5301         if (fork() == 0)
5302                 spawn(r->ws->idx, &a, 1);
5303
5304         for (i = 0; i < spawn_argc; i++)
5305                 free(real_args[i]);
5306         free(real_args);
5307 }
5308
5309 void
5310 spawn_select(struct swm_region *r, union arg *args, char *spawn_name, int *pid)
5311 {
5312         union arg               a;
5313         char                    **real_args;
5314         int                     i, spawn_argc;
5315
5316         if ((spawn_argc = spawn_expand(r, args, spawn_name, &real_args)) < 0)
5317                 return;
5318         a.argv = real_args;
5319
5320         if (pipe(select_list_pipe) == -1)
5321                 err(1, "pipe error");
5322         if (pipe(select_resp_pipe) == -1)
5323                 err(1, "pipe error");
5324
5325         if (signal(SIGPIPE, SIG_IGN) == SIG_ERR)
5326                 err(1, "could not disable SIGPIPE");
5327         switch (*pid = fork()) {
5328         case -1:
5329                 err(1, "cannot fork");
5330                 break;
5331         case 0: /* child */
5332                 if (dup2(select_list_pipe[0], 0) == -1)
5333                         err(1, "dup2");
5334                 if (dup2(select_resp_pipe[1], 1) == -1)
5335                         err(1, "dup2");
5336                 close(select_list_pipe[1]);
5337                 close(select_resp_pipe[0]);
5338                 spawn(r->ws->idx, &a, 0);
5339                 break;
5340         default: /* parent */
5341                 close(select_list_pipe[0]);
5342                 close(select_resp_pipe[1]);
5343                 break;
5344         }
5345
5346         for (i = 0; i < spawn_argc; i++)
5347                 free(real_args[i]);
5348         free(real_args);
5349 }
5350
5351 void
5352 spawn_insert(char *name, char *args)
5353 {
5354         char                    *arg, *cp, *ptr;
5355         struct spawn_prog       *sp;
5356
5357         DNPRINTF(SWM_D_SPAWN, "spawn_insert: %s\n", name);
5358
5359         if ((sp = calloc(1, sizeof *sp)) == NULL)
5360                 err(1, "spawn_insert: calloc");
5361         if ((sp->name = strdup(name)) == NULL)
5362                 err(1, "spawn_insert: strdup");
5363
5364         /* convert the arguments to an argument list */
5365         if ((ptr = cp = strdup(args)) == NULL)
5366                 err(1, "spawn_insert: strdup");
5367         while ((arg = strsep(&ptr, " \t")) != NULL) {
5368                 /* empty field; skip it */
5369                 if (*arg == '\0')
5370                         continue;
5371
5372                 sp->argc++;
5373                 if ((sp->argv = realloc(sp->argv, sp->argc *
5374                     sizeof *sp->argv)) == NULL)
5375                         err(1, "spawn_insert: realloc");
5376                 if ((sp->argv[sp->argc - 1] = strdup(arg)) == NULL)
5377                         err(1, "spawn_insert: strdup");
5378         }
5379         free(cp);
5380
5381         TAILQ_INSERT_TAIL(&spawns, sp, entry);
5382         DNPRINTF(SWM_D_SPAWN, "spawn_insert: leave\n");
5383 }
5384
5385 void
5386 spawn_remove(struct spawn_prog *sp)
5387 {
5388         int                     i;
5389
5390         DNPRINTF(SWM_D_SPAWN, "spawn_remove: %s\n", sp->name);
5391
5392         TAILQ_REMOVE(&spawns, sp, entry);
5393         for (i = 0; i < sp->argc; i++)
5394                 free(sp->argv[i]);
5395         free(sp->argv);
5396         free(sp->name);
5397         free(sp);
5398
5399         DNPRINTF(SWM_D_SPAWN, "spawn_remove: leave\n");
5400 }
5401
5402 void
5403 spawn_replace(struct spawn_prog *sp, char *name, char *args)
5404 {
5405         DNPRINTF(SWM_D_SPAWN, "spawn_replace: %s [%s]\n", sp->name, name);
5406
5407         spawn_remove(sp);
5408         spawn_insert(name, args);
5409
5410         DNPRINTF(SWM_D_SPAWN, "spawn_replace: leave\n");
5411 }
5412
5413 void
5414 setspawn(char *name, char *args)
5415 {
5416         struct spawn_prog       *sp;
5417
5418         DNPRINTF(SWM_D_SPAWN, "setspawn: %s\n", name);
5419
5420         if (name == NULL)
5421                 return;
5422
5423         TAILQ_FOREACH(sp, &spawns, entry) {
5424                 if (!strcmp(sp->name, name)) {
5425                         if (*args == '\0')
5426                                 spawn_remove(sp);
5427                         else
5428                                 spawn_replace(sp, name, args);
5429                         DNPRINTF(SWM_D_SPAWN, "setspawn: leave\n");
5430                         return;
5431                 }
5432         }
5433         if (*args == '\0') {
5434                 warnx("error: setspawn: cannot find program: %s", name);
5435                 return;
5436         }
5437
5438         spawn_insert(name, args);
5439         DNPRINTF(SWM_D_SPAWN, "setspawn: leave\n");
5440 }
5441
5442 int
5443 setconfspawn(char *selector, char *value, int flags)
5444 {
5445         char *args;
5446
5447         /* suppress unused warning since var is needed */
5448         (void)flags;
5449
5450         args = expand_tilde(value);
5451
5452         DNPRINTF(SWM_D_SPAWN, "setconfspawn: [%s] [%s]\n", selector, args);
5453
5454         setspawn(selector, args);
5455         free(args);
5456
5457         DNPRINTF(SWM_D_SPAWN, "setconfspawn: done.\n");
5458         return (0);
5459 }
5460
5461 void
5462 setup_spawn(void)
5463 {
5464         setconfspawn("term",            "xterm",                0);
5465         setconfspawn("spawn_term",      "xterm",                0);
5466         setconfspawn("screenshot_all",  "screenshot.sh full",   0);
5467         setconfspawn("screenshot_wind", "screenshot.sh window", 0);
5468         setconfspawn("lock",            "xlock",                0);
5469         setconfspawn("initscr",         "initscreen.sh",        0);
5470         setconfspawn("menu",            "dmenu_run"
5471                                         " -fn $bar_font"
5472                                         " -nb $bar_color"
5473                                         " -nf $bar_font_color"
5474                                         " -sb $bar_border"
5475                                         " -sf $bar_color",      0);
5476         setconfspawn("search",          "dmenu"
5477                                         " -i"
5478                                         " -fn $bar_font"
5479                                         " -nb $bar_color"
5480                                         " -nf $bar_font_color"
5481                                         " -sb $bar_border"
5482                                         " -sf $bar_color",      0);
5483         setconfspawn("name_workspace",  "dmenu"
5484                                         " -p Workspace"
5485                                         " -fn $bar_font"
5486                                         " -nb $bar_color"
5487                                         " -nf $bar_font_color"
5488                                         " -sb $bar_border"
5489                                         " -sf $bar_color",      0);
5490 }
5491
5492 /* key bindings */
5493 #define SWM_MODNAME_SIZE        32
5494 #define SWM_KEY_WS              "\n+ \t"
5495 int
5496 parsekeys(char *keystr, unsigned int currmod, unsigned int *mod, KeySym *ks)
5497 {
5498         char                    *cp, *name;
5499         KeySym                  uks;
5500         DNPRINTF(SWM_D_KEY, "parsekeys: enter [%s]\n", keystr);
5501         if (mod == NULL || ks == NULL) {
5502                 DNPRINTF(SWM_D_KEY, "parsekeys: no mod or key vars\n");
5503                 return (1);
5504         }
5505         if (keystr == NULL || strlen(keystr) == 0) {
5506                 DNPRINTF(SWM_D_KEY, "parsekeys: no keystr\n");
5507                 return (1);
5508         }
5509         cp = keystr;
5510         *ks = XCB_NO_SYMBOL;
5511         *mod = 0;
5512         while ((name = strsep(&cp, SWM_KEY_WS)) != NULL) {
5513                 DNPRINTF(SWM_D_KEY, "parsekeys: key [%s]\n", name);
5514                 if (cp)
5515                         cp += (long)strspn(cp, SWM_KEY_WS);
5516                 if (strncasecmp(name, "MOD", SWM_MODNAME_SIZE) == 0)
5517                         *mod |= currmod;
5518                 else if (!strncasecmp(name, "Mod1", SWM_MODNAME_SIZE))
5519                         *mod |= XCB_MOD_MASK_1;
5520                 else if (!strncasecmp(name, "Mod2", SWM_MODNAME_SIZE))
5521                         *mod += XCB_MOD_MASK_2;
5522                 else if (!strncmp(name, "Mod3", SWM_MODNAME_SIZE))
5523                         *mod |= XCB_MOD_MASK_3;
5524                 else if (!strncmp(name, "Mod4", SWM_MODNAME_SIZE))
5525                         *mod |= XCB_MOD_MASK_4;
5526                 else if (strncasecmp(name, "SHIFT", SWM_MODNAME_SIZE) == 0)
5527                         *mod |= XCB_MOD_MASK_SHIFT;
5528                 else if (strncasecmp(name, "CONTROL", SWM_MODNAME_SIZE) == 0)
5529                         *mod |= XCB_MOD_MASK_CONTROL;
5530                 else {
5531                         *ks = XStringToKeysym(name);
5532                         XConvertCase(*ks, ks, &uks);
5533                         if (ks == XCB_NO_SYMBOL) {
5534                                 DNPRINTF(SWM_D_KEY,
5535                                     "parsekeys: invalid key %s\n",
5536                                     name);
5537                                 return (1);
5538                         }
5539                 }
5540         }
5541         DNPRINTF(SWM_D_KEY, "parsekeys: leave ok\n");
5542         return (0);
5543 }
5544
5545 char *
5546 strdupsafe(char *str)
5547 {
5548         if (str == NULL)
5549                 return (NULL);
5550         else
5551                 return (strdup(str));
5552 }
5553
5554 void
5555 key_insert(unsigned int mod, KeySym ks, enum keyfuncid kfid, char *spawn_name)
5556 {
5557         struct key              *kp;
5558
5559         DNPRINTF(SWM_D_KEY, "key_insert: enter %s [%s]\n",
5560             keyfuncs[kfid].name, spawn_name);
5561
5562         if ((kp = malloc(sizeof *kp)) == NULL)
5563                 err(1, "key_insert: malloc");
5564
5565         kp->mod = mod;
5566         kp->keysym = ks;
5567         kp->funcid = kfid;
5568         kp->spawn_name = strdupsafe(spawn_name);
5569         RB_INSERT(key_tree, &keys, kp);
5570
5571         DNPRINTF(SWM_D_KEY, "key_insert: leave\n");
5572 }
5573
5574 struct key *
5575 key_lookup(unsigned int mod, KeySym ks)
5576 {
5577         struct key              kp;
5578
5579         kp.keysym = ks;
5580         kp.mod = mod;
5581
5582         return (RB_FIND(key_tree, &keys, &kp));
5583 }
5584
5585 void
5586 key_remove(struct key *kp)
5587 {
5588         DNPRINTF(SWM_D_KEY, "key_remove: %s\n", keyfuncs[kp->funcid].name);
5589
5590         RB_REMOVE(key_tree, &keys, kp);
5591         free(kp->spawn_name);
5592         free(kp);
5593
5594         DNPRINTF(SWM_D_KEY, "key_remove: leave\n");
5595 }
5596
5597 void
5598 key_replace(struct key *kp, unsigned int mod, KeySym ks, enum keyfuncid kfid,
5599     char *spawn_name)
5600 {
5601         DNPRINTF(SWM_D_KEY, "key_replace: %s [%s]\n", keyfuncs[kp->funcid].name,
5602             spawn_name);
5603
5604         key_remove(kp);
5605         key_insert(mod, ks, kfid, spawn_name);
5606
5607         DNPRINTF(SWM_D_KEY, "key_replace: leave\n");
5608 }
5609
5610 void
5611 setkeybinding(unsigned int mod, KeySym ks, enum keyfuncid kfid,
5612     char *spawn_name)
5613 {
5614         struct key              *kp;
5615
5616         DNPRINTF(SWM_D_KEY, "setkeybinding: enter %s [%s]\n",
5617             keyfuncs[kfid].name, spawn_name);
5618
5619         if ((kp = key_lookup(mod, ks)) != NULL) {
5620                 if (kfid == KF_INVALID)
5621                         key_remove(kp);
5622                 else
5623                         key_replace(kp, mod, ks, kfid, spawn_name);
5624                 DNPRINTF(SWM_D_KEY, "setkeybinding: leave\n");
5625                 return;
5626         }
5627         if (kfid == KF_INVALID) {
5628                 warnx("error: setkeybinding: cannot find mod/key combination");
5629                 DNPRINTF(SWM_D_KEY, "setkeybinding: leave\n");
5630                 return;
5631         }
5632
5633         key_insert(mod, ks, kfid, spawn_name);
5634         DNPRINTF(SWM_D_KEY, "setkeybinding: leave\n");
5635 }
5636
5637 int
5638 setconfbinding(char *selector, char *value, int flags)
5639 {
5640         enum keyfuncid          kfid;
5641         unsigned int            mod;
5642         KeySym                  ks;
5643         struct spawn_prog       *sp;
5644
5645         /* suppress unused warning since var is needed */
5646         (void)flags;
5647
5648         DNPRINTF(SWM_D_KEY, "setconfbinding: enter\n");
5649         if (selector == NULL) {
5650                 DNPRINTF(SWM_D_KEY, "setconfbinding: unbind %s\n", value);
5651                 if (parsekeys(value, mod_key, &mod, &ks) == 0) {
5652                         kfid = KF_INVALID;
5653                         setkeybinding(mod, ks, kfid, NULL);
5654                         return (0);
5655                 } else
5656                         return (1);
5657         }
5658         /* search by key function name */
5659         for (kfid = 0; kfid < KF_INVALID; (kfid)++) {
5660                 if (strncasecmp(selector, keyfuncs[kfid].name,
5661                     SWM_FUNCNAME_LEN) == 0) {
5662                         DNPRINTF(SWM_D_KEY, "setconfbinding: %s: match\n",
5663                             selector);
5664                         if (parsekeys(value, mod_key, &mod, &ks) == 0) {
5665                                 setkeybinding(mod, ks, kfid, NULL);
5666                                 return (0);
5667                         } else
5668                                 return (1);
5669                 }
5670         }
5671         /* search by custom spawn name */
5672         TAILQ_FOREACH(sp, &spawns, entry) {
5673                 if (strcasecmp(selector, sp->name) == 0) {
5674                         DNPRINTF(SWM_D_KEY, "setconfbinding: %s: match\n",
5675                             selector);
5676                         if (parsekeys(value, mod_key, &mod, &ks) == 0) {
5677                                 setkeybinding(mod, ks, KF_SPAWN_CUSTOM,
5678                                     sp->name);
5679                                 return (0);
5680                         } else
5681                                 return (1);
5682                 }
5683         }
5684         DNPRINTF(SWM_D_KEY, "setconfbinding: no match\n");
5685         return (1);
5686 }
5687
5688 void
5689 setup_keys(void)
5690 {
5691 #define MODKEY_SHIFT    MODKEY | XCB_MOD_MASK_SHIFT
5692         setkeybinding(MODKEY,           XK_space,       KF_CYCLE_LAYOUT,NULL);
5693         setkeybinding(MODKEY_SHIFT,     XK_backslash,   KF_FLIP_LAYOUT, NULL);
5694         setkeybinding(MODKEY_SHIFT,     XK_space,       KF_STACK_RESET, NULL);
5695         setkeybinding(MODKEY,           XK_h,           KF_MASTER_SHRINK, NULL);
5696         setkeybinding(MODKEY,           XK_l,           KF_MASTER_GROW, NULL);
5697         setkeybinding(MODKEY,           XK_comma,       KF_MASTER_ADD,  NULL);
5698         setkeybinding(MODKEY,           XK_period,      KF_MASTER_DEL,  NULL);
5699         setkeybinding(MODKEY_SHIFT,     XK_comma,       KF_STACK_INC,   NULL);
5700         setkeybinding(MODKEY_SHIFT,     XK_period,      KF_STACK_DEC,   NULL);
5701         setkeybinding(MODKEY,           XK_Return,      KF_SWAP_MAIN,   NULL);
5702         setkeybinding(MODKEY,           XK_j,           KF_FOCUS_NEXT,  NULL);
5703         setkeybinding(MODKEY,           XK_k,           KF_FOCUS_PREV,  NULL);
5704         setkeybinding(MODKEY_SHIFT,     XK_j,           KF_SWAP_NEXT,   NULL);
5705         setkeybinding(MODKEY_SHIFT,     XK_k,           KF_SWAP_PREV,   NULL);
5706         setkeybinding(MODKEY_SHIFT,     XK_Return,      KF_SPAWN_CUSTOM,"term");
5707         setkeybinding(MODKEY,           XK_p,           KF_SPAWN_CUSTOM,"menu");
5708         setkeybinding(MODKEY_SHIFT,     XK_q,           KF_QUIT,        NULL);
5709         setkeybinding(MODKEY,           XK_q,           KF_RESTART,     NULL);
5710         setkeybinding(MODKEY,           XK_m,           KF_FOCUS_MAIN,  NULL);
5711         setkeybinding(MODKEY,           XK_1,           KF_WS_1,        NULL);
5712         setkeybinding(MODKEY,           XK_2,           KF_WS_2,        NULL);
5713         setkeybinding(MODKEY,           XK_3,           KF_WS_3,        NULL);
5714         setkeybinding(MODKEY,           XK_4,           KF_WS_4,        NULL);
5715         setkeybinding(MODKEY,           XK_5,           KF_WS_5,        NULL);
5716         setkeybinding(MODKEY,           XK_6,           KF_WS_6,        NULL);
5717         setkeybinding(MODKEY,           XK_7,           KF_WS_7,        NULL);
5718         setkeybinding(MODKEY,           XK_8,           KF_WS_8,        NULL);
5719         setkeybinding(MODKEY,           XK_9,           KF_WS_9,        NULL);
5720         setkeybinding(MODKEY,           XK_0,           KF_WS_10,       NULL);
5721         setkeybinding(MODKEY,           XK_F1,          KF_WS_11,       NULL);
5722         setkeybinding(MODKEY,           XK_F2,          KF_WS_12,       NULL);
5723         setkeybinding(MODKEY,           XK_F3,          KF_WS_13,       NULL);
5724         setkeybinding(MODKEY,           XK_F4,          KF_WS_14,       NULL);
5725         setkeybinding(MODKEY,           XK_F5,          KF_WS_15,       NULL);
5726         setkeybinding(MODKEY,           XK_F6,          KF_WS_16,       NULL);
5727         setkeybinding(MODKEY,           XK_F7,          KF_WS_17,       NULL);
5728         setkeybinding(MODKEY,           XK_F8,          KF_WS_18,       NULL);
5729         setkeybinding(MODKEY,           XK_F9,          KF_WS_19,       NULL);
5730         setkeybinding(MODKEY,           XK_F10,         KF_WS_20,       NULL);
5731         setkeybinding(MODKEY,           XK_F11,         KF_WS_21,       NULL);
5732         setkeybinding(MODKEY,           XK_F12,         KF_WS_22,       NULL);
5733         setkeybinding(MODKEY,           XK_Right,       KF_WS_NEXT,     NULL);
5734         setkeybinding(MODKEY,           XK_Left,        KF_WS_PREV,     NULL);
5735         setkeybinding(MODKEY,           XK_Up,          KF_WS_NEXT_ALL, NULL);
5736         setkeybinding(MODKEY,           XK_Down,        KF_WS_PREV_ALL, NULL);
5737         setkeybinding(MODKEY,           XK_a,           KF_WS_PRIOR,    NULL);
5738         setkeybinding(MODKEY_SHIFT,     XK_Right,       KF_SCREEN_NEXT, NULL);
5739         setkeybinding(MODKEY_SHIFT,     XK_Left,        KF_SCREEN_PREV, NULL);
5740         setkeybinding(MODKEY_SHIFT,     XK_1,           KF_MVWS_1,      NULL);
5741         setkeybinding(MODKEY_SHIFT,     XK_2,           KF_MVWS_2,      NULL);
5742         setkeybinding(MODKEY_SHIFT,     XK_3,           KF_MVWS_3,      NULL);
5743         setkeybinding(MODKEY_SHIFT,     XK_4,           KF_MVWS_4,      NULL);
5744         setkeybinding(MODKEY_SHIFT,     XK_5,           KF_MVWS_5,      NULL);
5745         setkeybinding(MODKEY_SHIFT,     XK_6,           KF_MVWS_6,      NULL);
5746         setkeybinding(MODKEY_SHIFT,     XK_7,           KF_MVWS_7,      NULL);
5747         setkeybinding(MODKEY_SHIFT,     XK_8,           KF_MVWS_8,      NULL);
5748         setkeybinding(MODKEY_SHIFT,     XK_9,           KF_MVWS_9,      NULL);
5749         setkeybinding(MODKEY_SHIFT,     XK_0,           KF_MVWS_10,     NULL);
5750         setkeybinding(MODKEY_SHIFT,     XK_F1,          KF_MVWS_11,     NULL);
5751         setkeybinding(MODKEY_SHIFT,     XK_F2,          KF_MVWS_12,     NULL);
5752         setkeybinding(MODKEY_SHIFT,     XK_F3,          KF_MVWS_13,     NULL);
5753         setkeybinding(MODKEY_SHIFT,     XK_F4,          KF_MVWS_14,     NULL);
5754         setkeybinding(MODKEY_SHIFT,     XK_F5,          KF_MVWS_15,     NULL);
5755         setkeybinding(MODKEY_SHIFT,     XK_F6,          KF_MVWS_16,     NULL);
5756         setkeybinding(MODKEY_SHIFT,     XK_F7,          KF_MVWS_17,     NULL);
5757         setkeybinding(MODKEY_SHIFT,     XK_F8,          KF_MVWS_18,     NULL);
5758         setkeybinding(MODKEY_SHIFT,     XK_F9,          KF_MVWS_19,     NULL);
5759         setkeybinding(MODKEY_SHIFT,     XK_F10,         KF_MVWS_20,     NULL);
5760         setkeybinding(MODKEY_SHIFT,     XK_F11,         KF_MVWS_21,     NULL);
5761         setkeybinding(MODKEY_SHIFT,     XK_F12,         KF_MVWS_22,     NULL);
5762         setkeybinding(MODKEY,           XK_b,           KF_BAR_TOGGLE,  NULL);
5763         setkeybinding(MODKEY,           XK_Tab,         KF_FOCUS_NEXT,  NULL);
5764         setkeybinding(MODKEY_SHIFT,     XK_Tab,         KF_FOCUS_PREV,  NULL);
5765         setkeybinding(MODKEY_SHIFT,     XK_x,           KF_WIND_KILL,   NULL);
5766         setkeybinding(MODKEY,           XK_x,           KF_WIND_DEL,    NULL);
5767         setkeybinding(MODKEY,           XK_s,           KF_SPAWN_CUSTOM,"screenshot_all");
5768         setkeybinding(MODKEY_SHIFT,     XK_s,           KF_SPAWN_CUSTOM,"screenshot_wind");
5769         setkeybinding(MODKEY,           XK_t,           KF_FLOAT_TOGGLE,NULL);
5770         setkeybinding(MODKEY_SHIFT,     XK_v,           KF_VERSION,     NULL);
5771         setkeybinding(MODKEY_SHIFT,     XK_Delete,      KF_SPAWN_CUSTOM,"lock");
5772         setkeybinding(MODKEY_SHIFT,     XK_i,           KF_SPAWN_CUSTOM,"initscr");
5773         setkeybinding(MODKEY,           XK_w,           KF_ICONIFY,     NULL);
5774         setkeybinding(MODKEY_SHIFT,     XK_w,           KF_UNICONIFY,   NULL);
5775         setkeybinding(MODKEY_SHIFT,     XK_r,           KF_RAISE_TOGGLE,NULL);
5776         setkeybinding(MODKEY,           XK_v,           KF_BUTTON2,     NULL);
5777         setkeybinding(MODKEY,           XK_equal,       KF_WIDTH_GROW,  NULL);
5778         setkeybinding(MODKEY,           XK_minus,       KF_WIDTH_SHRINK,NULL);
5779         setkeybinding(MODKEY_SHIFT,     XK_equal,       KF_HEIGHT_GROW,NULL);
5780         setkeybinding(MODKEY_SHIFT,     XK_minus,       KF_HEIGHT_SHRINK,NULL);
5781         setkeybinding(MODKEY,           XK_bracketleft, KF_MOVE_LEFT,NULL);
5782         setkeybinding(MODKEY,           XK_bracketright,KF_MOVE_RIGHT,NULL);
5783         setkeybinding(MODKEY_SHIFT,     XK_bracketleft, KF_MOVE_UP,     NULL);
5784         setkeybinding(MODKEY_SHIFT,     XK_bracketright,KF_MOVE_DOWN,NULL);
5785         setkeybinding(MODKEY_SHIFT,     XK_slash,       KF_NAME_WORKSPACE,NULL);
5786         setkeybinding(MODKEY,           XK_slash,       KF_SEARCH_WORKSPACE,NULL);
5787         setkeybinding(MODKEY,           XK_f,           KF_SEARCH_WIN,  NULL);
5788 #ifdef SWM_DEBUG
5789         setkeybinding(MODKEY_SHIFT,     XK_d,           KF_DUMPWINS,    NULL);
5790 #endif
5791 #undef MODKEY_SHIFT
5792 }
5793
5794 void
5795 clear_keys(void)
5796 {
5797         struct key              *kp;
5798
5799         while (RB_EMPTY(&keys) == 0) {
5800                 kp = RB_ROOT(&keys);
5801                 key_remove(kp);
5802         }
5803 }
5804
5805 int
5806 setkeymapping(char *selector, char *value, int flags)
5807 {
5808         char                    keymapping_file[PATH_MAX];
5809
5810         /* suppress unused warnings since vars are needed */
5811         (void)selector;
5812         (void)flags;
5813
5814         DNPRINTF(SWM_D_KEY, "setkeymapping: enter\n");
5815         if (value[0] == '~')
5816                 snprintf(keymapping_file, sizeof keymapping_file, "%s/%s",
5817                     pwd->pw_dir, &value[1]);
5818         else
5819                 strlcpy(keymapping_file, value, sizeof keymapping_file);
5820         clear_keys();
5821         /* load new key bindings; if it fails, revert to default bindings */
5822         if (conf_load(keymapping_file, SWM_CONF_KEYMAPPING)) {
5823                 clear_keys();
5824                 setup_keys();
5825         }
5826         DNPRINTF(SWM_D_KEY, "setkeymapping: leave\n");
5827         return (0);
5828 }
5829
5830 void
5831 updatenumlockmask(void)
5832 {
5833         unsigned int                            i, j;
5834         xcb_get_modifier_mapping_reply_t        *modmap_r;
5835         xcb_keycode_t                           *modmap, kc, *keycode;
5836
5837         numlockmask = 0;
5838
5839         modmap_r = xcb_get_modifier_mapping_reply(conn,
5840             xcb_get_modifier_mapping(conn),
5841             NULL);
5842         if (modmap_r) {
5843                 modmap = xcb_get_modifier_mapping_keycodes(modmap_r);
5844                 for (i = 0; i < 8; i++) {
5845                         for (j = 0; j < modmap_r->keycodes_per_modifier; j++) {
5846                                 kc = modmap[i * modmap_r->keycodes_per_modifier
5847                                     + j];
5848                                 keycode = xcb_key_symbols_get_keycode(syms,
5849                                                 XK_Num_Lock);
5850                                 if (kc == *keycode)
5851                                         numlockmask = (1 << i);
5852                                 free(keycode);
5853                         }
5854                 }
5855                 free(modmap_r);
5856         }
5857         DNPRINTF(SWM_D_MISC, "updatenumlockmask: %d\n", numlockmask);
5858 }
5859
5860 void
5861 grabkeys(void)
5862 {
5863         struct key              *kp;
5864         int                     num_screens, k, j;
5865         unsigned int            modifiers[3];
5866         xcb_keycode_t           *code;
5867
5868         DNPRINTF(SWM_D_MISC, "grabkeys\n");
5869         updatenumlockmask();
5870
5871         modifiers[0] = 0;
5872         modifiers[1] = numlockmask;
5873         modifiers[2] = numlockmask | XCB_MOD_MASK_LOCK;
5874
5875         num_screens = xcb_setup_roots_length(xcb_get_setup(conn));
5876         for (k = 0; k < num_screens; k++) {
5877                 if (TAILQ_EMPTY(&screens[k].rl))
5878                         continue;
5879                 xcb_ungrab_key(conn, XCB_GRAB_ANY, screens[k].root,
5880                         XCB_MOD_MASK_ANY);
5881                 RB_FOREACH(kp, key_tree, &keys) {
5882                         if ((code = xcb_key_symbols_get_keycode(syms,
5883                                         kp->keysym))) {
5884                                 for (j = 0; j < LENGTH(modifiers); j++)
5885                                         xcb_grab_key(conn, 1,
5886                                             screens[k].root,
5887                                             kp->mod | modifiers[j],
5888                                             *code, XCB_GRAB_MODE_SYNC,
5889                                             XCB_GRAB_MODE_ASYNC);
5890                                 free(code);
5891                         }
5892                 }
5893         }
5894 }
5895
5896 void
5897 grabbuttons(struct ws_win *win)
5898 {
5899         int             i;
5900
5901         DNPRINTF(SWM_D_MOUSE, "grabbuttons: win 0x%x\n", win->id);
5902
5903         for (i = 0; i < LENGTH(buttons); i++)
5904                 if (buttons[i].action == client_click)
5905                         xcb_grab_button(conn, 0, win->id, BUTTONMASK,
5906                             XCB_GRAB_MODE_SYNC, XCB_GRAB_MODE_ASYNC,
5907                             XCB_WINDOW_NONE, XCB_CURSOR_NONE,
5908                             buttons[i].button, buttons[i].mask);
5909
5910         /* click to focus */
5911         xcb_grab_button(conn, 0, win->id, BUTTONMASK, XCB_GRAB_MODE_SYNC,
5912             XCB_GRAB_MODE_ASYNC, XCB_WINDOW_NONE, XCB_CURSOR_NONE,
5913             XCB_BUTTON_INDEX_1, XCB_BUTTON_MASK_ANY);
5914 }
5915
5916 const char *quirkname[] = {
5917         "NONE",         /* config string for "no value" */
5918         "FLOAT",
5919         "TRANSSZ",
5920         "ANYWHERE",
5921         "XTERM_FONTADJ",
5922         "FULLSCREEN",
5923         "FOCUSPREV",
5924 };
5925
5926 /* SWM_Q_WS: retain '|' for back compat for now (2009-08-11) */
5927 #define SWM_Q_WS                "\n|+ \t"
5928 int
5929 parsequirks(char *qstr, unsigned long *quirk)
5930 {
5931         char                    *cp, *name;
5932         int                     i;
5933
5934         if (quirk == NULL)
5935                 return (1);
5936
5937         cp = qstr;
5938         *quirk = 0;
5939         while ((name = strsep(&cp, SWM_Q_WS)) != NULL) {
5940                 if (cp)
5941                         cp += (long)strspn(cp, SWM_Q_WS);
5942                 for (i = 0; i < LENGTH(quirkname); i++) {
5943                         if (!strncasecmp(name, quirkname[i], SWM_QUIRK_LEN)) {
5944                                 DNPRINTF(SWM_D_QUIRK,
5945                                     "parsequirks: %s\n", name);
5946                                 if (i == 0) {
5947                                         *quirk = 0;
5948                                         return (0);
5949                                 }
5950                                 *quirk |= 1 << (i-1);
5951                                 break;
5952                         }
5953                 }
5954                 if (i >= LENGTH(quirkname)) {
5955                         DNPRINTF(SWM_D_QUIRK,
5956                             "parsequirks: invalid quirk [%s]\n", name);
5957                         return (1);
5958                 }
5959         }
5960         return (0);
5961 }
5962
5963 void
5964 quirk_insert(const char *class, const char *name, unsigned long quirk)
5965 {
5966         struct quirk            *qp;
5967
5968         DNPRINTF(SWM_D_QUIRK, "quirk_insert: %s:%s [%lu]\n", class, name,
5969             quirk);
5970
5971         if ((qp = malloc(sizeof *qp)) == NULL)
5972                 err(1, "quirk_insert: malloc");
5973         if ((qp->class = strdup(class)) == NULL)
5974                 err(1, "quirk_insert: strdup");
5975         if ((qp->name = strdup(name)) == NULL)
5976                 err(1, "quirk_insert: strdup");
5977
5978         qp->quirk = quirk;
5979         TAILQ_INSERT_TAIL(&quirks, qp, entry);
5980
5981         DNPRINTF(SWM_D_QUIRK, "quirk_insert: leave\n");
5982 }
5983
5984 void
5985 quirk_remove(struct quirk *qp)
5986 {
5987         DNPRINTF(SWM_D_QUIRK, "quirk_remove: %s:%s [%lu]\n", qp->class,
5988             qp->name, qp->quirk);
5989
5990         TAILQ_REMOVE(&quirks, qp, entry);
5991         free(qp->class);
5992         free(qp->name);
5993         free(qp);
5994
5995         DNPRINTF(SWM_D_QUIRK, "quirk_remove: leave\n");
5996 }
5997
5998 void
5999 quirk_replace(struct quirk *qp, const char *class, const char *name,
6000     unsigned long quirk)
6001 {
6002         DNPRINTF(SWM_D_QUIRK, "quirk_replace: %s:%s [%lu]\n", qp->class,
6003             qp->name, qp->quirk);
6004
6005         quirk_remove(qp);
6006         quirk_insert(class, name, quirk);
6007
6008         DNPRINTF(SWM_D_QUIRK, "quirk_replace: leave\n");
6009 }
6010
6011 void
6012 setquirk(const char *class, const char *name, unsigned long quirk)
6013 {
6014         struct quirk            *qp;
6015
6016         DNPRINTF(SWM_D_QUIRK, "setquirk: enter %s:%s [%lu]\n", class, name,
6017            quirk);
6018
6019         TAILQ_FOREACH(qp, &quirks, entry) {
6020                 if (!strcmp(qp->class, class) && !strcmp(qp->name, name)) {
6021                         if (!quirk)
6022                                 quirk_remove(qp);
6023                         else
6024                                 quirk_replace(qp, class, name, quirk);
6025                         DNPRINTF(SWM_D_QUIRK, "setquirk: leave\n");
6026                         return;
6027                 }
6028         }
6029         if (!quirk) {
6030                 warnx("error: setquirk: cannot find class/name combination");
6031                 return;
6032         }
6033
6034         quirk_insert(class, name, quirk);
6035         DNPRINTF(SWM_D_QUIRK, "setquirk: leave\n");
6036 }
6037
6038 int
6039 setconfquirk(char *selector, char *value, int flags)
6040 {
6041         char                    *cp, *class, *name;
6042         int                     retval;
6043         unsigned long           qrks;
6044
6045         /* suppress unused warning since var is needed */
6046         (void)flags;
6047
6048         if (selector == NULL)
6049                 return (0);
6050         if ((cp = strchr(selector, ':')) == NULL)
6051                 return (0);
6052         *cp = '\0';
6053         class = selector;
6054         name = cp + 1;
6055         if ((retval = parsequirks(value, &qrks)) == 0)
6056                 setquirk(class, name, qrks);
6057         return (retval);
6058 }
6059
6060 void
6061 setup_quirks(void)
6062 {
6063         setquirk("MPlayer",             "xv",           SWM_Q_FLOAT | SWM_Q_FULLSCREEN | SWM_Q_FOCUSPREV);
6064         setquirk("OpenOffice.org 3.2",  "VCLSalFrame",  SWM_Q_FLOAT);
6065         setquirk("Firefox-bin",         "firefox-bin",  SWM_Q_TRANSSZ);
6066         setquirk("Firefox",             "Dialog",       SWM_Q_FLOAT);
6067         setquirk("Gimp",                "gimp",         SWM_Q_FLOAT | SWM_Q_ANYWHERE);
6068         setquirk("XTerm",               "xterm",        SWM_Q_XTERM_FONTADJ);
6069         setquirk("xine",                "Xine Window",  SWM_Q_FLOAT | SWM_Q_ANYWHERE);
6070         setquirk("Xitk",                "Xitk Combo",   SWM_Q_FLOAT | SWM_Q_ANYWHERE);
6071         setquirk("xine",                "xine Panel",   SWM_Q_FLOAT | SWM_Q_ANYWHERE);
6072         setquirk("Xitk",                "Xine Window",  SWM_Q_FLOAT | SWM_Q_ANYWHERE);
6073         setquirk("xine",                "xine Video Fullscreen Window", SWM_Q_FULLSCREEN | SWM_Q_FLOAT);
6074         setquirk("pcb",                 "pcb",          SWM_Q_FLOAT);
6075         setquirk("SDL_App",             "SDL_App",      SWM_Q_FLOAT | SWM_Q_FULLSCREEN);
6076 }
6077
6078 /* conf file stuff */
6079 #define SWM_CONF_FILE           "spectrwm.conf"
6080 #define SWM_CONF_FILE_OLD       "scrotwm.conf"
6081
6082 enum {
6083         SWM_S_BAR_ACTION,
6084         SWM_S_BAR_AT_BOTTOM,
6085         SWM_S_BAR_BORDER_WIDTH,
6086         SWM_S_BAR_DELAY,
6087         SWM_S_BAR_ENABLED,
6088         SWM_S_BAR_FONT,
6089         SWM_S_BAR_FORMAT,
6090         SWM_S_BAR_JUSTIFY,
6091         SWM_S_BORDER_WIDTH,
6092         SWM_S_CLOCK_ENABLED,
6093         SWM_S_CLOCK_FORMAT,
6094         SWM_S_CYCLE_EMPTY,
6095         SWM_S_CYCLE_VISIBLE,
6096         SWM_S_DIALOG_RATIO,
6097         SWM_S_DISABLE_BORDER,
6098         SWM_S_FOCUS_CLOSE,
6099         SWM_S_FOCUS_CLOSE_WRAP,
6100         SWM_S_FOCUS_DEFAULT,
6101         SWM_S_FOCUS_MODE,
6102         SWM_S_SPAWN_ORDER,
6103         SWM_S_SPAWN_TERM,
6104         SWM_S_SS_APP,
6105         SWM_S_SS_ENABLED,
6106         SWM_S_STACK_ENABLED,
6107         SWM_S_TERM_WIDTH,
6108         SWM_S_TITLE_CLASS_ENABLED,
6109         SWM_S_TITLE_NAME_ENABLED,
6110         SWM_S_URGENT_ENABLED,
6111         SWM_S_VERBOSE_LAYOUT,
6112         SWM_S_WINDOW_NAME_ENABLED,
6113         SWM_S_WORKSPACE_LIMIT
6114 };
6115
6116 int
6117 setconfvalue(char *selector, char *value, int flags)
6118 {
6119         int     i;
6120         char    *b;
6121
6122         /* suppress unused warning since var is needed */
6123         (void)selector;
6124
6125         switch (flags) {
6126         case SWM_S_BAR_ACTION:
6127                 free(bar_argv[0]);
6128                 if ((bar_argv[0] = expand_tilde(value)) == NULL)
6129                         err(1, "setconfvalue: bar_action");
6130                 break;
6131         case SWM_S_BAR_AT_BOTTOM:
6132                 bar_at_bottom = atoi(value);
6133                 break;
6134         case SWM_S_BAR_BORDER_WIDTH:
6135                 bar_border_width = atoi(value);
6136                 if (bar_border_width < 0)
6137                         bar_border_width = 0;
6138                 break;
6139         case SWM_S_BAR_DELAY:
6140                 bar_delay = atoi(value);
6141                 break;
6142         case SWM_S_BAR_ENABLED:
6143                 bar_enabled = atoi(value);
6144                 break;
6145         case SWM_S_BAR_FONT:
6146                 b = bar_fonts;
6147                 if (asprintf(&bar_fonts, "%s,%s", value, bar_fonts) == -1)
6148                         err(1, "setconfvalue: asprintf: failed to allocate "
6149                                 "memory for bar_fonts.");
6150                 free(b);
6151
6152                 /* If already in xft mode, then we are done. */
6153                 if (!bar_font_legacy)
6154                         break;
6155
6156                 /* If there are any non-XLFD entries, switch to Xft mode. */
6157                 while ((b = strsep(&value, ",")) != NULL) {
6158                         if (*b == '\0')
6159                                 continue;
6160                         if (!isxlfd(b)) {
6161                                 bar_font_legacy = 0;
6162                                 break;
6163                         }
6164                 }
6165                 break;
6166         case SWM_S_BAR_FORMAT:
6167                 free(bar_format);
6168                 if ((bar_format = strdup(value)) == NULL)
6169                         err(1, "setconfvalue: bar_format");
6170                 break;
6171         case SWM_S_BAR_JUSTIFY:
6172                 if (!strcmp(value, "left"))
6173                         bar_justify = SWM_BAR_JUSTIFY_LEFT;
6174                 else if (!strcmp(value, "center"))
6175                         bar_justify = SWM_BAR_JUSTIFY_CENTER;
6176                 else if (!strcmp(value, "right"))
6177                         bar_justify = SWM_BAR_JUSTIFY_RIGHT;
6178                 else
6179                         errx(1, "invalid bar_justify");
6180                 break;
6181         case SWM_S_BORDER_WIDTH:
6182                 border_width = atoi(value);
6183                 if (border_width < 0)
6184                         border_width = 0;
6185                 break;
6186         case SWM_S_CLOCK_ENABLED:
6187                 clock_enabled = atoi(value);
6188                 break;
6189         case SWM_S_CLOCK_FORMAT:
6190 #ifndef SWM_DENY_CLOCK_FORMAT
6191                 free(clock_format);
6192                 if ((clock_format = strdup(value)) == NULL)
6193                         err(1, "setconfvalue: clock_format");
6194 #endif
6195                 break;
6196         case SWM_S_CYCLE_EMPTY:
6197                 cycle_empty = atoi(value);
6198                 break;
6199         case SWM_S_CYCLE_VISIBLE:
6200                 cycle_visible = atoi(value);
6201                 break;
6202         case SWM_S_DIALOG_RATIO:
6203                 dialog_ratio = atof(value);
6204                 if (dialog_ratio > 1.0 || dialog_ratio <= .3)
6205                         dialog_ratio = .6;
6206                 break;
6207         case SWM_S_DISABLE_BORDER:
6208                 disable_border = atoi(value);
6209                 break;
6210         case SWM_S_FOCUS_CLOSE:
6211                 if (!strcmp(value, "first"))
6212                         focus_close = SWM_STACK_BOTTOM;
6213                 else if (!strcmp(value, "last"))
6214                         focus_close = SWM_STACK_TOP;
6215                 else if (!strcmp(value, "next"))
6216                         focus_close = SWM_STACK_ABOVE;
6217                 else if (!strcmp(value, "previous"))
6218                         focus_close = SWM_STACK_BELOW;
6219                 else
6220                         errx(1, "focus_close");
6221                 break;
6222         case SWM_S_FOCUS_CLOSE_WRAP:
6223                 focus_close_wrap = atoi(value);
6224                 break;
6225         case SWM_S_FOCUS_DEFAULT:
6226                 if (!strcmp(value, "last"))
6227                         focus_default = SWM_STACK_TOP;
6228                 else if (!strcmp(value, "first"))
6229                         focus_default = SWM_STACK_BOTTOM;
6230                 else
6231                         errx(1, "focus_default");
6232                 break;
6233         case SWM_S_FOCUS_MODE:
6234                 if (!strcmp(value, "default"))
6235                         focus_mode = SWM_FOCUS_DEFAULT;
6236                 else if (!strcmp(value, "follow") ||
6237                     !strcmp(value, "follow_cursor"))
6238                         focus_mode = SWM_FOCUS_FOLLOW;
6239                 else if (!strcmp(value, "manual"))
6240                         focus_mode = SWM_FOCUS_MANUAL;
6241                 else
6242                         errx(1, "focus_mode");
6243                 break;
6244         case SWM_S_SPAWN_ORDER:
6245                 if (!strcmp(value, "first"))
6246                         spawn_position = SWM_STACK_BOTTOM;
6247                 else if (!strcmp(value, "last"))
6248                         spawn_position = SWM_STACK_TOP;
6249                 else if (!strcmp(value, "next"))
6250                         spawn_position = SWM_STACK_ABOVE;
6251                 else if (!strcmp(value, "previous"))
6252                         spawn_position = SWM_STACK_BELOW;
6253                 else
6254                         errx(1, "spawn_position");
6255                 break;
6256         case SWM_S_SPAWN_TERM:
6257                 setconfspawn("term", value, 0);
6258                 setconfspawn("spawn_term", value, 0);
6259                 break;
6260         case SWM_S_SS_APP:
6261                 break;
6262         case SWM_S_SS_ENABLED:
6263                 ss_enabled = atoi(value);
6264                 break;
6265         case SWM_S_STACK_ENABLED:
6266                 stack_enabled = atoi(value);
6267                 break;
6268         case SWM_S_TERM_WIDTH:
6269                 term_width = atoi(value);
6270                 if (term_width < 0)
6271                         term_width = 0;
6272                 break;
6273         case SWM_S_TITLE_CLASS_ENABLED:
6274                 title_class_enabled = atoi(value);
6275                 break;
6276         case SWM_S_TITLE_NAME_ENABLED:
6277                 title_name_enabled = atoi(value);
6278                 break;
6279         case SWM_S_URGENT_ENABLED:
6280                 urgent_enabled = atoi(value);
6281                 break;
6282         case SWM_S_VERBOSE_LAYOUT:
6283                 verbose_layout = atoi(value);
6284                 for (i = 0; layouts[i].l_stack != NULL; i++) {
6285                         if (verbose_layout)
6286                                 layouts[i].l_string = fancy_stacker;
6287                         else
6288                                 layouts[i].l_string = plain_stacker;
6289                 }
6290                 break;
6291         case SWM_S_WINDOW_NAME_ENABLED:
6292                 window_name_enabled = atoi(value);
6293                 break;
6294         case SWM_S_WORKSPACE_LIMIT:
6295                 workspace_limit = atoi(value);
6296                 if (workspace_limit > SWM_WS_MAX)
6297                         workspace_limit = SWM_WS_MAX;
6298                 else if (workspace_limit < 1)
6299                         workspace_limit = 1;
6300                 break;
6301         default:
6302                 return (1);
6303         }
6304         return (0);
6305 }
6306
6307 int
6308 setconfmodkey(char *selector, char *value, int flags)
6309 {
6310         /* suppress unused warnings since vars are needed */
6311         (void)selector;
6312         (void)flags;
6313
6314         if (!strncasecmp(value, "Mod1", strlen("Mod1")))
6315                 update_modkey(XCB_MOD_MASK_1);
6316         else if (!strncasecmp(value, "Mod2", strlen("Mod2")))
6317                 update_modkey(XCB_MOD_MASK_2);
6318         else if (!strncasecmp(value, "Mod3", strlen("Mod3")))
6319                 update_modkey(XCB_MOD_MASK_3);
6320         else if (!strncasecmp(value, "Mod4", strlen("Mod4")))
6321                 update_modkey(XCB_MOD_MASK_4);
6322         else
6323                 return (1);
6324         return (0);
6325 }
6326
6327 int
6328 setconfcolor(char *selector, char *value, int flags)
6329 {
6330         setscreencolor(value, ((selector == NULL)?-1:atoi(selector)), flags);
6331         return (0);
6332 }
6333
6334 int
6335 setconfregion(char *selector, char *value, int flags)
6336 {
6337         /* suppress unused warnings since vars are needed */
6338         (void)selector;
6339         (void)flags;
6340
6341         custom_region(value);
6342         return (0);
6343 }
6344
6345 int
6346 setautorun(char *selector, char *value, int flags)
6347 {
6348         int                     ws_id;
6349         char                    s[1024];
6350         char                    *ap, *sp = s;
6351         union arg               a;
6352         int                     argc = 0;
6353         pid_t                   pid;
6354         struct pid_e            *p;
6355
6356         /* suppress unused warnings since vars are needed */
6357         (void)selector;
6358         (void)flags;
6359
6360         if (getenv("SWM_STARTED"))
6361                 return (0);
6362
6363         bzero(s, sizeof s);
6364         if (sscanf(value, "ws[%d]:%1023c", &ws_id, s) != 2)
6365                 errx(1, "invalid autorun entry, should be 'ws[<idx>]:command'");
6366         ws_id--;
6367         if (ws_id < 0 || ws_id >= workspace_limit)
6368                 errx(1, "autorun: invalid workspace %d", ws_id + 1);
6369
6370         /*
6371          * This is a little intricate
6372          *
6373          * If the pid already exists we simply reuse it because it means it was
6374          * used before AND not claimed by manage_window.  We get away with
6375          * altering it in the parent after INSERT because this can not be a race
6376          */
6377         a.argv = NULL;
6378         while ((ap = strsep(&sp, " \t")) != NULL) {
6379                 if (*ap == '\0')
6380                         continue;
6381                 DNPRINTF(SWM_D_SPAWN, "setautorun: arg [%s]\n", ap);
6382                 argc++;
6383                 if ((a.argv = realloc(a.argv, argc * sizeof(char *))) == NULL)
6384                         err(1, "setautorun: realloc");
6385                 a.argv[argc - 1] = ap;
6386         }
6387
6388         if ((a.argv = realloc(a.argv, (argc + 1) * sizeof(char *))) == NULL)
6389                 err(1, "setautorun: realloc");
6390         a.argv[argc] = NULL;
6391
6392         if ((pid = fork()) == 0) {
6393                 spawn(ws_id, &a, 1);
6394                 /* NOTREACHED */
6395                 _exit(1);
6396         }
6397         free(a.argv);
6398
6399         /* parent */
6400         p = find_pid(pid);
6401         if (p == NULL) {
6402                 p = calloc(1, sizeof *p);
6403                 if (p == NULL)
6404                         return (1);
6405                 TAILQ_INSERT_TAIL(&pidlist, p, entry);
6406         }
6407
6408         p->pid = pid;
6409         p->ws = ws_id;
6410
6411         return (0);
6412 }
6413
6414 int
6415 setlayout(char *selector, char *value, int flags)
6416 {
6417         int                     ws_id, i, x, mg, ma, si, ar, f = 0;
6418         int                     st = SWM_V_STACK, num_screens;
6419         char                    s[1024];
6420         struct workspace        *ws;
6421
6422         /* suppress unused warnings since vars are needed */
6423         (void)selector;
6424         (void)flags;
6425
6426         if (getenv("SWM_STARTED"))
6427                 return (0);
6428
6429         bzero(s, sizeof s);
6430         if (sscanf(value, "ws[%d]:%d:%d:%d:%d:%1023c",
6431             &ws_id, &mg, &ma, &si, &ar, s) != 6)
6432                 errx(1, "invalid layout entry, should be 'ws[<idx>]:"
6433                     "<master_grow>:<master_add>:<stack_inc>:<always_raise>:"
6434                     "<type>'");
6435         ws_id--;
6436         if (ws_id < 0 || ws_id >= workspace_limit)
6437                 errx(1, "layout: invalid workspace %d", ws_id + 1);
6438
6439         if (!strcasecmp(s, "vertical"))
6440                 st = SWM_V_STACK;
6441         else if (!strcasecmp(s, "vertical_flip")) {
6442                 st = SWM_V_STACK;
6443                 f = 1;
6444         } else if (!strcasecmp(s, "horizontal"))
6445                 st = SWM_H_STACK;
6446         else if (!strcasecmp(s, "horizontal_flip")) {
6447                 st = SWM_H_STACK;
6448                 f = 1;
6449         } else if (!strcasecmp(s, "fullscreen"))
6450                 st = SWM_MAX_STACK;
6451         else
6452                 errx(1, "invalid layout entry, should be 'ws[<idx>]:"
6453                     "<master_grow>:<master_add>:<stack_inc>:<always_raise>:"
6454                     "<type>'");
6455
6456         num_screens = xcb_setup_roots_length(xcb_get_setup(conn));
6457         for (i = 0; i < num_screens; i++) {
6458                 ws = (struct workspace *)&screens[i].ws;
6459                 ws[ws_id].cur_layout = &layouts[st];
6460
6461                 ws[ws_id].always_raise = ar;
6462                 if (st == SWM_MAX_STACK)
6463                         continue;
6464
6465                 /* master grow */
6466                 for (x = 0; x < abs(mg); x++) {
6467                         ws[ws_id].cur_layout->l_config(&ws[ws_id],
6468                             mg >= 0 ?  SWM_ARG_ID_MASTERGROW :
6469                             SWM_ARG_ID_MASTERSHRINK);
6470                         stack();
6471                 }
6472                 /* master add */
6473                 for (x = 0; x < abs(ma); x++) {
6474                         ws[ws_id].cur_layout->l_config(&ws[ws_id],
6475                             ma >= 0 ?  SWM_ARG_ID_MASTERADD :
6476                             SWM_ARG_ID_MASTERDEL);
6477                         stack();
6478                 }
6479                 /* stack inc */
6480                 for (x = 0; x < abs(si); x++) {
6481                         ws[ws_id].cur_layout->l_config(&ws[ws_id],
6482                             si >= 0 ?  SWM_ARG_ID_STACKINC :
6483                             SWM_ARG_ID_STACKDEC);
6484                         stack();
6485                 }
6486                 /* Apply flip */
6487                 if (f) {
6488                         ws[ws_id].cur_layout->l_config(&ws[ws_id],
6489                             SWM_ARG_ID_FLIPLAYOUT);
6490                         stack();
6491                 }
6492         }
6493
6494         focus_flush();
6495
6496         return (0);
6497 }
6498
6499 /* config options */
6500 struct config_option {
6501         char                    *optname;
6502         int                     (*func)(char*, char*, int);
6503         int                     funcflags;
6504 };
6505 struct config_option configopt[] = {
6506         { "bar_enabled",                setconfvalue,   SWM_S_BAR_ENABLED },
6507         { "bar_at_bottom",              setconfvalue,   SWM_S_BAR_AT_BOTTOM },
6508         { "bar_border",                 setconfcolor,   SWM_S_COLOR_BAR_BORDER },
6509         { "bar_border_width",           setconfvalue,   SWM_S_BAR_BORDER_WIDTH },
6510         { "bar_color",                  setconfcolor,   SWM_S_COLOR_BAR },
6511         { "bar_font_color",             setconfcolor,   SWM_S_COLOR_BAR_FONT },
6512         { "bar_font",                   setconfvalue,   SWM_S_BAR_FONT },
6513         { "bar_action",                 setconfvalue,   SWM_S_BAR_ACTION },
6514         { "bar_delay",                  setconfvalue,   SWM_S_BAR_DELAY },
6515         { "bar_justify",                setconfvalue,   SWM_S_BAR_JUSTIFY },
6516         { "bar_format",                 setconfvalue,   SWM_S_BAR_FORMAT },
6517         { "keyboard_mapping",           setkeymapping,  0 },
6518         { "bind",                       setconfbinding, 0 },
6519         { "stack_enabled",              setconfvalue,   SWM_S_STACK_ENABLED },
6520         { "clock_enabled",              setconfvalue,   SWM_S_CLOCK_ENABLED },
6521         { "clock_format",               setconfvalue,   SWM_S_CLOCK_FORMAT },
6522         { "color_focus",                setconfcolor,   SWM_S_COLOR_FOCUS },
6523         { "color_unfocus",              setconfcolor,   SWM_S_COLOR_UNFOCUS },
6524         { "cycle_empty",                setconfvalue,   SWM_S_CYCLE_EMPTY },
6525         { "cycle_visible",              setconfvalue,   SWM_S_CYCLE_VISIBLE },
6526         { "workspace_limit",            setconfvalue,   SWM_S_WORKSPACE_LIMIT },
6527         { "dialog_ratio",               setconfvalue,   SWM_S_DIALOG_RATIO },
6528         { "verbose_layout",             setconfvalue,   SWM_S_VERBOSE_LAYOUT },
6529         { "modkey",                     setconfmodkey,  0 },
6530         { "program",                    setconfspawn,   0 },
6531         { "quirk",                      setconfquirk,   0 },
6532         { "region",                     setconfregion,  0 },
6533         { "spawn_term",                 setconfvalue,   SWM_S_SPAWN_TERM },
6534         { "screenshot_enabled",         setconfvalue,   SWM_S_SS_ENABLED },
6535         { "screenshot_app",             setconfvalue,   SWM_S_SS_APP },
6536         { "window_name_enabled",        setconfvalue,   SWM_S_WINDOW_NAME_ENABLED },
6537         { "urgent_enabled",             setconfvalue,   SWM_S_URGENT_ENABLED },
6538         { "term_width",                 setconfvalue,   SWM_S_TERM_WIDTH },
6539         { "title_class_enabled",        setconfvalue,   SWM_S_TITLE_CLASS_ENABLED },
6540         { "title_name_enabled",         setconfvalue,   SWM_S_TITLE_NAME_ENABLED },
6541         { "focus_mode",                 setconfvalue,   SWM_S_FOCUS_MODE },
6542         { "focus_close",                setconfvalue,   SWM_S_FOCUS_CLOSE },
6543         { "focus_close_wrap",           setconfvalue,   SWM_S_FOCUS_CLOSE_WRAP },
6544         { "focus_default",              setconfvalue,   SWM_S_FOCUS_DEFAULT },
6545         { "spawn_position",             setconfvalue,   SWM_S_SPAWN_ORDER },
6546         { "disable_border",             setconfvalue,   SWM_S_DISABLE_BORDER },
6547         { "border_width",               setconfvalue,   SWM_S_BORDER_WIDTH },
6548         { "autorun",                    setautorun,     0 },
6549         { "layout",                     setlayout,      0 },
6550 };
6551
6552 int
6553 conf_load(char *filename, int keymapping)
6554 {
6555         FILE                    *config;
6556         char                    *line, *cp, *optsub, *optval;
6557         size_t                  linelen, lineno = 0;
6558         int                     wordlen, i, optidx;
6559         struct config_option    *opt = NULL;
6560
6561         DNPRINTF(SWM_D_CONF, "conf_load: begin\n");
6562
6563         if (filename == NULL) {
6564                 warnx("conf_load: no filename");
6565                 return (1);
6566         }
6567         if ((config = fopen(filename, "r")) == NULL) {
6568                 warn("conf_load: fopen: %s", filename);
6569                 return (1);
6570         }
6571
6572         while (!feof(config)) {
6573                 if ((line = fparseln(config, &linelen, &lineno, NULL, 0))
6574                     == NULL) {
6575                         if (ferror(config))
6576                                 err(1, "%s", filename);
6577                         else
6578                                 continue;
6579                 }
6580                 cp = line;
6581                 cp += strspn(cp, " \t\n"); /* eat whitespace */
6582                 if (cp[0] == '\0') {
6583                         /* empty line */
6584                         free(line);
6585                         continue;
6586                 }
6587                 /* get config option */
6588                 wordlen = strcspn(cp, "=[ \t\n");
6589                 if (wordlen == 0) {
6590                         warnx("%s: line %zd: no option found",
6591                             filename, lineno);
6592                         goto out;
6593                 }
6594                 optidx = -1;
6595                 for (i = 0; i < LENGTH(configopt); i++) {
6596                         opt = &configopt[i];
6597                         if (!strncasecmp(cp, opt->optname, wordlen) &&
6598                             (int)strlen(opt->optname) == wordlen) {
6599                                 optidx = i;
6600                                 break;
6601                         }
6602                 }
6603                 if (optidx == -1) {
6604                         warnx("%s: line %zd: unknown option %.*s",
6605                             filename, lineno, wordlen, cp);
6606                         goto out;
6607                 }
6608                 if (keymapping && opt && strcmp(opt->optname, "bind")) {
6609                         warnx("%s: line %zd: invalid option %.*s",
6610                             filename, lineno, wordlen, cp);
6611                         goto out;
6612                 }
6613                 cp += wordlen;
6614                 cp += strspn(cp, " \t\n"); /* eat whitespace */
6615                 /* get [selector] if any */
6616                 optsub = NULL;
6617                 if (*cp == '[') {
6618                         cp++;
6619                         wordlen = strcspn(cp, "]");
6620                         if (*cp != ']') {
6621                                 if (wordlen == 0) {
6622                                         warnx("%s: line %zd: syntax error",
6623                                             filename, lineno);
6624                                         goto out;
6625                                 }
6626
6627                                 if (asprintf(&optsub, "%.*s", wordlen, cp) ==
6628                                     -1) {
6629                                         warnx("%s: line %zd: unable to allocate"
6630                                             "memory for selector", filename,
6631                                             lineno);
6632                                         goto out;
6633                                 }
6634                         }
6635                         cp += wordlen;
6636                         cp += strspn(cp, "] \t\n"); /* eat trailing */
6637                 }
6638                 cp += strspn(cp, "= \t\n"); /* eat trailing */
6639                 /* get RHS value */
6640                 optval = strdup(cp);
6641                 /* call function to deal with it all */
6642                 if (configopt[optidx].func(optsub, optval,
6643                     configopt[optidx].funcflags) != 0)
6644                         errx(1, "%s: line %zd: invalid data for %s",
6645                             filename, lineno, configopt[optidx].optname);
6646                 free(optval);
6647                 free(optsub);
6648                 free(line);
6649         }
6650
6651         fclose(config);
6652         DNPRINTF(SWM_D_CONF, "conf_load: end\n");
6653
6654         return (0);
6655
6656 out:
6657         free(line);
6658         fclose(config);
6659         DNPRINTF(SWM_D_CONF, "conf_load: end with error.\n");
6660
6661         return (1);
6662 }
6663
6664 void
6665 set_child_transient(struct ws_win *win, xcb_window_t *trans)
6666 {
6667         struct ws_win           *parent, *w;
6668         struct swm_region       *r;
6669         struct workspace        *ws;
6670         xcb_icccm_wm_hints_t    wmh;
6671
6672         parent = find_window(win->transient);
6673         if (parent)
6674                 parent->focus_child = win;
6675         else {
6676                 DNPRINTF(SWM_D_MISC, "set_child_transient: parent doesn't exist"
6677                     " for 0x%x trans 0x%x\n", win->id, win->transient);
6678
6679                 r = root_to_region(win->wa->root);
6680                 ws = r->ws;
6681                 /* parent doen't exist in our window list */
6682                 TAILQ_FOREACH(w, &ws->winlist, entry) {
6683                         if (xcb_icccm_get_wm_hints_reply(conn,
6684                             xcb_icccm_get_wm_hints(conn, w->id),
6685                             &wmh, NULL) != 1) {
6686                                 warnx("can't get hints for 0x%x", w->id);
6687                                 continue;
6688                         }
6689
6690                         if (win->hints.window_group != wmh.window_group)
6691                                 continue;
6692
6693                         w->focus_child = win;
6694                         win->transient = w->id;
6695                         *trans = w->id;
6696                         DNPRINTF(SWM_D_MISC, "set_child_transient: adjusting "
6697                             "transient to 0x%x\n", win->transient);
6698                         break;
6699                 }
6700         }
6701 }
6702
6703 pid_t
6704 window_get_pid(xcb_window_t win)
6705 {
6706         pid_t                           ret = 0;
6707         const char                      *errstr;
6708         xcb_atom_t                      apid;
6709         xcb_get_property_cookie_t       pc;
6710         xcb_get_property_reply_t        *pr;
6711
6712         apid = get_atom_from_string("_NET_WM_PID");
6713         if (apid == XCB_ATOM_NONE)
6714                 goto tryharder;
6715
6716         pc = xcb_get_property(conn, 0, win, apid, XCB_ATOM_CARDINAL, 0, 1);
6717         pr = xcb_get_property_reply(conn, pc, NULL);
6718         if (!pr)
6719                 goto tryharder;
6720         if (pr->type != XCB_ATOM_CARDINAL) {
6721                 free(pr);
6722                 goto tryharder;
6723         }
6724
6725         if (pr->type == apid && pr->format == 32)
6726                 ret = *((pid_t *)xcb_get_property_value(pr));
6727         free(pr);
6728
6729         return (ret);
6730
6731 tryharder:
6732         apid = get_atom_from_string("_SWM_PID");
6733         pc = xcb_get_property(conn, 0, win, apid, XCB_ATOM_STRING,
6734             0, SWM_PROPLEN);
6735         pr = xcb_get_property_reply(conn, pc, NULL);
6736         if (!pr)
6737                 return (0);
6738         if (pr->type != apid) {
6739                 free(pr);
6740                 return (0);
6741         }
6742
6743         ret = (pid_t)strtonum(xcb_get_property_value(pr), 0, INT_MAX, &errstr);
6744         free(pr);
6745
6746         return (ret);
6747 }
6748
6749 int
6750 get_ws_idx(xcb_window_t id)
6751 {
6752         int                     ws_idx = -1;
6753         char                    *prop = NULL;
6754         size_t                  proplen;
6755         const char              *errstr;
6756         xcb_get_property_reply_t        *gpr;
6757
6758         gpr = xcb_get_property_reply(conn,
6759                 xcb_get_property(conn, 0, id, a_swm_ws,
6760                     XCB_ATOM_STRING, 0, SWM_PROPLEN),
6761                 NULL);
6762         if (!gpr)
6763                 return (-1);
6764         if (gpr->type) {
6765                 proplen = xcb_get_property_value_length(gpr);
6766                 if (proplen > 0) {
6767                         prop = malloc(proplen + 1);
6768                         if (prop) {
6769                                 memcpy(prop,
6770                                     xcb_get_property_value(gpr),
6771                                     proplen);
6772                                 prop[proplen] = '\0';
6773                         }
6774                 }
6775         }
6776         free(gpr);
6777
6778         if (prop) {
6779                 DNPRINTF(SWM_D_PROP, "get_ws_idx: _SWM_WS: %s\n", prop);
6780                 ws_idx = (int)strtonum(prop, 0, workspace_limit - 1, &errstr);
6781                 if (errstr) {
6782                         DNPRINTF(SWM_D_PROP, "get_ws_idx: window: #%s: %s",
6783                             errstr, prop);
6784                 }
6785                 free(prop);
6786         }
6787
6788         return ws_idx;
6789 }
6790
6791 struct ws_win *
6792 manage_window(xcb_window_t id, uint16_t mapped)
6793 {
6794         xcb_window_t            trans = XCB_WINDOW_NONE;
6795         struct ws_win           *win, *ww;
6796         int                     ws_idx;
6797         char                    ws_idx_str[SWM_PROPLEN];
6798         struct swm_region       *r;
6799         struct pid_e            *p;
6800         struct quirk            *qp;
6801         uint32_t                i, wa[2];
6802         xcb_icccm_get_wm_protocols_reply_t      wpr;
6803
6804         if ((win = find_window(id)) != NULL) {
6805                 DNPRINTF(SWM_D_MISC, "manage_window: win 0x%x already "
6806                     "managed; skipping.)\n", id);
6807                 return (win);   /* Already managed. */
6808         }
6809
6810         /* See if window is on the unmanaged list. */
6811         if ((win = find_unmanaged_window(id)) != NULL) {
6812                 DNPRINTF(SWM_D_MISC, "manage_window: win 0x%x found on "
6813                     "unmanaged list.\n", id);
6814                 TAILQ_REMOVE(&win->ws->unmanagedlist, win, entry);
6815
6816                 if (win->transient)
6817                         set_child_transient(win, &trans);
6818
6819                 goto out;
6820         } else {
6821                 DNPRINTF(SWM_D_MISC, "manage_window: win 0x%x is new.\n", id);
6822         }
6823
6824         /* Create and initialize ws_win object. */
6825         if ((win = calloc(1, sizeof(struct ws_win))) == NULL)
6826                 err(1, "manage_window: calloc: failed to allocate memory for "
6827                     "new window");
6828
6829         win->id = id;
6830
6831         /* Get window geometry. */
6832         win->wa = xcb_get_geometry_reply(conn,
6833             xcb_get_geometry(conn, win->id),
6834             NULL);
6835
6836         /* Figure out which region the window belongs to. */
6837         r = root_to_region(win->wa->root);
6838
6839         /* Ignore window border if there is one. */
6840         WIDTH(win) = win->wa->width;
6841         HEIGHT(win) = win->wa->height;
6842         X(win) = win->wa->x + win->wa->border_width - border_width;
6843         Y(win) = win->wa->y + win->wa->border_width - border_width;
6844         win->bordered = 1;
6845         win->mapped = mapped;
6846         win->floatmaxed = 0;
6847         win->ewmh_flags = 0;
6848         win->s = r->s;  /* this never changes */
6849
6850         store_float_geom(win, r);
6851
6852         /* Get WM_SIZE_HINTS. */
6853         xcb_icccm_get_wm_normal_hints_reply(conn,
6854             xcb_icccm_get_wm_normal_hints(conn, win->id),
6855             &win->sh, NULL);
6856
6857         /* Get WM_HINTS. */
6858         xcb_icccm_get_wm_hints_reply(conn,
6859             xcb_icccm_get_wm_hints(conn, win->id),
6860             &win->hints, NULL);
6861
6862         /* Get WM_TRANSIENT_FOR; see if window is a transient. */
6863         xcb_icccm_get_wm_transient_for_reply(conn,
6864             xcb_icccm_get_wm_transient_for(conn, win->id),
6865             &trans, NULL);
6866         if (trans) {
6867                 win->transient = trans;
6868                 set_child_transient(win, &win->transient);
6869         }
6870
6871         /* Get supported protocols. */
6872         if (xcb_icccm_get_wm_protocols_reply(conn,
6873             xcb_icccm_get_wm_protocols(conn, win->id, a_prot),
6874             &wpr, NULL)) {
6875                 for (i = 0; i < wpr.atoms_len; i++) {
6876                         if (wpr.atoms[i] == a_takefocus)
6877                                 win->take_focus = 1;
6878                         if (wpr.atoms[i] == a_delete)
6879                                 win->can_delete = 1;
6880                 }
6881                 xcb_icccm_get_wm_protocols_reply_wipe(&wpr);
6882         }
6883
6884         win->iconic = get_swm_iconic(win);
6885
6886         /* Figure out which workspace the window belongs to. */
6887         if ((p = find_pid(window_get_pid(win->id))) != NULL) {
6888                 win->ws = &r->s->ws[p->ws];
6889                 TAILQ_REMOVE(&pidlist, p, entry);
6890                 free(p);
6891                 p = NULL;
6892         } else if ((ws_idx = get_ws_idx(win->id)) != -1 &&
6893             !win->transient) {
6894                 /* _SWM_WS is set; use that. */
6895                 win->ws = &r->s->ws[ws_idx];
6896         } else if (trans && (ww = find_window(trans)) != NULL) {
6897                 /* Launch transients in the same ws as parent. */
6898                 win->ws = ww->ws;
6899         } else {
6900                 win->ws = r->ws;
6901         }
6902
6903         /* Set the _SWM_WS atom so we can remember this after reincarnation. */
6904         if (snprintf(ws_idx_str, SWM_PROPLEN, "%d", win->ws->idx) <
6905             SWM_PROPLEN) {
6906                 DNPRINTF(SWM_D_PROP, "manage_window: set _SWM_WS: %s\n",
6907                     ws_idx_str);
6908                 xcb_change_property(conn, XCB_PROP_MODE_REPLACE, win->id,
6909                     a_swm_ws, XCB_ATOM_STRING, 8, strlen(ws_idx_str),
6910                     ws_idx_str);
6911         }
6912
6913         /* Handle EWMH */
6914         ewmh_autoquirk(win);
6915
6916         /* Determine initial quirks. */
6917         if (xcb_icccm_get_wm_class_reply(conn,
6918             xcb_icccm_get_wm_class(conn, win->id),
6919             &win->ch, NULL)) {
6920                 DNPRINTF(SWM_D_CLASS, "manage_window: class: %s, name: %s\n",
6921                     win->ch.class_name, win->ch.instance_name);
6922
6923                 /* java is retarded so treat it special */
6924                 if (strstr(win->ch.instance_name, "sun-awt")) {
6925                         DNPRINTF(SWM_D_CLASS, "manage_window: java window "
6926                             "detected.\n");
6927                         win->java = 1;
6928                 }
6929
6930                 TAILQ_FOREACH(qp, &quirks, entry) {
6931                         if (!strcmp(win->ch.class_name, qp->class) &&
6932                             !strcmp(win->ch.instance_name, qp->name)) {
6933                                 DNPRINTF(SWM_D_CLASS, "manage_window: on quirks"
6934                                     "list; mask: 0x%lx\n", qp->quirk);
6935                                 if (qp->quirk & SWM_Q_FLOAT)
6936                                         win->floating = 1;
6937                                 win->quirks = qp->quirk;
6938                         }
6939                 }
6940         }
6941
6942         /* Alter window position if quirky */
6943         if (win->quirks & SWM_Q_ANYWHERE)
6944                 win->manual = 1;
6945
6946         /* Reset font sizes (the bruteforce way; no default keybinding). */
6947         if (win->quirks & SWM_Q_XTERM_FONTADJ) {
6948                 for (i = 0; i < SWM_MAX_FONT_STEPS; i++)
6949                         fake_keypress(win, XK_KP_Subtract, XCB_MOD_MASK_SHIFT);
6950                 for (i = 0; i < SWM_MAX_FONT_STEPS; i++)
6951                         fake_keypress(win, XK_KP_Add, XCB_MOD_MASK_SHIFT);
6952         }
6953
6954         /* Make sure window is positioned inside its region, if its active. */
6955         if (win->ws->r) {
6956                 constrain_window(win, win->ws->r, 0);
6957                 update_window(win);
6958         }
6959
6960         /* Select which X events to monitor and set border pixel color. */
6961         wa[0] = win->s->c[SWM_S_COLOR_UNFOCUS].pixel;
6962         wa[1] = XCB_EVENT_MASK_ENTER_WINDOW | XCB_EVENT_MASK_PROPERTY_CHANGE |
6963             XCB_EVENT_MASK_STRUCTURE_NOTIFY;
6964 #ifdef SWM_DEBUG
6965         wa[1] |= XCB_EVENT_MASK_LEAVE_WINDOW | XCB_EVENT_MASK_FOCUS_CHANGE;
6966 #endif
6967
6968         xcb_change_window_attributes(conn, win->id, XCB_CW_BORDER_PIXEL |
6969             XCB_CW_EVENT_MASK, wa);
6970
6971 out:
6972         /* Figure out where to stack the window in the workspace. */
6973         if (trans && (ww = find_window(trans)))
6974                 TAILQ_INSERT_AFTER(&win->ws->winlist, ww, win, entry);
6975         else if (win->ws->focus && spawn_position == SWM_STACK_ABOVE)
6976                 TAILQ_INSERT_AFTER(&win->ws->winlist, win->ws->focus, win,
6977                     entry);
6978         else if (win->ws->focus && spawn_position == SWM_STACK_BELOW)
6979                 TAILQ_INSERT_BEFORE(win->ws->focus, win, entry);
6980         else switch (spawn_position) {
6981         default:
6982         case SWM_STACK_TOP:
6983         case SWM_STACK_ABOVE:
6984                 TAILQ_INSERT_TAIL(&win->ws->winlist, win, entry);
6985                 break;
6986         case SWM_STACK_BOTTOM:
6987         case SWM_STACK_BELOW:
6988                 TAILQ_INSERT_HEAD(&win->ws->winlist, win, entry);
6989         }
6990
6991         /* Get initial _NET_WM_STATE */
6992         ewmh_get_win_state(win);
6993         /* Set initial _NET_WM_ALLOWED_ACTIONS */
6994         ewmh_update_actions(win);
6995
6996         grabbuttons(win);
6997
6998         DNPRINTF(SWM_D_MISC, "manage_window: done. window: 0x%x, (x,y) w x h: "
6999             "(%d,%d) %d x %d, ws: %d, iconic: %s, transient: 0x%x\n", win->id,
7000             X(win), Y(win), WIDTH(win), HEIGHT(win), win->ws->idx,
7001             YESNO(win->iconic), win->transient);
7002
7003         return (win);
7004 }
7005
7006 void
7007 free_window(struct ws_win *win)
7008 {
7009         DNPRINTF(SWM_D_MISC, "free_window: window: 0x%x\n", win->id);
7010
7011         if (win == NULL)
7012                 return;
7013
7014         TAILQ_REMOVE(&win->ws->unmanagedlist, win, entry);
7015
7016         if (win->wa)
7017                 free(win->wa);
7018
7019         xcb_icccm_get_wm_class_reply_wipe(&win->ch);
7020
7021         kill_refs(win);
7022
7023         /* paint memory */
7024         memset(win, 0xff, sizeof *win); /* XXX kill later */
7025
7026         free(win);
7027         DNPRINTF(SWM_D_MISC, "free_window: done.\n");
7028 }
7029
7030 void
7031 unmanage_window(struct ws_win *win)
7032 {
7033         struct ws_win           *parent;
7034
7035         if (win == NULL)
7036                 return;
7037
7038         DNPRINTF(SWM_D_MISC, "unmanage_window: window: 0x%x\n", win->id);
7039
7040         if (win->transient) {
7041                 parent = find_window(win->transient);
7042                 if (parent)
7043                         parent->focus_child = NULL;
7044         }
7045
7046         TAILQ_REMOVE(&win->ws->winlist, win, entry);
7047         TAILQ_INSERT_TAIL(&win->ws->unmanagedlist, win, entry);
7048 }
7049
7050 void
7051 expose(xcb_expose_event_t *e)
7052 {
7053         int                     i, num_screens;
7054         struct swm_region       *r;
7055
7056         DNPRINTF(SWM_D_EVENT, "expose: window: 0x%x\n", e->window);
7057
7058         num_screens = xcb_setup_roots_length(xcb_get_setup(conn));
7059         for (i = 0; i < num_screens; i++)
7060                 TAILQ_FOREACH(r, &screens[i].rl, entry)
7061                         if (e->window == WINID(r->bar))
7062                                 bar_update();
7063
7064         xcb_flush(conn);
7065 }
7066
7067 #ifdef SWM_DEBUG
7068 void
7069 focusin(xcb_focus_in_event_t *e)
7070 {
7071         DNPRINTF(SWM_D_EVENT, "focusin: window: 0x%x, mode: %s(%u), "
7072             "detail: %s(%u)\n", e->event, get_notify_mode_label(e->mode),
7073             e->mode, get_notify_detail_label(e->detail), e->detail);
7074 }
7075
7076 void
7077 focusout(xcb_focus_out_event_t *e)
7078 {
7079         DNPRINTF(SWM_D_EVENT, "focusout: window: 0x%x, mode: %s(%u), "
7080             "detail: %s(%u)\n", e->event, get_notify_mode_label(e->mode),
7081             e->mode, get_notify_detail_label(e->detail), e->detail);
7082 }
7083 #endif
7084
7085 void
7086 keypress(xcb_key_press_event_t *e)
7087 {
7088         xcb_keysym_t            keysym;
7089         struct key              *kp;
7090
7091         keysym = xcb_key_press_lookup_keysym(syms, e, 0);
7092
7093         DNPRINTF(SWM_D_EVENT, "keypress: %u %u\n", e->detail, keysym);
7094
7095         if ((kp = key_lookup(CLEANMASK(e->state), keysym)) == NULL)
7096                 return;
7097
7098         last_event_time = e->time;
7099
7100         if (kp->funcid == KF_SPAWN_CUSTOM)
7101                 spawn_custom(root_to_region(e->root),
7102                     &(keyfuncs[kp->funcid].args), kp->spawn_name);
7103         else if (keyfuncs[kp->funcid].func)
7104                 keyfuncs[kp->funcid].func(root_to_region(e->root),
7105                     &(keyfuncs[kp->funcid].args));
7106 }
7107
7108 void
7109 buttonpress(xcb_button_press_event_t *e)
7110 {
7111         struct ws_win           *win;
7112         int                     i;
7113         int                     handled = 0;
7114
7115         DNPRINTF(SWM_D_EVENT, "buttonpress: window 0x%x, detail: %u\n",
7116             e->event, e->detail);
7117
7118         if ((win = find_window(e->event)) == NULL)
7119                 return;
7120
7121         last_event_time = e->time;
7122
7123         focus_win(get_focus_magic(win));
7124
7125         for (i = 0; i < LENGTH(buttons); i++)
7126                 if (client_click == buttons[i].action && buttons[i].func &&
7127                     buttons[i].button == e->detail &&
7128                     CLEANMASK(buttons[i].mask) == CLEANMASK(e->state)) {
7129                         buttons[i].func(win, &buttons[i].args);
7130                         handled = 1;
7131                 }
7132
7133         if (!handled) {
7134                 DNPRINTF(SWM_D_EVENT, "buttonpress: passing to window.\n");
7135                 xcb_allow_events(conn, XCB_ALLOW_REPLAY_POINTER, e->time);
7136         } else {
7137                 DNPRINTF(SWM_D_EVENT, "buttonpress: handled.\n");
7138         }
7139
7140         xcb_flush(conn);
7141 }
7142
7143 #ifdef SWM_DEBUG
7144 void
7145 print_win_geom(xcb_window_t w)
7146 {
7147         xcb_get_geometry_reply_t        *wa;
7148
7149         wa = xcb_get_geometry_reply(conn, xcb_get_geometry(conn, w), NULL);
7150
7151         if (!wa) {
7152                 DNPRINTF(SWM_D_MISC, "print_win_geom: window not found: 0x%x\n",
7153                     w);
7154                 return;
7155         }
7156
7157         DNPRINTF(SWM_D_MISC, "print_win_geom: window: 0x%x, root: 0x%x, "
7158             "depth: %u, (x,y) w x h: (%d,%d) %d x %d, border: %d\n",
7159             w, wa->root, wa->depth, wa->x,  wa->y, wa->width, wa->height,
7160             wa->border_width);
7161
7162         free(wa);
7163 }
7164 #endif
7165
7166 #ifdef SWM_DEBUG
7167 char *
7168 get_stack_mode_name(uint8_t mode)
7169 {
7170         char    *name;
7171
7172         switch(mode) {
7173         case XCB_STACK_MODE_ABOVE:
7174                 name = "Above";
7175                 break;
7176         case XCB_STACK_MODE_BELOW:
7177                 name = "Below";
7178                 break;
7179         case XCB_STACK_MODE_TOP_IF:
7180                 name = "TopIf";
7181                 break;
7182         case XCB_STACK_MODE_BOTTOM_IF:
7183                 name = "BottomIf";
7184                 break;
7185         case XCB_STACK_MODE_OPPOSITE:
7186                 name = "Opposite";
7187                 break;
7188         default:
7189                 name = "Unknown";
7190         }
7191
7192         return name;
7193 }
7194 #endif
7195
7196 void
7197 configurerequest(xcb_configure_request_event_t *e)
7198 {
7199         struct ws_win           *win;
7200         struct swm_region       *r = NULL;
7201         int                     new = 0, i = 0;
7202         uint16_t                mask = 0;
7203         uint32_t                wc[7] = {0};
7204
7205         if ((win = find_window(e->window)) == NULL)
7206                 if ((win = find_unmanaged_window(e->window)) == NULL)
7207                         new = 1;
7208
7209 #ifdef SWM_DEBUG
7210         if (swm_debug & SWM_D_EVENT) {
7211                 print_win_geom(e->window);
7212
7213                 DNPRINTF(SWM_D_EVENT, "configurerequest: window: 0x%x, "
7214                     "parent: 0x%x, new: %s, value_mask: %u { ", e->window,
7215                     e->parent, YESNO(new), e->value_mask);
7216                 if (e->value_mask & XCB_CONFIG_WINDOW_X)
7217                         DPRINTF("X: %d ", e->x);
7218                 if (e->value_mask & XCB_CONFIG_WINDOW_Y)
7219                         DPRINTF("Y: %d ", e->y);
7220                 if (e->value_mask & XCB_CONFIG_WINDOW_WIDTH)
7221                         DPRINTF("W: %u ", e->width);
7222                 if (e->value_mask & XCB_CONFIG_WINDOW_HEIGHT)
7223                         DPRINTF("H: %u ", e->height);
7224                 if (e->value_mask & XCB_CONFIG_WINDOW_BORDER_WIDTH)
7225                         DPRINTF("Border: %u ", e->border_width);
7226                 if (e->value_mask & XCB_CONFIG_WINDOW_SIBLING)
7227                         DPRINTF("Sibling: 0x%x ", e->sibling);
7228                 if (e->value_mask & XCB_CONFIG_WINDOW_STACK_MODE)
7229                         DPRINTF("StackMode: %s(%u) ",
7230                             get_stack_mode_name(e->stack_mode), e->stack_mode);
7231                 DPRINTF("}\n");
7232         }
7233 #endif
7234
7235         if (new) {
7236                 if (e->value_mask & XCB_CONFIG_WINDOW_X) {
7237                         mask |= XCB_CONFIG_WINDOW_X;
7238                         wc[i++] = e->x;
7239                 }
7240                 if (e->value_mask & XCB_CONFIG_WINDOW_Y) {
7241                         mask |= XCB_CONFIG_WINDOW_Y;
7242                         wc[i++] = e->y;
7243                 }
7244                 if (e->value_mask & XCB_CONFIG_WINDOW_WIDTH) {
7245                         mask |= XCB_CONFIG_WINDOW_WIDTH;
7246                         wc[i++] = e->width;
7247                 }
7248                 if (e->value_mask & XCB_CONFIG_WINDOW_HEIGHT) {
7249                         mask |= XCB_CONFIG_WINDOW_HEIGHT;
7250                         wc[i++] = e->height;
7251                 }
7252                 if (e->value_mask & XCB_CONFIG_WINDOW_BORDER_WIDTH) {
7253                         mask |= XCB_CONFIG_WINDOW_BORDER_WIDTH;
7254                         wc[i++] = e->border_width;
7255                 }
7256                 if (e->value_mask & XCB_CONFIG_WINDOW_SIBLING) {
7257                         mask |= XCB_CONFIG_WINDOW_SIBLING;
7258                         wc[i++] = e->sibling;
7259                 }
7260                 if (e->value_mask & XCB_CONFIG_WINDOW_STACK_MODE) {
7261                         mask |= XCB_CONFIG_WINDOW_STACK_MODE;
7262                         wc[i++] = e->stack_mode;
7263                 }
7264
7265                 if (mask != 0)
7266                         xcb_configure_window(conn, e->window, mask, wc);
7267         } else if ((!win->manual || win->quirks & SWM_Q_ANYWHERE) &&
7268             !(win->ewmh_flags & EWMH_F_FULLSCREEN)) {
7269                 if (win->ws->r)
7270                         r = win->ws->r;
7271                 else if (win->ws->old_r)
7272                         r = win->ws->old_r;
7273
7274                 /* windows are centered unless ANYWHERE quirk is set. */
7275                 if (win->quirks & SWM_Q_ANYWHERE) {
7276                         if (e->value_mask & XCB_CONFIG_WINDOW_X) {
7277                                 win->g_float.x = e->x;
7278                                 if (r)
7279                                         win->g_float.x -= X(r);
7280                         }
7281
7282                         if (e->value_mask & XCB_CONFIG_WINDOW_Y) {
7283                                 win->g_float.y = e->y;
7284                                 if (r)
7285                                         win->g_float.y -= Y(r);
7286                         }
7287                 }
7288
7289                 if (e->value_mask & XCB_CONFIG_WINDOW_WIDTH)
7290                         win->g_float.w = e->width;
7291
7292                 if (e->value_mask & XCB_CONFIG_WINDOW_HEIGHT)
7293                         win->g_float.h = e->height;
7294
7295                 win->g_floatvalid = 1;
7296
7297                 if (win->floating && r) {
7298                         WIDTH(win) = win->g_float.w;
7299                         HEIGHT(win) = win->g_float.h;
7300
7301                         stack_floater(win, win->ws->r);
7302
7303                         focus_flush();
7304                 } else {
7305                         config_win(win, e);
7306                         xcb_flush(conn);
7307                 }
7308         } else {
7309                 config_win(win, e);
7310                 xcb_flush(conn);
7311         }
7312 }
7313
7314 void
7315 configurenotify(xcb_configure_notify_event_t *e)
7316 {
7317         struct ws_win           *win;
7318
7319         DNPRINTF(SWM_D_EVENT, "configurenotify: win 0x%x, event win: 0x%x, "
7320             "(x,y) WxH: (%d,%d) %ux%u, border: %u, above_sibling: 0x%x, "
7321             "override_redirect: %s\n", e->window, e->event, e->x, e->y,
7322             e->width, e->height, e->border_width, e->above_sibling,
7323             YESNO(e->override_redirect));
7324
7325         win = find_window(e->window);
7326         if (win) {
7327                 xcb_icccm_get_wm_normal_hints_reply(conn,
7328                     xcb_icccm_get_wm_normal_hints(conn, win->id),
7329                     &win->sh, NULL);
7330                 adjust_font(win);
7331                 if (font_adjusted) {
7332                         stack();
7333                         xcb_flush(conn);
7334                 }
7335         }
7336 }
7337
7338 void
7339 destroynotify(xcb_destroy_notify_event_t *e)
7340 {
7341         struct ws_win           *win;
7342
7343         DNPRINTF(SWM_D_EVENT, "destroynotify: window: 0x%x\n", e->window);
7344
7345         if ((win = find_window(e->window)) == NULL) {
7346                 if ((win = find_unmanaged_window(e->window)) == NULL)
7347                         return;
7348                 free_window(win);
7349                 return;
7350         }
7351
7352         if (focus_mode != SWM_FOCUS_FOLLOW) {
7353                 /* If we were focused, make sure we focus on something else. */
7354                 if (win == win->ws->focus)
7355                         win->ws->focus_pending = get_focus_prev(win);
7356         }
7357
7358         unmanage_window(win);
7359         stack();
7360
7361         if (focus_mode != SWM_FOCUS_FOLLOW) {
7362                 if (win->ws->focus_pending) {
7363                         focus_win(win->ws->focus_pending);
7364                         win->ws->focus_pending = NULL;
7365                 }
7366         }
7367
7368         free_window(win);
7369
7370         focus_flush();
7371 }
7372
7373 #ifdef SWM_DEBUG
7374 char *
7375 get_notify_detail_label(uint8_t detail)
7376 {
7377         char *label;
7378
7379         switch (detail) {
7380         case XCB_NOTIFY_DETAIL_ANCESTOR:
7381                 label = "Ancestor";
7382                 break;
7383         case XCB_NOTIFY_DETAIL_VIRTUAL:
7384                 label = "Virtual";
7385                 break;
7386         case XCB_NOTIFY_DETAIL_INFERIOR:
7387                 label = "Inferior";
7388                 break;
7389         case XCB_NOTIFY_DETAIL_NONLINEAR:
7390                 label = "Nonlinear";
7391                 break;
7392         case XCB_NOTIFY_DETAIL_NONLINEAR_VIRTUAL:
7393                 label = "NonlinearVirtual";
7394                 break;
7395         case XCB_NOTIFY_DETAIL_POINTER:
7396                 label = "Pointer";
7397                 break;
7398         case XCB_NOTIFY_DETAIL_POINTER_ROOT:
7399                 label = "PointerRoot";
7400                 break;
7401         case XCB_NOTIFY_DETAIL_NONE:
7402                 label = "None";
7403                 break;
7404         default:
7405                 label = "Unknown";
7406         }
7407
7408         return label;
7409 }
7410
7411 char *
7412 get_notify_mode_label(uint8_t mode)
7413 {
7414         char *label;
7415
7416         switch (mode) {
7417         case XCB_NOTIFY_MODE_NORMAL:
7418                 label = "Normal";
7419                 break;
7420         case XCB_NOTIFY_MODE_GRAB:
7421                 label = "Grab";
7422                 break;
7423         case XCB_NOTIFY_MODE_UNGRAB:
7424                 label = "Ungrab";
7425                 break;
7426         case XCB_NOTIFY_MODE_WHILE_GRABBED:
7427                 label = "WhileGrabbed";
7428                 break;
7429         default:
7430                 label = "Unknown";
7431         }
7432
7433         return label;
7434 }
7435 #endif
7436
7437 void
7438 enternotify(xcb_enter_notify_event_t *e)
7439 {
7440         struct ws_win           *win;
7441
7442         DNPRINTF(SWM_D_FOCUS, "enternotify: time: %u, win (x,y): 0x%x "
7443             "(%d,%d), mode: %s(%d), detail: %s(%d), root (x,y): 0x%x (%d,%d), "
7444             "child: 0x%x, same_screen_focus: %s, state: %d\n",
7445             e->time, e->event, e->event_x, e->event_y,
7446             get_notify_mode_label(e->mode), e->mode,
7447             get_notify_detail_label(e->detail), e->detail,
7448             e->root, e->root_x, e->root_y, e->child,
7449             YESNO(e->same_screen_focus), e->state);
7450
7451         if (focus_mode == SWM_FOCUS_MANUAL &&
7452             e->mode == XCB_NOTIFY_MODE_NORMAL) {
7453                 DNPRINTF(SWM_D_EVENT, "enternotify: manual focus; ignoring.\n");
7454                 return;
7455         }
7456
7457         if ((win = find_window(e->event)) == NULL) {
7458                 DNPRINTF(SWM_D_EVENT, "enternotify: window is NULL; ignoring\n");
7459                 return;
7460         }
7461
7462         last_event_time = e->time;
7463
7464         focus_win(get_focus_magic(win));
7465
7466         xcb_flush(conn);
7467 }
7468
7469 #ifdef SWM_DEBUG
7470 void
7471 leavenotify(xcb_leave_notify_event_t *e)
7472 {
7473         DNPRINTF(SWM_D_FOCUS, "leavenotify: time: %u, win (x,y): 0x%x "
7474             "(%d,%d), mode: %s(%d), detail: %s(%d), root (x,y): 0x%x (%d,%d), "
7475             "child: 0x%x, same_screen_focus: %s, state: %d\n",
7476             e->time, e->event, e->event_x, e->event_y,
7477             get_notify_mode_label(e->mode), e->mode,
7478             get_notify_detail_label(e->detail), e->detail,
7479             e->root, e->root_x, e->root_y, e->child,
7480             YESNO(e->same_screen_focus), e->state);
7481 }
7482 #endif
7483
7484 /* lets us use one switch statement for arbitrary mode/detail combinations */
7485 #define MERGE_MEMBERS(a,b)      (((a & 0xffff) << 16) | (b & 0xffff))
7486
7487 void
7488 mapnotify(xcb_map_notify_event_t *e)
7489 {
7490         struct ws_win           *win;
7491
7492         DNPRINTF(SWM_D_EVENT, "mapnotify: window: 0x%x\n", e->window);
7493
7494         if ((win = find_window(e->window)) == NULL)
7495                 win = manage_window(e->window, 1);
7496
7497         win->mapped = 1;
7498         set_win_state(win, XCB_ICCCM_WM_STATE_NORMAL);
7499
7500         if (focus_mode != SWM_FOCUS_FOLLOW) {
7501                 if (win->ws->focus_pending == win) {
7502                         focus_win(win);
7503                         win->ws->focus_pending = NULL;
7504                 }
7505         }
7506
7507         xcb_flush(conn);
7508 }
7509
7510 void
7511 mappingnotify(xcb_mapping_notify_event_t *e)
7512 {
7513         xcb_refresh_keyboard_mapping(syms, e);
7514
7515         if (e->request == XCB_MAPPING_KEYBOARD)
7516                 grabkeys();
7517 }
7518
7519 void
7520 maprequest(xcb_map_request_event_t *e)
7521 {
7522         struct ws_win           *win;
7523         xcb_get_window_attributes_reply_t *war;
7524
7525         DNPRINTF(SWM_D_EVENT, "maprequest: win 0x%x\n",
7526             e->window);
7527
7528         war = xcb_get_window_attributes_reply(conn,
7529             xcb_get_window_attributes(conn, e->window),
7530             NULL);
7531         if (war == NULL) {
7532                 DNPRINTF(SWM_D_EVENT, "maprequest: window lost.\n");
7533                 goto out;
7534         }
7535
7536         if (war->override_redirect) {
7537                 DNPRINTF(SWM_D_EVENT, "maprequest: override_redirect; "
7538                     "skipping.\n");
7539                 goto out;
7540         }
7541
7542         win = manage_window(e->window,
7543             (war->map_state == XCB_MAP_STATE_VIEWABLE));
7544
7545         /* All windows need to be mapped if they are in the current workspace.*/
7546         if (win->ws->r)
7547                 stack();
7548
7549         /* The new window should get focus. */
7550         if (focus_mode != SWM_FOCUS_FOLLOW)
7551                 win->ws->focus_pending = get_focus_magic(win);
7552
7553         /* Ignore EnterNotify to handle the mapnotify without interference. */
7554         if (focus_mode == SWM_FOCUS_DEFAULT)
7555                 event_drain(XCB_ENTER_NOTIFY);
7556 out:
7557         free(war);
7558         DNPRINTF(SWM_D_EVENT, "maprequest: done.\n");
7559 }
7560
7561 #ifdef SWM_DEBUG
7562 char *
7563 get_atom_name(xcb_atom_t atom)
7564 {
7565         char                            *name = NULL;
7566 #if 0
7567         /*
7568          * This should be disabled during most debugging since
7569          * xcb_get_* causes an xcb_flush.
7570          */
7571         size_t                          len;
7572         xcb_get_atom_name_reply_t       *r;
7573
7574         r = xcb_get_atom_name_reply(conn,
7575             xcb_get_atom_name(conn, atom),
7576             NULL);
7577         if (r) {
7578                 len = xcb_get_atom_name_name_length(r);
7579                 if (len > 0) {
7580                         name = malloc(len + 1);
7581                         if (name) {
7582                                 memcpy(name, xcb_get_atom_name_name(r), len);
7583                                 name[len] = '\0';
7584                         }
7585                 }
7586                 free(r);
7587         }
7588 #else
7589         (void)atom;
7590 #endif
7591         return (name);
7592 }
7593 #endif
7594
7595 void
7596 propertynotify(xcb_property_notify_event_t *e)
7597 {
7598         struct ws_win           *win;
7599 #ifdef SWM_DEBUG
7600         char                    *name;
7601
7602         name = get_atom_name(e->atom);
7603         DNPRINTF(SWM_D_EVENT, "propertynotify: window: 0x%x, atom: %s(%u), "
7604             "time: %#x\n", e->window, name, e->atom, e->time);
7605         free(name);
7606 #endif
7607         win = find_window(e->window);
7608         if (win == NULL)
7609                 return;
7610
7611         last_event_time = e->time;
7612
7613         if (e->atom == a_swm_iconic) {
7614                 if (e->state == XCB_PROPERTY_NEW_VALUE) {
7615                         if (focus_mode != SWM_FOCUS_FOLLOW)
7616                                 win->ws->focus_pending = get_focus_prev(win);
7617
7618                         unfocus_win(win);
7619                         unmap_window(win);
7620
7621                         if (win->ws->r) {
7622                                 stack();
7623                                 if (focus_mode != SWM_FOCUS_FOLLOW) {
7624                                         focus_win(win->ws->focus_pending);
7625                                         win->ws->focus_pending = NULL;
7626                                 }
7627                                 focus_flush();
7628                         }
7629                 } else if (e->state == XCB_PROPERTY_DELETE) {
7630                         /* The window is no longer iconic, restack ws. */
7631                         if (focus_mode != SWM_FOCUS_FOLLOW)
7632                                 win->ws->focus_pending = get_focus_magic(win);
7633
7634                         stack();
7635
7636                         /* Flush EnterNotify for mapnotify, if needed. */
7637                         focus_flush();
7638                 }
7639         } else if (e->atom == a_state) {
7640                 /* State just changed, make sure it gets focused if mapped. */
7641                 if (e->state == XCB_PROPERTY_NEW_VALUE) {
7642                         if (focus_mode != SWM_FOCUS_FOLLOW) {
7643                                 if (win->mapped &&
7644                                     win->ws->focus_pending == win) {
7645                                         focus_win(win->ws->focus_pending);
7646                                         win->ws->focus_pending = NULL;
7647                                 }
7648                         }
7649                 }
7650         } else if (e->atom == XCB_ATOM_WM_CLASS ||
7651             e->atom == XCB_ATOM_WM_NAME) {
7652                 bar_update();
7653         }
7654
7655         xcb_flush(conn);
7656 }
7657
7658 void
7659 unmapnotify(xcb_unmap_notify_event_t *e)
7660 {
7661         struct ws_win           *win;
7662         struct workspace        *ws;
7663
7664         DNPRINTF(SWM_D_EVENT, "unmapnotify: window: 0x%x\n", e->window);
7665
7666         /* determine if we need to help unmanage this window */
7667         win = find_window(e->window);
7668         if (win == NULL)
7669                 return;
7670
7671         ws = win->ws;
7672
7673         if (getstate(e->window) == XCB_ICCCM_WM_STATE_NORMAL) {
7674                 win->mapped = 0;
7675                 set_win_state(win, XCB_ICCCM_WM_STATE_ICONIC);
7676
7677                 /* If we were focused, make sure we focus on something else. */
7678                 if (win == ws->focus)
7679                         if (focus_mode != SWM_FOCUS_FOLLOW)
7680                                 ws->focus_pending = get_focus_prev(win);
7681
7682                 unfocus_win(win);
7683                 unmanage_window(win);
7684                 stack();
7685
7686                 DNPRINTF(SWM_D_EVENT, "unmapnotify: focus_pending: 0x%x\n",
7687                     ws->focus_pending->id);
7688
7689                 if (focus_mode != SWM_FOCUS_FOLLOW) {
7690                         if (ws->focus_pending) {
7691                                 focus_win(ws->focus_pending);
7692                                 ws->focus_pending = NULL;
7693                         }
7694                 }
7695
7696                 focus_flush();
7697         }
7698 }
7699
7700 #if 0
7701 void
7702 visibilitynotify(xcb_visibility_notify_event_t *e)
7703 {
7704         DNPRINTF(SWM_D_EVENT, "visibilitynotify: window: 0x%x\n",
7705             e->window);
7706 }
7707 #endif
7708
7709 void
7710 clientmessage(xcb_client_message_event_t *e)
7711 {
7712         struct ws_win *win;
7713         xcb_map_request_event_t mre;
7714 #ifdef SWM_DEBUG
7715         char                    *name;
7716
7717         name = get_atom_name(e->type);
7718         DNPRINTF(SWM_D_EVENT, "clientmessage: window: 0x%x, atom: %s(%u)\n",
7719             e->window, name, e->type);
7720         free(name);
7721 #endif
7722         win = find_window(e->window);
7723
7724         if (win == NULL) {
7725                 if (e->type == ewmh[_NET_ACTIVE_WINDOW].atom) {
7726                         DNPRINTF(SWM_D_EVENT, "clientmessage: request focus on "
7727                             "unmanaged window.\n");
7728                         mre.window = e->window;
7729                         maprequest(&mre);
7730                 }
7731                 return;
7732         }
7733
7734         if (e->type == ewmh[_NET_ACTIVE_WINDOW].atom) {
7735                 DNPRINTF(SWM_D_EVENT, "clientmessage: _NET_ACTIVE_WINDOW\n");
7736                 focus_win(win);
7737         }
7738         if (e->type == ewmh[_NET_CLOSE_WINDOW].atom) {
7739                 DNPRINTF(SWM_D_EVENT, "clientmessage: _NET_CLOSE_WINDOW\n");
7740                 if (win->can_delete)
7741                         client_msg(win, a_delete, 0);
7742                 else
7743                         xcb_kill_client(conn, win->id);
7744         }
7745         if (e->type == ewmh[_NET_MOVERESIZE_WINDOW].atom) {
7746                 DNPRINTF(SWM_D_EVENT,
7747                     "clientmessage: _NET_MOVERESIZE_WINDOW\n");
7748                 if (win->floating) {
7749                         if (e->data.data32[0] & (1<<8)) /* x */
7750                                 X(win) = e->data.data32[1];
7751                         if (e->data.data32[0] & (1<<9)) /* y */
7752                                 Y(win) = e->data.data32[2];
7753                         if (e->data.data32[0] & (1<<10)) /* width */
7754                                 WIDTH(win) = e->data.data32[3];
7755                         if (e->data.data32[0] & (1<<11)) /* height */
7756                                 HEIGHT(win) = e->data.data32[4];
7757
7758                         update_window(win);
7759                 }
7760                 else {
7761                         /* TODO: Change stack sizes */
7762                         /* notify no change was made. */
7763                         config_win(win, NULL);
7764                 }
7765         }
7766         if (e->type == ewmh[_NET_WM_STATE].atom) {
7767                 DNPRINTF(SWM_D_EVENT, "clientmessage: _NET_WM_STATE\n");
7768                 ewmh_update_win_state(win, e->data.data32[1], e->data.data32[0]);
7769                 if (e->data.data32[2])
7770                         ewmh_update_win_state(win, e->data.data32[2],
7771                             e->data.data32[0]);
7772
7773                 stack();
7774         }
7775
7776         xcb_flush(conn);
7777 }
7778
7779 void
7780 check_conn(void)
7781 {
7782         int      errcode = xcb_connection_has_error(conn);
7783 #ifdef XCB_CONN_ERROR
7784         char    *s;
7785         switch (errcode) {
7786         case XCB_CONN_ERROR:
7787                 s = "Socket error, pipe error or other stream error.";
7788                 break;
7789         case XCB_CONN_CLOSED_EXT_NOTSUPPORTED:
7790                 s = "Extension not supported.";
7791                 break;
7792         case XCB_CONN_CLOSED_MEM_INSUFFICIENT:
7793                 s = "Insufficient memory.";
7794                 break;
7795         case XCB_CONN_CLOSED_REQ_LEN_EXCEED:
7796                 s = "Request length was exceeded.";
7797                 break;
7798         case XCB_CONN_CLOSED_PARSE_ERR:
7799                 s = "Error parsing display string.";
7800                 break;
7801         default:
7802                 s = "Unknown error.";
7803         }
7804         if (errcode)
7805                 errx(errcode, "X CONNECTION ERROR: %s", s);
7806 #else
7807         if (errcode)
7808                 errx(errcode, "X CONNECTION ERROR");
7809 #endif
7810 }
7811
7812 int
7813 enable_wm(void)
7814 {
7815         int                     num_screens, i;
7816         const uint32_t          val = XCB_EVENT_MASK_SUBSTRUCTURE_REDIRECT;
7817         xcb_screen_t            *sc;
7818         xcb_void_cookie_t       wac;
7819         xcb_generic_error_t     *error;
7820
7821         /* this causes an error if some other window manager is running */
7822         num_screens = xcb_setup_roots_length(xcb_get_setup(conn));
7823         for (i = 0; i < num_screens; i++) {
7824                 if ((sc = get_screen(i)) == NULL)
7825                         errx(1, "ERROR: can't get screen %d.", i);
7826                 DNPRINTF(SWM_D_INIT, "enable_wm: screen %d, root: 0x%x\n",
7827                     i, sc->root);
7828                 wac = xcb_change_window_attributes_checked(conn, sc->root,
7829                     XCB_CW_EVENT_MASK, &val);
7830                 if ((error = xcb_request_check(conn, wac))) {
7831                         DNPRINTF(SWM_D_INIT, "enable_wm: error_code: %u\n",
7832                             error->error_code);
7833                         free(error);
7834                         return 1;
7835                 }
7836         }
7837
7838         return 0;
7839 }
7840
7841 void
7842 new_region(struct swm_screen *s, int x, int y, int w, int h)
7843 {
7844         struct swm_region       *r, *n;
7845         struct workspace        *ws = NULL;
7846         int                     i;
7847
7848         DNPRINTF(SWM_D_MISC, "new region: screen[%d]:%dx%d+%d+%d\n",
7849              s->idx, w, h, x, y);
7850
7851         /* remove any conflicting regions */
7852         n = TAILQ_FIRST(&s->rl);
7853         while (n) {
7854                 r = n;
7855                 n = TAILQ_NEXT(r, entry);
7856                 if (X(r) < (x + w) &&
7857                     (X(r) + WIDTH(r)) > x &&
7858                     Y(r) < (y + h) &&
7859                     (Y(r) + HEIGHT(r)) > y) {
7860                         if (r->ws->r != NULL)
7861                                 r->ws->old_r = r->ws->r;
7862                         r->ws->r = NULL;
7863                         bar_cleanup(r);
7864                         TAILQ_REMOVE(&s->rl, r, entry);
7865                         TAILQ_INSERT_TAIL(&s->orl, r, entry);
7866                 }
7867         }
7868
7869         /* search old regions for one to reuse */
7870
7871         /* size + location match */
7872         TAILQ_FOREACH(r, &s->orl, entry)
7873                 if (X(r) == x && Y(r) == y &&
7874                     HEIGHT(r) == h && WIDTH(r) == w)
7875                         break;
7876
7877         /* size match */
7878         TAILQ_FOREACH(r, &s->orl, entry)
7879                 if (HEIGHT(r) == h && WIDTH(r) == w)
7880                         break;
7881
7882         if (r != NULL) {
7883                 TAILQ_REMOVE(&s->orl, r, entry);
7884                 /* try to use old region's workspace */
7885                 if (r->ws->r == NULL)
7886                         ws = r->ws;
7887         } else
7888                 if ((r = calloc(1, sizeof(struct swm_region))) == NULL)
7889                         err(1, "new_region: calloc: failed to allocate memory "
7890                             "for screen");
7891
7892         /* if we don't have a workspace already, find one */
7893         if (ws == NULL) {
7894                 for (i = 0; i < workspace_limit; i++)
7895                         if (s->ws[i].r == NULL) {
7896                                 ws = &s->ws[i];
7897                                 break;
7898                         }
7899         }
7900
7901         if (ws == NULL)
7902                 errx(1, "new_region: no free workspaces");
7903
7904         X(r) = x;
7905         Y(r) = y;
7906         WIDTH(r) = w;
7907         HEIGHT(r) = h;
7908         r->s = s;
7909         r->ws = ws;
7910         r->ws_prior = NULL;
7911         ws->r = r;
7912         outputs++;
7913         TAILQ_INSERT_TAIL(&s->rl, r, entry);
7914 }
7915
7916 void
7917 scan_xrandr(int i)
7918 {
7919 #ifdef SWM_XRR_HAS_CRTC
7920         int                                             c;
7921         int                                             ncrtc = 0;
7922 #endif /* SWM_XRR_HAS_CRTC */
7923         struct swm_region                               *r;
7924         int                                             num_screens;
7925         xcb_randr_get_screen_resources_current_cookie_t src;
7926         xcb_randr_get_screen_resources_current_reply_t  *srr;
7927         xcb_randr_get_crtc_info_cookie_t                cic;
7928         xcb_randr_get_crtc_info_reply_t                 *cir = NULL;
7929         xcb_randr_crtc_t                                *crtc;
7930         xcb_screen_t                                    *screen;
7931
7932         if ((screen = get_screen(i)) == NULL)
7933                 errx(1, "ERROR: can't get screen %d.", i);
7934
7935         num_screens = xcb_setup_roots_length(xcb_get_setup(conn));
7936         if (i >= num_screens)
7937                 errx(1, "scan_xrandr: invalid screen");
7938
7939         /* remove any old regions */
7940         while ((r = TAILQ_FIRST(&screens[i].rl)) != NULL) {
7941                 r->ws->old_r = r->ws->r = NULL;
7942                 bar_cleanup(r);
7943                 TAILQ_REMOVE(&screens[i].rl, r, entry);
7944                 TAILQ_INSERT_TAIL(&screens[i].orl, r, entry);
7945         }
7946         outputs = 0;
7947
7948         /* map virtual screens onto physical screens */
7949 #ifdef SWM_XRR_HAS_CRTC
7950         if (xrandr_support) {
7951                 src = xcb_randr_get_screen_resources_current(conn,
7952                     screens[i].root);
7953                 srr = xcb_randr_get_screen_resources_current_reply(conn, src,
7954                     NULL);
7955                 if (srr == NULL) {
7956                         new_region(&screens[i], 0, 0,
7957                             screen->width_in_pixels,
7958                             screen->height_in_pixels);
7959                         return;
7960                 } else
7961                         ncrtc = srr->num_crtcs;
7962
7963                 crtc = xcb_randr_get_screen_resources_current_crtcs(srr);
7964                 for (c = 0; c < ncrtc; c++) {
7965                         cic = xcb_randr_get_crtc_info(conn, crtc[c],
7966                             XCB_CURRENT_TIME);
7967                         cir = xcb_randr_get_crtc_info_reply(conn, cic, NULL);
7968                         if (cir == NULL)
7969                                 continue;
7970                         if (cir->num_outputs == 0) {
7971                                 free(cir);
7972                                 continue;
7973                         }
7974
7975                         if (cir->mode == 0)
7976                                 new_region(&screens[i], 0, 0,
7977                                     screen->width_in_pixels,
7978                                     screen->height_in_pixels);
7979                         else
7980                                 new_region(&screens[i],
7981                                     cir->x, cir->y, cir->width, cir->height);
7982                         free(cir);
7983                 }
7984                 free(srr);
7985         } else
7986 #endif /* SWM_XRR_HAS_CRTC */
7987         {
7988                 new_region(&screens[i], 0, 0, screen->width_in_pixels,
7989                     screen->height_in_pixels);
7990         }
7991 }
7992
7993 void
7994 screenchange(xcb_randr_screen_change_notify_event_t *e)
7995 {
7996         struct swm_region               *r;
7997         int                             i, num_screens;
7998
7999         DNPRINTF(SWM_D_EVENT, "screenchange: root: 0x%x\n", e->root);
8000
8001         num_screens = xcb_setup_roots_length(xcb_get_setup(conn));
8002         /* silly event doesn't include the screen index */
8003         for (i = 0; i < num_screens; i++)
8004                 if (screens[i].root == e->root)
8005                         break;
8006         if (i >= num_screens)
8007                 errx(1, "screenchange: screen not found");
8008
8009         /* brute force for now, just re-enumerate the regions */
8010         scan_xrandr(i);
8011
8012 #ifdef SWM_DEBUG
8013         print_win_geom(e->root);
8014 #endif
8015         /* add bars to all regions */
8016         for (i = 0; i < num_screens; i++)
8017                 TAILQ_FOREACH(r, &screens[i].rl, entry)
8018                         bar_setup(r);
8019         stack();
8020 }
8021
8022 void
8023 grab_windows(void)
8024 {
8025         xcb_window_t            *wins   = NULL;
8026         int                     no;
8027         int                     i, j, num_screens;
8028         uint16_t                state, manage, mapped;
8029
8030         xcb_query_tree_cookie_t                 qtc;
8031         xcb_query_tree_reply_t                  *qtr;
8032         xcb_get_window_attributes_cookie_t      c;
8033         xcb_get_window_attributes_reply_t       *r;
8034         xcb_get_property_cookie_t               pc;
8035
8036         DNPRINTF(SWM_D_INIT, "grab_windows: begin\n");
8037         num_screens = xcb_setup_roots_length(xcb_get_setup(conn));
8038         for (i = 0; i < num_screens; i++) {
8039                 qtc = xcb_query_tree(conn, screens[i].root);
8040                 qtr = xcb_query_tree_reply(conn, qtc, NULL);
8041                 if (!qtr)
8042                         continue;
8043                 wins = xcb_query_tree_children(qtr);
8044                 no = xcb_query_tree_children_length(qtr);
8045                 /* attach windows to a region */
8046                 /* normal windows */
8047                 for (j = 0; j < no; j++) {
8048                         c = xcb_get_window_attributes(conn, wins[j]);
8049                         r = xcb_get_window_attributes_reply(conn, c, NULL);
8050                         if (!r)
8051                                 continue;
8052                         if (r->override_redirect) {
8053                                 free(r);
8054                                 continue;
8055                         }
8056
8057                         pc = xcb_icccm_get_wm_transient_for(conn, wins[j]);
8058                         if (xcb_icccm_get_wm_transient_for_reply(conn, pc,
8059                             &wins[j], NULL)) {
8060                                 free(r);
8061                                 continue;
8062                         }
8063
8064                         state = getstate(wins[j]);
8065                         manage = state == XCB_ICCCM_WM_STATE_ICONIC;
8066                         mapped = r->map_state != XCB_MAP_STATE_UNMAPPED;
8067                         if (mapped || manage)
8068                                 manage_window(wins[j], mapped);
8069                         free(r);
8070                 }
8071                 /* transient windows */
8072                 for (j = 0; j < no; j++) {
8073                         c = xcb_get_window_attributes(conn, wins[j]);
8074                         r = xcb_get_window_attributes_reply(conn, c, NULL);
8075                         if (!r)
8076                                 continue;
8077                         if (r->override_redirect) {
8078                                 free(r);
8079                                 continue;
8080                         }
8081                         free(r);
8082
8083                         state = getstate(wins[j]);
8084                         manage = state == XCB_ICCCM_WM_STATE_ICONIC;
8085                         mapped = r->map_state != XCB_MAP_STATE_UNMAPPED;
8086                         pc = xcb_icccm_get_wm_transient_for(conn, wins[j]);
8087                         if (xcb_icccm_get_wm_transient_for_reply(conn, pc,
8088                             &wins[j], NULL) && manage)
8089                                 manage_window(wins[j], mapped);
8090                 }
8091                 free(qtr);
8092         }
8093         DNPRINTF(SWM_D_INIT, "grab_windows: done.\n");
8094 }
8095
8096 void
8097 setup_screens(void)
8098 {
8099         int                     i, j, k, num_screens;
8100         struct workspace        *ws;
8101         uint32_t                gcv[1], wa[1];
8102         const xcb_query_extension_reply_t *qep;
8103         xcb_screen_t                            *screen;
8104         xcb_cursor_t                            cursor;
8105         xcb_font_t                              cursor_font;
8106         xcb_randr_query_version_cookie_t        c;
8107         xcb_randr_query_version_reply_t         *r;
8108
8109         num_screens = xcb_setup_roots_length(xcb_get_setup(conn));
8110         if ((screens = calloc(num_screens,
8111              sizeof(struct swm_screen))) == NULL)
8112                 err(1, "setup_screens: calloc: failed to allocate memory for "
8113                     "screens");
8114
8115         /* initial Xrandr setup */
8116         xrandr_support = 0;
8117         qep = xcb_get_extension_data(conn, &xcb_randr_id);
8118         if (qep->present) {
8119                 c = xcb_randr_query_version(conn, 1, 1);
8120                 r = xcb_randr_query_version_reply(conn, c, NULL);
8121                 if (r) {
8122                         if (r->major_version >= 1) {
8123                                 xrandr_support = 1;
8124                                 xrandr_eventbase = qep->first_event;
8125                         }
8126                         free(r);
8127                 }
8128         }
8129
8130         cursor_font = xcb_generate_id(conn);
8131         xcb_open_font(conn, cursor_font, strlen("cursor"), "cursor");
8132
8133         cursor = xcb_generate_id(conn);
8134         xcb_create_glyph_cursor(conn, cursor, cursor_font, cursor_font,
8135             XC_left_ptr, XC_left_ptr + 1, 0, 0, 0, 0xffff, 0xffff, 0xffff);
8136         wa[0] = cursor;
8137
8138         /* map physical screens */
8139         for (i = 0; i < num_screens; i++) {
8140                 DNPRINTF(SWM_D_WS, "setup_screens: init screen: %d\n", i);
8141                 screens[i].idx = i;
8142                 TAILQ_INIT(&screens[i].rl);
8143                 TAILQ_INIT(&screens[i].orl);
8144                 if ((screen = get_screen(i)) == NULL)
8145                         errx(1, "ERROR: can't get screen %d.", i);
8146                 screens[i].root = screen->root;
8147
8148                 /* set default colors */
8149                 setscreencolor("red", i + 1, SWM_S_COLOR_FOCUS);
8150                 setscreencolor("rgb:88/88/88", i + 1, SWM_S_COLOR_UNFOCUS);
8151                 setscreencolor("rgb:00/80/80", i + 1, SWM_S_COLOR_BAR_BORDER);
8152                 setscreencolor("black", i + 1, SWM_S_COLOR_BAR);
8153                 setscreencolor("rgb:a0/a0/a0", i + 1, SWM_S_COLOR_BAR_FONT);
8154
8155                 /* create graphics context on screen */
8156                 screens[i].bar_gc = xcb_generate_id(conn);
8157                 gcv[0] = 0;
8158                 xcb_create_gc(conn, screens[i].bar_gc, screens[i].root,
8159                     XCB_GC_GRAPHICS_EXPOSURES, gcv);
8160
8161                 /* set default cursor */
8162                 xcb_change_window_attributes(conn, screens[i].root,
8163                     XCB_CW_CURSOR, wa);
8164
8165                 /* init all workspaces */
8166                 /* XXX these should be dynamically allocated too */
8167                 for (j = 0; j < SWM_WS_MAX; j++) {
8168                         ws = &screens[i].ws[j];
8169                         ws->idx = j;
8170                         ws->name = NULL;
8171                         ws->focus = NULL;
8172                         ws->focus_prev = NULL;
8173                         ws->focus_pending = NULL;
8174                         ws->r = NULL;
8175                         ws->old_r = NULL;
8176                         TAILQ_INIT(&ws->winlist);
8177                         TAILQ_INIT(&ws->unmanagedlist);
8178
8179                         for (k = 0; layouts[k].l_stack != NULL; k++)
8180                                 if (layouts[k].l_config != NULL)
8181                                         layouts[k].l_config(ws,
8182                                             SWM_ARG_ID_STACKINIT);
8183                         ws->cur_layout = &layouts[0];
8184                         ws->cur_layout->l_string(ws);
8185                 }
8186
8187                 scan_xrandr(i);
8188
8189                 if (xrandr_support)
8190                         xcb_randr_select_input(conn, screens[i].root,
8191                             XCB_RANDR_NOTIFY_MASK_SCREEN_CHANGE);
8192         }
8193         xcb_free_cursor(conn, cursor);
8194         xcb_close_font(conn, cursor_font);
8195 }
8196
8197 void
8198 setup_globals(void)
8199 {
8200         if ((bar_fonts = strdup(SWM_BAR_FONTS)) == NULL)
8201                 err(1, "setup_globals: strdup: failed to allocate memory.");
8202
8203         if ((clock_format = strdup("%a %b %d %R %Z %Y")) == NULL)
8204                 err(1, "setup_globals: strdup: failed to allocate memory.");
8205
8206         if ((syms = xcb_key_symbols_alloc(conn)) == NULL)
8207                 errx(1, "unable to allocate key symbols");
8208
8209         a_state = get_atom_from_string("WM_STATE");
8210         a_prot = get_atom_from_string("WM_PROTOCOLS");
8211         a_delete = get_atom_from_string("WM_DELETE_WINDOW");
8212         a_takefocus = get_atom_from_string("WM_TAKE_FOCUS");
8213         a_wmname = get_atom_from_string("WM_NAME");
8214         a_netwmname = get_atom_from_string("_NET_WM_NAME");
8215         a_utf8_string = get_atom_from_string("UTF8_STRING");
8216         a_string = get_atom_from_string("STRING");
8217         a_swm_iconic = get_atom_from_string("_SWM_ICONIC");
8218         a_swm_ws = get_atom_from_string("_SWM_WS");
8219 }
8220
8221 void
8222 workaround(void)
8223 {
8224         int                     i, num_screens;
8225         xcb_atom_t              netwmcheck;
8226         xcb_window_t            root, win;
8227
8228         /* work around sun jdk bugs, code from wmname */
8229         netwmcheck = get_atom_from_string("_NET_SUPPORTING_WM_CHECK");
8230
8231         num_screens = xcb_setup_roots_length(xcb_get_setup(conn));
8232         for (i = 0; i < num_screens; i++) {
8233                 root = screens[i].root;
8234
8235                 win = xcb_generate_id(conn);
8236                 xcb_create_window(conn, XCB_COPY_FROM_PARENT, win, root,
8237                     0, 0, 1, 1, 0, XCB_WINDOW_CLASS_INPUT_OUTPUT,
8238                     XCB_COPY_FROM_PARENT, 0, NULL);
8239
8240                 xcb_change_property(conn, XCB_PROP_MODE_REPLACE, root,
8241                     netwmcheck, XCB_ATOM_WINDOW, 32, 1, &win);
8242                 xcb_change_property(conn, XCB_PROP_MODE_REPLACE, win,
8243                     netwmcheck, XCB_ATOM_WINDOW, 32, 1, &win);
8244                 xcb_change_property(conn, XCB_PROP_MODE_REPLACE, win,
8245                     a_netwmname, a_utf8_string, 8, strlen("LG3D"), "LG3D");
8246         }
8247 }
8248
8249 void
8250 shutdown_cleanup(void)
8251 {
8252         int i, num_screens;
8253
8254         /* disable alarm because the following code may not be interrupted */
8255         alarm(0);
8256         if (signal(SIGALRM, SIG_IGN) == SIG_ERR)
8257                 err(1, "can't disable alarm");
8258
8259         bar_extra_stop();
8260         bar_extra = 1;
8261         unmap_all();
8262
8263         teardown_ewmh();
8264
8265         num_screens = xcb_setup_roots_length(xcb_get_setup(conn));
8266         for (i = 0; i < num_screens; ++i) {
8267                 if (screens[i].bar_gc != 0)
8268                         xcb_free_gc(conn, screens[i].bar_gc);
8269                 if (!bar_font_legacy)
8270                         XftColorFree(display, DefaultVisual(display, i),
8271                             DefaultColormap(display, i), &bar_font_color);
8272         }
8273
8274         if (bar_font_legacy)
8275                 XFreeFontSet(display, bar_fs);
8276         else {
8277                 XftFontClose(display, bar_font);
8278         }
8279
8280         xcb_key_symbols_free(syms);
8281         xcb_flush(conn);
8282         xcb_disconnect(conn);
8283 }
8284
8285 void
8286 event_error(xcb_generic_error_t *e)
8287 {
8288         (void)e;
8289
8290         DNPRINTF(SWM_D_EVENT, "event_error: %s(%u) from %s(%u), sequence: %u, "
8291             "resource_id: %u, minor_code: %u\n",
8292             xcb_event_get_error_label(e->error_code), e->error_code,
8293             xcb_event_get_request_label(e->major_code), e->major_code,
8294             e->sequence, e->resource_id, e->minor_code);
8295 }
8296
8297 void
8298 event_handle(xcb_generic_event_t *evt)
8299 {
8300         uint8_t type = XCB_EVENT_RESPONSE_TYPE(evt);
8301
8302         DNPRINTF(SWM_D_EVENT, "XCB Event: %s(%d), seq %u\n",
8303             xcb_event_get_label(XCB_EVENT_RESPONSE_TYPE(evt)),
8304             XCB_EVENT_RESPONSE_TYPE(evt), evt->sequence);
8305
8306         switch (type) {
8307 #define EVENT(type, callback) case type: callback((void *)evt); return
8308         EVENT(0, event_error);
8309         EVENT(XCB_BUTTON_PRESS, buttonpress);
8310         /*EVENT(XCB_BUTTON_RELEASE, buttonpress);*/
8311         /*EVENT(XCB_CIRCULATE_NOTIFY, );*/
8312         /*EVENT(XCB_CIRCULATE_REQUEST, );*/
8313         EVENT(XCB_CLIENT_MESSAGE, clientmessage);
8314         /*EVENT(XCB_COLORMAP_NOTIFY, );*/
8315         EVENT(XCB_CONFIGURE_NOTIFY, configurenotify);
8316         EVENT(XCB_CONFIGURE_REQUEST, configurerequest);
8317         /*EVENT(XCB_CREATE_NOTIFY, );*/
8318         EVENT(XCB_DESTROY_NOTIFY, destroynotify);
8319         EVENT(XCB_ENTER_NOTIFY, enternotify);
8320         EVENT(XCB_EXPOSE, expose);
8321 #ifdef SWM_DEBUG
8322         EVENT(XCB_FOCUS_IN, focusin);
8323         EVENT(XCB_FOCUS_OUT, focusout);
8324 #endif
8325         /*EVENT(XCB_GRAPHICS_EXPOSURE, );*/
8326         /*EVENT(XCB_GRAVITY_NOTIFY, );*/
8327         EVENT(XCB_KEY_PRESS, keypress);
8328         /*EVENT(XCB_KEY_RELEASE, keypress);*/
8329         /*EVENT(XCB_KEYMAP_NOTIFY, );*/
8330 #ifdef SWM_DEBUG
8331         EVENT(XCB_LEAVE_NOTIFY, leavenotify);
8332 #endif
8333         EVENT(XCB_MAP_NOTIFY, mapnotify);
8334         EVENT(XCB_MAP_REQUEST, maprequest);
8335         EVENT(XCB_MAPPING_NOTIFY, mappingnotify);
8336         /*EVENT(XCB_MOTION_NOTIFY, );*/
8337         /*EVENT(XCB_NO_EXPOSURE, );*/
8338         EVENT(XCB_PROPERTY_NOTIFY, propertynotify);
8339         /*EVENT(XCB_REPARENT_NOTIFY, );*/
8340         /*EVENT(XCB_RESIZE_REQUEST, );*/
8341         /*EVENT(XCB_SELECTION_CLEAR, );*/
8342         /*EVENT(XCB_SELECTION_NOTIFY, );*/
8343         /*EVENT(XCB_SELECTION_REQUEST, );*/
8344         EVENT(XCB_UNMAP_NOTIFY, unmapnotify);
8345         /*EVENT(XCB_VISIBILITY_NOTIFY, visibilitynotify);*/
8346 #undef EVENT
8347         }
8348         if (type - xrandr_eventbase == XCB_RANDR_SCREEN_CHANGE_NOTIFY)
8349                 screenchange((void *)evt);
8350 }
8351
8352 int
8353 main(int argc, char *argv[])
8354 {
8355         struct swm_region       *r, *rr;
8356         struct ws_win           *winfocus = NULL;
8357         char                    conf[PATH_MAX], *cfile = NULL;
8358         struct stat             sb;
8359         int                     xfd, i, num_screens;
8360         struct sigaction        sact;
8361         xcb_generic_event_t     *evt;
8362         struct timeval          tv;
8363         fd_set                  rd;
8364
8365         /* suppress unused warning since var is needed */
8366         (void)argc;
8367
8368         time_started = time(NULL);
8369
8370         start_argv = argv;
8371         warnx("Welcome to spectrwm V%s Build: %s", SPECTRWM_VERSION, buildstr);
8372         if (!setlocale(LC_CTYPE, "") || !setlocale(LC_TIME, ""))
8373                 warnx("no locale support");
8374
8375         /* handle some signals */
8376         bzero(&sact, sizeof(sact));
8377         sigemptyset(&sact.sa_mask);
8378         sact.sa_flags = 0;
8379         sact.sa_handler = sighdlr;
8380         sigaction(SIGINT, &sact, NULL);
8381         sigaction(SIGQUIT, &sact, NULL);
8382         sigaction(SIGTERM, &sact, NULL);
8383         sigaction(SIGHUP, &sact, NULL);
8384
8385         sact.sa_handler = sighdlr;
8386         sact.sa_flags = SA_NOCLDSTOP;
8387         sigaction(SIGCHLD, &sact, NULL);
8388
8389         if (!(display = XOpenDisplay(0)))
8390                 errx(1, "can not open display");
8391
8392         conn = XGetXCBConnection(display);
8393         if (xcb_connection_has_error(conn))
8394                 errx(1, "can not get XCB connection");
8395
8396         XSetEventQueueOwner(display, XCBOwnsEventQueue);
8397
8398         xcb_prefetch_extension_data(conn, &xcb_randr_id);
8399         xfd = xcb_get_file_descriptor(conn);
8400
8401         /* look for local and global conf file */
8402         pwd = getpwuid(getuid());
8403         if (pwd == NULL)
8404                 errx(1, "invalid user: %d", getuid());
8405
8406         xcb_grab_server(conn);
8407         xcb_aux_sync(conn);
8408
8409         /* flush all events */
8410         while ((evt = xcb_poll_for_event(conn))) {
8411                 if (XCB_EVENT_RESPONSE_TYPE(evt) == 0)
8412                         event_handle(evt);
8413                 free(evt);
8414         }
8415
8416         if (enable_wm() != 0)
8417                 errx(1, "another window manager is currently running");
8418
8419         xcb_aux_sync(conn);
8420
8421         setup_globals();
8422         setup_screens();
8423         setup_keys();
8424         setup_quirks();
8425         setup_spawn();
8426
8427         /* load config */
8428         for (i = 0; ; i++) {
8429                 conf[0] = '\0';
8430                 switch (i) {
8431                 case 0:
8432                         /* ~ */
8433                         snprintf(conf, sizeof conf, "%s/.%s",
8434                             pwd->pw_dir, SWM_CONF_FILE);
8435                         break;
8436                 case 1:
8437                         /* global */
8438                         snprintf(conf, sizeof conf, "/etc/%s",
8439                             SWM_CONF_FILE);
8440                         break;
8441                 case 2:
8442                         /* ~ compat */
8443                         snprintf(conf, sizeof conf, "%s/.%s",
8444                             pwd->pw_dir, SWM_CONF_FILE_OLD);
8445                         break;
8446                 case 3:
8447                         /* global compat */
8448                         snprintf(conf, sizeof conf, "/etc/%s",
8449                             SWM_CONF_FILE_OLD);
8450                         break;
8451                 default:
8452                         goto noconfig;
8453                 }
8454
8455                 if (strlen(conf) && stat(conf, &sb) != -1)
8456                         if (S_ISREG(sb.st_mode)) {
8457                                 cfile = conf;
8458                                 break;
8459                         }
8460         }
8461 noconfig:
8462
8463         /* load conf (if any) */
8464         if (cfile)
8465                 conf_load(cfile, SWM_CONF_DEFAULT);
8466
8467         setup_ewmh();
8468         /* set some values to work around bad programs */
8469         workaround();
8470         /* grab existing windows (before we build the bars) */
8471         grab_windows();
8472
8473         if (getenv("SWM_STARTED") == NULL)
8474                 setenv("SWM_STARTED", "YES", 1);
8475
8476         /* setup all bars */
8477         num_screens = xcb_setup_roots_length(xcb_get_setup(conn));
8478         for (i = 0; i < num_screens; i++)
8479                 TAILQ_FOREACH(r, &screens[i].rl, entry) {
8480                         if (winfocus == NULL)
8481                                 winfocus = TAILQ_FIRST(&r->ws->winlist);
8482                         bar_setup(r);
8483                 }
8484
8485         grabkeys();
8486         stack();
8487
8488         xcb_ungrab_server(conn);
8489         xcb_flush(conn);
8490
8491         while (running) {
8492                 while ((evt = xcb_poll_for_event(conn))) {
8493                         if (!running)
8494                                 goto done;
8495                         event_handle(evt);
8496                         free(evt);
8497                 }
8498
8499                 /* if we are being restarted go focus on first window */
8500                 if (winfocus) {
8501                         rr = winfocus->ws->r;
8502                         if (rr == NULL) {
8503                                 /* not a visible window */
8504                                 winfocus = NULL;
8505                                 continue;
8506                         }
8507                         /* move pointer to first screen if multi screen */
8508                         if (num_screens > 1 || outputs > 1)
8509                                 xcb_warp_pointer(conn, XCB_WINDOW_NONE,
8510                                     rr->s[0].root, 0, 0, 0, 0, X(rr),
8511                                     Y(rr) + (bar_enabled ? bar_height : 0));
8512
8513                         focus_win(get_region_focus(rr));
8514                         focus_flush();
8515                         winfocus = NULL;
8516                         continue;
8517                 }
8518
8519                 FD_ZERO(&rd);
8520                 FD_SET(xfd, &rd);
8521                 tv.tv_sec = 1;
8522                 tv.tv_usec = 0;
8523                 if (select(xfd + 1, &rd, NULL, NULL, &tv) == -1)
8524                         if (errno != EINTR) {
8525                                 DNPRINTF(SWM_D_MISC, "select failed");
8526                         }
8527                 if (restart_wm)
8528                         restart(NULL, NULL);
8529                 if (search_resp)
8530                         search_do_resp();
8531                 if (!running)
8532                         goto done;
8533                 if (bar_alarm) {
8534                         bar_alarm = 0;
8535                         bar_update();
8536                 }
8537         }
8538 done:
8539         shutdown_cleanup();
8540
8541         return (0);
8542 }