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