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