JasonWoof Got questions, comments, patches, etc.? Contact Jason Woofenden
5fc8877587acf17aecf5261a8142119486ebf0bf
[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
3224         DNPRINTF(SWM_D_EVENT, "center_pointer: win %#x.\n", WINID(win));
3225
3226         if (win && win->mapped)
3227                 xcb_warp_pointer(conn, XCB_NONE, win->id, 0, 0, 0, 0,
3228                     WIDTH(win) / 2, HEIGHT(win) / 2);
3229         else
3230                 xcb_warp_pointer(conn, XCB_NONE, r->id, 0, 0, 0, 0,
3231                     WIDTH(r) / 2, HEIGHT(r) / 2);
3232 }
3233
3234 struct swm_region *
3235 root_to_region(xcb_window_t root, int check)
3236 {
3237         struct ws_win                   *cfw;
3238         struct swm_region               *r = NULL;
3239         int                             i, num_screens;
3240         xcb_query_pointer_reply_t       *qpr;
3241         xcb_get_input_focus_reply_t     *gifr;
3242
3243         DNPRINTF(SWM_D_MISC, "root_to_region: win %#x\n", root);
3244
3245         num_screens = get_screen_count();
3246         for (i = 0; i < num_screens; i++)
3247                 if (screens[i].root == root)
3248                         break;
3249
3250         if (check & SWM_CK_REGION)
3251                 r = screens[i].r_focus;
3252
3253         if (r == NULL && check & SWM_CK_FOCUS) {
3254                 /* Try to find an actively focused window */
3255                 gifr = xcb_get_input_focus_reply(conn,
3256                     xcb_get_input_focus(conn), NULL);
3257                 if (gifr) {
3258                         cfw = find_window(gifr->focus);
3259                         if (cfw && cfw->ws->r)
3260                                 r = cfw->ws->r;
3261
3262                         free(gifr);
3263                 }
3264         }
3265
3266         if (r == NULL && check & SWM_CK_POINTER) {
3267                 /* No region with an active focus; try to use pointer. */
3268                 qpr = xcb_query_pointer_reply(conn, xcb_query_pointer(conn,
3269                     screens[i].root), NULL);
3270                 if (qpr) {
3271                         DNPRINTF(SWM_D_MISC, "root_to_region: pointer: "
3272                             "(%d,%d)\n", qpr->root_x, qpr->root_y);
3273                         TAILQ_FOREACH(r, &screens[i].rl, entry)
3274                                 if (X(r) <= qpr->root_x &&
3275                                     qpr->root_x < MAX_X(r) &&
3276                                     Y(r) <= qpr->root_y &&
3277                                     qpr->root_y < MAX_Y(r))
3278                                         break;
3279                         free(qpr);
3280                 }
3281         }
3282
3283         /* Last resort. */
3284         if (r == NULL && check & SWM_CK_FALLBACK)
3285                 r = TAILQ_FIRST(&screens[i].rl);
3286
3287         DNPRINTF(SWM_D_MISC, "root_to_region: idx: %d\n", get_region_index(r));
3288
3289         return (r);
3290 }
3291
3292 struct ws_win *
3293 find_unmanaged_window(xcb_window_t id)
3294 {
3295         struct ws_win           *win;
3296         int                     i, j, num_screens;
3297
3298         num_screens = get_screen_count();
3299         for (i = 0; i < num_screens; i++)
3300                 for (j = 0; j < workspace_limit; j++)
3301                         TAILQ_FOREACH(win, &screens[i].ws[j].unmanagedlist,
3302                             entry)
3303                                 if (id == win->id)
3304                                         return (win);
3305         return (NULL);
3306 }
3307
3308 struct ws_win *
3309 find_window(xcb_window_t id)
3310 {
3311         struct ws_win           *win;
3312         int                     i, j, num_screens;
3313         xcb_query_tree_reply_t  *r;
3314
3315         num_screens = get_screen_count();
3316         for (i = 0; i < num_screens; i++)
3317                 for (j = 0; j < workspace_limit; j++)
3318                         TAILQ_FOREACH(win, &screens[i].ws[j].winlist, entry)
3319                                 if (id == win->id)
3320                                         return (win);
3321
3322         r = xcb_query_tree_reply(conn, xcb_query_tree(conn, id), NULL);
3323         if (r == NULL)
3324                 return (NULL);
3325
3326         /* if we were looking for the parent return that window instead */
3327         if (r->parent == 0 || r->root == r->parent) {
3328                 free(r);
3329                 return (NULL);
3330         }
3331
3332         /* look for parent */
3333         for (i = 0; i < num_screens; i++)
3334                 for (j = 0; j < workspace_limit; j++)
3335                         TAILQ_FOREACH(win, &screens[i].ws[j].winlist, entry)
3336                                 if (r->parent == win->id) {
3337                                         free(r);
3338                                         return (win);
3339                                 }
3340
3341         free(r);
3342         return (NULL);
3343 }
3344
3345 void
3346 spawn(int ws_idx, union arg *args, bool close_fd)
3347 {
3348         int                     fd;
3349         char                    *ret = NULL;
3350
3351         DNPRINTF(SWM_D_MISC, "spawn: %s\n", args->argv[0]);
3352
3353         close(xcb_get_file_descriptor(conn));
3354
3355         setenv("LD_PRELOAD", SWM_LIB, 1);
3356
3357         if (asprintf(&ret, "%d", ws_idx) == -1) {
3358                 warn("spawn: asprintf SWM_WS");
3359                 _exit(1);
3360         }
3361         setenv("_SWM_WS", ret, 1);
3362         free(ret);
3363         ret = NULL;
3364
3365         if (asprintf(&ret, "%d", getpid()) == -1) {
3366                 warn("spawn: asprintf _SWM_PID");
3367                 _exit(1);
3368         }
3369         setenv("_SWM_PID", ret, 1);
3370         free(ret);
3371         ret = NULL;
3372
3373         if (setsid() == -1) {
3374                 warn("spawn: setsid");
3375                 _exit(1);
3376         }
3377
3378         if (close_fd) {
3379                 /*
3380                  * close stdin and stdout to prevent interaction between apps
3381                  * and the baraction script
3382                  * leave stderr open to record errors
3383                 */
3384                 if ((fd = open(_PATH_DEVNULL, O_RDWR, 0)) == -1) {
3385                         warn("spawn: open");
3386                         _exit(1);
3387                 }
3388                 dup2(fd, STDIN_FILENO);
3389                 dup2(fd, STDOUT_FILENO);
3390                 if (fd > 2)
3391                         close(fd);
3392         }
3393
3394         execvp(args->argv[0], args->argv);
3395
3396         warn("spawn: execvp");
3397         _exit(1);
3398 }
3399
3400 void
3401 kill_refs(struct ws_win *win)
3402 {
3403         int                     i, x, num_screens;
3404         struct swm_region       *r;
3405         struct workspace        *ws;
3406
3407         if (win == NULL)
3408                 return;
3409
3410         num_screens = get_screen_count();
3411         for (i = 0; i < num_screens; i++)
3412                 TAILQ_FOREACH(r, &screens[i].rl, entry)
3413                         for (x = 0; x < workspace_limit; x++) {
3414                                 ws = &r->s->ws[x];
3415                                 if (win == ws->focus)
3416                                         ws->focus = NULL;
3417                                 if (win == ws->focus_prev)
3418                                         ws->focus_prev = NULL;
3419                         }
3420 }
3421
3422 int
3423 validate_win(struct ws_win *testwin)
3424 {
3425         struct ws_win           *win;
3426         struct workspace        *ws;
3427         struct swm_region       *r;
3428         int                     i, x, num_screens;
3429
3430         if (testwin == NULL)
3431                 return (0);
3432
3433         num_screens = get_screen_count();
3434         for (i = 0; i < num_screens; i++)
3435                 TAILQ_FOREACH(r, &screens[i].rl, entry)
3436                         for (x = 0; x < workspace_limit; x++) {
3437                                 ws = &r->s->ws[x];
3438                                 TAILQ_FOREACH(win, &ws->winlist, entry)
3439                                         if (win == testwin)
3440                                                 return (0);
3441                         }
3442         return (1);
3443 }
3444
3445 int
3446 validate_ws(struct workspace *testws)
3447 {
3448         struct swm_region       *r;
3449         struct workspace        *ws;
3450         int                     i, x, num_screens;
3451
3452         /* validate all ws */
3453         num_screens = get_screen_count();
3454         for (i = 0; i < num_screens; i++)
3455                 TAILQ_FOREACH(r, &screens[i].rl, entry)
3456                         for (x = 0; x < workspace_limit; x++) {
3457                                 ws = &r->s->ws[x];
3458                                 if (ws == testws)
3459                                         return (0);
3460                         }
3461         return (1);
3462 }
3463
3464 void
3465 unfocus_win(struct ws_win *win)
3466 {
3467         xcb_window_t            none = XCB_WINDOW_NONE;
3468
3469         DNPRINTF(SWM_D_FOCUS, "unfocus_win: win %#x\n", WINID(win));
3470
3471         if (win == NULL)
3472                 return;
3473
3474         if (win->ws == NULL) {
3475                 DNPRINTF(SWM_D_FOCUS, "unfocus_win: NULL ws.\n");
3476                 return;
3477         }
3478
3479         if (validate_ws(win->ws)) {
3480                 DNPRINTF(SWM_D_FOCUS, "unfocus_win: invalid ws.\n");
3481                 return;
3482         }
3483
3484         if (win->ws->r == NULL) {
3485                 DNPRINTF(SWM_D_FOCUS, "unfocus_win: NULL region.\n");
3486                 return;
3487         }
3488
3489         if (validate_win(win)) {
3490                 DNPRINTF(SWM_D_FOCUS, "unfocus_win: invalid win.\n");
3491                 kill_refs(win);
3492                 return;
3493         }
3494
3495         if (win->ws->focus == win) {
3496                 win->ws->focus = NULL;
3497                 win->ws->focus_prev = win;
3498         }
3499
3500         if (validate_win(win->ws->focus)) {
3501                 kill_refs(win->ws->focus);
3502                 win->ws->focus = NULL;
3503         }
3504
3505         if (validate_win(win->ws->focus_prev)) {
3506                 kill_refs(win->ws->focus_prev);
3507                 win->ws->focus_prev = NULL;
3508         }
3509
3510         update_window_color(win);
3511
3512         xcb_change_property(conn, XCB_PROP_MODE_REPLACE, win->s->root,
3513             ewmh[_NET_ACTIVE_WINDOW].atom, XCB_ATOM_WINDOW, 32, 1, &none);
3514
3515         DNPRINTF(SWM_D_FOCUS, "unfocus_win: done.\n");
3516 }
3517
3518 void
3519 focus_win(struct ws_win *win)
3520 {
3521         struct ws_win                   *cfw = NULL, *parent = NULL, *w, *tmpw;
3522         struct workspace                *ws;
3523         xcb_get_input_focus_reply_t     *gifr;
3524
3525         DNPRINTF(SWM_D_FOCUS, "focus_win: win %#x\n", WINID(win));
3526
3527         if (win == NULL || win->ws == NULL || !win->mapped)
3528                 goto out;
3529
3530         ws = win->ws;
3531
3532         if (validate_ws(ws))
3533                 goto out;
3534
3535         if (validate_win(win)) {
3536                 kill_refs(win);
3537                 goto out;
3538         }
3539
3540         gifr = xcb_get_input_focus_reply(conn, xcb_get_input_focus(conn), NULL);
3541         if (gifr) {
3542                 cfw = find_window(gifr->focus);
3543                 if (cfw != NULL && cfw != win) {
3544                         if (cfw->ws != ws && cfw->ws->r != NULL) {
3545                                 /* Change border to unfocused color. */
3546                                 xcb_change_window_attributes(conn, cfw->id,
3547                                     XCB_CW_BORDER_PIXEL,
3548                                     &cfw->s->c[(MAXIMIZED(cfw) ?
3549                                     SWM_S_COLOR_UNFOCUS_MAXIMIZED :
3550                                     SWM_S_COLOR_UNFOCUS)].pixel);
3551                         } else {
3552                                 unfocus_win(cfw);
3553                         }
3554                 }
3555                 free(gifr);
3556         }
3557
3558         if (ws->focus != win) {
3559                 if (ws->focus && ws->focus != cfw)
3560                         unfocus_win(ws->focus);
3561                 ws->focus = win;
3562         }
3563
3564         /* If this window directs focus to a child window, then clear. */
3565         if (win->focus_child)
3566                 win->focus_child = NULL;
3567
3568         /* If transient, adjust parent's focus child for focus_magic. */
3569         if (TRANS(win)) {
3570                 parent = find_window(win->transient);
3571                 if (parent && parent->focus_child != win)
3572                         parent->focus_child = win;
3573         }
3574
3575         if (cfw != win && ws->r != NULL) {
3576                 /* Set input focus if no input hint, or indicated by hint. */
3577                 if (!(win->hints.flags & XCB_ICCCM_WM_HINT_INPUT) ||
3578                     (win->hints.flags & XCB_ICCCM_WM_HINT_INPUT &&
3579                      win->hints.input))
3580                         xcb_set_input_focus(conn, XCB_INPUT_FOCUS_PARENT,
3581                                         win->id, last_event_time);
3582                 else
3583                         xcb_set_input_focus(conn, XCB_INPUT_FOCUS_PARENT,
3584                             ws->r->id, XCB_CURRENT_TIME);
3585
3586                 /* Tell app it can adjust focus to a specific window. */
3587                 if (win->take_focus) {
3588                         /* java is special; always tell parent */
3589                         if (TRANS(win) && win->java)
3590                                 client_msg(parent, a_takefocus,
3591                                     last_event_time);
3592                         else
3593                                 client_msg(win, a_takefocus, last_event_time);
3594                 }
3595
3596                 if (ws->cur_layout->flags & SWM_L_MAPONFOCUS ||
3597                     ws->always_raise) {
3598                         /* If a parent exists, map it first. */
3599                         if (parent) {
3600                                 raise_window(parent);
3601                                 map_window(parent);
3602
3603                                 /* Map siblings next. */
3604                                 TAILQ_FOREACH_SAFE(w, &ws->stack, stack_entry,
3605                                     tmpw)
3606                                         if (w != win && !ICONIC(w) &&
3607                                             w->transient == parent->id) {
3608                                                 raise_window(w);
3609                                                 map_window(w);
3610                                         }
3611                         }
3612
3613                         /* Map focused window. */
3614                         raise_window(win);
3615                         map_window(win);
3616
3617                         /* Stack any children of focus window. */
3618                         TAILQ_FOREACH_SAFE(w, &ws->stack, stack_entry, tmpw)
3619                                 if (w->transient == win->id && !ICONIC(w)) {
3620                                         raise_window(w);
3621                                         map_window(w);
3622                                 }
3623                 } else if (tile_gap < 0 && !ABOVE(win)) {
3624                         /*
3625                          * Windows overlap in the layout.
3626                          * Raise focused win above all tiled wins.
3627                          */
3628                         raise_window(win);
3629                         map_window(win);
3630                 }
3631
3632                 set_region(ws->r);
3633
3634                 xcb_change_property(conn, XCB_PROP_MODE_REPLACE, win->s->root,
3635                     ewmh[_NET_ACTIVE_WINDOW].atom, XCB_ATOM_WINDOW, 32, 1,
3636                     &win->id);
3637         }
3638
3639         if (cfw != win)
3640                 /* Update window border even if workspace is hidden. */
3641                 update_window_color(win);
3642
3643 out:
3644         bar_draw();
3645
3646         DNPRINTF(SWM_D_FOCUS, "focus_win: done.\n");
3647 }
3648
3649 /* If a child window should have focus instead, return it. */
3650 struct ws_win *
3651 get_focus_magic(struct ws_win *win)
3652 {
3653         struct ws_win   *parent = NULL;
3654         struct ws_win   *child = NULL;
3655
3656         DNPRINTF(SWM_D_FOCUS, "get_focus_magic: win %#x\n", WINID(win));
3657         if (win == NULL)
3658                 return win;
3659
3660         if (TRANS(win)) {
3661                 parent = find_window(win->transient);
3662
3663                 /* If parent prefers focus elsewhere, then try to do so. */
3664                 if (parent && (child = parent->focus_child)) {
3665                         if (validate_win(child) == 0 && child->mapped)
3666                                 win = child;
3667                         else
3668                                 parent->focus_child = NULL;
3669                 }
3670         }
3671
3672         /* If this window prefers focus elsewhere, then try to do so. */
3673         if ((child = win->focus_child)) {
3674                 if (validate_win(child) == 0 && child->mapped)
3675                         win = child;
3676                 else
3677                         win->focus_child = NULL;
3678         }
3679
3680         return win;
3681 }
3682
3683 void
3684 event_drain(uint8_t rt)
3685 {
3686         xcb_generic_event_t     *evt;
3687
3688         /* ensure all pending requests have been processed before filtering. */
3689         xcb_aux_sync(conn);
3690         while ((evt = xcb_poll_for_event(conn))) {
3691                 if (XCB_EVENT_RESPONSE_TYPE(evt) != rt)
3692                         event_handle(evt);
3693
3694                 free(evt);
3695         }
3696 }
3697
3698 void
3699 set_region(struct swm_region *r)
3700 {
3701         struct swm_region       *rf;
3702         int                     vals[2];
3703
3704         if (r == NULL)
3705                 return;
3706
3707         rf = r->s->r_focus;
3708         /* Unfocus old region bar. */
3709         if (rf != NULL) {
3710                 if (rf == r)
3711                         return;
3712
3713                 xcb_change_window_attributes(conn, rf->bar->id,
3714                     XCB_CW_BORDER_PIXEL,
3715                     &r->s->c[SWM_S_COLOR_BAR_BORDER_UNFOCUS].pixel);
3716         }
3717
3718         if (rf != NULL && rf != r && (X(rf) != X(r) || Y(rf) != Y(r) ||
3719             WIDTH(rf) != WIDTH(r) || HEIGHT(rf) != HEIGHT(r))) {
3720                 /* Set _NET_DESKTOP_GEOMETRY. */
3721                 vals[0] = WIDTH(r);
3722                 vals[1] = HEIGHT(r);
3723                 xcb_change_property(conn, XCB_PROP_MODE_REPLACE, r->s->root,
3724                     ewmh[_NET_DESKTOP_GEOMETRY].atom, XCB_ATOM_CARDINAL, 32, 2,
3725                     &vals);
3726         }
3727
3728         /* Set region bar border to focus_color. */
3729         xcb_change_window_attributes(conn, r->bar->id,
3730             XCB_CW_BORDER_PIXEL, &r->s->c[SWM_S_COLOR_BAR_BORDER].pixel);
3731
3732         r->s->r_focus = r;
3733
3734         ewmh_update_current_desktop();
3735 }
3736
3737 void
3738 focus_region(struct swm_region *r)
3739 {
3740         struct ws_win           *nfw;
3741         struct swm_region       *old_r;
3742
3743         if (r == NULL)
3744                 return;
3745
3746         old_r = r->s->r_focus;
3747         set_region(r);
3748
3749         nfw = get_region_focus(r);
3750         if (nfw) {
3751                 focus_win(nfw);
3752         } else {
3753                 /* New region is empty; need to manually unfocus win. */
3754                 if (old_r)
3755                         unfocus_win(old_r->ws->focus);
3756
3757                 xcb_set_input_focus(conn, XCB_INPUT_FOCUS_PARENT, r->id,
3758                     XCB_CURRENT_TIME);
3759
3760                 /* Clear bar since empty. */
3761                 bar_draw();
3762         }
3763 }
3764
3765 void
3766 switchws(struct swm_region *r, union arg *args)
3767 {
3768         struct swm_region       *this_r, *other_r;
3769         struct ws_win           *win;
3770         struct workspace        *new_ws, *old_ws;
3771         xcb_window_t            none = XCB_WINDOW_NONE;
3772         int                     wsid = args->id;
3773         bool                    unmap_old = false;
3774
3775         if (!(r && r->s))
3776                 return;
3777
3778         if (wsid >= workspace_limit)
3779                 return;
3780
3781         this_r = r;
3782         old_ws = this_r->ws;
3783         new_ws = &this_r->s->ws[wsid];
3784
3785         DNPRINTF(SWM_D_WS, "switchws: screen[%d]:%dx%d+%d+%d: %d -> %d\n",
3786             r->s->idx, WIDTH(r), HEIGHT(r), X(r), Y(r), old_ws->idx, wsid);
3787
3788         if (new_ws == NULL || old_ws == NULL)
3789                 return;
3790         if (new_ws == old_ws)
3791                 return;
3792
3793         if ((win = old_ws->focus) != NULL) {
3794                 update_window_color(win);
3795
3796                 xcb_change_property(conn, XCB_PROP_MODE_REPLACE, win->s->root,
3797                     ewmh[_NET_ACTIVE_WINDOW].atom, XCB_ATOM_WINDOW, 32, 1,
3798                     &none);
3799         }
3800
3801         other_r = new_ws->r;
3802         if (other_r == NULL) {
3803                 /* the other workspace is hidden, hide this one */
3804                 old_ws->r = NULL;
3805                 unmap_old = true;
3806         } else {
3807                 /* the other ws is visible in another region, exchange them */
3808                 other_r->ws_prior = new_ws;
3809                 other_r->ws = old_ws;
3810                 old_ws->r = other_r;
3811         }
3812         this_r->ws_prior = old_ws;
3813         this_r->ws = new_ws;
3814         new_ws->r = this_r;
3815
3816         /* Set focus_pending before stacking, if needed. */
3817         if (focus_mode != SWM_FOCUS_FOLLOW && (!new_ws->focus_pending ||
3818             validate_win(new_ws->focus_pending))) {
3819                 new_ws->focus_pending = get_region_focus(new_ws->r);
3820                 new_ws->focus = new_ws->focus_prev;
3821                 new_ws->focus_prev = NULL;
3822         }
3823
3824         new_ws->state = SWM_WS_STATE_MAPPING;
3825         stack();
3826
3827         /* unmap old windows */
3828         if (unmap_old) {
3829                 TAILQ_FOREACH(win, &old_ws->winlist, entry)
3830                         unmap_window(win);
3831                 old_ws->state = SWM_WS_STATE_HIDDEN;
3832         }
3833
3834         /* if workspaces were swapped, then don't wait to set focus */
3835         if (old_ws->r && focus_mode != SWM_FOCUS_FOLLOW) {
3836                 if (new_ws->focus_pending) {
3837                         focus_win(new_ws->focus_pending);
3838                         new_ws->focus_pending = NULL;
3839                 }
3840         }
3841
3842         /* Clear bar and set focus on region input win if new ws is empty. */
3843         if (new_ws->focus_pending == NULL && new_ws->focus == NULL) {
3844                 xcb_set_input_focus(conn, XCB_INPUT_FOCUS_PARENT, r->id,
3845                     XCB_CURRENT_TIME);
3846                 bar_draw();
3847         }
3848
3849         ewmh_update_current_desktop();
3850
3851         center_pointer(r);
3852         focus_flush();
3853         new_ws->state = SWM_WS_STATE_MAPPED;
3854
3855         DNPRINTF(SWM_D_WS, "switchws: done.\n");
3856 }
3857
3858 void
3859 cyclews(struct swm_region *r, union arg *args)
3860 {
3861         union                   arg a;
3862         struct swm_screen       *s = r->s;
3863         bool                    cycle_all = false, mv = false;
3864
3865         DNPRINTF(SWM_D_WS, "cyclews: id: %d, screen[%d]:%dx%d+%d+%d, ws: %d\n",
3866             args->id, r->s->idx, WIDTH(r), HEIGHT(r), X(r), Y(r), r->ws->idx);
3867
3868         a.id = r->ws->idx;
3869
3870         do {
3871                 switch (args->id) {
3872                 case SWM_ARG_ID_CYCLEWS_MOVE_UP:
3873                         mv = true;
3874                         /* FALLTHROUGH */
3875                 case SWM_ARG_ID_CYCLEWS_UP_ALL:
3876                         cycle_all = true;
3877                         /* FALLTHROUGH */
3878                 case SWM_ARG_ID_CYCLEWS_UP:
3879                         a.id = (a.id < workspace_limit - 1) ? a.id + 1 : 0;
3880                         break;
3881                 case SWM_ARG_ID_CYCLEWS_MOVE_DOWN:
3882                         mv = true;
3883                         /* FALLTHROUGH */
3884                 case SWM_ARG_ID_CYCLEWS_DOWN_ALL:
3885                         cycle_all = true;
3886                         /* FALLTHROUGH */
3887                 case SWM_ARG_ID_CYCLEWS_DOWN:
3888                         a.id = (a.id > 0) ? a.id - 1 : workspace_limit - 1;
3889                         break;
3890                 default:
3891                         return;
3892                 };
3893
3894                 if (!cycle_all &&
3895                     (!cycle_empty && TAILQ_EMPTY(&s->ws[a.id].winlist)))
3896                         continue;
3897                 if (!cycle_visible && s->ws[a.id].r != NULL)
3898                         continue;
3899
3900                 if (mv)
3901                         send_to_ws(r, &a);
3902
3903                 switchws(r, &a);
3904         } while (a.id != r->ws->idx);
3905
3906         DNPRINTF(SWM_D_FOCUS, "cyclews: done\n");
3907 }
3908
3909 void
3910 priorws(struct swm_region *r, union arg *args)
3911 {
3912         union arg               a;
3913
3914         (void)args;
3915
3916         DNPRINTF(SWM_D_WS, "priorws: id: %d, screen[%d]:%dx%d+%d+%d, ws: %d\n",
3917             args->id, r->s->idx, WIDTH(r), HEIGHT(r), X(r), Y(r), r->ws->idx);
3918
3919         if (r->ws_prior == NULL)
3920                 return;
3921
3922         a.id = r->ws_prior->idx;
3923         switchws(r, &a);
3924         DNPRINTF(SWM_D_FOCUS, "priorws: done\n");
3925 }
3926
3927 void
3928 focusrg(struct swm_region *r, union arg *args)
3929 {
3930         int                     ridx = args->id, i, num_screens;
3931         struct swm_region       *rr = NULL;
3932
3933         num_screens = get_screen_count();
3934         /* do nothing if we don't have more than one screen */
3935         if (!(num_screens > 1 || outputs > 1))
3936                 return;
3937
3938         DNPRINTF(SWM_D_FOCUS, "focusrg: id: %d\n", ridx);
3939
3940         rr = TAILQ_FIRST(&r->s->rl);
3941         for (i = 0; i < ridx && rr != NULL; ++i)
3942                 rr = TAILQ_NEXT(rr, entry);
3943
3944         if (rr == NULL)
3945                 return;
3946
3947         focus_region(rr);
3948         center_pointer(rr);
3949         focus_flush();
3950         DNPRINTF(SWM_D_FOCUS, "focusrg: done\n");
3951 }
3952
3953 void
3954 cyclerg(struct swm_region *r, union arg *args)
3955 {
3956         struct swm_region       *rr = NULL;
3957         int                     i, num_screens;
3958
3959         num_screens = get_screen_count();
3960         /* do nothing if we don't have more than one screen */
3961         if (!(num_screens > 1 || outputs > 1))
3962                 return;
3963
3964         i = r->s->idx;
3965         DNPRINTF(SWM_D_FOCUS, "cyclerg: id: %d, region: %d\n", args->id, i);
3966
3967         switch (args->id) {
3968         case SWM_ARG_ID_CYCLERG_UP:
3969                 rr = TAILQ_NEXT(r, entry);
3970                 if (rr == NULL)
3971                         rr = TAILQ_FIRST(&screens[i].rl);
3972                 break;
3973         case SWM_ARG_ID_CYCLERG_DOWN:
3974                 rr = TAILQ_PREV(r, swm_region_list, entry);
3975                 if (rr == NULL)
3976                         rr = TAILQ_LAST(&screens[i].rl, swm_region_list);
3977                 break;
3978         default:
3979                 return;
3980         };
3981         if (rr == NULL)
3982                 return;
3983
3984         focus_region(rr);
3985         center_pointer(rr);
3986         focus_flush();
3987         DNPRINTF(SWM_D_FOCUS, "cyclerg: done\n");
3988 }
3989
3990 /* Sorts transients after parent. */
3991 void
3992 sort_windows(struct ws_win_list *wl)
3993 {
3994         struct ws_win           *win, *parent, *nxt;
3995
3996         if (wl == NULL)
3997                 return;
3998
3999         for (win = TAILQ_FIRST(wl); win != TAILQ_END(wl); win = nxt) {
4000                 nxt = TAILQ_NEXT(win, entry);
4001                 if (TRANS(win)) {
4002                         parent = find_window(win->transient);
4003                         if (parent == NULL) {
4004                                 warnx("not possible bug");
4005                                 continue;
4006                         }
4007                         TAILQ_REMOVE(wl, win, entry);
4008                         TAILQ_INSERT_AFTER(wl, parent, win, entry);
4009                 }
4010         }
4011 }
4012
4013 void
4014 swapwin(struct swm_region *r, union arg *args)
4015 {
4016         struct ws_win           *target, *source;
4017         struct ws_win           *cur_focus;
4018         struct ws_win_list      *wl;
4019
4020         DNPRINTF(SWM_D_WS, "swapwin: id: %d, screen[%d]:%dx%d+%d+%d, ws: %d\n",
4021             args->id, r->s->idx, WIDTH(r), HEIGHT(r), X(r), Y(r), r->ws->idx);
4022
4023         cur_focus = r->ws->focus;
4024         if (cur_focus == NULL || FULLSCREEN(cur_focus))
4025                 return;
4026
4027         /* Adjust stacking in floating layer. */
4028         if (ABOVE(cur_focus)) {
4029                 switch (args->id) {
4030                 case SWM_ARG_ID_SWAPPREV:
4031                         target = TAILQ_PREV(cur_focus, ws_win_stack,
4032                             stack_entry);
4033                         if (target != NULL && FLOATING(target)) {
4034                                 TAILQ_REMOVE(&cur_focus->ws->stack, cur_focus,
4035                                     stack_entry);
4036                                 TAILQ_INSERT_BEFORE(target, cur_focus,
4037                                     stack_entry);
4038                                 update_win_stacking(cur_focus);
4039                                 focus_flush();
4040                         }
4041                         break;
4042                 case SWM_ARG_ID_SWAPNEXT:
4043                         target = TAILQ_NEXT(cur_focus, stack_entry);
4044                         if (target != NULL && FLOATING(target)) {
4045                                 TAILQ_REMOVE(&cur_focus->ws->stack, cur_focus,
4046                                     stack_entry);
4047                                 TAILQ_INSERT_AFTER(&cur_focus->ws->stack,
4048                                     target, cur_focus, stack_entry);
4049                                 update_win_stacking(cur_focus);
4050                                 focus_flush();
4051                         }
4052                         break;
4053                 }
4054                 goto out;
4055         }
4056
4057         if (r->ws->cur_layout == &layouts[SWM_MAX_STACK])
4058                 return;
4059
4060         clear_maximized(r->ws);
4061
4062         source = cur_focus;
4063         wl = &source->ws->winlist;
4064
4065         switch (args->id) {
4066         case SWM_ARG_ID_SWAPPREV:
4067                 if (TRANS(source))
4068                         source = find_window(source->transient);
4069                 target = TAILQ_PREV(source, ws_win_list, entry);
4070                 if (target && target->transient)
4071                         target = find_window(target->transient);
4072                 TAILQ_REMOVE(wl, source, entry);
4073                 if (target == NULL)
4074                         TAILQ_INSERT_TAIL(wl, source, entry);
4075                 else
4076                         TAILQ_INSERT_BEFORE(target, source, entry);
4077                 break;
4078         case SWM_ARG_ID_SWAPNEXT:
4079                 target = TAILQ_NEXT(source, entry);
4080                 /* move the parent and let the sort handle the move */
4081                 if (TRANS(source))
4082                         source = find_window(source->transient);
4083                 TAILQ_REMOVE(wl, source, entry);
4084                 if (target == NULL)
4085                         TAILQ_INSERT_HEAD(wl, source, entry);
4086                 else
4087                         TAILQ_INSERT_AFTER(wl, target, source, entry);
4088                 break;
4089         case SWM_ARG_ID_SWAPMAIN:
4090                 target = TAILQ_FIRST(wl);
4091                 if (target == source) {
4092                         if (source->ws->focus_prev != NULL &&
4093                             source->ws->focus_prev != target)
4094                                 source = source->ws->focus_prev;
4095                         else
4096                                 return;
4097                 }
4098                 if (target == NULL || source == NULL)
4099                         return;
4100                 source->ws->focus_prev = target;
4101                 TAILQ_REMOVE(wl, target, entry);
4102                 TAILQ_INSERT_BEFORE(source, target, entry);
4103                 TAILQ_REMOVE(wl, source, entry);
4104                 TAILQ_INSERT_HEAD(wl, source, entry);
4105                 break;
4106         case SWM_ARG_ID_MOVELAST:
4107                 TAILQ_REMOVE(wl, source, entry);
4108                 TAILQ_INSERT_TAIL(wl, source, entry);
4109                 break;
4110         default:
4111                 DNPRINTF(SWM_D_MOVE, "swapwin: invalid id: %d\n", args->id);
4112                 return;
4113         }
4114
4115         sort_windows(wl);
4116         ewmh_update_client_list();
4117
4118         stack();
4119         center_pointer(r);
4120         focus_flush();
4121 out:
4122         DNPRINTF(SWM_D_MOVE, "swapwin: done\n");
4123 }
4124
4125 struct ws_win *
4126 get_focus_prev(struct ws_win *win)
4127 {
4128         struct ws_win           *winfocus = NULL;
4129         struct ws_win           *cur_focus = NULL;
4130         struct ws_win_list      *wl = NULL;
4131         struct workspace        *ws = NULL;
4132
4133         if (!(win && win->ws))
4134                 return NULL;
4135
4136         ws = win->ws;
4137         wl = &ws->winlist;
4138         cur_focus = ws->focus;
4139
4140         DNPRINTF(SWM_D_FOCUS, "get_focus_prev: win %#x, cur_focus: %#x, "
4141             "focus_prev: %#x\n", WINID(win), WINID(cur_focus),
4142             WINID(ws->focus_prev));
4143
4144         /* pickle, just focus on whatever */
4145         if (cur_focus == NULL) {
4146                 /* use prev_focus if valid */
4147                 if (ws->focus_prev && find_window(ws->focus_prev->id))
4148                         winfocus = ws->focus_prev;
4149                 goto done;
4150         }
4151
4152         /* if transient focus on parent */
4153         if (TRANS(cur_focus)) {
4154                 winfocus = find_window(cur_focus->transient);
4155                 goto done;
4156         }
4157
4158         /* if in max_stack try harder */
4159         if ((win->quirks & SWM_Q_FOCUSPREV) ||
4160             (ws->cur_layout->flags & SWM_L_FOCUSPREV)) {
4161                 if (cur_focus != ws->focus_prev)
4162                         winfocus = ws->focus_prev;
4163                 else
4164                         winfocus = TAILQ_PREV(win, ws_win_list, entry);
4165                 if (winfocus)
4166                         goto done;
4167         }
4168
4169         DNPRINTF(SWM_D_FOCUS, "get_focus_prev: focus_close: %d\n", focus_close);
4170
4171         if (winfocus == NULL || winfocus == win) {
4172                 switch (focus_close) {
4173                 case SWM_STACK_BOTTOM:
4174                         TAILQ_FOREACH(winfocus, wl, entry)
4175                                 if (!ICONIC(winfocus) && winfocus != cur_focus)
4176                                         break;
4177                         break;
4178                 case SWM_STACK_TOP:
4179                         TAILQ_FOREACH_REVERSE(winfocus, wl, ws_win_list, entry)
4180                                 if (!ICONIC(winfocus) && winfocus != cur_focus)
4181                                         break;
4182                         break;
4183                 case SWM_STACK_ABOVE:
4184                         winfocus = TAILQ_NEXT(cur_focus, entry);
4185                         while (winfocus && ICONIC(winfocus))
4186                                 winfocus = TAILQ_NEXT(winfocus, entry);
4187
4188                         if (winfocus == NULL) {
4189                                 if (focus_close_wrap) {
4190                                         TAILQ_FOREACH(winfocus, wl, entry)
4191                                                 if (!ICONIC(winfocus) &&
4192                                                     winfocus != cur_focus)
4193                                                         break;
4194                                 } else {
4195                                         TAILQ_FOREACH_REVERSE(winfocus, wl,
4196                                             ws_win_list, entry)
4197                                                 if (!ICONIC(winfocus) &&
4198                                                     winfocus != cur_focus)
4199                                                         break;
4200                                 }
4201                         }
4202                         break;
4203                 case SWM_STACK_BELOW:
4204                         winfocus = TAILQ_PREV(cur_focus, ws_win_list, entry);
4205                         while (winfocus && ICONIC(winfocus))
4206                                 winfocus = TAILQ_PREV(winfocus, ws_win_list,
4207                                     entry);
4208
4209                         if (winfocus == NULL) {
4210                                 if (focus_close_wrap) {
4211                                         TAILQ_FOREACH_REVERSE(winfocus, wl,
4212                                             ws_win_list, entry)
4213                                                 if (!ICONIC(winfocus) &&
4214                                                     winfocus != cur_focus)
4215                                                         break;
4216                                 } else {
4217                                         TAILQ_FOREACH(winfocus, wl, entry)
4218                                                 if (!ICONIC(winfocus) &&
4219                                                     winfocus != cur_focus)
4220                                                         break;
4221                                 }
4222                         }
4223                         break;
4224                 }
4225         }
4226 done:
4227         if (winfocus == NULL ||
4228             (winfocus && (ICONIC(winfocus) || winfocus == cur_focus))) {
4229                 if (focus_default == SWM_STACK_TOP) {
4230                         TAILQ_FOREACH_REVERSE(winfocus, wl, ws_win_list, entry)
4231                                 if (!ICONIC(winfocus) && winfocus != cur_focus)
4232                                         break;
4233                 } else {
4234                         TAILQ_FOREACH(winfocus, wl, entry)
4235                                 if (!ICONIC(winfocus) && winfocus != cur_focus)
4236                                         break;
4237                 }
4238         }
4239
4240         kill_refs(win);
4241
4242         return get_focus_magic(winfocus);
4243 }
4244
4245 struct ws_win *
4246 get_region_focus(struct swm_region *r)
4247 {
4248         struct ws_win           *winfocus = NULL;
4249
4250         if (!(r && r->ws))
4251                 return NULL;
4252
4253         if (r->ws->focus && !ICONIC(r->ws->focus))
4254                 winfocus = r->ws->focus;
4255         else if (r->ws->focus_prev && !ICONIC(r->ws->focus_prev))
4256                 winfocus = r->ws->focus_prev;
4257         else
4258                 TAILQ_FOREACH(winfocus, &r->ws->winlist, entry)
4259                         if (!ICONIC(winfocus))
4260                                 break;
4261
4262         return get_focus_magic(winfocus);
4263 }
4264
4265 void
4266 focus(struct swm_region *r, union arg *args)
4267 {
4268         struct ws_win           *head, *cur_focus = NULL, *winfocus = NULL;
4269         struct ws_win_list      *wl = NULL;
4270         struct workspace        *ws = NULL;
4271         union arg               a;
4272         int                     i;
4273         xcb_icccm_wm_hints_t    hints;
4274
4275         if (!(r && r->ws))
4276                 goto out;
4277
4278         cur_focus = r->ws->focus;
4279         ws = r->ws;
4280         wl = &ws->winlist;
4281
4282         DNPRINTF(SWM_D_FOCUS, "focus: id: %d, cur_focus: %#x\n", args->id,
4283             WINID(cur_focus));
4284
4285         /* Make sure an uniconified window has focus, if one exists. */
4286         if (cur_focus == NULL) {
4287                 cur_focus = TAILQ_FIRST(wl);
4288                 while (cur_focus != NULL && ICONIC(cur_focus))
4289                         cur_focus = TAILQ_NEXT(cur_focus, entry);
4290
4291                 DNPRINTF(SWM_D_FOCUS, "focus: new cur_focus: %#x\n",
4292                     WINID(cur_focus));
4293         }
4294
4295         switch (args->id) {
4296         case SWM_ARG_ID_FOCUSPREV:
4297                 if (cur_focus == NULL)
4298                         goto out;
4299
4300                 winfocus = cur_focus;
4301                 do {
4302                         winfocus = TAILQ_PREV(winfocus, ws_win_list, entry);
4303                         if (winfocus == NULL)
4304                                 winfocus = TAILQ_LAST(wl, ws_win_list);
4305                         if (winfocus == cur_focus)
4306                                 break;
4307                 } while (winfocus && (ICONIC(winfocus) ||
4308                     winfocus->id == cur_focus->transient ||
4309                     (cur_focus->transient != XCB_WINDOW_NONE &&
4310                     winfocus->transient == cur_focus->transient)));
4311                 break;
4312         case SWM_ARG_ID_FOCUSNEXT:
4313                 if (cur_focus == NULL)
4314                         goto out;
4315
4316                 winfocus = cur_focus;
4317                 do {
4318                         winfocus = TAILQ_NEXT(winfocus, entry);
4319                         if (winfocus == NULL)
4320                                 winfocus = TAILQ_FIRST(wl);
4321                         if (winfocus == cur_focus)
4322                                 break;
4323                 } while (winfocus && (ICONIC(winfocus) ||
4324                     winfocus->id == cur_focus->transient ||
4325                     (cur_focus->transient != XCB_WINDOW_NONE &&
4326                     winfocus->transient == cur_focus->transient)));
4327                 break;
4328         case SWM_ARG_ID_FOCUSMAIN:
4329                 if (cur_focus == NULL)
4330                         goto out;
4331
4332                 winfocus = TAILQ_FIRST(wl);
4333                 if (winfocus == cur_focus)
4334                         winfocus = cur_focus->ws->focus_prev;
4335                 break;
4336         case SWM_ARG_ID_FOCUSURGENT:
4337                 /* Search forward for the next urgent window. */
4338                 winfocus = NULL;
4339                 head = cur_focus;
4340
4341                 for (i = 0; i <= workspace_limit; ++i) {
4342                         if (head == NULL)
4343                                 head = TAILQ_FIRST(&r->s->ws[(ws->idx + i) %
4344                                     workspace_limit].winlist);
4345
4346                         while (head != NULL &&
4347                             (head = TAILQ_NEXT(head, entry)) != NULL) {
4348                                 if (head == cur_focus) {
4349                                         winfocus = cur_focus;
4350                                         break;
4351                                 }
4352                                 if (xcb_icccm_get_wm_hints_reply(conn,
4353                                     xcb_icccm_get_wm_hints(conn, head->id),
4354                                     &hints, NULL) != 0 &&
4355                                     xcb_icccm_wm_hints_get_urgency(&hints)) {
4356                                         winfocus = head;
4357                                         break;
4358                                 }
4359                         }
4360
4361                         if (winfocus != NULL)
4362                                 break;
4363                 }
4364
4365                 /* Switch ws if new focus is on a different ws. */
4366                 if (winfocus != NULL && winfocus->ws != ws) {
4367                         a.id = winfocus->ws->idx;
4368                         switchws(r, &a);
4369                 }
4370                 break;
4371         default:
4372                 goto out;
4373         }
4374
4375         if (clear_maximized(ws) > 0)
4376                 stack();
4377
4378         focus_win(get_focus_magic(winfocus));
4379         center_pointer(r);
4380         focus_flush();
4381
4382 out:
4383         DNPRINTF(SWM_D_FOCUS, "focus: done\n");
4384 }
4385
4386 void
4387 cycle_layout(struct swm_region *r, union arg *args)
4388 {
4389         struct workspace        *ws = r->ws;
4390
4391         /* suppress unused warning since var is needed */
4392         (void)args;
4393
4394         DNPRINTF(SWM_D_EVENT, "cycle_layout: workspace: %d\n", ws->idx);
4395
4396         ws->cur_layout++;
4397         if (ws->cur_layout->l_stack == NULL)
4398                 ws->cur_layout = &layouts[0];
4399
4400         clear_maximized(ws);
4401
4402         stack();
4403         bar_draw();
4404
4405         focus_win(get_region_focus(r));
4406
4407         center_pointer(r);
4408         focus_flush();
4409 }
4410
4411 void
4412 stack_config(struct swm_region *r, union arg *args)
4413 {
4414         struct workspace        *ws = r->ws;
4415
4416         DNPRINTF(SWM_D_STACK, "stack_config: id: %d workspace: %d\n",
4417             args->id, ws->idx);
4418
4419         if (clear_maximized(ws) > 0)
4420                 stack();
4421
4422         if (ws->cur_layout->l_config != NULL)
4423                 ws->cur_layout->l_config(ws, args->id);
4424
4425         if (args->id != SWM_ARG_ID_STACKINIT)
4426                 stack();
4427         bar_draw();
4428
4429         center_pointer(r);
4430         focus_flush();
4431 }
4432
4433 void
4434 stack(void) {
4435         struct swm_geometry     g;
4436         struct swm_region       *r, *r_prev = NULL;
4437         int                     i, num_screens;
4438         uint32_t                val[2];
4439 #ifdef SWM_DEBUG
4440         int j;
4441 #endif
4442
4443         DNPRINTF(SWM_D_STACK, "stack: begin\n");
4444
4445         num_screens = get_screen_count();
4446         for (i = 0; i < num_screens; i++) {
4447 #ifdef SWM_DEBUG
4448                 j = 0;
4449 #endif
4450                 TAILQ_FOREACH(r, &screens[i].rl, entry) {
4451                         /* Adjust stack area for region bar and padding. */
4452                         g = r->g;
4453                         g.x += region_padding;
4454                         g.y += region_padding;
4455                         g.w -= 2 * border_width + 2 * region_padding;
4456                         g.h -= 2 * border_width + 2 * region_padding;
4457                         if (bar_enabled && r->ws->bar_enabled) {
4458                                 if (!bar_at_bottom)
4459                                         g.y += bar_height;
4460                                 g.h -= bar_height;
4461                         }
4462
4463                         DNPRINTF(SWM_D_STACK, "stack: workspace: %d (screen: "
4464                             "%d, region: %d), (x,y) WxH: (%d,%d) %d x %d\n",
4465                             r->ws->idx, i, j++, g.x, g.y, g.w, g.h);
4466
4467                         if (r_prev) {
4468                                 /* Stack bar/input relative to prev. region. */
4469                                 val[1] = XCB_STACK_MODE_ABOVE;
4470
4471                                 val[0] = r_prev->id;
4472                                 DNPRINTF(SWM_D_STACK, "stack: region input %#x "
4473                                     "relative to %#x.\n", r->id, val[0]);
4474                                 xcb_configure_window(conn, r->id,
4475                                     XCB_CONFIG_WINDOW_SIBLING |
4476                                     XCB_CONFIG_WINDOW_STACK_MODE, val);
4477
4478                                 val[0] = r_prev->bar->id;
4479                                 DNPRINTF(SWM_D_STACK, "stack: region bar %#x "
4480                                     "relative to %#x.\n", r->bar->id, val[0]);
4481                                 xcb_configure_window(conn, r->bar->id,
4482                                     XCB_CONFIG_WINDOW_SIBLING |
4483                                     XCB_CONFIG_WINDOW_STACK_MODE, val);
4484                         }
4485
4486                         r->ws->cur_layout->l_stack(r->ws, &g);
4487                         r->ws->cur_layout->l_string(r->ws);
4488                         /* save r so we can track region changes */
4489                         r->ws->old_r = r;
4490                         r_prev = r;
4491                 }
4492         }
4493         if (font_adjusted)
4494                 font_adjusted--;
4495
4496         DNPRINTF(SWM_D_STACK, "stack: end\n");
4497 }
4498
4499 void
4500 store_float_geom(struct ws_win *win)
4501 {
4502         if (win == NULL || win->ws->r == NULL)
4503                 return;
4504
4505         /* retain window geom and region geom */
4506         win->g_float = win->g;
4507         win->g_float.x -= X(win->ws->r);
4508         win->g_float.y -= Y(win->ws->r);
4509         win->g_floatvalid = true;
4510         DNPRINTF(SWM_D_MISC, "store_float_geom: win %#x, g: (%d,%d)"
4511             " %d x %d, g_float: (%d,%d) %d x %d\n", win->id, X(win), Y(win),
4512             WIDTH(win), HEIGHT(win), win->g_float.x, win->g_float.y,
4513             win->g_float.w, win->g_float.h);
4514 }
4515
4516 void
4517 load_float_geom(struct ws_win *win)
4518 {
4519         if (win == NULL || win->ws->r == NULL)
4520                 return;
4521
4522         if (win->g_floatvalid) {
4523                 win->g = win->g_float;
4524                 X(win) += X(win->ws->r);
4525                 Y(win) += Y(win->ws->r);
4526                 DNPRINTF(SWM_D_MISC, "load_float_geom: win %#x, g: (%d,%d)"
4527                     "%d x %d\n", win->id, X(win), Y(win), WIDTH(win),
4528                     HEIGHT(win));
4529         } else {
4530                 DNPRINTF(SWM_D_MISC, "load_float_geom: win %#x, g_float "
4531                     "is not set.\n", win->id);
4532         }
4533 }
4534
4535 void
4536 update_floater(struct ws_win *win)
4537 {
4538         struct workspace        *ws;
4539         struct swm_region       *r;
4540
4541         if (win == NULL)
4542                 return;
4543
4544         ws = win->ws;
4545
4546         if ((r = ws->r) == NULL)
4547                 return;
4548
4549         DNPRINTF(SWM_D_MISC, "update_floater: win %#x\n", win->id);
4550
4551         win->bordered = true;
4552
4553         if (FULLSCREEN(win)) {
4554                 /* _NET_WM_FULLSCREEN: fullscreen without border. */
4555                 if (!win->g_floatvalid)
4556                         store_float_geom(win);
4557
4558                 win->g = r->g;
4559                 win->bordered = false;
4560         } else if (MAXIMIZED(win)) {
4561                 /* Maximize: like a single stacked window. */
4562                 if (!win->g_floatvalid)
4563                         store_float_geom(win);
4564
4565                 win->g = r->g;
4566
4567                 if (bar_enabled && ws->bar_enabled) {
4568                         if (!bar_at_bottom)
4569                                 Y(win) += bar_height;
4570                         HEIGHT(win) -= bar_height;
4571                 } else if (disable_border) {
4572                         win->bordered = false;
4573                 }
4574
4575                 if (win->bordered) {
4576                         HEIGHT(win) -= 2 * border_width;
4577                         WIDTH(win) -= 2 * border_width;
4578                 }
4579         } else {
4580                 /* Normal floating window. */
4581                 /* Update geometry if new region. */
4582                 if (r != ws->old_r)
4583                         load_float_geom(win);
4584
4585                 if ((win->quirks & SWM_Q_FULLSCREEN) &&
4586                     WIDTH(win) >= WIDTH(r) && HEIGHT(win) >= HEIGHT(r)) {
4587                         /* Remove border for FULLSCREEN quirk. */
4588                         win->bordered = false;
4589                 } else if (!MANUAL(win)) {
4590                         if (TRANS(win) && (win->quirks & SWM_Q_TRANSSZ)) {
4591                                 /* Adjust size on TRANSSZ quirk. */
4592                                 WIDTH(win) = (double)WIDTH(r) * dialog_ratio;
4593                                 HEIGHT(win) = (double)HEIGHT(r) * dialog_ratio;
4594                         }
4595
4596                         if (!(win->quirks & SWM_Q_ANYWHERE)) {
4597                                 /*
4598                                  * Floaters and transients are auto-centred
4599                                  * unless manually moved, resized or ANYWHERE
4600                                  * quirk is set.
4601                                  */
4602                                 X(win) = X(r) + (WIDTH(r) - WIDTH(win)) / 2 -
4603                                     BORDER(win);
4604                                 Y(win) = Y(r) + (HEIGHT(r) - HEIGHT(win)) / 2 -
4605                                     BORDER(win);
4606                                 store_float_geom(win);
4607                         }
4608                 }
4609         }
4610
4611         /* Ensure at least 1 pixel of the window is in the region. */
4612         region_containment(win, r, SWM_CW_ALLSIDES);
4613
4614         update_window(win);
4615 }
4616
4617 /*
4618  * Send keystrokes to terminal to decrease/increase the font size as the
4619  * window size changes.
4620  */
4621 void
4622 adjust_font(struct ws_win *win)
4623 {
4624         if (!(win->quirks & SWM_Q_XTERM_FONTADJ) ||
4625             ABOVE(win) || TRANS(win))
4626                 return;
4627
4628         if (win->sh.width_inc && win->last_inc != win->sh.width_inc &&
4629             WIDTH(win) / win->sh.width_inc < term_width &&
4630             win->font_steps < SWM_MAX_FONT_STEPS) {
4631                 win->font_size_boundary[win->font_steps] =
4632                     (win->sh.width_inc * term_width) + win->sh.base_width;
4633                 win->font_steps++;
4634                 font_adjusted++;
4635                 win->last_inc = win->sh.width_inc;
4636                 fake_keypress(win, XK_KP_Subtract, XCB_MOD_MASK_SHIFT);
4637         } else if (win->font_steps && win->last_inc != win->sh.width_inc &&
4638             WIDTH(win) > win->font_size_boundary[win->font_steps - 1]) {
4639                 win->font_steps--;
4640                 font_adjusted++;
4641                 win->last_inc = win->sh.width_inc;
4642                 fake_keypress(win, XK_KP_Add, XCB_MOD_MASK_SHIFT);
4643         }
4644 }
4645
4646 #define SWAPXY(g)       do {                            \
4647         int tmp;                                        \
4648         tmp = (g)->y; (g)->y = (g)->x; (g)->x = tmp;    \
4649         tmp = (g)->h; (g)->h = (g)->w; (g)->w = tmp;    \
4650 } while (0)
4651 void
4652 stack_master(struct workspace *ws, struct swm_geometry *g, int rot, bool flip)
4653 {
4654         struct swm_geometry     win_g, r_g = *g;
4655         struct ws_win           *win;
4656         int                     i, j, s, stacks;
4657         int                     w_inc = 1, h_inc, w_base = 1, h_base;
4658         int                     hrh, extra = 0, h_slice, last_h = 0;
4659         int                     split, colno, winno, mwin, msize, mscale;
4660         int                     remain, missing, v_slice;
4661         bool                    bordered = true, reconfigure = false;
4662
4663         DNPRINTF(SWM_D_STACK, "stack_master: workspace: %d, rot: %s, "
4664             "flip: %s\n", ws->idx, YESNO(rot), YESNO(flip));
4665
4666         /* Prepare tiling variables, if needed. */
4667         if ((winno = count_win(ws, false)) > 0) {
4668                 /* Find first tiled window. */
4669                 TAILQ_FOREACH(win, &ws->winlist, entry)
4670                         if (!FLOATING(win) && !ICONIC(win))
4671                                 break;
4672
4673                 /* Take into account size hints of first tiled window. */
4674                 if (rot) {
4675                         w_inc = win->sh.width_inc;
4676                         w_base = win->sh.base_width;
4677                         mwin = ws->l_state.horizontal_mwin;
4678                         mscale = ws->l_state.horizontal_msize;
4679                         stacks = ws->l_state.horizontal_stacks;
4680                         SWAPXY(&r_g);
4681                 } else {
4682                         w_inc = win->sh.height_inc;
4683                         w_base = win->sh.base_height;
4684                         mwin = ws->l_state.vertical_mwin;
4685                         mscale = ws->l_state.vertical_msize;
4686                         stacks = ws->l_state.vertical_stacks;
4687                 }
4688                 win_g = r_g;
4689
4690                 if (stacks > winno - mwin)
4691                         stacks = winno - mwin;
4692                 if (stacks < 1)
4693                         stacks = 1;
4694
4695                 h_slice = r_g.h / SWM_H_SLICE;
4696                 if (mwin && winno > mwin) {
4697                         v_slice = r_g.w / SWM_V_SLICE;
4698
4699                         split = mwin;
4700                         colno = split;
4701                         win_g.w = v_slice * mscale;
4702
4703                         if (w_inc > 1 && w_inc < v_slice) {
4704                                 /* Adjust for requested size increment. */
4705                                 remain = (win_g.w - w_base) % w_inc;
4706                                 win_g.w -= remain;
4707                         }
4708
4709                         msize = win_g.w;
4710                         if (flip)
4711                                 win_g.x += r_g.w - msize;
4712                 } else {
4713                         msize = -2;
4714                         colno = split = winno / stacks;
4715                         win_g.w = ((r_g.w - (stacks * 2 * border_width) +
4716                             2 * border_width) / stacks);
4717                 }
4718                 hrh = r_g.h / colno;
4719                 extra = r_g.h - (colno * hrh);
4720                 win_g.h = hrh - 2 * border_width;
4721                 i = j = 0, s = stacks;
4722         }
4723
4724         /* Update window geometry. */
4725         TAILQ_FOREACH(win, &ws->winlist, entry) {
4726                 if (ICONIC(win))
4727                         continue;
4728
4729                 if (FLOATING(win)) {
4730                         update_floater(win);
4731                         continue;
4732                 }
4733
4734                 /* Tiled. */
4735                 if (split && i == split) {
4736                         colno = (winno - mwin) / stacks;
4737                         if (s <= (winno - mwin) % stacks)
4738                                 colno++;
4739                         split += colno;
4740                         hrh = r_g.h / colno;
4741                         extra = r_g.h - (colno * hrh);
4742
4743                         if (!flip)
4744                                 win_g.x += win_g.w + 2 * border_width +
4745                                     tile_gap;
4746
4747                         win_g.w = (r_g.w - msize -
4748                             (stacks * (2 * border_width + tile_gap))) / stacks;
4749                         if (s == 1)
4750                                 win_g.w += (r_g.w - msize -
4751                                     (stacks * (2 * border_width + tile_gap))) %
4752                                     stacks;
4753
4754                         if (flip)
4755                                 win_g.x -= win_g.w + 2 * border_width +
4756                                     tile_gap;
4757                         s--;
4758                         j = 0;
4759                 }
4760
4761                 win_g.h = hrh - 2 * border_width - tile_gap;
4762
4763                 if (rot) {
4764                         h_inc = win->sh.width_inc;
4765                         h_base = win->sh.base_width;
4766                 } else {
4767                         h_inc = win->sh.height_inc;
4768                         h_base = win->sh.base_height;
4769                 }
4770
4771                 if (j == colno - 1) {
4772                         win_g.h = hrh + extra;
4773                 } else if (h_inc > 1 && h_inc < h_slice) {
4774                         /* adjust for window's requested size increment */
4775                         remain = (win_g.h - h_base) % h_inc;
4776                         missing = h_inc - remain;
4777
4778                         if (missing <= extra || j == 0) {
4779                                 extra -= missing;
4780                                 win_g.h += missing;
4781                         } else {
4782                                 win_g.h -= remain;
4783                                 extra += remain;
4784                         }
4785                 }
4786
4787                 if (j == 0)
4788                         win_g.y = r_g.y;
4789                 else
4790                         win_g.y += last_h + 2 * border_width + tile_gap;
4791
4792                 if (disable_border && !(bar_enabled && ws->bar_enabled) &&
4793                     winno == 1){
4794                         bordered = false;
4795                         win_g.w += 2 * border_width;
4796                         win_g.h += 2 * border_width;
4797                 } else {
4798                         bordered = true;
4799                 }
4800
4801                 if (rot) {
4802                         if (X(win) != win_g.y || Y(win) != win_g.x ||
4803                             WIDTH(win) != win_g.h || HEIGHT(win) != win_g.w) {
4804                                 reconfigure = true;
4805                                 X(win) = win_g.y;
4806                                 Y(win) = win_g.x;
4807                                 WIDTH(win) = win_g.h;
4808                                 HEIGHT(win) = win_g.w;
4809                         }
4810                 } else {
4811                         if (X(win) != win_g.x || Y(win) != win_g.y ||
4812                             WIDTH(win) != win_g.w || HEIGHT(win) != win_g.h) {
4813                                 reconfigure = true;
4814                                 X(win) = win_g.x;
4815                                 Y(win) = win_g.y;
4816                                 WIDTH(win) = win_g.w;
4817                                 HEIGHT(win) = win_g.h;
4818                         }
4819                 }
4820
4821                 if (bordered != win->bordered) {
4822                         reconfigure = true;
4823                         win->bordered = bordered;
4824                 }
4825
4826                 if (reconfigure) {
4827                         adjust_font(win);
4828                         update_window(win);
4829                 }
4830
4831                 last_h = win_g.h;
4832                 i++;
4833                 j++;
4834         }
4835
4836         /* Stack all windows from bottom up. */
4837         TAILQ_FOREACH_REVERSE(win, &ws->stack, ws_win_stack, stack_entry)
4838                 if (!ICONIC(win))
4839                         update_win_stacking(win);
4840
4841         /* Map all windows from top down. */
4842         TAILQ_FOREACH(win, &ws->stack, stack_entry)
4843                 if (!ICONIC(win))
4844                         map_window(win);
4845
4846         DNPRINTF(SWM_D_STACK, "stack_master: done\n");
4847 }
4848
4849 void
4850 vertical_config(struct workspace *ws, int id)
4851 {
4852         DNPRINTF(SWM_D_STACK, "vertical_config: id: %d, workspace: %d\n",
4853             id, ws->idx);
4854
4855         switch (id) {
4856         case SWM_ARG_ID_STACKRESET:
4857         case SWM_ARG_ID_STACKINIT:
4858                 ws->l_state.vertical_msize = SWM_V_SLICE / 2;
4859                 ws->l_state.vertical_mwin = 1;
4860                 ws->l_state.vertical_stacks = 1;
4861                 break;
4862         case SWM_ARG_ID_MASTERSHRINK:
4863                 if (ws->l_state.vertical_msize > 1)
4864                         ws->l_state.vertical_msize--;
4865                 break;
4866         case SWM_ARG_ID_MASTERGROW:
4867                 if (ws->l_state.vertical_msize < SWM_V_SLICE - 1)
4868                         ws->l_state.vertical_msize++;
4869                 break;
4870         case SWM_ARG_ID_MASTERADD:
4871                 ws->l_state.vertical_mwin++;
4872                 break;
4873         case SWM_ARG_ID_MASTERDEL:
4874                 if (ws->l_state.vertical_mwin > 0)
4875                         ws->l_state.vertical_mwin--;
4876                 break;
4877         case SWM_ARG_ID_STACKINC:
4878                 ws->l_state.vertical_stacks++;
4879                 break;
4880         case SWM_ARG_ID_STACKDEC:
4881                 if (ws->l_state.vertical_stacks > 1)
4882                         ws->l_state.vertical_stacks--;
4883                 break;
4884         case SWM_ARG_ID_FLIPLAYOUT:
4885                 ws->l_state.vertical_flip = !ws->l_state.vertical_flip;
4886                 break;
4887         default:
4888                 return;
4889         }
4890 }
4891
4892 void
4893 vertical_stack(struct workspace *ws, struct swm_geometry *g)
4894 {
4895         DNPRINTF(SWM_D_STACK, "vertical_stack: workspace: %d\n", ws->idx);
4896
4897         stack_master(ws, g, 0, ws->l_state.vertical_flip);
4898 }
4899
4900 void
4901 horizontal_config(struct workspace *ws, int id)
4902 {
4903         DNPRINTF(SWM_D_STACK, "horizontal_config: workspace: %d\n", ws->idx);
4904
4905         switch (id) {
4906         case SWM_ARG_ID_STACKRESET:
4907         case SWM_ARG_ID_STACKINIT:
4908                 ws->l_state.horizontal_mwin = 1;
4909                 ws->l_state.horizontal_msize = SWM_H_SLICE / 2;
4910                 ws->l_state.horizontal_stacks = 1;
4911                 break;
4912         case SWM_ARG_ID_MASTERSHRINK:
4913                 if (ws->l_state.horizontal_msize > 1)
4914                         ws->l_state.horizontal_msize--;
4915                 break;
4916         case SWM_ARG_ID_MASTERGROW:
4917                 if (ws->l_state.horizontal_msize < SWM_H_SLICE - 1)
4918                         ws->l_state.horizontal_msize++;
4919                 break;
4920         case SWM_ARG_ID_MASTERADD:
4921                 ws->l_state.horizontal_mwin++;
4922                 break;
4923         case SWM_ARG_ID_MASTERDEL:
4924                 if (ws->l_state.horizontal_mwin > 0)
4925                         ws->l_state.horizontal_mwin--;
4926                 break;
4927         case SWM_ARG_ID_STACKINC:
4928                 ws->l_state.horizontal_stacks++;
4929                 break;
4930         case SWM_ARG_ID_STACKDEC:
4931                 if (ws->l_state.horizontal_stacks > 1)
4932                         ws->l_state.horizontal_stacks--;
4933                 break;
4934         case SWM_ARG_ID_FLIPLAYOUT:
4935                 ws->l_state.horizontal_flip = !ws->l_state.horizontal_flip;
4936                 break;
4937         default:
4938                 return;
4939         }
4940 }
4941
4942 void
4943 horizontal_stack(struct workspace *ws, struct swm_geometry *g)
4944 {
4945         DNPRINTF(SWM_D_STACK, "horizontal_stack: workspace: %d\n", ws->idx);
4946
4947         stack_master(ws, g, 1, ws->l_state.horizontal_flip);
4948 }
4949
4950 /* fullscreen view */
4951 void
4952 max_stack(struct workspace *ws, struct swm_geometry *g)
4953 {
4954         struct swm_geometry     gg = *g;
4955         struct ws_win           *w, *win = NULL, *parent = NULL, *tmpw;
4956         int                     winno;
4957
4958         DNPRINTF(SWM_D_STACK, "max_stack: workspace: %d\n", ws->idx);
4959
4960         if (ws == NULL)
4961                 return;
4962
4963         winno = count_win(ws, false);
4964         if (winno == 0 && count_win(ws, true) == 0)
4965                 return;
4966
4967         /* Figure out which top level window should be visible. */
4968         if (ws->focus_pending)
4969                 win = ws->focus_pending;
4970         else if (ws->focus)
4971                 win = ws->focus;
4972         else if (ws->focus_prev)
4973                 win = ws->focus_prev;
4974         else
4975                 win = TAILQ_FIRST(&ws->winlist);
4976
4977         DNPRINTF(SWM_D_STACK, "max_stack: focus_pending: %#x, focus: %#x, "
4978             "focus_prev: %#x, first: %#x, win: %#x\n", WINID(ws->focus_pending),
4979             WINID(ws->focus), WINID(ws->focus_prev),
4980             WINID(TAILQ_FIRST(&ws->winlist)), win->id);
4981
4982         /* Update window geometry. */
4983         TAILQ_FOREACH(w, &ws->winlist, entry) {
4984                 if (ICONIC(w))
4985                         continue;
4986
4987                 if (TRANS(w)) {
4988                         update_floater(w);
4989                         continue;
4990                 }
4991
4992                 /* Set maximized flag for all maxed windows. */
4993                 if (!MAXIMIZED(w)) {
4994                         /* Preserve floating geometry. */
4995                         if (ABOVE(w))
4996                                 store_float_geom(w);
4997
4998                         ewmh_apply_flags(w, w->ewmh_flags | EWMH_F_MAXIMIZED);
4999                         ewmh_update_wm_state(w);
5000                 }
5001
5002                 /* Only reconfigure if necessary. */
5003                 if (X(w) != gg.x || Y(w) != gg.y || WIDTH(w) != gg.w ||
5004                     HEIGHT(w) != gg.h) {
5005                         w->g = gg;
5006                         if (bar_enabled && ws->bar_enabled){
5007                                 w->bordered = true;
5008                         } else {
5009                                 w->bordered = false;
5010                                 WIDTH(w) += 2 * border_width;
5011                                 HEIGHT(w) += 2 * border_width;
5012                         }
5013
5014                         update_window(w);
5015                 }
5016         }
5017
5018         /* If transient, stack parent and its children. */
5019         if (TRANS(win) && (parent = find_window(win->transient))) {
5020                 raise_window(parent);
5021
5022                 TAILQ_FOREACH_SAFE(w, &ws->stack, stack_entry, tmpw)
5023                         if (w->transient == parent->id)
5024                                 raise_window(w);
5025         }
5026
5027         /* Make sure focus window is on top. */
5028         raise_window(win);
5029
5030         /* Stack any children of focus window. */
5031         TAILQ_FOREACH_SAFE(w, &ws->stack, stack_entry, tmpw)
5032                 if (w->transient == win->id)
5033                         raise_window(w);
5034
5035         /* Map all windows. */
5036         TAILQ_FOREACH(w, &ws->stack, stack_entry)
5037                 if (!ICONIC(w))
5038                         map_window(w);
5039 }
5040
5041 void
5042 send_to_rg(struct swm_region *r, union arg *args)
5043 {
5044         int                     ridx = args->id, i, num_screens;
5045         struct swm_region       *rr = NULL;
5046         union arg               a;
5047
5048         num_screens = get_screen_count();
5049         /* do nothing if we don't have more than one screen */
5050         if (!(num_screens > 1 || outputs > 1))
5051                 return;
5052
5053         DNPRINTF(SWM_D_FOCUS, "send_to_rg: id: %d\n", ridx);
5054
5055         rr = TAILQ_FIRST(&r->s->rl);
5056         for (i = 0; i < ridx && rr != NULL; ++i)
5057                 rr = TAILQ_NEXT(rr, entry);
5058
5059         if (rr == NULL)
5060                 return;
5061
5062         a.id = rr->ws->idx;
5063
5064         send_to_ws(r, &a);
5065 }
5066
5067 struct swm_region *
5068 region_under(struct swm_screen *s, int x, int y)
5069 {
5070         struct swm_region       *r = NULL;
5071
5072         TAILQ_FOREACH(r, &s->rl, entry) {
5073                 DNPRINTF(SWM_D_MISC, "region_under: ws: %d, region g: (%d,%d) "
5074                     "%d x %d, coords: (%d,%d)\n", r->ws->idx, X(r), Y(r),
5075                     WIDTH(r), HEIGHT(r), x, y);
5076                 if (X(r) <= x && x < MAX_X(r))
5077                         if (Y(r) <= y && y < MAX_Y(r))
5078                                 return (r);
5079         }
5080
5081         return (NULL);
5082 }
5083
5084 /* Transfer focused window to target workspace and focus. */
5085 void
5086 send_to_ws(struct swm_region *r, union arg *args)
5087 {
5088         int                     wsid = args->id;
5089         struct ws_win           *win = NULL;
5090
5091         if (r && r->ws && r->ws->focus)
5092                 win = r->ws->focus;
5093         else
5094                 return;
5095
5096         DNPRINTF(SWM_D_MOVE, "send_to_ws: win %#x, ws %d\n", win->id, wsid);
5097
5098         if (wsid < 0 || wsid >= workspace_limit)
5099                 return;
5100
5101         if (win->ws->idx == wsid)
5102                 return;
5103
5104         win_to_ws(win, wsid, true);
5105
5106         /* Set new focus on target ws. */
5107         if (focus_mode != SWM_FOCUS_FOLLOW) {
5108                 win->ws->focus_prev = win->ws->focus;
5109                 win->ws->focus = win;
5110                 win->ws->focus_pending = NULL;
5111
5112                 if (win->ws->focus_prev)
5113                         update_window_color(win->ws->focus_prev);
5114         }
5115
5116         DNPRINTF(SWM_D_STACK, "send_to_ws: focus_pending: %#x, focus: %#x, "
5117             "focus_prev: %#x, first: %#x, win: %#x\n",
5118             WINID(r->ws->focus_pending), WINID(r->ws->focus),
5119             WINID(r->ws->focus_prev), WINID(TAILQ_FIRST(&r->ws->winlist)),
5120             win->id);
5121
5122         ewmh_apply_flags(win, win->ewmh_flags & ~EWMH_F_MAXIMIZED);
5123         ewmh_update_wm_state(win);
5124
5125         /* Restack and set new focus on current ws. */
5126         if (FLOATING(win))
5127                 load_float_geom(win);
5128
5129         stack();
5130
5131         if (focus_mode != SWM_FOCUS_FOLLOW) {
5132                 if (r->ws->focus != NULL) {
5133                         focus_win(r->ws->focus);
5134                 } else {
5135                         xcb_set_input_focus(conn, XCB_INPUT_FOCUS_PARENT, r->id,
5136                             XCB_CURRENT_TIME);
5137                         bar_draw();
5138                 }
5139         }
5140
5141         center_pointer(r);
5142         focus_flush();
5143 }
5144
5145 void
5146 win_to_ws(struct ws_win *win, int wsid, bool unfocus)
5147 {
5148         struct ws_win           *parent;
5149         struct workspace        *ws, *nws, *pws;
5150
5151         if (wsid < 0 || wsid >= workspace_limit)
5152                 return;
5153
5154         if (win->ws->idx == wsid)
5155                 return;
5156
5157         ws = win->ws;
5158         nws = &win->s->ws[wsid];
5159
5160         DNPRINTF(SWM_D_MOVE, "win_to_ws: win %#x, ws %d -> %d\n", win->id,
5161             ws->idx, wsid);
5162
5163         /* Cleanup focus on source ws. */
5164         if (focus_mode != SWM_FOCUS_FOLLOW &&
5165             (ws->focus == win || ws->focus_pending == win))
5166                 ws->focus_pending = get_focus_prev(win);
5167
5168         /* Move the parent if this is a transient window. */
5169         if (TRANS(win)) {
5170                 parent = find_window(win->transient);
5171                 if (parent) {
5172                         pws = parent->ws;
5173                         /* Set new focus in parent's ws if needed. */
5174                         if (pws->focus == parent) {
5175                                 if (focus_mode != SWM_FOCUS_FOLLOW)
5176                                         pws->focus_pending =
5177                                             get_focus_prev(parent);
5178
5179                                 unfocus_win(parent);
5180
5181                                 if (focus_mode != SWM_FOCUS_FOLLOW) {
5182                                         pws->focus = pws->focus_pending;
5183                                         pws->focus_pending = NULL;
5184                                 }
5185                         }
5186
5187                         /* Don't unmap parent if new ws is visible */
5188                         if (nws->r == NULL)
5189                                 unmap_window(parent);
5190
5191                         /* Transfer */
5192                         TAILQ_REMOVE(&ws->winlist, parent, entry);
5193                         TAILQ_REMOVE(&ws->stack, parent, stack_entry);
5194                         TAILQ_INSERT_TAIL(&nws->winlist, parent, entry);
5195                         TAILQ_INSERT_TAIL(&nws->stack, parent, stack_entry);
5196                         parent->ws = nws;
5197
5198                         DNPRINTF(SWM_D_PROP, "win_to_ws: set property: "
5199                             "_NET_WM_DESKTOP: %d\n", wsid);
5200                         xcb_change_property(conn, XCB_PROP_MODE_REPLACE,
5201                             parent->id, ewmh[_NET_WM_DESKTOP].atom,
5202                             XCB_ATOM_CARDINAL, 32, 1, &wsid);
5203                 }
5204         }
5205
5206         if (unfocus)
5207                 unfocus_win(win);
5208
5209         if (ws->focus_prev == win)
5210                 ws->focus_prev = NULL;
5211
5212         if (focus_mode != SWM_FOCUS_FOLLOW && ws->focus_pending != NULL) {
5213                 ws->focus = ws->focus_pending;
5214                 ws->focus_pending = NULL;
5215         }
5216
5217         /* Don't unmap if new ws is visible */
5218         if (nws->r == NULL)
5219                 unmap_window(win);
5220
5221         /* Transfer */
5222         TAILQ_REMOVE(&ws->winlist, win, entry);
5223         TAILQ_REMOVE(&ws->stack, win, stack_entry);
5224         TAILQ_INSERT_TAIL(&nws->winlist, win, entry);
5225         TAILQ_INSERT_TAIL(&nws->stack, win, stack_entry);
5226         win->ws = nws;
5227
5228         /* Update the window's workspace property: _NET_WM_DESKTOP */
5229         DNPRINTF(SWM_D_PROP, "win_to_ws: set property: "
5230             "_NET_WM_DESKTOP: %d\n", wsid);
5231         xcb_change_property(conn, XCB_PROP_MODE_REPLACE, win->id,
5232             ewmh[_NET_WM_DESKTOP].atom, XCB_ATOM_CARDINAL, 32, 1, &wsid);
5233
5234         ewmh_update_client_list();
5235
5236         DNPRINTF(SWM_D_MOVE, "win_to_ws: done.\n");
5237 }
5238
5239 void
5240 pressbutton(struct swm_region *r, union arg *args)
5241 {
5242         /* suppress unused warning since var is needed */
5243         (void)r;
5244
5245         xcb_test_fake_input(conn, XCB_BUTTON_PRESS, args->id,
5246             XCB_CURRENT_TIME, XCB_WINDOW_NONE, 0, 0, 0);
5247         xcb_test_fake_input(conn, XCB_BUTTON_RELEASE, args->id,
5248             XCB_CURRENT_TIME, XCB_WINDOW_NONE, 0, 0, 0);
5249 }
5250
5251 void
5252 raise_toggle(struct swm_region *r, union arg *args)
5253 {
5254         /* suppress unused warning since var is needed */
5255         (void)args;
5256
5257         if (r == NULL || r->ws == NULL)
5258                 return;
5259
5260         if (r->ws->focus && MAXIMIZED(r->ws->focus))
5261                 return;
5262
5263         r->ws->always_raise = !r->ws->always_raise;
5264
5265         /* bring floaters back to top */
5266         if (!r->ws->always_raise)
5267                 stack();
5268
5269         focus_flush();
5270 }
5271
5272 void
5273 iconify(struct swm_region *r, union arg *args)
5274 {
5275         struct ws_win           *w;
5276         /* suppress unused warning since var is needed */
5277         (void)args;
5278
5279         if ((w = r->ws->focus) == NULL)
5280                 return;
5281
5282         ewmh_apply_flags(w, w->ewmh_flags | EWMH_F_HIDDEN);
5283         ewmh_update_wm_state(w);
5284
5285         stack();
5286
5287         focus_flush();
5288 }
5289
5290 char *
5291 get_win_name(xcb_window_t win)
5292 {
5293         char                            *name = NULL;
5294         xcb_get_property_cookie_t       c;
5295         xcb_get_property_reply_t        *r;
5296
5297         /* First try _NET_WM_NAME for UTF-8. */
5298         c = xcb_get_property(conn, 0, win, ewmh[_NET_WM_NAME].atom,
5299             XCB_GET_PROPERTY_TYPE_ANY, 0, UINT_MAX);
5300         r = xcb_get_property_reply(conn, c, NULL);
5301         if (r && r->type == XCB_NONE) {
5302                 free(r);
5303                 /* Use WM_NAME instead; no UTF-8. */
5304                 c = xcb_get_property(conn, 0, win, XCB_ATOM_WM_NAME,
5305                     XCB_GET_PROPERTY_TYPE_ANY, 0, UINT_MAX);
5306                 r = xcb_get_property_reply(conn, c, NULL);
5307         }
5308
5309         if (r && r->type != XCB_NONE && r->length > 0)
5310                 name = strndup(xcb_get_property_value(r),
5311                     xcb_get_property_value_length(r));
5312         else
5313                 name = strdup("");
5314
5315         if (name == NULL)
5316                 err(1, "get_win_name: failed to allocate memory.");
5317
5318         free(r);
5319
5320         return (name);
5321 }
5322
5323 void
5324 uniconify(struct swm_region *r, union arg *args)
5325 {
5326         struct ws_win           *win;
5327         FILE                    *lfile;
5328         char                    *name;
5329         int                     count = 0;
5330
5331         DNPRINTF(SWM_D_MISC, "uniconify\n");
5332
5333         if (r == NULL || r->ws == NULL)
5334                 return;
5335
5336         /* make sure we have anything to uniconify */
5337         TAILQ_FOREACH(win, &r->ws->winlist, entry) {
5338                 if (win->ws == NULL)
5339                         continue; /* should never happen */
5340                 if (!ICONIC(win))
5341                         continue;
5342                 count++;
5343         }
5344
5345         DNPRINTF(SWM_D_MISC, "uniconify: count: %d\n", count);
5346
5347         if (count == 0)
5348                 return;
5349
5350         search_r = r;
5351         search_resp_action = SWM_SEARCH_UNICONIFY;
5352
5353         spawn_select(r, args, "search", &searchpid);
5354
5355         if ((lfile = fdopen(select_list_pipe[1], "w")) == NULL)
5356                 return;
5357
5358         TAILQ_FOREACH(win, &r->ws->winlist, entry) {
5359                 if (win->ws == NULL)
5360                         continue; /* should never happen */
5361                 if (!ICONIC(win))
5362                         continue;
5363
5364                 name = get_win_name(win->id);
5365                 fprintf(lfile, "%s.%u\n", name, win->id);
5366                 free(name);
5367         }
5368
5369         fclose(lfile);
5370 }
5371
5372 void
5373 name_workspace(struct swm_region *r, union arg *args)
5374 {
5375         FILE                    *lfile;
5376
5377         DNPRINTF(SWM_D_MISC, "name_workspace\n");
5378
5379         if (r == NULL)
5380                 return;
5381
5382         search_r = r;
5383         search_resp_action = SWM_SEARCH_NAME_WORKSPACE;
5384
5385         spawn_select(r, args, "name_workspace", &searchpid);
5386
5387         if ((lfile = fdopen(select_list_pipe[1], "w")) == NULL)
5388                 return;
5389
5390         fprintf(lfile, "%s", "");
5391         fclose(lfile);
5392 }
5393
5394 void
5395 search_workspace(struct swm_region *r, union arg *args)
5396 {
5397         int                     i;
5398         struct workspace        *ws;
5399         FILE                    *lfile;
5400
5401         DNPRINTF(SWM_D_MISC, "search_workspace\n");
5402
5403         if (r == NULL)
5404                 return;
5405
5406         search_r = r;
5407         search_resp_action = SWM_SEARCH_SEARCH_WORKSPACE;
5408
5409         spawn_select(r, args, "search", &searchpid);
5410
5411         if ((lfile = fdopen(select_list_pipe[1], "w")) == NULL)
5412                 return;
5413
5414         for (i = 0; i < workspace_limit; i++) {
5415                 ws = &r->s->ws[i];
5416                 if (ws == NULL)
5417                         continue;
5418                 fprintf(lfile, "%d%s%s\n", ws->idx + 1,
5419                     (ws->name ? ":" : ""), (ws->name ? ws->name : ""));
5420         }
5421
5422         fclose(lfile);
5423 }
5424
5425 void
5426 search_win_cleanup(void)
5427 {
5428         struct search_window    *sw = NULL;
5429
5430         while ((sw = TAILQ_FIRST(&search_wl)) != NULL) {
5431                 xcb_destroy_window(conn, sw->indicator);
5432                 TAILQ_REMOVE(&search_wl, sw, entry);
5433                 free(sw);
5434         }
5435 }
5436
5437 void
5438 search_win(struct swm_region *r, union arg *args)
5439 {
5440         struct ws_win           *win = NULL;
5441         struct search_window    *sw = NULL;
5442         xcb_window_t            w;
5443         uint32_t                wa[3];
5444         xcb_screen_t            *screen;
5445         int                     i, width, height;
5446         char                    s[8];
5447         FILE                    *lfile;
5448         size_t                  len;
5449         XftDraw                 *draw;
5450         XGlyphInfo              info;
5451         GC                      l_draw;
5452         XGCValues               l_gcv;
5453         XRectangle              l_ibox, l_lbox;
5454
5455         DNPRINTF(SWM_D_MISC, "search_win\n");
5456
5457         search_r = r;
5458         search_resp_action = SWM_SEARCH_SEARCH_WINDOW;
5459
5460         spawn_select(r, args, "search", &searchpid);
5461
5462         if ((lfile = fdopen(select_list_pipe[1], "w")) == NULL)
5463                 return;
5464
5465         if ((screen = get_screen(r->s->idx)) == NULL)
5466                 errx(1, "ERROR: can't get screen %d.", r->s->idx);
5467
5468         TAILQ_INIT(&search_wl);
5469
5470         i = 1;
5471         TAILQ_FOREACH(win, &r->ws->winlist, entry) {
5472                 if (ICONIC(win))
5473                         continue;
5474
5475                 sw = calloc(1, sizeof(struct search_window));
5476                 if (sw == NULL) {
5477                         warn("search_win: calloc");
5478                         fclose(lfile);
5479                         search_win_cleanup();
5480                         return;
5481                 }
5482                 sw->idx = i;
5483                 sw->win = win;
5484
5485                 snprintf(s, sizeof s, "%d", i);
5486                 len = strlen(s);
5487
5488                 w = xcb_generate_id(conn);
5489                 wa[0] = r->s->c[SWM_S_COLOR_FOCUS].pixel;
5490                 wa[1] = r->s->c[SWM_S_COLOR_UNFOCUS].pixel;
5491                 wa[2] = screen->default_colormap;
5492
5493                 if (bar_font_legacy) {
5494                         XmbTextExtents(bar_fs, s, len, &l_ibox, &l_lbox);
5495                         width = l_lbox.width + 4;
5496                         height = bar_fs_extents->max_logical_extent.height + 4;
5497                 } else {
5498                         XftTextExtentsUtf8(display, bar_font, (FcChar8 *)s, len,
5499                             &info);
5500                         width = info.width + 4;
5501                         height = bar_font->height + 4;
5502                 }
5503
5504                 xcb_create_window(conn, screen->root_depth, w, win->id, 0, 0,
5505                     width, height, 1, XCB_WINDOW_CLASS_INPUT_OUTPUT,
5506                     screen->root_visual, XCB_CW_BACK_PIXEL |
5507                     XCB_CW_BORDER_PIXEL | XCB_CW_COLORMAP, wa);
5508
5509                 xcb_map_window(conn, w);
5510
5511                 sw->indicator = w;
5512                 TAILQ_INSERT_TAIL(&search_wl, sw, entry);
5513
5514                 if (bar_font_legacy) {
5515                         l_gcv.graphics_exposures = 0;
5516                         l_draw = XCreateGC(display, w, 0, &l_gcv);
5517
5518                         XSetForeground(display, l_draw,
5519                                 r->s->c[SWM_S_COLOR_BAR].pixel);
5520
5521                         DRAWSTRING(display, w, bar_fs, l_draw, 2,
5522                             (bar_fs_extents->max_logical_extent.height -
5523                             l_lbox.height) / 2 - l_lbox.y, s, len);
5524
5525                         XFreeGC(display, l_draw);
5526                 } else {
5527
5528                         draw = XftDrawCreate(display, w,
5529                             DefaultVisual(display, r->s->idx),
5530                             DefaultColormap(display, r->s->idx));
5531
5532                         XftDrawStringUtf8(draw, &search_font_color, bar_font, 2,
5533                             (HEIGHT(r->bar) + bar_font->height) / 2 -
5534                             bar_font->descent, (FcChar8 *)s, len);
5535
5536                         XftDrawDestroy(draw);
5537                 }
5538
5539                 DNPRINTF(SWM_D_MISC, "search_win: mapped win %#x\n", w);
5540
5541                 fprintf(lfile, "%d\n", i);
5542                 i++;
5543         }
5544
5545         fclose(lfile);
5546
5547         xcb_flush(conn);
5548 }
5549
5550 void
5551 search_resp_uniconify(const char *resp, size_t len)
5552 {
5553         char                    *name;
5554         struct ws_win           *win;
5555         char                    *s;
5556
5557         DNPRINTF(SWM_D_MISC, "search_resp_uniconify: resp: %s\n", resp);
5558
5559         TAILQ_FOREACH(win, &search_r->ws->winlist, entry) {
5560                 if (!ICONIC(win))
5561                         continue;
5562                 name = get_win_name(win->id);
5563                 if (asprintf(&s, "%s.%u", name, win->id) == -1) {
5564                         free(name);
5565                         continue;
5566                 }
5567                 free(name);
5568                 if (strncmp(s, resp, len) == 0) {
5569                         /* XXX this should be a callback to generalize */
5570                         ewmh_apply_flags(win, win->ewmh_flags & ~EWMH_F_HIDDEN);
5571                         ewmh_update_wm_state(win);
5572                         stack();
5573                         free(s);
5574                         break;
5575                 }
5576                 free(s);
5577         }
5578 }
5579
5580 void
5581 search_resp_name_workspace(const char *resp, size_t len)
5582 {
5583         struct workspace        *ws;
5584
5585         DNPRINTF(SWM_D_MISC, "search_resp_name_workspace: resp: %s\n", resp);
5586
5587         if (search_r->ws == NULL)
5588                 return;
5589         ws = search_r->ws;
5590
5591         if (ws->name) {
5592                 free(search_r->ws->name);
5593                 search_r->ws->name = NULL;
5594         }
5595
5596         if (len > 1) {
5597                 ws->name = strdup(resp);
5598                 if (ws->name == NULL) {
5599                         DNPRINTF(SWM_D_MISC, "search_resp_name_workspace: "
5600                             "strdup: %s", strerror(errno));
5601                         return;
5602                 }
5603
5604                 ewmh_update_desktop_names();
5605                 ewmh_get_desktop_names();
5606         }
5607 }
5608
5609 void
5610 ewmh_update_desktop_names(void)
5611 {
5612         char                    *name_list = NULL, *p;
5613         int                     num_screens, i, j, len = 0, tot = 0;
5614
5615         num_screens = get_screen_count();
5616         for (i = 0; i < num_screens; ++i) {
5617                 for (j = 0; j < workspace_limit; ++j) {
5618                         if (screens[i].ws[j].name != NULL)
5619                                 len += strlen(screens[i].ws[j].name);
5620                         ++len;
5621                 }
5622
5623                 if((name_list = calloc(len, sizeof(char))) == NULL)
5624                         err(1, "update_desktop_names: calloc: failed to "
5625                             "allocate memory.");
5626
5627                 p = name_list;
5628                 for (j = 0; j < workspace_limit; ++j) {
5629                         if (screens[i].ws[j].name != NULL) {
5630                                 len = strlen(screens[i].ws[j].name);
5631                                 memcpy(p, screens[i].ws[j].name, len);
5632                         } else {
5633                                 len = 0;
5634                         }
5635
5636                         p += len + 1;
5637                         tot += len + 1;
5638                 }
5639
5640                 xcb_change_property(conn, XCB_PROP_MODE_REPLACE,
5641                     screens[i].root, ewmh[_NET_DESKTOP_NAMES].atom,
5642                     a_utf8_string, 8, tot, name_list);
5643
5644                 free(name_list);
5645                 name_list = NULL;
5646         }
5647
5648         free(name_list);
5649 }
5650
5651 void
5652 ewmh_get_desktop_names(void)
5653 {
5654         char                            *names = NULL;
5655         xcb_get_property_cookie_t       c;
5656         xcb_get_property_reply_t        *r;
5657         int                             num_screens, i, j, n, k;
5658
5659         num_screens = get_screen_count();
5660         for (i = 0; i < num_screens; ++i) {
5661                 for (j = 0; j < workspace_limit; ++j) {
5662                         free(screens[i].ws[j].name);
5663                         screens[i].ws[j].name = NULL;
5664                 }
5665
5666                 c = xcb_get_property(conn, 0, screens[i].root,
5667                     ewmh[_NET_DESKTOP_NAMES].atom,
5668                     a_utf8_string, 0, UINT32_MAX);
5669                 r = xcb_get_property_reply(conn, c, NULL);
5670                 if (r == NULL)
5671                         continue;
5672
5673                 names = xcb_get_property_value(r);
5674                 n = xcb_get_property_value_length(r);
5675
5676                 for (j = 0, k = 0; j < n; ++j) {
5677                         if (*(names + j) != '\0') {
5678                                 screens[i].ws[k].name = strdup(names + j);
5679                                 j += strlen(names + j);
5680                         }
5681                         ++k;
5682                 }
5683                 free(r);
5684         }
5685 }
5686
5687 void
5688 ewmh_update_client_list(void)
5689 {
5690         struct ws_win           *win;
5691         int                     num_screens, i, j, k = 0, count = 0;
5692         xcb_window_t            *wins;
5693
5694         num_screens = get_screen_count();
5695         for (i = 0; i < num_screens; ++i) {
5696                 for (j = 0; j < workspace_limit; ++j)
5697                         TAILQ_FOREACH(win, &screens[i].ws[j].winlist, entry)
5698                                 ++count;
5699
5700                 DNPRINTF(SWM_D_PROP, "ewmh_update_client_list: win count: %d\n",
5701                     count);
5702
5703                 if (count == 0)
5704                         continue;
5705
5706                 wins = calloc(count, sizeof(xcb_window_t));
5707                 if (wins == NULL)
5708                         err(1, "ewmh_update_client_list: calloc: failed to "
5709                             "allocate memory.");
5710
5711                 for (j = 0, k = 0; j < workspace_limit; ++j)
5712                         TAILQ_FOREACH(win, &screens[i].ws[j].winlist, entry)
5713                                 wins[k++] = win->id;
5714
5715                 xcb_change_property(conn, XCB_PROP_MODE_REPLACE,
5716                     screens[i].root, ewmh[_NET_CLIENT_LIST].atom,
5717                     XCB_ATOM_WINDOW, 32, count, wins);
5718
5719                 free(wins);
5720         }
5721 }
5722
5723 void
5724 ewmh_update_current_desktop(void)
5725 {
5726         int                     num_screens, i;
5727
5728         num_screens = get_screen_count();
5729         for (i = 0; i < num_screens; ++i)
5730                 xcb_change_property(conn, XCB_PROP_MODE_REPLACE,
5731                     screens[i].root, ewmh[_NET_CURRENT_DESKTOP].atom,
5732                     XCB_ATOM_CARDINAL, 32, 1, &screens[i].r_focus->ws->idx);
5733 }
5734
5735 void
5736 ewmh_update_desktops(void)
5737 {
5738         int                     num_screens, i, j;
5739         uint32_t                *vals;
5740
5741         vals = calloc(workspace_limit * 2, sizeof(uint32_t));
5742         if (vals == NULL)
5743                 err(1, "ewmh_update_desktops: calloc: failed to allocate "
5744                     "memory.");
5745
5746         num_screens = get_screen_count();
5747         for (i = 0; i < num_screens; i++) {
5748                 xcb_change_property(conn, XCB_PROP_MODE_REPLACE,
5749                     screens[i].root, ewmh[_NET_NUMBER_OF_DESKTOPS].atom,
5750                     XCB_ATOM_CARDINAL, 32, 1, &workspace_limit);
5751
5752                 for (j = 0; j < workspace_limit; ++j) {
5753                         if (screens[i].ws[j].r != NULL) {
5754                                 vals[j * 2] = X(screens[i].ws[j].r);
5755                                 vals[j * 2 + 1] = Y(screens[i].ws[j].r);
5756                         } else if (screens[i].ws[j].old_r != NULL) {
5757                                 vals[j * 2] = X(screens[i].ws[j].old_r);
5758                                 vals[j * 2 + 1] = Y(screens[i].ws[j].old_r);
5759                         } else {
5760                                 vals[j * 2] = vals[j * 2 + 1] = 0;
5761                         }
5762                 }
5763
5764                 xcb_change_property(conn, XCB_PROP_MODE_REPLACE,
5765                     screens[i].root, ewmh[_NET_DESKTOP_VIEWPORT].atom,
5766                     XCB_ATOM_CARDINAL, 32, workspace_limit * 2, vals);
5767         }
5768
5769         free(vals);
5770 }
5771
5772 void
5773 search_resp_search_workspace(const char *resp)
5774 {
5775         char                    *p, *q;
5776         int                     ws_idx;
5777         const char              *errstr;
5778         union arg               a;
5779
5780         DNPRINTF(SWM_D_MISC, "search_resp_search_workspace: resp: %s\n", resp);
5781
5782         q = strdup(resp);
5783         if (q == NULL) {
5784                 DNPRINTF(SWM_D_MISC, "search_resp_search_workspace: strdup: %s",
5785                     strerror(errno));
5786                 return;
5787         }
5788         p = strchr(q, ':');
5789         if (p != NULL)
5790                 *p = '\0';
5791         ws_idx = (int)strtonum(q, 1, workspace_limit, &errstr);
5792         if (errstr) {
5793                 DNPRINTF(SWM_D_MISC, "workspace idx is %s: %s",
5794                     errstr, q);
5795                 free(q);
5796                 return;
5797         }
5798         free(q);
5799         a.id = ws_idx - 1;
5800         switchws(search_r, &a);
5801 }
5802
5803 void
5804 search_resp_search_window(const char *resp)
5805 {
5806         char                    *s;
5807         int                     idx;
5808         const char              *errstr;
5809         struct search_window    *sw;
5810
5811         DNPRINTF(SWM_D_MISC, "search_resp_search_window: resp: %s\n", resp);
5812
5813         s = strdup(resp);
5814         if (s == NULL) {
5815                 DNPRINTF(SWM_D_MISC, "search_resp_search_window: strdup: %s",
5816                     strerror(errno));
5817                 return;
5818         }
5819
5820         idx = (int)strtonum(s, 1, INT_MAX, &errstr);
5821         if (errstr) {
5822                 DNPRINTF(SWM_D_MISC, "window idx is %s: %s",
5823                     errstr, s);
5824                 free(s);
5825                 return;
5826         }
5827         free(s);
5828
5829         TAILQ_FOREACH(sw, &search_wl, entry)
5830                 if (idx == sw->idx) {
5831                         focus_win(sw->win);
5832                         break;
5833                 }
5834 }
5835
5836 #define MAX_RESP_LEN    1024
5837
5838 void
5839 search_do_resp(void)
5840 {
5841         ssize_t                 rbytes;
5842         char                    *resp;
5843         size_t                  len;
5844
5845         DNPRINTF(SWM_D_MISC, "search_do_resp:\n");
5846
5847         search_resp = 0;
5848         searchpid = 0;
5849
5850         if ((resp = calloc(1, MAX_RESP_LEN + 1)) == NULL) {
5851                 warn("search: calloc");
5852                 goto done;
5853         }
5854
5855         rbytes = read(select_resp_pipe[0], resp, MAX_RESP_LEN);
5856         if (rbytes <= 0) {
5857                 warn("search: read error");
5858                 goto done;
5859         }
5860         resp[rbytes] = '\0';
5861
5862         /* XXX:
5863          * Older versions of dmenu (Atleast pre 4.4.1) do not send a
5864          * newline, so work around that by sanitizing the resp now.
5865          */
5866         resp[strcspn(resp, "\n")] = '\0';
5867         len = strlen(resp);
5868
5869         switch (search_resp_action) {
5870         case SWM_SEARCH_UNICONIFY:
5871                 search_resp_uniconify(resp, len);
5872                 break;
5873         case SWM_SEARCH_NAME_WORKSPACE:
5874                 search_resp_name_workspace(resp, len);
5875                 break;
5876         case SWM_SEARCH_SEARCH_WORKSPACE:
5877                 search_resp_search_workspace(resp);
5878                 break;
5879         case SWM_SEARCH_SEARCH_WINDOW:
5880                 search_resp_search_window(resp);
5881                 break;
5882         }
5883
5884 done:
5885         if (search_resp_action == SWM_SEARCH_SEARCH_WINDOW)
5886                 search_win_cleanup();
5887
5888         search_resp_action = SWM_SEARCH_NONE;
5889         close(select_resp_pipe[0]);
5890         free(resp);
5891
5892         xcb_flush(conn);
5893 }
5894
5895 void
5896 wkill(struct swm_region *r, union arg *args)
5897 {
5898         DNPRINTF(SWM_D_MISC, "wkill: win %#x, id: %d\n", WINID(r->ws->focus),
5899             args->id);
5900
5901         if (r->ws->focus == NULL)
5902                 return;
5903
5904         if (args->id == SWM_ARG_ID_KILLWINDOW)
5905                 xcb_kill_client(conn, r->ws->focus->id);
5906         else
5907                 if (r->ws->focus->can_delete)
5908                         client_msg(r->ws->focus, a_delete, 0);
5909
5910         focus_flush();
5911 }
5912
5913 int
5914 clear_maximized(struct workspace *ws)
5915 {
5916         struct ws_win           *w;
5917         int                     count = 0;
5918
5919         /* Clear any maximized win(s) on ws, from bottom up. */
5920         TAILQ_FOREACH_REVERSE(w, &ws->stack, ws_win_stack, stack_entry)
5921                 if (MAXIMIZED(w)) {
5922                         ewmh_apply_flags(w, w->ewmh_flags & ~EWMH_F_MAXIMIZED);
5923                         ewmh_update_wm_state(w);
5924                         ++count;
5925                 }
5926
5927         return count;
5928 }
5929
5930 void
5931 maximize_toggle(struct swm_region *r, union arg *args)
5932 {
5933         struct ws_win           *w = r->ws->focus;
5934
5935         /* suppress unused warning since var is needed */
5936         (void)args;
5937
5938         if (w == NULL)
5939                 return;
5940
5941         DNPRINTF(SWM_D_MISC, "maximize_toggle: win %#x\n", w->id);
5942
5943         if (FULLSCREEN(w))
5944                 return;
5945
5946         if (w->ws->cur_layout == &layouts[SWM_MAX_STACK])
5947                 return;
5948
5949         ewmh_apply_flags(w, w->ewmh_flags ^ EWMH_F_MAXIMIZED);
5950         ewmh_update_wm_state(w);
5951
5952         stack();
5953
5954         if (w == w->ws->focus)
5955                 focus_win(w);
5956
5957         center_pointer(r);
5958         focus_flush();
5959         DNPRINTF(SWM_D_MISC, "maximize_toggle: done\n");
5960 }
5961
5962 void
5963 floating_toggle(struct swm_region *r, union arg *args)
5964 {
5965         struct ws_win           *w = r->ws->focus;
5966
5967         /* suppress unused warning since var is needed */
5968         (void)args;
5969
5970         if (w == NULL)
5971                 return;
5972
5973         DNPRINTF(SWM_D_MISC, "floating_toggle: win %#x\n", w->id);
5974
5975         if (FULLSCREEN(w) || TRANS(w))
5976                 return;
5977
5978         if (w->ws->cur_layout == &layouts[SWM_MAX_STACK])
5979                 return;
5980
5981         ewmh_apply_flags(w, w->ewmh_flags ^ EWMH_F_ABOVE);
5982         ewmh_update_wm_state(w);
5983
5984         stack();
5985
5986         if (w == w->ws->focus)
5987                 focus_win(w);
5988
5989         center_pointer(r);
5990         focus_flush();
5991         DNPRINTF(SWM_D_MISC, "floating_toggle: done\n");
5992 }
5993
5994 void
5995 region_containment(struct ws_win *win, struct swm_region *r, int opts)
5996 {
5997         struct swm_geometry             g = r->g;
5998         int                             rt, lt, tp, bm, bw;
5999
6000         bw = (opts & SWM_CW_SOFTBOUNDARY) ? boundary_width : 0;
6001
6002         /*
6003          * Perpendicular distance of each side of the window to the respective
6004          * side of the region boundary.  Positive values indicate the side of
6005          * the window has passed beyond the region boundary.
6006          */
6007         rt = opts & SWM_CW_RIGHT ? MAX_X(win) + BORDER(win) - MAX_X(r) : bw;
6008         lt = opts & SWM_CW_LEFT ? X(r) - X(win) + BORDER(win) : bw;
6009         bm = opts & SWM_CW_BOTTOM ? MAX_Y(win) + BORDER(win) - MAX_Y(r) : bw;
6010         tp = opts & SWM_CW_TOP ? Y(r) - Y(win) + BORDER(win) : bw;
6011
6012         DNPRINTF(SWM_D_MISC, "region_containment: win %#x, rt: %d, lt: %d, "
6013             "bm: %d, tp: %d, SOFTBOUNDARY: %s, HARDBOUNDARY: %s\n", win->id, rt,
6014             lt, bm, tp, YESNO(opts & SWM_CW_SOFTBOUNDARY),
6015             YESNO(opts & SWM_CW_HARDBOUNDARY));
6016
6017         /*
6018          * Disable containment if any of the flagged sides went beyond the
6019          * containment boundary, or if containment is disabled.
6020          */
6021         if (!(opts & SWM_CW_HARDBOUNDARY || opts & SWM_CW_SOFTBOUNDARY) ||
6022             (bw != 0 && ((rt > bw) || (lt > bw) || (bm > bw) || (tp > bw)))) {
6023                 /* Make sure window has at least 1 pixel in the region */
6024                 g.x += 1 - WIDTH(win);
6025                 g.y += 1 - HEIGHT(win);
6026                 g.w += 2 * WIDTH(win) - 2;
6027                 g.h += 2 * HEIGHT(win) - 2;
6028         }
6029
6030         constrain_window(win, &g, &opts);
6031 }
6032
6033 /* Move or resize a window so that flagged side(s) fit into the supplied box. */
6034 void
6035 constrain_window(struct ws_win *win, struct swm_geometry *b, int *opts)
6036 {
6037         DNPRINTF(SWM_D_MISC, "constrain_window: win %#x, (x,y) w x h: "
6038             "(%d,%d) %d x %d, box: (x,y) w x h: (%d,%d) %d x %d, rt: %s, "
6039             "lt: %s, bt: %s, tp: %s, allow resize: %s\n", win->id, X(win),
6040             Y(win), WIDTH(win), HEIGHT(win), b->x, b->y, b->w, b->h,
6041             YESNO(*opts & SWM_CW_RIGHT), YESNO(*opts & SWM_CW_LEFT),
6042             YESNO(*opts & SWM_CW_BOTTOM), YESNO(*opts & SWM_CW_TOP),
6043             YESNO(*opts & SWM_CW_RESIZABLE));
6044
6045         if ((*opts & SWM_CW_RIGHT) && MAX_X(win) + BORDER(win) > b->x + b->w) {
6046                 if (*opts & SWM_CW_RESIZABLE)
6047                         WIDTH(win) = b->x + b->w - X(win) - BORDER(win);
6048                 else
6049                         X(win) = b->x + b->w - WIDTH(win) - BORDER(win);
6050         }
6051
6052         if ((*opts & SWM_CW_LEFT) && X(win) + BORDER(win) < b->x) {
6053                 if (*opts & SWM_CW_RESIZABLE)
6054                         WIDTH(win) -= b->x - X(win) - BORDER(win);
6055
6056                 X(win) = b->x - BORDER(win);
6057         }
6058
6059         if ((*opts & SWM_CW_BOTTOM) && MAX_Y(win) + BORDER(win) > b->y + b->h) {
6060                 if (*opts & SWM_CW_RESIZABLE)
6061                         HEIGHT(win) = b->y + b->h - Y(win) - BORDER(win);
6062                 else
6063                         Y(win) = b->y + b->h - HEIGHT(win) - BORDER(win);
6064         }
6065
6066         if ((*opts & SWM_CW_TOP) && Y(win) + BORDER(win) < b->y) {
6067                 if (*opts & SWM_CW_RESIZABLE)
6068                         HEIGHT(win) -= b->y - Y(win) - BORDER(win);
6069
6070                 Y(win) = b->y - BORDER(win);
6071         }
6072
6073         if (*opts & SWM_CW_RESIZABLE) {
6074                 if (WIDTH(win) < 1)
6075                         WIDTH(win) = 1;
6076                 if (HEIGHT(win) < 1)
6077                         HEIGHT(win) = 1;
6078         }
6079 }
6080
6081 void
6082 update_window_color(struct ws_win *win)
6083 {
6084         uint32_t        *pixel;
6085
6086         if (WS_FOCUSED(win->ws) && win->ws->focus == win)
6087                 pixel = MAXIMIZED(win) ?
6088                     &win->s->c[SWM_S_COLOR_FOCUS_MAXIMIZED].pixel :
6089                     &win->s->c[SWM_S_COLOR_FOCUS].pixel;
6090         else
6091                 pixel = MAXIMIZED(win) ?
6092                     &win->s->c[SWM_S_COLOR_UNFOCUS_MAXIMIZED].pixel :
6093                     &win->s->c[SWM_S_COLOR_UNFOCUS].pixel;
6094
6095         xcb_change_window_attributes(conn, win->id,
6096             XCB_CW_BORDER_PIXEL, pixel);
6097 }
6098
6099 void
6100 update_window(struct ws_win *win)
6101 {
6102         uint16_t        mask;
6103         uint32_t        wc[5];
6104
6105         mask = XCB_CONFIG_WINDOW_X | XCB_CONFIG_WINDOW_Y |
6106             XCB_CONFIG_WINDOW_WIDTH | XCB_CONFIG_WINDOW_HEIGHT |
6107             XCB_CONFIG_WINDOW_BORDER_WIDTH;
6108         wc[0] = X(win);
6109         wc[1] = Y(win);
6110         wc[2] = WIDTH(win);
6111         wc[3] = HEIGHT(win);
6112         wc[4] = BORDER(win);
6113
6114         DNPRINTF(SWM_D_EVENT, "update_window: win %#x, (x,y) w x h: "
6115             "(%d,%d) %d x %d, bordered: %s\n", win->id, wc[0], wc[1], wc[2],
6116             wc[3], YESNO(win->bordered));
6117
6118         xcb_configure_window(conn, win->id, mask, wc);
6119 }
6120
6121 #define SWM_RESIZE_STEPS        (50)
6122
6123 void
6124 resize(struct ws_win *win, union arg *args)
6125 {
6126         xcb_timestamp_t         timestamp = 0;
6127         struct swm_region       *r = NULL;
6128         struct swm_geometry     g;
6129         int                     resize_stp = 0;
6130         int                     top = 0, left = 0;
6131         int                     dx, dy;
6132         xcb_cursor_t                    cursor;
6133         xcb_query_pointer_reply_t       *xpr = NULL;
6134         xcb_generic_event_t             *evt;
6135         xcb_motion_notify_event_t       *mne;
6136         bool                    resizing;
6137
6138         if (win == NULL)
6139                 return;
6140         r = win->ws->r;
6141
6142         if (FULLSCREEN(win))
6143                 return;
6144
6145         /* In max_stack mode, should only resize transients. */
6146         if (win->ws->cur_layout == &layouts[SWM_MAX_STACK] && !TRANS(win))
6147                 return;
6148
6149         DNPRINTF(SWM_D_EVENT, "resize: win %#x, floating: %s, "
6150             "transient: %#x\n", win->id, YESNO(ABOVE(win)),
6151             win->transient);
6152
6153         if (MAXIMIZED(win))
6154                 store_float_geom(win);
6155         else if (!(TRANS(win) || ABOVE(win)))
6156                 return;
6157
6158         ewmh_apply_flags(win, (win->ewmh_flags | SWM_F_MANUAL | EWMH_F_ABOVE) &
6159             ~EWMH_F_MAXIMIZED);
6160         ewmh_update_wm_state(win);
6161
6162         stack();
6163
6164         focus_flush();
6165
6166         /* It's possible for win to have been freed during focus_flush(). */
6167         if (validate_win(win)) {
6168                 DNPRINTF(SWM_D_EVENT, "resize: invalid win.\n");
6169                 goto out;
6170         }
6171
6172         switch (args->id) {
6173         case SWM_ARG_ID_WIDTHSHRINK:
6174                 WIDTH(win) -= SWM_RESIZE_STEPS;
6175                 resize_stp = 1;
6176                 break;
6177         case SWM_ARG_ID_WIDTHGROW:
6178                 WIDTH(win) += SWM_RESIZE_STEPS;
6179                 resize_stp = 1;
6180                 break;
6181         case SWM_ARG_ID_HEIGHTSHRINK:
6182                 HEIGHT(win) -= SWM_RESIZE_STEPS;
6183                 resize_stp = 1;
6184                 break;
6185         case SWM_ARG_ID_HEIGHTGROW:
6186                 HEIGHT(win) += SWM_RESIZE_STEPS;
6187                 resize_stp = 1;
6188                 break;
6189         default:
6190                 break;
6191         }
6192         if (resize_stp) {
6193                 region_containment(win, r, SWM_CW_ALLSIDES | SWM_CW_RESIZABLE |
6194                     SWM_CW_HARDBOUNDARY);
6195                 update_window(win);
6196                 store_float_geom(win);
6197                 return;
6198         }
6199
6200         region_containment(win, r, SWM_CW_ALLSIDES | SWM_CW_RESIZABLE |
6201             SWM_CW_SOFTBOUNDARY);
6202         update_window(win);
6203
6204         /* get cursor offset from window root */
6205         xpr = xcb_query_pointer_reply(conn, xcb_query_pointer(conn, win->id),
6206             NULL);
6207         if (xpr == NULL)
6208                 return;
6209
6210         g = win->g;
6211
6212         if (xpr->win_x < WIDTH(win) / 2)
6213                 left = 1;
6214
6215         if (xpr->win_y < HEIGHT(win) / 2)
6216                 top = 1;
6217
6218         if (args->id == SWM_ARG_ID_CENTER)
6219                 cursor = cursors[XC_SIZING].cid;
6220         else if (top)
6221                 cursor = cursors[left ? XC_TOP_LEFT_CORNER :
6222                     XC_TOP_RIGHT_CORNER].cid;
6223         else
6224                 cursor = cursors[left ? XC_BOTTOM_LEFT_CORNER :
6225                     XC_BOTTOM_RIGHT_CORNER].cid;
6226
6227         xcb_grab_pointer(conn, 0, win->id, MOUSEMASK,
6228             XCB_GRAB_MODE_ASYNC, XCB_GRAB_MODE_ASYNC, XCB_WINDOW_NONE, cursor,
6229             XCB_CURRENT_TIME),
6230
6231         xcb_flush(conn);
6232         resizing = true;
6233         while (resizing && (evt = xcb_wait_for_event(conn))) {
6234                 switch (XCB_EVENT_RESPONSE_TYPE(evt)) {
6235                 case XCB_BUTTON_RELEASE:
6236                         DNPRINTF(SWM_D_EVENT, "resize: BUTTON_RELEASE\n");
6237                         resizing = false;
6238                         break;
6239                 case XCB_MOTION_NOTIFY:
6240                         mne = (xcb_motion_notify_event_t *)evt;
6241                         /* cursor offset/delta from start of the operation */
6242                         dx = mne->root_x - xpr->root_x;
6243                         dy = mne->root_y - xpr->root_y;
6244
6245                         /* vertical */
6246                         if (top)
6247                                 dy = -dy;
6248
6249                         if (args->id == SWM_ARG_ID_CENTER) {
6250                                 if (g.h / 2 + dy < 1)
6251                                         dy = 1 - g.h / 2;
6252
6253                                 Y(win) = g.y - dy;
6254                                 HEIGHT(win) = g.h + 2 * dy;
6255                         } else {
6256                                 if (g.h + dy < 1)
6257                                         dy = 1 - g.h;
6258
6259                                 if (top)
6260                                         Y(win) = g.y - dy;
6261
6262                                 HEIGHT(win) = g.h + dy;
6263                         }
6264
6265                         /* horizontal */
6266                         if (left)
6267                                 dx = -dx;
6268
6269                         if (args->id == SWM_ARG_ID_CENTER) {
6270                                 if (g.w / 2 + dx < 1)
6271                                         dx = 1 - g.w / 2;
6272
6273                                 X(win) = g.x - dx;
6274                                 WIDTH(win) = g.w + 2 * dx;
6275                         } else {
6276                                 if (g.w + dx < 1)
6277                                         dx = 1 - g.w;
6278
6279                                 if (left)
6280                                         X(win) = g.x - dx;
6281
6282                                 WIDTH(win) = g.w + dx;
6283                         }
6284
6285                         /* not free, don't sync more than 120 times / second */
6286                         if ((mne->time - timestamp) > (1000 / 120) ) {
6287                                 timestamp = mne->time;
6288                                 regionize(win, mne->root_x, mne->root_y);
6289                                 region_containment(win, r, SWM_CW_ALLSIDES |
6290                                     SWM_CW_RESIZABLE | SWM_CW_HARDBOUNDARY |
6291                                     SWM_CW_SOFTBOUNDARY);
6292                                 update_window(win);
6293                                 xcb_flush(conn);
6294                         }
6295                         break;
6296                 case XCB_KEY_PRESS:
6297                         /* Ignore. */
6298                         xcb_allow_events(conn, XCB_ALLOW_ASYNC_KEYBOARD,
6299                             ((xcb_key_press_event_t *)evt)->time);
6300                         xcb_flush(conn);
6301                         break;
6302                 default:
6303                         event_handle(evt);
6304
6305                         /* It's possible for win to have been freed above. */
6306                         if (validate_win(win)) {
6307                                 DNPRINTF(SWM_D_EVENT, "resize: invalid win.\n");
6308                                 goto out;
6309                         }
6310                         break;
6311                 }
6312                 free(evt);
6313         }
6314         if (timestamp) {
6315                 region_containment(win, r, SWM_CW_ALLSIDES | SWM_CW_RESIZABLE |
6316                     SWM_CW_HARDBOUNDARY | SWM_CW_SOFTBOUNDARY);
6317                 update_window(win);
6318                 xcb_flush(conn);
6319         }
6320         store_float_geom(win);
6321 out:
6322         xcb_ungrab_pointer(conn, XCB_CURRENT_TIME);
6323         free(xpr);
6324         DNPRINTF(SWM_D_EVENT, "resize: done.\n");
6325 }
6326
6327 void
6328 resize_step(struct swm_region *r, union arg *args)
6329 {
6330         struct ws_win           *win = NULL;
6331
6332         if (r && r->ws && r->ws->focus)
6333                 win = r->ws->focus;
6334         else
6335                 return;
6336
6337         resize(win, args);
6338         center_pointer(r);
6339         focus_flush();
6340 }
6341
6342 /* Try to set window region based on supplied coordinates or window center. */
6343 void
6344 regionize(struct ws_win *win, int x, int y)
6345 {
6346         struct swm_region *r = NULL;
6347
6348         r = region_under(win->s, x, y);
6349         if (r == NULL)
6350                 r = region_under(win->s, X(win) + WIDTH(win) / 2,
6351                     Y(win) + HEIGHT(win) / 2);
6352
6353         if (r != NULL && r != win->ws->r) {
6354                 if (clear_maximized(r->ws) > 0)
6355                         stack();
6356
6357                 win_to_ws(win, r->ws->idx, false);
6358
6359                 /* Set focus on new ws. */
6360                 unfocus_win(r->ws->focus);
6361                 r->ws->focus = win;
6362
6363                 set_region(r);
6364                 raise_window(win);
6365         }
6366 }
6367
6368 #define SWM_MOVE_STEPS  (50)
6369
6370 void
6371 move(struct ws_win *win, union arg *args)
6372 {
6373         struct swm_region               *r;
6374         xcb_timestamp_t                 timestamp = 0;
6375         int                             move_stp = 0;
6376         xcb_query_pointer_reply_t       *qpr = NULL;
6377         xcb_generic_event_t             *evt;
6378         xcb_motion_notify_event_t       *mne;
6379         bool                            moving, restack = false;
6380
6381         if (win == NULL)
6382                 return;
6383
6384         if ((r = win->ws->r) == NULL)
6385                 return;
6386
6387         if (FULLSCREEN(win))
6388                 return;
6389
6390         DNPRINTF(SWM_D_EVENT, "move: win %#x, floating: %s, transient: "
6391             "%#x\n", win->id, YESNO(ABOVE(win)), win->transient);
6392
6393         /* in max_stack mode should only move transients */
6394         if (win->ws->cur_layout == &layouts[SWM_MAX_STACK] && !TRANS(win))
6395                 return;
6396
6397         if (!(ABOVE(win) || TRANS(win)) || MAXIMIZED(win)) {
6398                 store_float_geom(win);
6399                 restack = true;
6400         }
6401
6402         ewmh_apply_flags(win, (win->ewmh_flags | SWM_F_MANUAL | EWMH_F_ABOVE) &
6403             ~EWMH_F_MAXIMIZED);
6404         ewmh_update_wm_state(win);
6405
6406         if (restack)
6407                 stack();
6408
6409         focus_flush();
6410
6411         /* It's possible for win to have been freed during focus_flush(). */
6412         if (validate_win(win)) {
6413                 DNPRINTF(SWM_D_EVENT, "move: invalid win.\n");
6414                 goto out;
6415         }
6416
6417         move_stp = 0;
6418         switch (args->id) {
6419         case SWM_ARG_ID_MOVELEFT:
6420                 X(win) -= (SWM_MOVE_STEPS - border_width);
6421                 move_stp = 1;
6422                 break;
6423         case SWM_ARG_ID_MOVERIGHT:
6424                 X(win) += (SWM_MOVE_STEPS - border_width);
6425                 move_stp = 1;
6426                 break;
6427         case SWM_ARG_ID_MOVEUP:
6428                 Y(win) -= (SWM_MOVE_STEPS - border_width);
6429                 move_stp = 1;
6430                 break;
6431         case SWM_ARG_ID_MOVEDOWN:
6432                 Y(win) += (SWM_MOVE_STEPS - border_width);
6433                 move_stp = 1;
6434                 break;
6435         default:
6436                 break;
6437         }
6438         if (move_stp) {
6439                 regionize(win, -1, -1);
6440                 region_containment(win, win->ws->r, SWM_CW_ALLSIDES);
6441                 update_window(win);
6442                 store_float_geom(win);
6443                 return;
6444         }
6445
6446         xcb_grab_pointer(conn, 0, win->id, MOUSEMASK,
6447             XCB_GRAB_MODE_ASYNC, XCB_GRAB_MODE_ASYNC,
6448             XCB_WINDOW_NONE, cursors[XC_FLEUR].cid, XCB_CURRENT_TIME);
6449
6450         /* get cursor offset from window root */
6451         qpr = xcb_query_pointer_reply(conn, xcb_query_pointer(conn, win->id),
6452                 NULL);
6453         if (qpr == NULL) {
6454                 xcb_ungrab_pointer(conn, XCB_CURRENT_TIME);
6455                 return;
6456         }
6457
6458         regionize(win, qpr->root_x, qpr->root_y);
6459         region_containment(win, win->ws->r, SWM_CW_ALLSIDES |
6460             SWM_CW_SOFTBOUNDARY);
6461         update_window(win);
6462         xcb_flush(conn);
6463         moving = true;
6464         while (moving && (evt = xcb_wait_for_event(conn))) {
6465                 switch (XCB_EVENT_RESPONSE_TYPE(evt)) {
6466                 case XCB_BUTTON_RELEASE:
6467                         DNPRINTF(SWM_D_EVENT, "move: BUTTON_RELEASE\n");
6468                         moving = false;
6469                         break;
6470                 case XCB_MOTION_NOTIFY:
6471                         mne = (xcb_motion_notify_event_t *)evt;
6472                         DNPRINTF(SWM_D_EVENT, "motion: root: %#x\n", mne->root);
6473                         X(win) = mne->root_x - qpr->win_x - border_width;
6474                         Y(win) = mne->root_y - qpr->win_y - border_width;
6475
6476                         /* not free, don't sync more than 120 times / second */
6477                         if ((mne->time - timestamp) > (1000 / 120) ) {
6478                                 timestamp = mne->time;
6479                                 regionize(win, mne->root_x, mne->root_y);
6480                                 region_containment(win, win->ws->r,
6481                                     SWM_CW_ALLSIDES | SWM_CW_SOFTBOUNDARY);
6482                                 update_window(win);
6483                                 xcb_flush(conn);
6484                         }
6485                         break;
6486                 case XCB_KEY_PRESS:
6487                         /* Ignore. */
6488                         xcb_allow_events(conn, XCB_ALLOW_ASYNC_KEYBOARD,
6489                             ((xcb_key_press_event_t *)evt)->time);
6490                         xcb_flush(conn);
6491                         break;
6492                 default:
6493                         event_handle(evt);
6494
6495                         /* It's possible for win to have been freed above. */
6496                         if (validate_win(win)) {
6497                                 DNPRINTF(SWM_D_EVENT, "move: invalid win.\n");
6498                                 goto out;
6499                         }
6500                         break;
6501                 }
6502                 free(evt);
6503         }
6504         if (timestamp) {
6505                 region_containment(win, win->ws->r, SWM_CW_ALLSIDES |
6506                     SWM_CW_SOFTBOUNDARY);
6507                 update_window(win);
6508                 xcb_flush(conn);
6509         }
6510         store_float_geom(win);
6511
6512         /* New region set to fullscreen layout. */
6513         if (win->ws->cur_layout == &layouts[SWM_MAX_STACK]) {
6514                 stack();
6515                 focus_flush();
6516         }
6517
6518 out:
6519         free(qpr);
6520         xcb_ungrab_pointer(conn, XCB_CURRENT_TIME);
6521         DNPRINTF(SWM_D_EVENT, "move: done.\n");
6522 }
6523
6524 void
6525 move_step(struct swm_region *r, union arg *args)
6526 {
6527         struct ws_win           *win = NULL;
6528
6529         if (r && r->ws && r->ws->focus)
6530                 win = r->ws->focus;
6531         else
6532                 return;
6533
6534         if (!TRANS(win) && !ABOVE(win))
6535                 return;
6536
6537         move(win, args);
6538         center_pointer(r);
6539         focus_flush();
6540 }
6541
6542 /* key definitions */
6543 struct keyfunc {
6544         char                    name[SWM_FUNCNAME_LEN];
6545         void                    (*func)(struct swm_region *r, union arg *);
6546         union arg               args;
6547 } keyfuncs[KF_INVALID + 1] = {
6548         /* name                 function        argument */
6549         { "bar_toggle",         bar_toggle,     {.id = SWM_ARG_ID_BAR_TOGGLE} },
6550         { "bar_toggle_ws",      bar_toggle,     {.id = SWM_ARG_ID_BAR_TOGGLE_WS} },
6551         { "button2",            pressbutton,    {2} },
6552         { "cycle_layout",       cycle_layout,   {0} },
6553         { "flip_layout",        stack_config,   {.id = SWM_ARG_ID_FLIPLAYOUT} },
6554         { "float_toggle",       floating_toggle,{0} },
6555         { "focus_main",         focus,          {.id = SWM_ARG_ID_FOCUSMAIN} },
6556         { "focus_next",         focus,          {.id = SWM_ARG_ID_FOCUSNEXT} },
6557         { "focus_prev",         focus,          {.id = SWM_ARG_ID_FOCUSPREV} },
6558         { "focus_urgent",       focus,          {.id = SWM_ARG_ID_FOCUSURGENT} },
6559         { "maximize_toggle",    maximize_toggle,{0} },
6560         { "height_grow",        resize_step,    {.id = SWM_ARG_ID_HEIGHTGROW} },
6561         { "height_shrink",      resize_step,    {.id = SWM_ARG_ID_HEIGHTSHRINK} },
6562         { "iconify",            iconify,        {0} },
6563         { "master_shrink",      stack_config,   {.id = SWM_ARG_ID_MASTERSHRINK} },
6564         { "master_grow",        stack_config,   {.id = SWM_ARG_ID_MASTERGROW} },
6565         { "master_add",         stack_config,   {.id = SWM_ARG_ID_MASTERADD} },
6566         { "master_del",         stack_config,   {.id = SWM_ARG_ID_MASTERDEL} },
6567         { "move_down",          move_step,      {.id = SWM_ARG_ID_MOVEDOWN} },
6568         { "move_left",          move_step,      {.id = SWM_ARG_ID_MOVELEFT} },
6569         { "move_right",         move_step,      {.id = SWM_ARG_ID_MOVERIGHT} },
6570         { "move_up",            move_step,      {.id = SWM_ARG_ID_MOVEUP} },
6571         { "mvrg_1",             send_to_rg,     {.id = 0} },
6572         { "mvrg_2",             send_to_rg,     {.id = 1} },
6573         { "mvrg_3",             send_to_rg,     {.id = 2} },
6574         { "mvrg_4",             send_to_rg,     {.id = 3} },
6575         { "mvrg_5",             send_to_rg,     {.id = 4} },
6576         { "mvrg_6",             send_to_rg,     {.id = 5} },
6577         { "mvrg_7",             send_to_rg,     {.id = 6} },
6578         { "mvrg_8",             send_to_rg,     {.id = 7} },
6579         { "mvrg_9",             send_to_rg,     {.id = 8} },
6580         { "mvws_1",             send_to_ws,     {.id = 0} },
6581         { "mvws_2",             send_to_ws,     {.id = 1} },
6582         { "mvws_3",             send_to_ws,     {.id = 2} },
6583         { "mvws_4",             send_to_ws,     {.id = 3} },
6584         { "mvws_5",             send_to_ws,     {.id = 4} },
6585         { "mvws_6",             send_to_ws,     {.id = 5} },
6586         { "mvws_7",             send_to_ws,     {.id = 6} },
6587         { "mvws_8",             send_to_ws,     {.id = 7} },
6588         { "mvws_9",             send_to_ws,     {.id = 8} },
6589         { "mvws_10",            send_to_ws,     {.id = 9} },
6590         { "mvws_11",            send_to_ws,     {.id = 10} },
6591         { "mvws_12",            send_to_ws,     {.id = 11} },
6592         { "mvws_13",            send_to_ws,     {.id = 12} },
6593         { "mvws_14",            send_to_ws,     {.id = 13} },
6594         { "mvws_15",            send_to_ws,     {.id = 14} },
6595         { "mvws_16",            send_to_ws,     {.id = 15} },
6596         { "mvws_17",            send_to_ws,     {.id = 16} },
6597         { "mvws_18",            send_to_ws,     {.id = 17} },
6598         { "mvws_19",            send_to_ws,     {.id = 18} },
6599         { "mvws_20",            send_to_ws,     {.id = 19} },
6600         { "mvws_21",            send_to_ws,     {.id = 20} },
6601         { "mvws_22",            send_to_ws,     {.id = 21} },
6602         { "name_workspace",     name_workspace, {0} },
6603         { "quit",               quit,           {0} },
6604         { "raise_toggle",       raise_toggle,   {0} },
6605         { "restart",            restart,        {0} },
6606         { "rg_1",               focusrg,        {.id = 0} },
6607         { "rg_2",               focusrg,        {.id = 1} },
6608         { "rg_3",               focusrg,        {.id = 2} },
6609         { "rg_4",               focusrg,        {.id = 3} },
6610         { "rg_5",               focusrg,        {.id = 4} },
6611         { "rg_6",               focusrg,        {.id = 5} },
6612         { "rg_7",               focusrg,        {.id = 6} },
6613         { "rg_8",               focusrg,        {.id = 7} },
6614         { "rg_9",               focusrg,        {.id = 8} },
6615         { "rg_next",            cyclerg,        {.id = SWM_ARG_ID_CYCLERG_UP} },
6616         { "rg_prev",            cyclerg,        {.id = SWM_ARG_ID_CYCLERG_DOWN} },
6617         { "screen_next",        cyclerg,        {.id = SWM_ARG_ID_CYCLERG_UP} },
6618         { "screen_prev",        cyclerg,        {.id = SWM_ARG_ID_CYCLERG_DOWN} },
6619         { "search_win",         search_win,     {0} },
6620         { "search_workspace",   search_workspace,       {0} },
6621         { "spawn_custom",       NULL,           {0} },
6622         { "stack_inc",          stack_config,   {.id = SWM_ARG_ID_STACKINC} },
6623         { "stack_dec",          stack_config,   {.id = SWM_ARG_ID_STACKDEC} },
6624         { "stack_reset",        stack_config,   {.id = SWM_ARG_ID_STACKRESET} },
6625         { "swap_main",          swapwin,        {.id = SWM_ARG_ID_SWAPMAIN} },
6626         { "swap_next",          swapwin,        {.id = SWM_ARG_ID_SWAPNEXT} },
6627         { "swap_prev",          swapwin,        {.id = SWM_ARG_ID_SWAPPREV} },
6628         { "uniconify",          uniconify,      {0} },
6629         { "version",            version,        {0} },
6630         { "width_grow",         resize_step,    {.id = SWM_ARG_ID_WIDTHGROW} },
6631         { "width_shrink",       resize_step,    {.id = SWM_ARG_ID_WIDTHSHRINK} },
6632         { "wind_del",           wkill,          {.id = SWM_ARG_ID_DELETEWINDOW} },
6633         { "wind_kill",          wkill,          {.id = SWM_ARG_ID_KILLWINDOW} },
6634         { "ws_1",               switchws,       {.id = 0} },
6635         { "ws_2",               switchws,       {.id = 1} },
6636         { "ws_3",               switchws,       {.id = 2} },
6637         { "ws_4",               switchws,       {.id = 3} },
6638         { "ws_5",               switchws,       {.id = 4} },
6639         { "ws_6",               switchws,       {.id = 5} },
6640         { "ws_7",               switchws,       {.id = 6} },
6641         { "ws_8",               switchws,       {.id = 7} },
6642         { "ws_9",               switchws,       {.id = 8} },
6643         { "ws_10",              switchws,       {.id = 9} },
6644         { "ws_11",              switchws,       {.id = 10} },
6645         { "ws_12",              switchws,       {.id = 11} },
6646         { "ws_13",              switchws,       {.id = 12} },
6647         { "ws_14",              switchws,       {.id = 13} },
6648         { "ws_15",              switchws,       {.id = 14} },
6649         { "ws_16",              switchws,       {.id = 15} },
6650         { "ws_17",              switchws,       {.id = 16} },
6651         { "ws_18",              switchws,       {.id = 17} },
6652         { "ws_19",              switchws,       {.id = 18} },
6653         { "ws_20",              switchws,       {.id = 19} },
6654         { "ws_21",              switchws,       {.id = 20} },
6655         { "ws_22",              switchws,       {.id = 21} },
6656         { "ws_next",            cyclews,        {.id = SWM_ARG_ID_CYCLEWS_UP} },
6657         { "ws_next_all",        cyclews,        {.id = SWM_ARG_ID_CYCLEWS_UP_ALL} },
6658         { "ws_next_move",       cyclews,        {.id = SWM_ARG_ID_CYCLEWS_MOVE_UP} },
6659         { "ws_prev",            cyclews,        {.id = SWM_ARG_ID_CYCLEWS_DOWN} },
6660         { "ws_prev_all",        cyclews,        {.id = SWM_ARG_ID_CYCLEWS_DOWN_ALL} },
6661         { "ws_prev_move",       cyclews,        {.id = SWM_ARG_ID_CYCLEWS_MOVE_DOWN} },
6662         { "ws_prior",           priorws,        {0} },
6663         { "dumpwins",           dumpwins,       {0} }, /* MUST BE LAST */
6664         { "invalid key func",   NULL,           {0} },
6665 };
6666
6667 int
6668 key_cmp(struct key *kp1, struct key *kp2)
6669 {
6670         if (kp1->keysym < kp2->keysym)
6671                 return (-1);
6672         if (kp1->keysym > kp2->keysym)
6673                 return (1);
6674
6675         if (kp1->mod < kp2->mod)
6676                 return (-1);
6677         if (kp1->mod > kp2->mod)
6678                 return (1);
6679
6680         return (0);
6681 }
6682
6683 /* mouse */
6684 enum { client_click, root_click };
6685 struct button {
6686         unsigned int            action;
6687         unsigned int            mask;
6688         unsigned int            button;
6689         void                    (*func)(struct ws_win *, union arg *);
6690         union arg               args;
6691 } buttons[] = {
6692 #define MODKEY_SHIFT    MODKEY | XCB_MOD_MASK_SHIFT
6693           /* action     key             mouse button    func    args */
6694         { client_click, MODKEY,         XCB_BUTTON_INDEX_3,     resize, {.id = SWM_ARG_ID_DONTCENTER} },
6695         { client_click, MODKEY_SHIFT,   XCB_BUTTON_INDEX_3,     resize, {.id = SWM_ARG_ID_CENTER} },
6696         { client_click, MODKEY,         XCB_BUTTON_INDEX_1,     move,   {0} },
6697 #undef MODKEY_SHIFT
6698 };
6699
6700 void
6701 update_modkey(unsigned int mod)
6702 {
6703         int                     i;
6704         struct key              *kp;
6705
6706         mod_key = mod;
6707         RB_FOREACH(kp, key_tree, &keys)
6708                 if (kp->mod & XCB_MOD_MASK_SHIFT)
6709                         kp->mod = mod | XCB_MOD_MASK_SHIFT;
6710                 else
6711                         kp->mod = mod;
6712
6713         for (i = 0; i < LENGTH(buttons); i++)
6714                 if (buttons[i].mask & XCB_MOD_MASK_SHIFT)
6715                         buttons[i].mask = mod | XCB_MOD_MASK_SHIFT;
6716                 else
6717                         buttons[i].mask = mod;
6718 }
6719
6720 int
6721 spawn_expand(struct swm_region *r, union arg *args, const char *spawn_name,
6722     char ***ret_args)
6723 {
6724         struct spawn_prog       *prog = NULL;
6725         int                     i, c;
6726         char                    *ap, **real_args;
6727
6728         /* suppress unused warning since var is needed */
6729         (void)args;
6730
6731         DNPRINTF(SWM_D_SPAWN, "spawn_expand: %s\n", spawn_name);
6732
6733         /* find program */
6734         TAILQ_FOREACH(prog, &spawns, entry) {
6735                 if (strcasecmp(spawn_name, prog->name) == 0)
6736                         break;
6737         }
6738         if (prog == NULL) {
6739                 warnx("spawn_custom: program %s not found", spawn_name);
6740                 return (-1);
6741         }
6742
6743         /* make room for expanded args */
6744         if ((real_args = calloc(prog->argc + 1, sizeof(char *))) == NULL)
6745                 err(1, "spawn_custom: calloc real_args");
6746
6747         /* expand spawn_args into real_args */
6748         for (i = c = 0; i < prog->argc; i++) {
6749                 ap = prog->argv[i];
6750                 DNPRINTF(SWM_D_SPAWN, "spawn_custom: raw arg: %s\n", ap);
6751                 if (strcasecmp(ap, "$bar_border") == 0) {
6752                         if ((real_args[c] =
6753                             strdup(r->s->c[SWM_S_COLOR_BAR_BORDER].name))
6754                             == NULL)
6755                                 err(1,  "spawn_custom border color");
6756                 } else if (strcasecmp(ap, "$bar_color") == 0) {
6757                         if ((real_args[c] =
6758                             strdup(r->s->c[SWM_S_COLOR_BAR].name))
6759                             == NULL)
6760                                 err(1, "spawn_custom bar color");
6761                 } else if (strcasecmp(ap, "$bar_font") == 0) {
6762                         if ((real_args[c] = strdup(bar_fonts))
6763                             == NULL)
6764                                 err(1, "spawn_custom bar fonts");
6765                 } else if (strcasecmp(ap, "$bar_font_color") == 0) {
6766                         if ((real_args[c] =
6767                             strdup(r->s->c[SWM_S_COLOR_BAR_FONT].name))
6768                             == NULL)
6769                                 err(1, "spawn_custom color font");
6770                 } else if (strcasecmp(ap, "$color_focus") == 0) {
6771                         if ((real_args[c] =
6772                             strdup(r->s->c[SWM_S_COLOR_FOCUS].name))
6773                             == NULL)
6774                                 err(1, "spawn_custom color focus");
6775                 } else if (strcasecmp(ap, "$color_focus_maximized") == 0) {
6776                         if ((real_args[c] =
6777                             strdup(r->s->c[SWM_S_COLOR_FOCUS_MAXIMIZED].name))
6778                             == NULL)
6779                                 err(1, "spawn_custom color focus maximized");
6780                 } else if (strcasecmp(ap, "$color_unfocus") == 0) {
6781                         if ((real_args[c] =
6782                             strdup(r->s->c[SWM_S_COLOR_UNFOCUS].name))
6783                             == NULL)
6784                                 err(1, "spawn_custom color unfocus");
6785                 } else if (strcasecmp(ap, "$color_unfocus_maximized") == 0) {
6786                         if ((real_args[c] =
6787                             strdup(r->s->c[SWM_S_COLOR_UNFOCUS_MAXIMIZED].name))
6788                             == NULL)
6789                                 err(1, "spawn_custom color unfocus maximized");
6790                 } else if (strcasecmp(ap, "$region_index") == 0) {
6791                         if (asprintf(&real_args[c], "%d",
6792                             get_region_index(r) + 1) < 1)
6793                                 err(1, "spawn_custom region index");
6794                 } else if (strcasecmp(ap, "$workspace_index") == 0) {
6795                         if (asprintf(&real_args[c], "%d", r->ws->idx + 1) < 1)
6796                                 err(1, "spawn_custom workspace index");
6797                 } else if (strcasecmp(ap, "$dmenu_bottom") == 0) {
6798                         if (!bar_at_bottom)
6799                                 continue;
6800                         if ((real_args[c] = strdup("-b")) == NULL)
6801                                 err(1, "spawn_custom workspace index");
6802                 } else {
6803                         /* no match --> copy as is */
6804                         if ((real_args[c] = strdup(ap)) == NULL)
6805                                 err(1, "spawn_custom strdup(ap)");
6806                 }
6807                 DNPRINTF(SWM_D_SPAWN, "spawn_custom: cooked arg: %s\n",
6808                     real_args[c]);
6809                 ++c;
6810         }
6811
6812 #ifdef SWM_DEBUG
6813         DNPRINTF(SWM_D_SPAWN, "spawn_custom: result: ");
6814         for (i = 0; i < c; ++i)
6815                 DPRINTF("\"%s\" ", real_args[i]);
6816         DPRINTF("\n");
6817 #endif
6818         *ret_args = real_args;
6819         return (c);
6820 }
6821
6822 void
6823 spawn_custom(struct swm_region *r, union arg *args, const char *spawn_name)
6824 {
6825         union arg               a;
6826         char                    **real_args;
6827         int                     spawn_argc, i;
6828
6829         if ((spawn_argc = spawn_expand(r, args, spawn_name, &real_args)) < 0)
6830                 return;
6831         a.argv = real_args;
6832         if (fork() == 0)
6833                 spawn(r->ws->idx, &a, true);
6834
6835         for (i = 0; i < spawn_argc; i++)
6836                 free(real_args[i]);
6837         free(real_args);
6838 }
6839
6840 void
6841 spawn_select(struct swm_region *r, union arg *args, const char *spawn_name,
6842     int *pid)
6843 {
6844         union arg               a;
6845         char                    **real_args;
6846         int                     i, spawn_argc;
6847
6848         if ((spawn_argc = spawn_expand(r, args, spawn_name, &real_args)) < 0)
6849                 return;
6850         a.argv = real_args;
6851
6852         if (pipe(select_list_pipe) == -1)
6853                 err(1, "pipe error");
6854         if (pipe(select_resp_pipe) == -1)
6855                 err(1, "pipe error");
6856
6857         if (signal(SIGPIPE, SIG_IGN) == SIG_ERR)
6858                 err(1, "could not disable SIGPIPE");
6859         switch (*pid = fork()) {
6860         case -1:
6861                 err(1, "cannot fork");
6862                 break;
6863         case 0: /* child */
6864                 if (dup2(select_list_pipe[0], STDIN_FILENO) == -1)
6865                         err(1, "dup2");
6866                 if (dup2(select_resp_pipe[1], STDOUT_FILENO) == -1)
6867                         err(1, "dup2");
6868                 close(select_list_pipe[1]);
6869                 close(select_resp_pipe[0]);
6870                 spawn(r->ws->idx, &a, false);
6871                 break;
6872         default: /* parent */
6873                 close(select_list_pipe[0]);
6874                 close(select_resp_pipe[1]);
6875                 break;
6876         }
6877
6878         for (i = 0; i < spawn_argc; i++)
6879                 free(real_args[i]);
6880         free(real_args);
6881 }
6882
6883 /* Argument tokenizer. */
6884 char *
6885 argsep(char **sp) {
6886         char                    *arg, *cp, *next;
6887         bool                    single_quoted = false, double_quoted = false;
6888
6889         if (*sp == NULL)
6890                 return NULL;
6891
6892         /* Eat and move characters until end of argument is found. */
6893         for (arg = next = cp = *sp; *cp != '\0'; ++cp) {
6894                 if (!double_quoted && *cp == '\'') {
6895                         /* Eat single-quote. */
6896                         single_quoted = !single_quoted;
6897                 } else if (!single_quoted && *cp == '"') {
6898                         /* Eat double-quote. */
6899                         double_quoted = !double_quoted;
6900                 } else if (!single_quoted && *cp == '\\' && *(cp + 1) == '"') {
6901                         /* Eat backslash; copy escaped character to arg. */
6902                         *next++ = *(++cp);
6903                 } else if (!single_quoted && !double_quoted && *cp == '\\' &&
6904                     (*(cp + 1) == '\'' || *(cp + 1) == ' ')) {
6905                         /* Eat backslash; move escaped character. */
6906                         *next++ = *(++cp);
6907                 } else if (!single_quoted && !double_quoted &&
6908                     (*cp == ' ' || *cp == '\t')) {
6909                         /* Terminate argument. */
6910                         *next++ = '\0';
6911                         /* Point sp to beginning of next argument. */
6912                         *sp = ++cp;
6913                         break;
6914                 } else {
6915                         /* Move regular character. */
6916                         *next++ = *cp;
6917                 }
6918         }
6919
6920         /* Terminate argument if end of string. */
6921         if (*cp == '\0') {
6922                 *next = '\0';
6923                 *sp = NULL;
6924         }
6925
6926         return arg;
6927 }
6928
6929 void
6930 spawn_insert(const char *name, const char *args, int flags)
6931 {
6932         struct spawn_prog       *sp;
6933         char                    *arg, *cp, *ptr;
6934
6935         DNPRINTF(SWM_D_SPAWN, "spawn_insert: %s[%s]\n", name, args);
6936
6937         if (args == NULL || *args == '\0')
6938                 return;
6939
6940         if ((sp = calloc(1, sizeof *sp)) == NULL)
6941                 err(1, "spawn_insert: calloc");
6942         if ((sp->name = strdup(name)) == NULL)
6943                 err(1, "spawn_insert: strdup");
6944
6945         /* Convert the arguments to an argument list. */
6946         if ((ptr = cp = strdup(args)) == NULL)
6947                 err(1, "spawn_insert: strdup");
6948         while ((arg = argsep(&ptr)) != NULL) {
6949                 /* Null argument; skip it. */
6950                 if (*arg == '\0')
6951                         continue;
6952
6953                 sp->argc++;
6954                 if ((sp->argv = realloc(sp->argv, sp->argc *
6955                     sizeof *sp->argv)) == NULL)
6956                         err(1, "spawn_insert: realloc");
6957                 if ((sp->argv[sp->argc - 1] = strdup(arg)) == NULL)
6958                         err(1, "spawn_insert: strdup");
6959         }
6960         free(cp);
6961
6962         sp->flags = flags;
6963
6964         DNPRINTF(SWM_D_SPAWN, "arg %d: [%s]\n", sp->argc, sp->argv[sp->argc-1]);
6965         TAILQ_INSERT_TAIL(&spawns, sp, entry);
6966         DNPRINTF(SWM_D_SPAWN, "spawn_insert: leave\n");
6967 }
6968
6969 void
6970 spawn_remove(struct spawn_prog *sp)
6971 {
6972         int                     i;
6973
6974         DNPRINTF(SWM_D_SPAWN, "spawn_remove: %s\n", sp->name);
6975
6976         TAILQ_REMOVE(&spawns, sp, entry);
6977         for (i = 0; i < sp->argc; i++)
6978                 free(sp->argv[i]);
6979         free(sp->argv);
6980         free(sp->name);
6981         free(sp);
6982
6983         DNPRINTF(SWM_D_SPAWN, "spawn_remove: leave\n");
6984 }
6985
6986 struct spawn_prog*
6987 spawn_find(const char *name)
6988 {
6989         struct spawn_prog       *sp;
6990
6991         TAILQ_FOREACH(sp, &spawns, entry)
6992                 if (strcasecmp(sp->name, name) == 0)
6993                         return sp;
6994
6995         return NULL;
6996 }
6997
6998 void
6999 setspawn(const char *name, const char *args, int flags)
7000 {
7001         struct spawn_prog       *sp;
7002
7003         DNPRINTF(SWM_D_SPAWN, "setspawn: %s\n", name);
7004
7005         if (name == NULL)
7006                 return;
7007
7008         /* Remove any old spawn under the same name. */
7009         if ((sp = spawn_find(name)) != NULL)
7010                 spawn_remove(sp);
7011
7012         if (*args != '\0')
7013                 spawn_insert(name, args, flags);
7014         else
7015                 warnx("error: setspawn: cannot find program: %s", name);
7016
7017         DNPRINTF(SWM_D_SPAWN, "setspawn: leave\n");
7018 }
7019
7020 int
7021 setconfspawn(const char *selector, const char *value, int flags)
7022 {
7023         char            *args;
7024
7025         if (selector == NULL || strlen(selector) == 0)
7026                 return (1);
7027
7028         args = expand_tilde(value);
7029
7030         DNPRINTF(SWM_D_SPAWN, "setconfspawn: [%s] [%s]\n", selector, args);
7031
7032         setspawn(selector, args, flags);
7033         free(args);
7034
7035         DNPRINTF(SWM_D_SPAWN, "setconfspawn: done.\n");
7036         return (0);
7037 }
7038
7039 void
7040 validate_spawns(void)
7041 {
7042         struct spawn_prog       *sp;
7043         char                    which[PATH_MAX];
7044         size_t                  i;
7045
7046         struct key              *kp;
7047
7048         RB_FOREACH(kp, key_tree, &keys) {
7049                 if (kp->funcid != KF_SPAWN_CUSTOM)
7050                         continue;
7051
7052                 /* find program */
7053                 sp = spawn_find(kp->spawn_name);
7054                 if (sp == NULL || sp->flags & SWM_SPAWN_OPTIONAL)
7055                         continue;
7056
7057                 /* verify we have the goods */
7058                 snprintf(which, sizeof which, "which %s", sp->argv[0]);
7059                 DNPRINTF(SWM_D_CONF, "validate_spawns: which %s\n",
7060                     sp->argv[0]);
7061                 for (i = strlen("which "); i < strlen(which); i++)
7062                         if (which[i] == ' ') {
7063                                 which[i] = '\0';
7064                                 break;
7065                         }
7066                 if (system(which) != 0)
7067                         add_startup_exception("could not find %s",
7068                             &which[strlen("which ")]);
7069         }
7070 }
7071
7072 void
7073 setup_spawn(void)
7074 {
7075         setconfspawn("lock",            "xlock",                0);
7076
7077         setconfspawn("term",            "xterm",                0);
7078         setconfspawn("spawn_term",      "xterm",                0);
7079
7080         setconfspawn("menu",            "dmenu_run"
7081                                         " $dmenu_bottom"
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("search",          "dmenu"
7089                                         " $dmenu_bottom"
7090                                         " -i"
7091                                         " -fn $bar_font"
7092                                         " -nb $bar_color"
7093                                         " -nf $bar_font_color"
7094                                         " -sb $bar_border"
7095                                         " -sf $bar_color",      0);
7096
7097         setconfspawn("name_workspace",  "dmenu"
7098                                         " $dmenu_bottom"
7099                                         " -p Workspace"
7100                                         " -fn $bar_font"
7101                                         " -nb $bar_color"
7102                                         " -nf $bar_font_color"
7103                                         " -sb $bar_border"
7104                                         " -sf $bar_color",      0);
7105
7106          /* These are not verified for existence, even with a binding set. */
7107         setconfspawn("screenshot_all",  "screenshot.sh full",   SWM_SPAWN_OPTIONAL);
7108         setconfspawn("screenshot_wind", "screenshot.sh window", SWM_SPAWN_OPTIONAL);
7109         setconfspawn("initscr",         "initscreen.sh",        SWM_SPAWN_OPTIONAL);
7110 }
7111
7112 /* key bindings */
7113 #define SWM_MODNAME_SIZE        32
7114 #define SWM_KEY_WS              "\n+ \t"
7115 int
7116 parsekeys(const char *keystr, unsigned int currmod, unsigned int *mod, KeySym *ks)
7117 {
7118         char                    *str, *cp, *name;
7119         KeySym                  uks;
7120
7121         DNPRINTF(SWM_D_KEY, "parsekeys: enter [%s]\n", keystr);
7122         if (mod == NULL || ks == NULL) {
7123                 DNPRINTF(SWM_D_KEY, "parsekeys: no mod or key vars\n");
7124                 return (1);
7125         }
7126         if (keystr == NULL || strlen(keystr) == 0) {
7127                 DNPRINTF(SWM_D_KEY, "parsekeys: no keystr\n");
7128                 return (1);
7129         }
7130
7131         if ((cp = str = strdup(keystr)) == NULL)
7132                 err(1, "parsekeys: strdup");
7133
7134         *ks = XCB_NO_SYMBOL;
7135         *mod = 0;
7136         while ((name = strsep(&cp, SWM_KEY_WS)) != NULL) {
7137                 DNPRINTF(SWM_D_KEY, "parsekeys: key [%s]\n", name);
7138                 if (cp)
7139                         cp += (long)strspn(cp, SWM_KEY_WS);
7140                 if (strncasecmp(name, "MOD", SWM_MODNAME_SIZE) == 0)
7141                         *mod |= currmod;
7142                 else if (strncasecmp(name, "Mod1", SWM_MODNAME_SIZE) == 0)
7143                         *mod |= XCB_MOD_MASK_1;
7144                 else if (strncasecmp(name, "Mod2", SWM_MODNAME_SIZE) == 0)
7145                         *mod += XCB_MOD_MASK_2;
7146                 else if (strncmp(name, "Mod3", SWM_MODNAME_SIZE) == 0)
7147                         *mod |= XCB_MOD_MASK_3;
7148                 else if (strncmp(name, "Mod4", SWM_MODNAME_SIZE) == 0)
7149                         *mod |= XCB_MOD_MASK_4;
7150                 else if (strncasecmp(name, "SHIFT", SWM_MODNAME_SIZE) == 0)
7151                         *mod |= XCB_MOD_MASK_SHIFT;
7152                 else if (strncasecmp(name, "CONTROL", SWM_MODNAME_SIZE) == 0)
7153                         *mod |= XCB_MOD_MASK_CONTROL;
7154                 else {
7155                         *ks = XStringToKeysym(name);
7156                         XConvertCase(*ks, ks, &uks);
7157                         if (ks == XCB_NO_SYMBOL) {
7158                                 DNPRINTF(SWM_D_KEY,
7159                                     "parsekeys: invalid key %s\n",
7160                                     name);
7161                                 free(str);
7162                                 return (1);
7163                         }
7164                 }
7165         }
7166
7167         free(str);
7168         DNPRINTF(SWM_D_KEY, "parsekeys: leave ok\n");
7169         return (0);
7170 }
7171
7172 char *
7173 strdupsafe(const char *str)
7174 {
7175         if (str == NULL)
7176                 return (NULL);
7177         else
7178                 return (strdup(str));
7179 }
7180
7181 void
7182 key_insert(unsigned int mod, KeySym ks, enum keyfuncid kfid,
7183     const char *spawn_name)
7184 {
7185         struct key              *kp;
7186
7187         DNPRINTF(SWM_D_KEY, "key_insert: enter %s [%s]\n",
7188             keyfuncs[kfid].name, spawn_name);
7189
7190         if ((kp = malloc(sizeof *kp)) == NULL)
7191                 err(1, "key_insert: malloc");
7192
7193         kp->mod = mod;
7194         kp->keysym = ks;
7195         kp->funcid = kfid;
7196         kp->spawn_name = strdupsafe(spawn_name);
7197         RB_INSERT(key_tree, &keys, kp);
7198
7199         DNPRINTF(SWM_D_KEY, "key_insert: leave\n");
7200 }
7201
7202 struct key *
7203 key_lookup(unsigned int mod, KeySym ks)
7204 {
7205         struct key              kp;
7206
7207         kp.keysym = ks;
7208         kp.mod = mod;
7209
7210         return (RB_FIND(key_tree, &keys, &kp));
7211 }
7212
7213 void
7214 key_remove(struct key *kp)
7215 {
7216         DNPRINTF(SWM_D_KEY, "key_remove: %s\n", keyfuncs[kp->funcid].name);
7217
7218         RB_REMOVE(key_tree, &keys, kp);
7219         free(kp->spawn_name);
7220         free(kp);
7221
7222         DNPRINTF(SWM_D_KEY, "key_remove: leave\n");
7223 }
7224
7225 void
7226 key_replace(struct key *kp, unsigned int mod, KeySym ks, enum keyfuncid kfid,
7227     const char *spawn_name)
7228 {
7229         DNPRINTF(SWM_D_KEY, "key_replace: %s [%s]\n", keyfuncs[kp->funcid].name,
7230             spawn_name);
7231
7232         key_remove(kp);
7233         key_insert(mod, ks, kfid, spawn_name);
7234
7235         DNPRINTF(SWM_D_KEY, "key_replace: leave\n");
7236 }
7237
7238 void
7239 setkeybinding(unsigned int mod, KeySym ks, enum keyfuncid kfid,
7240     const char *spawn_name)
7241 {
7242         struct key              *kp;
7243
7244         DNPRINTF(SWM_D_KEY, "setkeybinding: enter %s [%s]\n",
7245             keyfuncs[kfid].name, spawn_name);
7246
7247         if ((kp = key_lookup(mod, ks)) != NULL) {
7248                 if (kfid == KF_INVALID)
7249                         key_remove(kp);
7250                 else
7251                         key_replace(kp, mod, ks, kfid, spawn_name);
7252                 DNPRINTF(SWM_D_KEY, "setkeybinding: leave\n");
7253                 return;
7254         }
7255         if (kfid == KF_INVALID) {
7256                 warnx("bind: Key combination already unbound.");
7257                 DNPRINTF(SWM_D_KEY, "setkeybinding: leave\n");
7258                 return;
7259         }
7260
7261         key_insert(mod, ks, kfid, spawn_name);
7262         DNPRINTF(SWM_D_KEY, "setkeybinding: leave\n");
7263 }
7264
7265 int
7266 setconfbinding(const char *selector, const char *value, int flags)
7267 {
7268         enum keyfuncid          kfid;
7269         unsigned int            mod;
7270         KeySym                  ks;
7271         struct spawn_prog       *sp;
7272
7273         /* suppress unused warning since var is needed */
7274         (void)flags;
7275
7276         DNPRINTF(SWM_D_KEY, "setconfbinding: enter selector: [%s], "
7277             "value: [%s]\n", selector, value);
7278         if (selector == NULL || strlen(selector) == 0) {
7279                 DNPRINTF(SWM_D_KEY, "setconfbinding: unbind %s\n", value);
7280                 if (parsekeys(value, mod_key, &mod, &ks) == 0) {
7281                         kfid = KF_INVALID;
7282                         setkeybinding(mod, ks, kfid, NULL);
7283                         return (0);
7284                 } else
7285                         return (1);
7286         }
7287         /* search by key function name */
7288         for (kfid = 0; kfid < KF_INVALID; (kfid)++) {
7289                 if (strncasecmp(selector, keyfuncs[kfid].name,
7290                     SWM_FUNCNAME_LEN) == 0) {
7291                         DNPRINTF(SWM_D_KEY, "setconfbinding: %s: match "
7292                             "keyfunc\n", selector);
7293                         if (parsekeys(value, mod_key, &mod, &ks) == 0) {
7294                                 setkeybinding(mod, ks, kfid, NULL);
7295                                 return (0);
7296                         } else
7297                                 return (1);
7298                 }
7299         }
7300         /* search by custom spawn name */
7301         if ((sp = spawn_find(selector)) != NULL) {
7302                 DNPRINTF(SWM_D_KEY, "setconfbinding: %s: match "
7303                     "spawn\n", selector);
7304                 if (parsekeys(value, mod_key, &mod, &ks) == 0) {
7305                         setkeybinding(mod, ks, KF_SPAWN_CUSTOM,
7306                             sp->name);
7307                         return (0);
7308                 } else
7309                         return (1);
7310         }
7311         DNPRINTF(SWM_D_KEY, "setconfbinding: no match\n");
7312         return (1);
7313 }
7314
7315 void
7316 setup_keys(void)
7317 {
7318 #define MODKEY_SHIFT    MODKEY | XCB_MOD_MASK_SHIFT
7319         setkeybinding(MODKEY,           XK_b,           KF_BAR_TOGGLE,  NULL);
7320         setkeybinding(MODKEY_SHIFT,     XK_b,           KF_BAR_TOGGLE_WS,NULL);
7321         setkeybinding(MODKEY,           XK_v,           KF_BUTTON2,     NULL);
7322         setkeybinding(MODKEY,           XK_space,       KF_CYCLE_LAYOUT,NULL);
7323         setkeybinding(MODKEY_SHIFT,     XK_backslash,   KF_FLIP_LAYOUT, NULL);
7324         setkeybinding(MODKEY,           XK_t,           KF_FLOAT_TOGGLE,NULL);
7325         setkeybinding(MODKEY,           XK_m,           KF_FOCUS_MAIN,  NULL);
7326         setkeybinding(MODKEY,           XK_j,           KF_FOCUS_NEXT,  NULL);
7327         setkeybinding(MODKEY,           XK_Tab,         KF_FOCUS_NEXT,  NULL);
7328         setkeybinding(MODKEY,           XK_k,           KF_FOCUS_PREV,  NULL);
7329         setkeybinding(MODKEY_SHIFT,     XK_Tab,         KF_FOCUS_PREV,  NULL);
7330         setkeybinding(MODKEY,           XK_u,           KF_FOCUS_URGENT,NULL);
7331         setkeybinding(MODKEY,           XK_e,           KF_MAXIMIZE_TOGGLE,NULL);
7332         setkeybinding(MODKEY_SHIFT,     XK_equal,       KF_HEIGHT_GROW,NULL);
7333         setkeybinding(MODKEY_SHIFT,     XK_minus,       KF_HEIGHT_SHRINK,NULL);
7334         setkeybinding(MODKEY,           XK_w,           KF_ICONIFY,     NULL);
7335         setkeybinding(MODKEY,           XK_h,           KF_MASTER_SHRINK, NULL);
7336         setkeybinding(MODKEY,           XK_l,           KF_MASTER_GROW, NULL);
7337         setkeybinding(MODKEY,           XK_comma,       KF_MASTER_ADD,  NULL);
7338         setkeybinding(MODKEY,           XK_period,      KF_MASTER_DEL,  NULL);
7339         setkeybinding(MODKEY_SHIFT,     XK_bracketright,KF_MOVE_DOWN,NULL);
7340         setkeybinding(MODKEY,           XK_bracketleft, KF_MOVE_LEFT,NULL);
7341         setkeybinding(MODKEY,           XK_bracketright,KF_MOVE_RIGHT,NULL);
7342         setkeybinding(MODKEY_SHIFT,     XK_bracketleft, KF_MOVE_UP,     NULL);
7343         setkeybinding(MODKEY_SHIFT,     XK_KP_End,      KF_MVRG_1,      NULL);
7344         setkeybinding(MODKEY_SHIFT,     XK_KP_Down,     KF_MVRG_2,      NULL);
7345         setkeybinding(MODKEY_SHIFT,     XK_KP_Next,     KF_MVRG_3,      NULL);
7346         setkeybinding(MODKEY_SHIFT,     XK_KP_Left,     KF_MVRG_4,      NULL);
7347         setkeybinding(MODKEY_SHIFT,     XK_KP_Begin,    KF_MVRG_5,      NULL);
7348         setkeybinding(MODKEY_SHIFT,     XK_KP_Right,    KF_MVRG_6,      NULL);
7349         setkeybinding(MODKEY_SHIFT,     XK_KP_Home,     KF_MVRG_7,      NULL);
7350         setkeybinding(MODKEY_SHIFT,     XK_KP_Up,       KF_MVRG_8,      NULL);
7351         setkeybinding(MODKEY_SHIFT,     XK_KP_Prior,    KF_MVRG_9,      NULL);
7352         setkeybinding(MODKEY_SHIFT,     XK_1,           KF_MVWS_1,      NULL);
7353         setkeybinding(MODKEY_SHIFT,     XK_2,           KF_MVWS_2,      NULL);
7354         setkeybinding(MODKEY_SHIFT,     XK_3,           KF_MVWS_3,      NULL);
7355         setkeybinding(MODKEY_SHIFT,     XK_4,           KF_MVWS_4,      NULL);
7356         setkeybinding(MODKEY_SHIFT,     XK_5,           KF_MVWS_5,      NULL);
7357         setkeybinding(MODKEY_SHIFT,     XK_6,           KF_MVWS_6,      NULL);
7358         setkeybinding(MODKEY_SHIFT,     XK_7,           KF_MVWS_7,      NULL);
7359         setkeybinding(MODKEY_SHIFT,     XK_8,           KF_MVWS_8,      NULL);
7360         setkeybinding(MODKEY_SHIFT,     XK_9,           KF_MVWS_9,      NULL);
7361         setkeybinding(MODKEY_SHIFT,     XK_0,           KF_MVWS_10,     NULL);
7362         setkeybinding(MODKEY_SHIFT,     XK_F1,          KF_MVWS_11,     NULL);
7363         setkeybinding(MODKEY_SHIFT,     XK_F2,          KF_MVWS_12,     NULL);
7364         setkeybinding(MODKEY_SHIFT,     XK_F3,          KF_MVWS_13,     NULL);
7365         setkeybinding(MODKEY_SHIFT,     XK_F4,          KF_MVWS_14,     NULL);
7366         setkeybinding(MODKEY_SHIFT,     XK_F5,          KF_MVWS_15,     NULL);
7367         setkeybinding(MODKEY_SHIFT,     XK_F6,          KF_MVWS_16,     NULL);
7368         setkeybinding(MODKEY_SHIFT,     XK_F7,          KF_MVWS_17,     NULL);
7369         setkeybinding(MODKEY_SHIFT,     XK_F8,          KF_MVWS_18,     NULL);
7370         setkeybinding(MODKEY_SHIFT,     XK_F9,          KF_MVWS_19,     NULL);
7371         setkeybinding(MODKEY_SHIFT,     XK_F10,         KF_MVWS_20,     NULL);
7372         setkeybinding(MODKEY_SHIFT,     XK_F11,         KF_MVWS_21,     NULL);
7373         setkeybinding(MODKEY_SHIFT,     XK_F12,         KF_MVWS_22,     NULL);
7374         setkeybinding(MODKEY_SHIFT,     XK_slash,       KF_NAME_WORKSPACE,NULL);
7375         setkeybinding(MODKEY_SHIFT,     XK_q,           KF_QUIT,        NULL);
7376         setkeybinding(MODKEY_SHIFT,     XK_r,           KF_RAISE_TOGGLE,NULL);
7377         setkeybinding(MODKEY,           XK_q,           KF_RESTART,     NULL);
7378         setkeybinding(MODKEY,           XK_KP_End,      KF_RG_1,        NULL);
7379         setkeybinding(MODKEY,           XK_KP_Down,     KF_RG_2,        NULL);
7380         setkeybinding(MODKEY,           XK_KP_Next,     KF_RG_3,        NULL);
7381         setkeybinding(MODKEY,           XK_KP_Left,     KF_RG_4,        NULL);
7382         setkeybinding(MODKEY,           XK_KP_Begin,    KF_RG_5,        NULL);
7383         setkeybinding(MODKEY,           XK_KP_Right,    KF_RG_6,        NULL);
7384         setkeybinding(MODKEY,           XK_KP_Home,     KF_RG_7,        NULL);
7385         setkeybinding(MODKEY,           XK_KP_Up,       KF_RG_8,        NULL);
7386         setkeybinding(MODKEY,           XK_KP_Prior,    KF_RG_9,        NULL);
7387         setkeybinding(MODKEY_SHIFT,     XK_Right,       KF_RG_NEXT,     NULL);
7388         setkeybinding(MODKEY_SHIFT,     XK_Left,        KF_RG_PREV,     NULL);
7389         setkeybinding(MODKEY,           XK_f,           KF_SEARCH_WIN,  NULL);
7390         setkeybinding(MODKEY,           XK_slash,       KF_SEARCH_WORKSPACE,NULL);
7391         setkeybinding(MODKEY_SHIFT,     XK_i,           KF_SPAWN_CUSTOM,"initscr");
7392         setkeybinding(MODKEY_SHIFT,     XK_Delete,      KF_SPAWN_CUSTOM,"lock");
7393         setkeybinding(MODKEY,           XK_p,           KF_SPAWN_CUSTOM,"menu");
7394         setkeybinding(MODKEY,           XK_s,           KF_SPAWN_CUSTOM,"screenshot_all");
7395         setkeybinding(MODKEY_SHIFT,     XK_s,           KF_SPAWN_CUSTOM,"screenshot_wind");
7396         setkeybinding(MODKEY_SHIFT,     XK_Return,      KF_SPAWN_CUSTOM,"term");
7397         setkeybinding(MODKEY_SHIFT,     XK_comma,       KF_STACK_INC,   NULL);
7398         setkeybinding(MODKEY_SHIFT,     XK_period,      KF_STACK_DEC,   NULL);
7399         setkeybinding(MODKEY_SHIFT,     XK_space,       KF_STACK_RESET, NULL);
7400         setkeybinding(MODKEY,           XK_Return,      KF_SWAP_MAIN,   NULL);
7401         setkeybinding(MODKEY_SHIFT,     XK_j,           KF_SWAP_NEXT,   NULL);
7402         setkeybinding(MODKEY_SHIFT,     XK_k,           KF_SWAP_PREV,   NULL);
7403         setkeybinding(MODKEY_SHIFT,     XK_w,           KF_UNICONIFY,   NULL);
7404         setkeybinding(MODKEY_SHIFT,     XK_v,           KF_VERSION,     NULL);
7405         setkeybinding(MODKEY,           XK_equal,       KF_WIDTH_GROW,  NULL);
7406         setkeybinding(MODKEY,           XK_minus,       KF_WIDTH_SHRINK,NULL);
7407         setkeybinding(MODKEY,           XK_x,           KF_WIND_DEL,    NULL);
7408         setkeybinding(MODKEY_SHIFT,     XK_x,           KF_WIND_KILL,   NULL);
7409         setkeybinding(MODKEY,           XK_1,           KF_WS_1,        NULL);
7410         setkeybinding(MODKEY,           XK_2,           KF_WS_2,        NULL);
7411         setkeybinding(MODKEY,           XK_3,           KF_WS_3,        NULL);
7412         setkeybinding(MODKEY,           XK_4,           KF_WS_4,        NULL);
7413         setkeybinding(MODKEY,           XK_5,           KF_WS_5,        NULL);
7414         setkeybinding(MODKEY,           XK_6,           KF_WS_6,        NULL);
7415         setkeybinding(MODKEY,           XK_7,           KF_WS_7,        NULL);
7416         setkeybinding(MODKEY,           XK_8,           KF_WS_8,        NULL);
7417         setkeybinding(MODKEY,           XK_9,           KF_WS_9,        NULL);
7418         setkeybinding(MODKEY,           XK_0,           KF_WS_10,       NULL);
7419         setkeybinding(MODKEY,           XK_F1,          KF_WS_11,       NULL);
7420         setkeybinding(MODKEY,           XK_F2,          KF_WS_12,       NULL);
7421         setkeybinding(MODKEY,           XK_F3,          KF_WS_13,       NULL);
7422         setkeybinding(MODKEY,           XK_F4,          KF_WS_14,       NULL);
7423         setkeybinding(MODKEY,           XK_F5,          KF_WS_15,       NULL);
7424         setkeybinding(MODKEY,           XK_F6,          KF_WS_16,       NULL);
7425         setkeybinding(MODKEY,           XK_F7,          KF_WS_17,       NULL);
7426         setkeybinding(MODKEY,           XK_F8,          KF_WS_18,       NULL);
7427         setkeybinding(MODKEY,           XK_F9,          KF_WS_19,       NULL);
7428         setkeybinding(MODKEY,           XK_F10,         KF_WS_20,       NULL);
7429         setkeybinding(MODKEY,           XK_F11,         KF_WS_21,       NULL);
7430         setkeybinding(MODKEY,           XK_F12,         KF_WS_22,       NULL);
7431         setkeybinding(MODKEY,           XK_Right,       KF_WS_NEXT,     NULL);
7432         setkeybinding(MODKEY,           XK_Left,        KF_WS_PREV,     NULL);
7433         setkeybinding(MODKEY,           XK_Up,          KF_WS_NEXT_ALL, NULL);
7434         setkeybinding(MODKEY,           XK_Down,        KF_WS_PREV_ALL, NULL);
7435         setkeybinding(MODKEY_SHIFT,     XK_Up,          KF_WS_NEXT_MOVE,NULL);
7436         setkeybinding(MODKEY_SHIFT,     XK_Down,        KF_WS_PREV_MOVE,NULL);
7437         setkeybinding(MODKEY,           XK_a,           KF_WS_PRIOR,    NULL);
7438 #ifdef SWM_DEBUG
7439         setkeybinding(MODKEY_SHIFT,     XK_d,           KF_DUMPWINS,    NULL);
7440 #endif
7441 #undef MODKEY_SHIFT
7442 }
7443
7444 void
7445 clear_keys(void)
7446 {
7447         struct key              *kp;
7448
7449         while (RB_EMPTY(&keys) == 0) {
7450                 kp = RB_ROOT(&keys);
7451                 key_remove(kp);
7452         }
7453 }
7454
7455 int
7456 setkeymapping(const char *selector, const char *value, int flags)
7457 {
7458         char                    *keymapping_file;
7459
7460         /* suppress unused warnings since vars are needed */
7461         (void)selector;
7462         (void)flags;
7463
7464         DNPRINTF(SWM_D_KEY, "setkeymapping: enter\n");
7465
7466         keymapping_file = expand_tilde(value);
7467
7468         clear_keys();
7469         /* load new key bindings; if it fails, revert to default bindings */
7470         if (conf_load(keymapping_file, SWM_CONF_KEYMAPPING)) {
7471                 clear_keys();
7472                 setup_keys();
7473         }
7474
7475         free(keymapping_file);
7476
7477         DNPRINTF(SWM_D_KEY, "setkeymapping: leave\n");
7478         return (0);
7479 }
7480
7481 void
7482 updatenumlockmask(void)
7483 {
7484         unsigned int                            i, j;
7485         xcb_get_modifier_mapping_reply_t        *modmap_r;
7486         xcb_keycode_t                           *modmap, kc, *keycode;
7487
7488         numlockmask = 0;
7489
7490         modmap_r = xcb_get_modifier_mapping_reply(conn,
7491             xcb_get_modifier_mapping(conn),
7492             NULL);
7493         if (modmap_r) {
7494                 modmap = xcb_get_modifier_mapping_keycodes(modmap_r);
7495                 for (i = 0; i < 8; i++) {
7496                         for (j = 0; j < modmap_r->keycodes_per_modifier; j++) {
7497                                 kc = modmap[i * modmap_r->keycodes_per_modifier
7498                                     + j];
7499                                 keycode = xcb_key_symbols_get_keycode(syms,
7500                                                 XK_Num_Lock);
7501                                 if (keycode) {
7502                                         if (kc == *keycode)
7503                                                 numlockmask = (1 << i);
7504                                         free(keycode);
7505                                 }
7506                         }
7507                 }
7508                 free(modmap_r);
7509         }
7510         DNPRINTF(SWM_D_MISC, "updatenumlockmask: %d\n", numlockmask);
7511 }
7512
7513 void
7514 grabkeys(void)
7515 {
7516         struct key              *kp;
7517         int                     num_screens, k, j;
7518         unsigned int            modifiers[4];
7519         xcb_keycode_t           *code;
7520
7521         DNPRINTF(SWM_D_MISC, "grabkeys\n");
7522         updatenumlockmask();
7523
7524         modifiers[0] = 0;
7525         modifiers[1] = numlockmask;
7526         modifiers[2] = XCB_MOD_MASK_LOCK;
7527         modifiers[3] = numlockmask | XCB_MOD_MASK_LOCK;
7528
7529         num_screens = get_screen_count();
7530         for (k = 0; k < num_screens; k++) {
7531                 if (TAILQ_EMPTY(&screens[k].rl))
7532                         continue;
7533                 xcb_ungrab_key(conn, XCB_GRAB_ANY, screens[k].root,
7534                         XCB_MOD_MASK_ANY);
7535                 RB_FOREACH(kp, key_tree, &keys) {
7536                         /* Skip unused ws binds. */
7537                         if ((int)kp->funcid > KF_WS_1 + workspace_limit - 1 &&
7538                             kp->funcid <= KF_WS_22)
7539                                 continue;
7540
7541                         /* Skip unused mvws binds. */
7542                         if ((int)kp->funcid > KF_MVWS_1 + workspace_limit - 1 &&
7543                             kp->funcid <= KF_MVWS_22)
7544                                 continue;
7545
7546                         if ((code = xcb_key_symbols_get_keycode(syms,
7547                                         kp->keysym))) {
7548                                 for (j = 0; j < LENGTH(modifiers); j++)
7549                                         xcb_grab_key(conn, 1,
7550                                             screens[k].root,
7551                                             kp->mod | modifiers[j],
7552                                             *code, XCB_GRAB_MODE_SYNC,
7553                                             XCB_GRAB_MODE_SYNC);
7554                                 free(code);
7555                         }
7556                 }
7557         }
7558 }
7559
7560 void
7561 grabbuttons(struct ws_win *win)
7562 {
7563         unsigned int    modifiers[4];
7564         int             i, j;
7565
7566         DNPRINTF(SWM_D_MOUSE, "grabbuttons: win %#x\n", win->id);
7567         updatenumlockmask();
7568
7569         modifiers[0] = 0;
7570         modifiers[1] = numlockmask;
7571         modifiers[2] = XCB_MOD_MASK_LOCK;
7572         modifiers[3] = numlockmask | XCB_MOD_MASK_LOCK;
7573
7574         for (i = 0; i < LENGTH(buttons); i++)
7575                 if (buttons[i].action == client_click)
7576                         for (j = 0; j < LENGTH(modifiers); ++j)
7577                                 xcb_grab_button(conn, 0, win->id, BUTTONMASK,
7578                                     XCB_GRAB_MODE_SYNC, XCB_GRAB_MODE_ASYNC,
7579                                     XCB_WINDOW_NONE, XCB_CURSOR_NONE,
7580                                     buttons[i].button, buttons[i].mask |
7581                                     modifiers[j]);
7582 }
7583
7584 const char *quirkname[] = {
7585         "NONE",         /* config string for "no value" */
7586         "FLOAT",
7587         "TRANSSZ",
7588         "ANYWHERE",
7589         "XTERM_FONTADJ",
7590         "FULLSCREEN",
7591         "FOCUSPREV",
7592         "NOFOCUSONMAP",
7593         "FOCUSONMAP_SINGLE",
7594         "OBEYAPPFOCUSREQ",
7595         "IGNOREPID",
7596         "IGNORESPAWNWS",
7597 };
7598
7599 /* SWM_Q_DELIM: retain '|' for back compat for now (2009-08-11) */
7600 #define SWM_Q_DELIM             "\n|+ \t"
7601 int
7602 parsequirks(const char *qstr, uint32_t *quirk, int *ws)
7603 {
7604         char                    *str, *cp, *name;
7605         int                     i;
7606
7607         if (quirk == NULL || qstr == NULL)
7608                 return (1);
7609
7610         if ((str = strdup(qstr)) == NULL)
7611                 err(1, "parsequirks: strdup");
7612
7613         cp = str;
7614         *quirk = 0;
7615         while ((name = strsep(&cp, SWM_Q_DELIM)) != NULL) {
7616                 if (cp)
7617                         cp += (long)strspn(cp, SWM_Q_DELIM);
7618
7619                 if (sscanf(name, "WS[%d]", ws) == 1) {
7620                         if (*ws > 0)
7621                                 *ws -= 1;
7622                         continue;
7623                 }
7624
7625                 for (i = 0; i < LENGTH(quirkname); i++) {
7626                         if (strncasecmp(name, quirkname[i],
7627                             SWM_QUIRK_LEN) == 0) {
7628                                 DNPRINTF(SWM_D_QUIRK,
7629                                     "parsequirks: %s\n", name);
7630                                 if (i == 0) {
7631                                         *quirk = 0;
7632                                         free(str);
7633                                         return (0);
7634                                 }
7635                                 *quirk |= 1 << (i-1);
7636                                 break;
7637                         }
7638                 }
7639                 if (i >= LENGTH(quirkname)) {
7640                         DNPRINTF(SWM_D_QUIRK,
7641                             "parsequirks: invalid quirk [%s]\n", name);
7642                         free(str);
7643                         return (1);
7644                 }
7645         }
7646
7647         free(str);
7648         return (0);
7649 }
7650
7651 void
7652 quirk_insert(const char *class, const char *instance, const char *name,
7653     uint32_t quirk, int ws)
7654 {
7655         struct quirk            *qp;
7656         char                    *str;
7657         bool                    failed = false;
7658
7659         DNPRINTF(SWM_D_QUIRK, "quirk_insert: class: %s, instance: %s, name: %s,"
7660             " value: %u, ws: %d\n", class, instance, name, quirk, ws);
7661
7662         if ((qp = malloc(sizeof *qp)) == NULL)
7663                 err(1, "quirk_insert: malloc");
7664
7665         if ((qp->class = strdup(class)) == NULL)
7666                 err(1, "quirk_insert: strdup");
7667         if ((qp->instance = strdup(instance)) == NULL)
7668                 err(1, "quirk_insert: strdup");
7669         if ((qp->name = strdup(name)) == NULL)
7670                 err(1, "quirk_insert: strdup");
7671
7672         if (asprintf(&str, "^%s$", class) == -1)
7673                 err(1, "quirk_insert: asprintf");
7674         if (regcomp(&qp->regex_class, str, REG_EXTENDED | REG_NOSUB)) {
7675                 add_startup_exception("regex failed to compile quirk 'class' "
7676                     "field: %s", class);
7677                 failed = true;
7678         }
7679         DNPRINTF(SWM_D_QUIRK, "quirk_insert: compiled: %s\n", str);
7680         free(str);
7681
7682         if (asprintf(&str, "^%s$", instance) == -1)
7683                 err(1, "quirk_insert: asprintf");
7684         if (regcomp(&qp->regex_instance, str, REG_EXTENDED | REG_NOSUB)) {
7685                 add_startup_exception("regex failed to compile quirk 'instance'"
7686                     " field: %s", instance);
7687                 failed = true;
7688         }
7689         DNPRINTF(SWM_D_QUIRK, "quirk_insert: compiled: %s\n", str);
7690         free(str);
7691
7692         if (asprintf(&str, "^%s$", name) == -1)
7693                 err(1, "quirk_insert: asprintf");
7694         if (regcomp(&qp->regex_name, str, REG_EXTENDED | REG_NOSUB)) {
7695                 add_startup_exception("regex failed to compile quirk 'name' "
7696                     "field: %s", name);
7697                 failed = true;
7698         }
7699         DNPRINTF(SWM_D_QUIRK, "quirk_insert: compiled: %s\n", str);
7700         free(str);
7701
7702         if (failed) {
7703                 DNPRINTF(SWM_D_QUIRK, "quirk_insert: regex error; skipping.\n");
7704                 quirk_free(qp);
7705         } else {
7706                 qp->quirk = quirk;
7707                 qp->ws = ws;
7708                 TAILQ_INSERT_TAIL(&quirks, qp, entry);
7709         }
7710         DNPRINTF(SWM_D_QUIRK, "quirk_insert: leave\n");
7711 }
7712
7713 void
7714 quirk_remove(struct quirk *qp)
7715 {
7716         DNPRINTF(SWM_D_QUIRK, "quirk_remove: %s:%s [%u]\n", qp->class,
7717             qp->name, qp->quirk);
7718
7719         TAILQ_REMOVE(&quirks, qp, entry);
7720         quirk_free(qp);
7721
7722         DNPRINTF(SWM_D_QUIRK, "quirk_remove: leave\n");
7723 }
7724
7725 void
7726 quirk_free(struct quirk *qp)
7727 {
7728         regfree(&qp->regex_class);
7729         regfree(&qp->regex_instance);
7730         regfree(&qp->regex_name);
7731         free(qp->class);
7732         free(qp->instance);
7733         free(qp->name);
7734         free(qp);
7735 }
7736
7737 void
7738 quirk_replace(struct quirk *qp, const char *class, const char *instance,
7739     const char *name, uint32_t quirk, int ws)
7740 {
7741         DNPRINTF(SWM_D_QUIRK, "quirk_replace: %s:%s:%s [%u], ws: %d\n", qp->class,
7742             qp->instance, qp->name, qp->quirk, qp->ws);
7743
7744         quirk_remove(qp);
7745         quirk_insert(class, instance, name, quirk, ws);
7746
7747         DNPRINTF(SWM_D_QUIRK, "quirk_replace: leave\n");
7748 }
7749
7750 void
7751 setquirk(const char *class, const char *instance, const char *name,
7752     uint32_t quirk, int ws)
7753 {
7754         struct quirk            *qp;
7755
7756         DNPRINTF(SWM_D_QUIRK, "setquirk: enter %s:%s:%s [%u], ws: %d\n", class,
7757             instance, name, quirk, ws);
7758
7759         /* Remove/replace existing quirk. */
7760         TAILQ_FOREACH(qp, &quirks, entry) {
7761                 if (strcmp(qp->class, class) == 0 &&
7762                     strcmp(qp->instance, instance) == 0 &&
7763                     strcmp(qp->name, name) == 0) {
7764                         if (quirk == 0 && ws == -1)
7765                                 quirk_remove(qp);
7766                         else
7767                                 quirk_replace(qp, class, instance, name, quirk,
7768                                     ws);
7769                         DNPRINTF(SWM_D_QUIRK, "setquirk: leave\n");
7770                         return;
7771                 }
7772         }
7773
7774         /* Only insert if quirk is not NONE or forced ws is set. */
7775         if (quirk || ws != -1)
7776                 quirk_insert(class, instance, name, quirk, ws);
7777
7778         DNPRINTF(SWM_D_QUIRK, "setquirk: leave\n");
7779 }
7780
7781 /* Eat '\' in str used to escape square brackets and colon. */
7782 void
7783 unescape_selector(char *str)
7784 {
7785         char *cp;
7786
7787         for (cp = str; *str != '\0'; ++str, ++cp) {
7788                 if (*str == '\\' && (*(str + 1) == ':' || *(str + 1) == ']' ||
7789                     *(str + 1) == '['))
7790                         ++str;
7791
7792                 *cp = *str;
7793         }
7794         *cp = '\0';
7795 }
7796
7797 int
7798 setconfquirk(const char *selector, const char *value, int flags)
7799 {
7800         char                    *str, *cp, *class;
7801         char                    *instance = NULL, *name = NULL;
7802         int                     retval, count = 0, ws = -1;
7803         uint32_t                qrks;
7804
7805         /* suppress unused warning since var is needed */
7806         (void)flags;
7807
7808         if (selector == NULL || strlen(selector) == 0)
7809                 return (0);
7810
7811         if ((str = strdup(selector)) == NULL)
7812                 err(1, "setconfquirk: strdup");
7813
7814         /* Find non-escaped colon. */
7815         class = cp = str;
7816         if (*cp == ':') {
7817                 *cp = '\0';
7818                 ++count;
7819         }
7820
7821         for (++cp; *cp != '\0'; ++cp) {
7822                 if (*cp == ':' && *(cp - 1) != '\\') {
7823                         *cp = '\0';
7824                         ++count;
7825                 }
7826         }
7827
7828         unescape_selector(class);
7829         if (count) {
7830                 instance = class + strlen(class) + 1;
7831                 unescape_selector(instance);
7832         } else {
7833                 instance = ".*";
7834         }
7835
7836         if (count > 1) {
7837                 name = instance + strlen(instance) + 1;
7838                 unescape_selector(name);
7839         } else {
7840                 name = ".*";
7841         }
7842
7843         DNPRINTF(SWM_D_CONF, "setconfquirk: class: %s, instance: %s, "
7844             "name: %s\n", class, instance, name);
7845
7846         if ((retval = parsequirks(value, &qrks, &ws)) == 0)
7847                 setquirk(class, instance, name, qrks, ws);
7848
7849         free(str);
7850         return (retval);
7851 }
7852
7853 void
7854 setup_quirks(void)
7855 {
7856         setquirk("MPlayer",             "xv",           ".*",
7857             SWM_Q_FLOAT | SWM_Q_FULLSCREEN | SWM_Q_FOCUSPREV, -1);
7858         setquirk("OpenOffice.org 3.2",  "VCLSalFrame",  ".*",
7859             SWM_Q_FLOAT, -1);
7860         setquirk("Firefox-bin",         "firefox-bin",  ".*",
7861             SWM_Q_TRANSSZ, -1);
7862         setquirk("Firefox",             "Dialog",       ".*",
7863             SWM_Q_FLOAT, -1);
7864         setquirk("Gimp",                "gimp",         ".*",
7865             SWM_Q_FLOAT | SWM_Q_ANYWHERE, -1);
7866         setquirk("XTerm",               "xterm",        ".*",
7867             SWM_Q_XTERM_FONTADJ, -1);
7868         setquirk("xine",                "Xine Window",  ".*",
7869             SWM_Q_FLOAT | SWM_Q_ANYWHERE, -1);
7870         setquirk("Xitk",                "Xitk Combo",   ".*",
7871             SWM_Q_FLOAT | SWM_Q_ANYWHERE, -1);
7872         setquirk("xine",                "xine Panel",   ".*",
7873             SWM_Q_FLOAT | SWM_Q_ANYWHERE, -1);
7874         setquirk("Xitk",                "Xine Window",  ".*",
7875             SWM_Q_FLOAT | SWM_Q_ANYWHERE, -1);
7876         setquirk("xine",                "xine Video Fullscreen Window", ".*",
7877             SWM_Q_FULLSCREEN | SWM_Q_FLOAT, -1);
7878         setquirk("pcb",                 "pcb",          ".*",
7879             SWM_Q_FLOAT, -1);
7880         setquirk("SDL_App",             "SDL_App",      ".*",
7881             SWM_Q_FLOAT | SWM_Q_FULLSCREEN, -1);
7882 }
7883
7884 /* conf file stuff */
7885 #define SWM_CONF_FILE           "spectrwm.conf"
7886 #define SWM_CONF_FILE_OLD       "scrotwm.conf"
7887
7888 enum {
7889         SWM_S_BAR_ACTION,
7890         SWM_S_BAR_AT_BOTTOM,
7891         SWM_S_BAR_BORDER_WIDTH,
7892         SWM_S_BAR_DELAY,
7893         SWM_S_BAR_ENABLED,
7894         SWM_S_BAR_ENABLED_WS,
7895         SWM_S_BAR_FONT,
7896         SWM_S_BAR_FORMAT,
7897         SWM_S_BAR_JUSTIFY,
7898         SWM_S_BORDER_WIDTH,
7899         SWM_S_BOUNDARY_WIDTH,
7900         SWM_S_CLOCK_ENABLED,
7901         SWM_S_CLOCK_FORMAT,
7902         SWM_S_CYCLE_EMPTY,
7903         SWM_S_CYCLE_VISIBLE,
7904         SWM_S_DIALOG_RATIO,
7905         SWM_S_DISABLE_BORDER,
7906         SWM_S_FOCUS_CLOSE,
7907         SWM_S_FOCUS_CLOSE_WRAP,
7908         SWM_S_FOCUS_DEFAULT,
7909         SWM_S_FOCUS_MODE,
7910         SWM_S_ICONIC_ENABLED,
7911         SWM_S_JAVA_WORKAROUND,
7912         SWM_S_REGION_PADDING,
7913         SWM_S_SPAWN_ORDER,
7914         SWM_S_SPAWN_TERM,
7915         SWM_S_SS_APP,
7916         SWM_S_SS_ENABLED,
7917         SWM_S_STACK_ENABLED,
7918         SWM_S_TERM_WIDTH,
7919         SWM_S_TILE_GAP,
7920         SWM_S_URGENT_COLLAPSE,
7921         SWM_S_URGENT_ENABLED,
7922         SWM_S_VERBOSE_LAYOUT,
7923         SWM_S_WARP_POINTER,
7924         SWM_S_WINDOW_CLASS_ENABLED,
7925         SWM_S_WINDOW_INSTANCE_ENABLED,
7926         SWM_S_WINDOW_NAME_ENABLED,
7927         SWM_S_WORKSPACE_LIMIT,
7928         SWM_S_WORKSPACE_NAME,
7929 };
7930
7931 int
7932 setconfvalue(const char *selector, const char *value, int flags)
7933 {
7934         struct workspace        *ws;
7935         int                     i, ws_id, num_screens;
7936         char                    *b, *str, s[1024];
7937
7938         switch (flags) {
7939         case SWM_S_BAR_ACTION:
7940                 free(bar_argv[0]);
7941                 if ((bar_argv[0] = expand_tilde(value)) == NULL)
7942                         err(1, "setconfvalue: bar_action");
7943                 break;
7944         case SWM_S_BAR_AT_BOTTOM:
7945                 bar_at_bottom = (atoi(value) != 0);
7946                 break;
7947         case SWM_S_BAR_BORDER_WIDTH:
7948                 bar_border_width = atoi(value);
7949                 if (bar_border_width < 0)
7950                         bar_border_width = 0;
7951                 break;
7952         case SWM_S_BAR_DELAY:
7953                 /* No longer needed; leave to not break old conf files. */
7954                 break;
7955         case SWM_S_BAR_ENABLED:
7956                 bar_enabled = (atoi(value) != 0);
7957                 break;
7958         case SWM_S_BAR_ENABLED_WS:
7959                 ws_id = atoi(selector) - 1;
7960                 if (ws_id < 0 || ws_id >= workspace_limit)
7961                         errx(1, "setconfvalue: bar_enabled_ws: invalid "
7962                             "workspace %d.", ws_id + 1);
7963
7964                 num_screens = get_screen_count();
7965                 for (i = 0; i < num_screens; i++) {
7966                         ws = (struct workspace *)&screens[i].ws;
7967                         ws[ws_id].bar_enabled = (atoi(value) != 0);
7968                 }
7969                 break;
7970         case SWM_S_BAR_FONT:
7971                 b = bar_fonts;
7972                 if (asprintf(&bar_fonts, "%s,%s", value, bar_fonts) == -1)
7973                         err(1, "setconfvalue: asprintf: failed to allocate "
7974                                 "memory for bar_fonts.");
7975                 free(b);
7976
7977                 /* If already in xft mode, then we are done. */
7978                 if (!bar_font_legacy)
7979                         break;
7980
7981                 if ((str = strdup(value)) == NULL)
7982                         err(1, "setconfvalue: strdup");
7983
7984                 /* If there are any non-XLFD entries, switch to Xft mode. */
7985                 while ((b = strsep(&str, ",")) != NULL) {
7986                         if (*b == '\0')
7987                                 continue;
7988                         if (!isxlfd(b)) {
7989                                 bar_font_legacy = false;
7990                                 break;
7991                         }
7992                 }
7993
7994                 free(str);
7995                 break;
7996         case SWM_S_BAR_FORMAT:
7997                 free(bar_format);
7998                 if ((bar_format = strdup(value)) == NULL)
7999                         err(1, "setconfvalue: bar_format");
8000                 break;
8001         case SWM_S_BAR_JUSTIFY:
8002                 if (strcmp(value, "left") == 0)
8003                         bar_justify = SWM_BAR_JUSTIFY_LEFT;
8004                 else if (strcmp(value, "center") == 0)
8005                         bar_justify = SWM_BAR_JUSTIFY_CENTER;
8006                 else if (strcmp(value, "right") == 0)
8007                         bar_justify = SWM_BAR_JUSTIFY_RIGHT;
8008                 else
8009                         errx(1, "invalid bar_justify");
8010                 break;
8011         case SWM_S_BORDER_WIDTH:
8012                 border_width = atoi(value);
8013                 if (border_width < 0)
8014                         border_width = 0;
8015                 break;
8016         case SWM_S_BOUNDARY_WIDTH:
8017                 boundary_width = atoi(value);
8018                 if (boundary_width < 0)
8019                         boundary_width = 0;
8020                 break;
8021         case SWM_S_CLOCK_ENABLED:
8022                 clock_enabled = (atoi(value) != 0);
8023                 break;
8024         case SWM_S_CLOCK_FORMAT:
8025 #ifndef SWM_DENY_CLOCK_FORMAT
8026                 free(clock_format);
8027                 if ((clock_format = strdup(value)) == NULL)
8028                         err(1, "setconfvalue: clock_format");
8029 #endif
8030                 break;
8031         case SWM_S_CYCLE_EMPTY:
8032                 cycle_empty = (atoi(value) != 0);
8033                 break;
8034         case SWM_S_CYCLE_VISIBLE:
8035                 cycle_visible = (atoi(value) != 0);
8036                 break;
8037         case SWM_S_DIALOG_RATIO:
8038                 dialog_ratio = atof(value);
8039                 if (dialog_ratio > 1.0 || dialog_ratio <= .3)
8040                         dialog_ratio = .6;
8041                 break;
8042         case SWM_S_DISABLE_BORDER:
8043                 disable_border = (atoi(value) != 0);
8044                 break;
8045         case SWM_S_FOCUS_CLOSE:
8046                 if (strcmp(value, "first") == 0)
8047                         focus_close = SWM_STACK_BOTTOM;
8048                 else if (strcmp(value, "last") == 0)
8049                         focus_close = SWM_STACK_TOP;
8050                 else if (strcmp(value, "next") == 0)
8051                         focus_close = SWM_STACK_ABOVE;
8052                 else if (strcmp(value, "previous") == 0)
8053                         focus_close = SWM_STACK_BELOW;
8054                 else
8055                         errx(1, "focus_close");
8056                 break;
8057         case SWM_S_FOCUS_CLOSE_WRAP:
8058                 focus_close_wrap = (atoi(value) != 0);
8059                 break;
8060         case SWM_S_FOCUS_DEFAULT:
8061                 if (strcmp(value, "last") == 0)
8062                         focus_default = SWM_STACK_TOP;
8063                 else if (strcmp(value, "first") == 0)
8064                         focus_default = SWM_STACK_BOTTOM;
8065                 else
8066                         errx(1, "focus_default");
8067                 break;
8068         case SWM_S_FOCUS_MODE:
8069                 if (strcmp(value, "default") == 0)
8070                         focus_mode = SWM_FOCUS_DEFAULT;
8071                 else if (strcmp(value, "follow") == 0 ||
8072                     strcmp(value, "follow_cursor") == 0)
8073                         focus_mode = SWM_FOCUS_FOLLOW;
8074                 else if (strcmp(value, "manual") == 0)
8075                         focus_mode = SWM_FOCUS_MANUAL;
8076                 else
8077                         errx(1, "focus_mode");
8078                 break;
8079         case SWM_S_ICONIC_ENABLED:
8080                 iconic_enabled = (atoi(value) != 0);
8081                 break;
8082         case SWM_S_JAVA_WORKAROUND:
8083                 java_workaround = (atoi(value) != 0);
8084                 break;
8085         case SWM_S_REGION_PADDING:
8086                 region_padding = atoi(value);
8087                 if (region_padding < 0)
8088                         region_padding = 0;
8089                 break;
8090         case SWM_S_SPAWN_ORDER:
8091                 if (strcmp(value, "first") == 0)
8092                         spawn_position = SWM_STACK_BOTTOM;
8093                 else if (strcmp(value, "last") == 0)
8094                         spawn_position = SWM_STACK_TOP;
8095                 else if (strcmp(value, "next") == 0)
8096                         spawn_position = SWM_STACK_ABOVE;
8097                 else if (strcmp(value, "previous") == 0)
8098                         spawn_position = SWM_STACK_BELOW;
8099                 else
8100                         errx(1, "spawn_position");
8101                 break;
8102         case SWM_S_SPAWN_TERM:
8103                 setconfspawn("term", value, 0);
8104                 setconfspawn("spawn_term", value, 0);
8105                 break;
8106         case SWM_S_SS_APP:
8107                 /* No longer needed; leave to not break old conf files. */
8108                 break;
8109         case SWM_S_SS_ENABLED:
8110                 /* No longer needed; leave to not break old conf files. */
8111                 break;
8112         case SWM_S_STACK_ENABLED:
8113                 stack_enabled = (atoi(value) != 0);
8114                 break;
8115         case SWM_S_TERM_WIDTH:
8116                 term_width = atoi(value);
8117                 if (term_width < 0)
8118                         term_width = 0;
8119                 break;
8120         case SWM_S_TILE_GAP:
8121                 tile_gap = atoi(value);
8122                 break;
8123         case SWM_S_URGENT_COLLAPSE:
8124                 urgent_collapse = (atoi(value) != 0);
8125                 break;
8126         case SWM_S_URGENT_ENABLED:
8127                 urgent_enabled = (atoi(value) != 0);
8128                 break;
8129         case SWM_S_VERBOSE_LAYOUT:
8130                 verbose_layout = (atoi(value) != 0);
8131                 for (i = 0; layouts[i].l_stack != NULL; i++) {
8132                         if (verbose_layout)
8133                                 layouts[i].l_string = fancy_stacker;
8134                         else
8135                                 layouts[i].l_string = plain_stacker;
8136                 }
8137                 break;
8138         case SWM_S_WARP_POINTER:
8139                 warp_pointer = (atoi(value) != 0);
8140                 break;
8141         case SWM_S_WINDOW_CLASS_ENABLED:
8142                 window_class_enabled = (atoi(value) != 0);
8143                 break;
8144         case SWM_S_WINDOW_INSTANCE_ENABLED:
8145                 window_instance_enabled = (atoi(value) != 0);
8146                 break;
8147         case SWM_S_WINDOW_NAME_ENABLED:
8148                 window_name_enabled = (atoi(value) != 0);
8149                 break;
8150         case SWM_S_WORKSPACE_LIMIT:
8151                 workspace_limit = atoi(value);
8152                 if (workspace_limit > SWM_WS_MAX)
8153                         workspace_limit = SWM_WS_MAX;
8154                 else if (workspace_limit < 1)
8155                         workspace_limit = 1;
8156
8157                 ewmh_update_desktops();
8158                 break;
8159         case SWM_S_WORKSPACE_NAME:
8160                 if (getenv("SWM_STARTED") != NULL)
8161                         return (0);
8162
8163                 bzero(s, sizeof s);
8164                 if (sscanf(value, "ws[%d]:%1023c", &ws_id, s) != 2)
8165                         errx(1, "invalid entry, should be 'ws[<idx>]:name'");
8166                 ws_id--;
8167                 if (ws_id < 0 || ws_id >= workspace_limit)
8168                         errx(1, "setconfvalue: workspace_name: invalid "
8169                             "workspace %d.", ws_id + 1);
8170
8171                 num_screens = get_screen_count();
8172                 for (i = 0; i < num_screens; ++i) {
8173                         ws = (struct workspace *)&screens[i].ws;
8174
8175                         if (strlen(s) > 0) {
8176                                 free(ws[ws_id].name);
8177                                 if ((ws[ws_id].name = strdup(s)) == NULL)
8178                                         err(1, "setconfvalue: workspace_name.");
8179
8180                                 ewmh_update_desktop_names();
8181                                 ewmh_get_desktop_names();
8182                         }
8183                 }
8184                 break;
8185         default:
8186                 return (1);
8187         }
8188         return (0);
8189 }
8190
8191 int
8192 setconfmodkey(const char *selector, const char *value, int flags)
8193 {
8194         /* suppress unused warnings since vars are needed */
8195         (void)selector;
8196         (void)flags;
8197
8198         if (strncasecmp(value, "Mod1", strlen("Mod1")) == 0)
8199                 update_modkey(XCB_MOD_MASK_1);
8200         else if (strncasecmp(value, "Mod2", strlen("Mod2")) == 0)
8201                 update_modkey(XCB_MOD_MASK_2);
8202         else if (strncasecmp(value, "Mod3", strlen("Mod3")) == 0)
8203                 update_modkey(XCB_MOD_MASK_3);
8204         else if (strncasecmp(value, "Mod4", strlen("Mod4")) == 0)
8205                 update_modkey(XCB_MOD_MASK_4);
8206         else
8207                 return (1);
8208         return (0);
8209 }
8210
8211 int
8212 setconfcolor(const char *selector, const char *value, int flags)
8213 {
8214         int     first, last, i = 0, num_screens;
8215
8216         num_screens = get_screen_count();
8217
8218         /* conf screen indices begin at 1; treat vals <= 0 as 'all screens.' */
8219         if (selector == NULL || strlen(selector) == 0 ||
8220             (last = atoi(selector) - 1) < 0) {
8221                 first = 0;
8222                 last = num_screens - 1;
8223         } else {
8224                 first = last;
8225         }
8226
8227         if (last >= num_screens) {
8228                 add_startup_exception("invalid screen index: %d out of bounds "
8229                     "(maximum %d)", last + 1, num_screens);
8230                 return (1);
8231         }
8232
8233         for (i = first; i <= last; ++i) {
8234                 setscreencolor(value, i, flags);
8235
8236                 /*
8237                  * When setting focus/unfocus colors, we need to also
8238                  * set maximize colors to match if they haven't been customized.
8239                  */
8240                 if (flags == SWM_S_COLOR_FOCUS &&
8241                     !screens[i].c[SWM_S_COLOR_FOCUS_MAXIMIZED].manual)
8242                         setscreencolor(value, i, SWM_S_COLOR_FOCUS_MAXIMIZED);
8243                 else if (flags == SWM_S_COLOR_UNFOCUS &&
8244                     !screens[i].c[SWM_S_COLOR_UNFOCUS_MAXIMIZED].manual)
8245                         setscreencolor(value, i, SWM_S_COLOR_UNFOCUS_MAXIMIZED);
8246
8247                 screens[i].c[flags].manual = 1;
8248         }
8249
8250         return (0);
8251 }
8252
8253 int
8254 setconfregion(const char *selector, const char *value, int flags)
8255 {
8256         /* suppress unused warnings since vars are needed */
8257         (void)selector;
8258         (void)flags;
8259
8260         custom_region(value);
8261         return (0);
8262 }
8263
8264 int
8265 setautorun(const char *selector, const char *value, int flags)
8266 {
8267         int                     ws_id;
8268         char                    s[1024];
8269         char                    *ap, *sp;
8270         union arg               a;
8271         int                     argc = 0;
8272         pid_t                   pid;
8273         struct pid_e            *p;
8274
8275         /* suppress unused warnings since vars are needed */
8276         (void)selector;
8277         (void)flags;
8278
8279         if (getenv("SWM_STARTED"))
8280                 return (0);
8281
8282         bzero(s, sizeof s);
8283         if (sscanf(value, "ws[%d]:%1023c", &ws_id, s) != 2)
8284                 errx(1, "invalid autorun entry, should be 'ws[<idx>]:command'");
8285         ws_id--;
8286         if (ws_id < 0 || ws_id >= workspace_limit)
8287                 errx(1, "autorun: invalid workspace %d", ws_id + 1);
8288
8289         sp = expand_tilde((char *)&s);
8290
8291         /*
8292          * This is a little intricate
8293          *
8294          * If the pid already exists we simply reuse it because it means it was
8295          * used before AND not claimed by manage_window.  We get away with
8296          * altering it in the parent after INSERT because this can not be a race
8297          */
8298         a.argv = NULL;
8299         while ((ap = strsep(&sp, " \t")) != NULL) {
8300                 if (*ap == '\0')
8301                         continue;
8302                 DNPRINTF(SWM_D_SPAWN, "setautorun: arg [%s]\n", ap);
8303                 argc++;
8304                 if ((a.argv = realloc(a.argv, argc * sizeof(char *))) == NULL)
8305                         err(1, "setautorun: realloc");
8306                 a.argv[argc - 1] = ap;
8307         }
8308         free(sp);
8309
8310         if ((a.argv = realloc(a.argv, (argc + 1) * sizeof(char *))) == NULL)
8311                 err(1, "setautorun: realloc");
8312         a.argv[argc] = NULL;
8313
8314         if ((pid = fork()) == 0) {
8315                 spawn(ws_id, &a, true);
8316                 /* NOTREACHED */
8317                 _exit(1);
8318         }
8319         free(a.argv);
8320
8321         /* parent */
8322         p = find_pid(pid);
8323         if (p == NULL) {
8324                 p = calloc(1, sizeof *p);
8325                 if (p == NULL)
8326                         return (1);
8327                 TAILQ_INSERT_TAIL(&pidlist, p, entry);
8328         }
8329
8330         p->pid = pid;
8331         p->ws = ws_id;
8332
8333         return (0);
8334 }
8335
8336 int
8337 setlayout(const char *selector, const char *value, int flags)
8338 {
8339         struct workspace        *ws;
8340         int                     ws_id, i, x, mg, ma, si, ar;
8341         int                     st = SWM_V_STACK, num_screens;
8342         char                    s[1024];
8343         bool                    f = false;
8344
8345         /* suppress unused warnings since vars are needed */
8346         (void)selector;
8347         (void)flags;
8348
8349         if (getenv("SWM_STARTED"))
8350                 return (0);
8351
8352         bzero(s, sizeof s);
8353         if (sscanf(value, "ws[%d]:%d:%d:%d:%d:%1023c",
8354             &ws_id, &mg, &ma, &si, &ar, s) != 6)
8355                 errx(1, "invalid layout entry, should be 'ws[<idx>]:"
8356                     "<master_grow>:<master_add>:<stack_inc>:<always_raise>:"
8357                     "<type>'");
8358         ws_id--;
8359         if (ws_id < 0 || ws_id >= workspace_limit)
8360                 errx(1, "layout: invalid workspace %d", ws_id + 1);
8361
8362         if (strcasecmp(s, "vertical") == 0)
8363                 st = SWM_V_STACK;
8364         else if (strcasecmp(s, "vertical_flip") == 0) {
8365                 st = SWM_V_STACK;
8366                 f = true;
8367         } else if (strcasecmp(s, "horizontal") == 0)
8368                 st = SWM_H_STACK;
8369         else if (strcasecmp(s, "horizontal_flip") == 0) {
8370                 st = SWM_H_STACK;
8371                 f = true;
8372         } else if (strcasecmp(s, "fullscreen") == 0)
8373                 st = SWM_MAX_STACK;
8374         else
8375                 errx(1, "invalid layout entry, should be 'ws[<idx>]:"
8376                     "<master_grow>:<master_add>:<stack_inc>:<always_raise>:"
8377                     "<type>'");
8378
8379         num_screens = get_screen_count();
8380         for (i = 0; i < num_screens; i++) {
8381                 ws = (struct workspace *)&screens[i].ws;
8382                 ws[ws_id].cur_layout = &layouts[st];
8383
8384                 ws[ws_id].always_raise = (ar != 0);
8385                 if (st == SWM_MAX_STACK)
8386                         continue;
8387
8388                 /* master grow */
8389                 for (x = 0; x < abs(mg); x++) {
8390                         ws[ws_id].cur_layout->l_config(&ws[ws_id],
8391                             mg >= 0 ?  SWM_ARG_ID_MASTERGROW :
8392                             SWM_ARG_ID_MASTERSHRINK);
8393                 }
8394                 /* master add */
8395                 for (x = 0; x < abs(ma); x++) {
8396                         ws[ws_id].cur_layout->l_config(&ws[ws_id],
8397                             ma >= 0 ?  SWM_ARG_ID_MASTERADD :
8398                             SWM_ARG_ID_MASTERDEL);
8399                 }
8400                 /* stack inc */
8401                 for (x = 0; x < abs(si); x++) {
8402                         ws[ws_id].cur_layout->l_config(&ws[ws_id],
8403                             si >= 0 ?  SWM_ARG_ID_STACKINC :
8404                             SWM_ARG_ID_STACKDEC);
8405                 }
8406                 /* Apply flip */
8407                 if (f) {
8408                         ws[ws_id].cur_layout->l_config(&ws[ws_id],
8409                             SWM_ARG_ID_FLIPLAYOUT);
8410                 }
8411         }
8412
8413         return (0);
8414 }
8415
8416 /* config options */
8417 struct config_option {
8418         char                    *optname;
8419         int                     (*func)(const char*, const char*, int);
8420         int                     funcflags;
8421 };
8422 struct config_option configopt[] = {
8423         { "autorun",                    setautorun,     0 },
8424         { "bar_action",                 setconfvalue,   SWM_S_BAR_ACTION },
8425         { "bar_at_bottom",              setconfvalue,   SWM_S_BAR_AT_BOTTOM },
8426         { "bar_border",                 setconfcolor,   SWM_S_COLOR_BAR_BORDER },
8427         { "bar_border_unfocus",         setconfcolor,   SWM_S_COLOR_BAR_BORDER_UNFOCUS },
8428         { "bar_border_width",           setconfvalue,   SWM_S_BAR_BORDER_WIDTH },
8429         { "bar_color",                  setconfcolor,   SWM_S_COLOR_BAR },
8430         { "bar_delay",                  setconfvalue,   SWM_S_BAR_DELAY },
8431         { "bar_enabled",                setconfvalue,   SWM_S_BAR_ENABLED },
8432         { "bar_enabled_ws",             setconfvalue,   SWM_S_BAR_ENABLED_WS },
8433         { "bar_font",                   setconfvalue,   SWM_S_BAR_FONT },
8434         { "bar_font_color",             setconfcolor,   SWM_S_COLOR_BAR_FONT },
8435         { "bar_format",                 setconfvalue,   SWM_S_BAR_FORMAT },
8436         { "bar_justify",                setconfvalue,   SWM_S_BAR_JUSTIFY },
8437         { "bind",                       setconfbinding, 0 },
8438         { "border_width",               setconfvalue,   SWM_S_BORDER_WIDTH },
8439         { "boundary_width",             setconfvalue,   SWM_S_BOUNDARY_WIDTH },
8440         { "clock_enabled",              setconfvalue,   SWM_S_CLOCK_ENABLED },
8441         { "clock_format",               setconfvalue,   SWM_S_CLOCK_FORMAT },
8442         { "color_focus",                setconfcolor,   SWM_S_COLOR_FOCUS },
8443         { "color_focus_maximized",      setconfcolor,   SWM_S_COLOR_FOCUS_MAXIMIZED },
8444         { "color_unfocus",              setconfcolor,   SWM_S_COLOR_UNFOCUS },
8445         { "color_unfocus_maximized",    setconfcolor,   SWM_S_COLOR_UNFOCUS_MAXIMIZED },
8446         { "cycle_empty",                setconfvalue,   SWM_S_CYCLE_EMPTY },
8447         { "cycle_visible",              setconfvalue,   SWM_S_CYCLE_VISIBLE },
8448         { "dialog_ratio",               setconfvalue,   SWM_S_DIALOG_RATIO },
8449         { "disable_border",             setconfvalue,   SWM_S_DISABLE_BORDER },
8450         { "focus_close",                setconfvalue,   SWM_S_FOCUS_CLOSE },
8451         { "focus_close_wrap",           setconfvalue,   SWM_S_FOCUS_CLOSE_WRAP },
8452         { "focus_default",              setconfvalue,   SWM_S_FOCUS_DEFAULT },
8453         { "focus_mode",                 setconfvalue,   SWM_S_FOCUS_MODE },
8454         { "iconic_enabled",             setconfvalue,   SWM_S_ICONIC_ENABLED },
8455         { "java_workaround",            setconfvalue,   SWM_S_JAVA_WORKAROUND },
8456         { "keyboard_mapping",           setkeymapping,  0 },
8457         { "layout",                     setlayout,      0 },
8458         { "modkey",                     setconfmodkey,  0 },
8459         { "program",                    setconfspawn,   0 },
8460         { "quirk",                      setconfquirk,   0 },
8461         { "region",                     setconfregion,  0 },
8462         { "region_padding",             setconfvalue,   SWM_S_REGION_PADDING },
8463         { "screenshot_app",             setconfvalue,   SWM_S_SS_APP },
8464         { "screenshot_enabled",         setconfvalue,   SWM_S_SS_ENABLED },
8465         { "spawn_position",             setconfvalue,   SWM_S_SPAWN_ORDER },
8466         { "spawn_term",                 setconfvalue,   SWM_S_SPAWN_TERM },
8467         { "stack_enabled",              setconfvalue,   SWM_S_STACK_ENABLED },
8468         { "term_width",                 setconfvalue,   SWM_S_TERM_WIDTH },
8469         { "tile_gap",                   setconfvalue,   SWM_S_TILE_GAP },
8470         { "title_class_enabled",        setconfvalue,   SWM_S_WINDOW_CLASS_ENABLED }, /* For backwards compat. */
8471         { "title_name_enabled",         setconfvalue,   SWM_S_WINDOW_INSTANCE_ENABLED }, /* For backwards compat. */
8472         { "urgent_collapse",            setconfvalue,   SWM_S_URGENT_COLLAPSE },
8473         { "urgent_enabled",             setconfvalue,   SWM_S_URGENT_ENABLED },
8474         { "verbose_layout",             setconfvalue,   SWM_S_VERBOSE_LAYOUT },
8475         { "warp_pointer",               setconfvalue,   SWM_S_WARP_POINTER },
8476         { "window_class_enabled",       setconfvalue,   SWM_S_WINDOW_CLASS_ENABLED },
8477         { "window_instance_enabled",    setconfvalue,   SWM_S_WINDOW_INSTANCE_ENABLED },
8478         { "window_name_enabled",        setconfvalue,   SWM_S_WINDOW_NAME_ENABLED },
8479         { "workspace_limit",            setconfvalue,   SWM_S_WORKSPACE_LIMIT },
8480         { "name",                       setconfvalue,   SWM_S_WORKSPACE_NAME },
8481 };
8482
8483 void
8484 _add_startup_exception(const char *fmt, va_list ap)
8485 {
8486         if (vasprintf(&startup_exception, fmt, ap) == -1)
8487                 warn("%s: asprintf", __func__);
8488 }
8489
8490 void
8491 add_startup_exception(const char *fmt, ...)
8492 {
8493         va_list ap;
8494
8495         nr_exceptions++;
8496
8497         if (startup_exception)
8498                 return;
8499
8500         /* force bar to be enabled due to exception */
8501         bar_enabled = true;
8502
8503         va_start(ap, fmt);
8504         _add_startup_exception(fmt, ap);
8505         va_end(ap);
8506 }
8507
8508 int
8509 conf_load(const char *filename, int keymapping)
8510 {
8511         FILE                    *config;
8512         char                    *line = NULL, *cp, *ce, *optsub, *optval = NULL;
8513         size_t                  linelen, lineno = 0;
8514         int                     wordlen, i, optidx, count;
8515         struct config_option    *opt = NULL;
8516
8517         DNPRINTF(SWM_D_CONF, "conf_load: begin\n");
8518
8519         if (filename == NULL) {
8520                 warnx("conf_load: no filename");
8521                 return (1);
8522         }
8523
8524         DNPRINTF(SWM_D_CONF, "conf_load: open %s\n", filename);
8525
8526         if ((config = fopen(filename, "r")) == NULL) {
8527                 warn("conf_load: fopen: %s", filename);
8528                 return (1);
8529         }
8530
8531         while (!feof(config)) {
8532                 if (line)
8533                         free(line);
8534
8535                 if ((line = fparseln(config, &linelen, &lineno, NULL,
8536                     FPARSELN_UNESCCOMM | FPARSELN_UNESCCONT)) == NULL) {
8537                         if (ferror(config))
8538                                 err(1, "%s", filename);
8539                         else
8540                                 continue;
8541                 }
8542                 cp = line;
8543                 cp += strspn(cp, " \t\n"); /* eat whitespace */
8544                 if (cp[0] == '\0') {
8545                         /* empty line */
8546                         continue;
8547                 }
8548                 /* get config option */
8549                 wordlen = strcspn(cp, "=[ \t\n");
8550                 if (wordlen == 0) {
8551                         add_startup_exception("%s: line %zd: no option found",
8552                             filename, lineno);
8553                         continue;
8554                 }
8555                 optidx = -1;
8556                 for (i = 0; i < LENGTH(configopt); i++) {
8557                         opt = &configopt[i];
8558                         if (strncasecmp(cp, opt->optname, wordlen) == 0 &&
8559                             (int)strlen(opt->optname) == wordlen) {
8560                                 optidx = i;
8561                                 break;
8562                         }
8563                 }
8564                 if (optidx == -1) {
8565                         add_startup_exception("%s: line %zd: unknown option "
8566                             "%.*s", filename, lineno, wordlen, cp);
8567                         continue;
8568                 }
8569                 if (keymapping && opt && strcmp(opt->optname, "bind")) {
8570                         add_startup_exception("%s: line %zd: invalid option "
8571                             "%.*s", filename, lineno, wordlen, cp);
8572                         continue;
8573                 }
8574                 cp += wordlen;
8575                 cp += strspn(cp, " \t\n"); /* eat whitespace */
8576
8577                 /* get [selector] if any */
8578                 optsub = NULL;
8579                 count = 0;
8580                 if (*cp == '[') {
8581                         ++count;
8582                         /* Get length of selector. */
8583                         for (ce = ++cp; *ce != '\0'; ++ce) {
8584                                 /* Find matching (not escaped) bracket. */
8585                                 if (*ce == ']' && *(ce - 1) != '\\') {
8586                                         --count;
8587                                         break;
8588                                 }
8589                         }
8590
8591                         if (count > 0) {
8592                                 add_startup_exception("%s: line %zd: syntax "
8593                                     "error: unterminated selector", filename,
8594                                     lineno);
8595                                 continue;
8596                         }
8597
8598                         /* ce points at ']'; terminate optsub. */
8599                         *ce = '\0';
8600                         optsub = cp;
8601                         cp = ce + 1;
8602                 }
8603                 cp += strspn(cp, "= \t\n"); /* eat trailing */
8604                 /* get RHS value */
8605                 optval = cp;
8606                 if (strlen(optval) == 0) {
8607                         add_startup_exception("%s: line %zd: must supply value "
8608                             "to %s", filename, lineno,
8609                             configopt[optidx].optname);
8610                         continue;
8611                 }
8612                 /* call function to deal with it all */
8613                 if (configopt[optidx].func(optsub, optval,
8614                     configopt[optidx].funcflags) != 0) {
8615                         add_startup_exception("%s: line %zd: invalid data for "
8616                             "%s", filename, lineno, configopt[optidx].optname);
8617                         continue;
8618                 }
8619         }
8620
8621         if (line)
8622                 free(line);
8623         fclose(config);
8624         DNPRINTF(SWM_D_CONF, "conf_load: end\n");
8625
8626         return (0);
8627 }
8628
8629 void
8630 set_child_transient(struct ws_win *win, xcb_window_t *trans)
8631 {
8632         struct ws_win           *parent, *w;
8633         struct swm_region       *r;
8634         struct workspace        *ws;
8635         xcb_icccm_wm_hints_t    wmh;
8636
8637         parent = find_window(win->transient);
8638         if (parent)
8639                 parent->focus_child = win;
8640         else {
8641                 DNPRINTF(SWM_D_MISC, "set_child_transient: parent doesn't exist"
8642                     " for %#x trans %#x\n", win->id, win->transient);
8643
8644                 r = root_to_region(win->s->root, SWM_CK_ALL);
8645                 ws = r->ws;
8646                 /* parent doen't exist in our window list */
8647                 TAILQ_FOREACH(w, &ws->winlist, entry) {
8648                         if (xcb_icccm_get_wm_hints_reply(conn,
8649                             xcb_icccm_get_wm_hints(conn, w->id),
8650                             &wmh, NULL) != 1) {
8651                                 warnx("can't get hints for %#x", w->id);
8652                                 continue;
8653                         }
8654
8655                         if (win->hints.window_group != wmh.window_group)
8656                                 continue;
8657
8658                         w->focus_child = win;
8659                         win->transient = w->id;
8660                         *trans = w->id;
8661                         DNPRINTF(SWM_D_MISC, "set_child_transient: adjusting "
8662                             "transient to %#x\n", win->transient);
8663                         break;
8664                 }
8665         }
8666 }
8667
8668 pid_t
8669 window_get_pid(xcb_window_t win)
8670 {
8671         pid_t                           ret = 0;
8672         const char                      *errstr;
8673         xcb_atom_t                      apid;
8674         xcb_get_property_cookie_t       pc;
8675         xcb_get_property_reply_t        *pr;
8676
8677         apid = get_atom_from_string("_NET_WM_PID");
8678         if (apid == XCB_ATOM_NONE)
8679                 goto tryharder;
8680
8681         pc = xcb_get_property(conn, 0, win, apid, XCB_ATOM_CARDINAL, 0, 1);
8682         pr = xcb_get_property_reply(conn, pc, NULL);
8683         if (pr == NULL)
8684                 goto tryharder;
8685         if (pr->type != XCB_ATOM_CARDINAL) {
8686                 free(pr);
8687                 goto tryharder;
8688         }
8689
8690         if (pr->type == apid && pr->format == 32)
8691                 ret = *((pid_t *)xcb_get_property_value(pr));
8692         free(pr);
8693
8694         return (ret);
8695
8696 tryharder:
8697         apid = get_atom_from_string("_SWM_PID");
8698         pc = xcb_get_property(conn, 0, win, apid, XCB_ATOM_STRING,
8699             0, SWM_PROPLEN);
8700         pr = xcb_get_property_reply(conn, pc, NULL);
8701         if (pr == NULL)
8702                 return (0);
8703         if (pr->type != apid) {
8704                 free(pr);
8705                 return (0);
8706         }
8707
8708         ret = (pid_t)strtonum(xcb_get_property_value(pr), 0, INT_MAX, &errstr);
8709         free(pr);
8710
8711         return (ret);
8712 }
8713
8714 int
8715 get_swm_ws(xcb_window_t id)
8716 {
8717         int                     ws_idx = -1;
8718         char                    *prop = NULL;
8719         size_t                  proplen;
8720         const char              *errstr;
8721         xcb_get_property_reply_t        *gpr;
8722
8723         gpr = xcb_get_property_reply(conn,
8724                 xcb_get_property(conn, 0, id, a_swm_ws,
8725                     XCB_ATOM_STRING, 0, SWM_PROPLEN),
8726                 NULL);
8727         if (gpr == NULL)
8728                 return (-1);
8729         if (gpr->type) {
8730                 proplen = xcb_get_property_value_length(gpr);
8731                 if (proplen > 0) {
8732                         prop = malloc(proplen + 1);
8733                         if (prop) {
8734                                 memcpy(prop,
8735                                     xcb_get_property_value(gpr),
8736                                     proplen);
8737                                 prop[proplen] = '\0';
8738                         }
8739                 }
8740         }
8741         free(gpr);
8742
8743         if (prop) {
8744                 DNPRINTF(SWM_D_PROP, "get_swm_ws: _SWM_WS: %s\n", prop);
8745                 ws_idx = (int)strtonum(prop, 0, workspace_limit - 1, &errstr);
8746                 if (errstr) {
8747                         DNPRINTF(SWM_D_PROP, "get_swm_ws: win #%s: %s",
8748                             errstr, prop);
8749                 }
8750                 free(prop);
8751         }
8752
8753         return ws_idx;
8754 }
8755
8756 int
8757 get_ws_idx(struct ws_win *win)
8758 {
8759         xcb_get_property_reply_t        *gpr;
8760         int                     ws_idx = -1;
8761
8762         if (win == NULL)
8763                 return -1;
8764
8765         gpr = xcb_get_property_reply(conn,
8766                 xcb_get_property(conn, 0, win->id, ewmh[_NET_WM_DESKTOP].atom,
8767                     XCB_ATOM_CARDINAL, 0, 1),
8768                 NULL);
8769         if (gpr) {
8770                 if (gpr->type == XCB_ATOM_CARDINAL && gpr->format == 32)
8771                         ws_idx = *((int *)xcb_get_property_value(gpr));
8772                 free(gpr);
8773         }
8774
8775         if (ws_idx == -1 && !(win->quirks & SWM_Q_IGNORESPAWNWS))
8776                 ws_idx = get_swm_ws(win->id);
8777
8778         if (ws_idx > workspace_limit - 1 || ws_idx < -1)
8779                 ws_idx = -1;
8780
8781         DNPRINTF(SWM_D_PROP, "get_ws_idx: win %#x, ws_idx: %d\n", win->id,
8782             ws_idx);
8783
8784         return ws_idx;
8785 }
8786
8787 struct ws_win *
8788 manage_window(xcb_window_t id, int spawn_pos, bool mapped)
8789 {
8790         struct ws_win           *win, *ww;
8791         struct swm_region       *r;
8792         struct pid_e            *p;
8793         struct quirk            *qp;
8794         xcb_get_geometry_reply_t        *gr;
8795         xcb_window_t            trans = XCB_WINDOW_NONE;
8796         uint32_t                i, wa[2], new_flags;
8797         int                     ws_idx, force_ws = -1;
8798         char                    *class, *instance, *name;
8799
8800         if ((win = find_window(id)) != NULL) {
8801                 DNPRINTF(SWM_D_MISC, "manage_window: win %#x already "
8802                     "managed; skipping.)\n", id);
8803                 return (win);   /* Already managed. */
8804         }
8805
8806         /* See if window is on the unmanaged list. */
8807         if ((win = find_unmanaged_window(id)) != NULL) {
8808                 DNPRINTF(SWM_D_MISC, "manage_window: win %#x found on "
8809                     "unmanaged list.\n", id);
8810                 TAILQ_REMOVE(&win->ws->unmanagedlist, win, entry);
8811
8812                 if (TRANS(win))
8813                         set_child_transient(win, &trans);
8814
8815                 goto out;
8816         } else {
8817                 DNPRINTF(SWM_D_MISC, "manage_window: win %#x is new.\n", id);
8818         }
8819
8820         /* Try to get initial window geometry. */
8821         gr = xcb_get_geometry_reply(conn, xcb_get_geometry(conn, id), NULL);
8822         if (gr == NULL) {
8823                 DNPRINTF(SWM_D_MISC, "manage_window: get geometry failed.\n");
8824                 return (NULL);
8825         }
8826
8827         /* Create and initialize ws_win object. */
8828         if ((win = calloc(1, sizeof(struct ws_win))) == NULL)
8829                 err(1, "manage_window: calloc: failed to allocate memory for "
8830                     "new window");
8831
8832         win->id = id;
8833
8834         /* Figureout which region the window belongs to. */
8835         r = root_to_region(gr->root, SWM_CK_ALL);
8836
8837         /* Ignore window border if there is one. */
8838         WIDTH(win) = gr->width;
8839         HEIGHT(win) = gr->height;
8840         X(win) = gr->x + gr->border_width - border_width;
8841         Y(win) = gr->y + gr->border_width - border_width;
8842         win->bordered = true;
8843         win->mapped = mapped;
8844         win->s = r->s;  /* this never changes */
8845
8846         free(gr);
8847
8848         /* Select which X events to monitor and set border pixel color. */
8849         wa[0] = win->s->c[SWM_S_COLOR_UNFOCUS].pixel;
8850         wa[1] = XCB_EVENT_MASK_ENTER_WINDOW | XCB_EVENT_MASK_PROPERTY_CHANGE |
8851             XCB_EVENT_MASK_STRUCTURE_NOTIFY;
8852 #ifdef SWM_DEBUG
8853         wa[1] |= XCB_EVENT_MASK_LEAVE_WINDOW | XCB_EVENT_MASK_FOCUS_CHANGE;
8854 #endif
8855
8856         xcb_change_window_attributes(conn, win->id, XCB_CW_BORDER_PIXEL |
8857             XCB_CW_EVENT_MASK, wa);
8858
8859         /* Get WM_SIZE_HINTS. */
8860         xcb_icccm_get_wm_normal_hints_reply(conn,
8861             xcb_icccm_get_wm_normal_hints(conn, win->id),
8862             &win->sh, NULL);
8863
8864         /* Get WM_HINTS. */
8865         xcb_icccm_get_wm_hints_reply(conn,
8866             xcb_icccm_get_wm_hints(conn, win->id),
8867             &win->hints, NULL);
8868
8869         /* Get WM_TRANSIENT_FOR; see if window is a transient. */
8870         xcb_icccm_get_wm_transient_for_reply(conn,
8871             xcb_icccm_get_wm_transient_for(conn, win->id),
8872             &trans, NULL);
8873         if (trans) {
8874                 win->transient = trans;
8875                 set_child_transient(win, &win->transient);
8876         }
8877
8878         /* Get WM_PROTOCOLS. */
8879         get_wm_protocols(win);
8880
8881         /* Set initial quirks based on EWMH. */
8882         ewmh_autoquirk(win);
8883
8884         /* Determine initial quirks. */
8885         xcb_icccm_get_wm_class_reply(conn,
8886             xcb_icccm_get_wm_class(conn, win->id),
8887             &win->ch, NULL);
8888
8889         class = win->ch.class_name ? win->ch.class_name : "";
8890         instance = win->ch.instance_name ? win->ch.instance_name : "";
8891         name = get_win_name(win->id);
8892
8893         DNPRINTF(SWM_D_CLASS, "manage_window: class: %s, instance: %s, "
8894             "name: %s\n", class, instance, name);
8895
8896         /* java is retarded so treat it special */
8897         if (strstr(instance, "sun-awt")) {
8898                 DNPRINTF(SWM_D_CLASS, "manage_window: java window detected.\n");
8899                 win->java = true;
8900         }
8901
8902         TAILQ_FOREACH(qp, &quirks, entry) {
8903                 if (regexec(&qp->regex_class, class, 0, NULL, 0) == 0 &&
8904                     regexec(&qp->regex_instance, instance, 0, NULL, 0) == 0 &&
8905                     regexec(&qp->regex_name, name, 0, NULL, 0) == 0) {
8906                         DNPRINTF(SWM_D_CLASS, "manage_window: matched "
8907                             "quirk: %s:%s:%s mask: %#x, ws: %d\n", qp->class,
8908                             qp->instance, qp->name, qp->quirk, qp->ws);
8909                         win->quirks = qp->quirk;
8910                         if (qp->ws >= 0 && qp->ws < workspace_limit)
8911                                 force_ws = qp->ws;
8912                 }
8913         }
8914
8915         free(name);
8916
8917         /* Reset font sizes (the bruteforce way; no default keybinding). */
8918         if (win->quirks & SWM_Q_XTERM_FONTADJ) {
8919                 for (i = 0; i < SWM_MAX_FONT_STEPS; i++)
8920                         fake_keypress(win, XK_KP_Subtract, XCB_MOD_MASK_SHIFT);
8921                 for (i = 0; i < SWM_MAX_FONT_STEPS; i++)
8922                         fake_keypress(win, XK_KP_Add, XCB_MOD_MASK_SHIFT);
8923         }
8924
8925         /* Figure out which workspace the window belongs to. */
8926         if (!(win->quirks & SWM_Q_IGNOREPID) &&
8927             (p = find_pid(window_get_pid(win->id))) != NULL) {
8928                 win->ws = &r->s->ws[p->ws];
8929                 TAILQ_REMOVE(&pidlist, p, entry);
8930                 free(p);
8931                 p = NULL;
8932         } else if ((ws_idx = get_ws_idx(win)) != -1 &&
8933             !TRANS(win)) {
8934                 /* _SWM_WS is set; use that. */
8935                 win->ws = &r->s->ws[ws_idx];
8936         } else if (trans && (ww = find_window(trans)) != NULL) {
8937                 /* Launch transients in the same ws as parent. */
8938                 win->ws = ww->ws;
8939         } else {
8940                 win->ws = r->ws;
8941         }
8942
8943         if (force_ws != -1)
8944                 win->ws = &r->s->ws[force_ws];
8945
8946         /* Set the _NET_WM_DESKTOP atom. */
8947         DNPRINTF(SWM_D_PROP, "manage_window: set _NET_WM_DESKTOP: %d\n",
8948             win->ws->idx);
8949         xcb_change_property(conn, XCB_PROP_MODE_REPLACE, win->id,
8950             ewmh[_NET_WM_DESKTOP].atom, XCB_ATOM_CARDINAL, 32, 1, &win->ws->idx);
8951
8952         /* Remove any _SWM_WS now that we set _NET_WM_DESKTOP. */
8953         xcb_delete_property(conn, win->id, a_swm_ws);
8954
8955         /* WS must already be set for this to work. */
8956         store_float_geom(win);
8957
8958         /* Make sure window is positioned inside its region, if its active. */
8959         if (win->ws->r) {
8960                 region_containment(win, r, SWM_CW_ALLSIDES |
8961                     SWM_CW_HARDBOUNDARY);
8962                 update_window(win);
8963         }
8964
8965 out:
8966         /* Figure out where to stack the window in the workspace. */
8967         if (trans && (ww = find_window(trans)))
8968                 TAILQ_INSERT_AFTER(&win->ws->winlist, ww, win, entry);
8969         else if (win->ws->focus && spawn_pos == SWM_STACK_ABOVE)
8970                 TAILQ_INSERT_AFTER(&win->ws->winlist, win->ws->focus, win,
8971                     entry);
8972         else if (win->ws->focus && spawn_pos == SWM_STACK_BELOW)
8973                 TAILQ_INSERT_BEFORE(win->ws->focus, win, entry);
8974         else switch (spawn_pos) {
8975         default:
8976         case SWM_STACK_TOP:
8977         case SWM_STACK_ABOVE:
8978                 TAILQ_INSERT_TAIL(&win->ws->winlist, win, entry);
8979                 break;
8980         case SWM_STACK_BOTTOM:
8981         case SWM_STACK_BELOW:
8982                 TAILQ_INSERT_HEAD(&win->ws->winlist, win, entry);
8983         }
8984
8985         ewmh_update_client_list();
8986
8987         TAILQ_INSERT_TAIL(&win->ws->stack, win, stack_entry);
8988
8989         /* Get/apply initial _NET_WM_STATE */
8990         ewmh_get_wm_state(win);
8991
8992         /* Apply quirks. */
8993         new_flags = win->ewmh_flags;
8994
8995         if (win->quirks & SWM_Q_FLOAT)
8996                 new_flags |= EWMH_F_ABOVE;
8997
8998         if (win->quirks & SWM_Q_ANYWHERE)
8999                 new_flags |= SWM_F_MANUAL;
9000
9001         ewmh_apply_flags(win, new_flags);
9002         ewmh_update_wm_state(win);
9003
9004         /* Set initial _NET_WM_ALLOWED_ACTIONS */
9005         ewmh_update_actions(win);
9006
9007         grabbuttons(win);
9008
9009         DNPRINTF(SWM_D_MISC, "manage_window: done. win %#x, (x,y) w x h: "
9010             "(%d,%d) %d x %d, ws: %d, iconic: %s, transient: %#x\n", win->id,
9011             X(win), Y(win), WIDTH(win), HEIGHT(win), win->ws->idx,
9012             YESNO(ICONIC(win)), win->transient);
9013
9014         return (win);
9015 }
9016
9017 void
9018 free_window(struct ws_win *win)
9019 {
9020         DNPRINTF(SWM_D_MISC, "free_window: win %#x\n", win->id);
9021
9022         if (win == NULL)
9023                 return;
9024
9025         TAILQ_REMOVE(&win->ws->unmanagedlist, win, entry);
9026
9027         xcb_icccm_get_wm_class_reply_wipe(&win->ch);
9028
9029         kill_refs(win);
9030
9031         /* paint memory */
9032         memset(win, 0xff, sizeof *win); /* XXX kill later */
9033
9034         free(win);
9035         DNPRINTF(SWM_D_MISC, "free_window: done.\n");
9036 }
9037
9038 void
9039 unmanage_window(struct ws_win *win)
9040 {
9041         struct ws_win           *parent;
9042
9043         if (win == NULL)
9044                 return;
9045
9046         DNPRINTF(SWM_D_MISC, "unmanage_window: win %#x\n", win->id);
9047
9048         if (TRANS(win)) {
9049                 parent = find_window(win->transient);
9050                 if (parent)
9051                         parent->focus_child = NULL;
9052         }
9053
9054         TAILQ_REMOVE(&win->ws->stack, win, stack_entry);
9055         TAILQ_REMOVE(&win->ws->winlist, win, entry);
9056         TAILQ_INSERT_TAIL(&win->ws->unmanagedlist, win, entry);
9057
9058         ewmh_update_client_list();
9059 }
9060
9061 void
9062 expose(xcb_expose_event_t *e)
9063 {
9064         int                     i, num_screens;
9065         struct swm_region       *r;
9066
9067         DNPRINTF(SWM_D_EVENT, "expose: win %#x\n", e->window);
9068
9069         num_screens = get_screen_count();
9070         for (i = 0; i < num_screens; i++)
9071                 TAILQ_FOREACH(r, &screens[i].rl, entry)
9072                         if (e->window == WINID(r->bar))
9073                                 bar_draw();
9074
9075         xcb_flush(conn);
9076 }
9077
9078 #ifdef SWM_DEBUG
9079 void
9080 focusin(xcb_focus_in_event_t *e)
9081 {
9082         DNPRINTF(SWM_D_EVENT, "focusin: win %#x, mode: %s(%u), "
9083             "detail: %s(%u)\n", e->event, get_notify_mode_label(e->mode),
9084             e->mode, get_notify_detail_label(e->detail), e->detail);
9085 }
9086
9087 void
9088 focusout(xcb_focus_out_event_t *e)
9089 {
9090         DNPRINTF(SWM_D_EVENT, "focusout: win %#x, mode: %s(%u), "
9091             "detail: %s(%u)\n", e->event, get_notify_mode_label(e->mode),
9092             e->mode, get_notify_detail_label(e->detail), e->detail);
9093 }
9094 #endif
9095
9096 void
9097 keypress(xcb_key_press_event_t *e)
9098 {
9099         xcb_keysym_t            keysym;
9100         struct key              *kp;
9101
9102         keysym = xcb_key_press_lookup_keysym(syms, e, 0);
9103
9104         DNPRINTF(SWM_D_EVENT, "keypress: keysym: %u, win (x,y): %#x (%d,%d), "
9105             "detail: %u, time: %u, root (x,y): %#x (%d,%d), child: %#x, "
9106             "state: %u, same_screen: %s\n", keysym, e->event, e->event_x,
9107             e->event_y, e->detail, e->time, e->root, e->root_x, e->root_y,
9108             e->child, e->state, YESNO(e->same_screen));
9109
9110         if ((kp = key_lookup(CLEANMASK(e->state), keysym)) == NULL)
9111                 goto out;
9112
9113         last_event_time = e->time;
9114
9115         if (kp->funcid == KF_SPAWN_CUSTOM)
9116                 spawn_custom(root_to_region(e->root, SWM_CK_ALL),
9117                     &(keyfuncs[kp->funcid].args), kp->spawn_name);
9118         else if (keyfuncs[kp->funcid].func)
9119                 keyfuncs[kp->funcid].func(root_to_region(e->root, SWM_CK_ALL),
9120                     &(keyfuncs[kp->funcid].args));
9121
9122 out:
9123         /* Unfreeze grab events. */
9124         xcb_allow_events(conn, XCB_ALLOW_ASYNC_KEYBOARD, e->time);
9125         xcb_flush(conn);
9126
9127         DNPRINTF(SWM_D_EVENT, "keypress: done.\n");
9128 }
9129
9130 void
9131 buttonpress(xcb_button_press_event_t *e)
9132 {
9133         struct ws_win           *win = NULL;
9134         struct swm_region       *r, *old_r;
9135         int                     i;
9136         bool                    handled = false;
9137
9138         DNPRINTF(SWM_D_EVENT, "buttonpress: win (x,y): %#x (%d,%d), "
9139             "detail: %u, time: %u, root (x,y): %#x (%d,%d), child: %#x, "
9140             "state: %u, same_screen: %s\n", e->event, e->event_x, e->event_y,
9141             e->detail, e->time, e->root, e->root_x, e->root_y, e->child,
9142             e->state, YESNO(e->same_screen));
9143
9144         if (e->event == e->root) {
9145                 if (e->child != 0) {
9146                         win = find_window(e->child);
9147                         /* Pass ButtonPress to window if it isn't managed. */
9148                         if (win == NULL)
9149                                 goto out;
9150                 } else {
9151                         /* Focus on empty region */
9152                         /* If no windows on region if its empty. */
9153                         r = root_to_region(e->root, SWM_CK_POINTER);
9154                         if (r == NULL) {
9155                                 DNPRINTF(SWM_D_EVENT, "buttonpress: "
9156                                     "NULL region; ignoring.\n");
9157                                 goto out;
9158                         }
9159
9160                         if (TAILQ_EMPTY(&r->ws->winlist)) {
9161                                 old_r = root_to_region(e->root, SWM_CK_FOCUS);
9162                                 if (old_r && old_r != r)
9163                                         unfocus_win(old_r->ws->focus);
9164
9165                                 xcb_set_input_focus(conn,
9166                                     XCB_INPUT_FOCUS_PARENT, e->root, e->time);
9167
9168                                 /* Clear bar since empty. */
9169                                 bar_draw();
9170
9171                                 handled = true;
9172                                 goto out;
9173                         }
9174                 }
9175         } else {
9176                 win = find_window(e->event);
9177         }
9178
9179         if (win == NULL)
9180                 goto out;
9181
9182         last_event_time = e->time;
9183
9184         focus_win(get_focus_magic(win));
9185
9186         for (i = 0; i < LENGTH(buttons); i++)
9187                 if (client_click == buttons[i].action && buttons[i].func &&
9188                     buttons[i].button == e->detail &&
9189                     CLEANMASK(buttons[i].mask) == CLEANMASK(e->state)) {
9190                         buttons[i].func(win, &buttons[i].args);
9191                         handled = true;
9192                 }
9193
9194 out:
9195         if (!handled) {
9196                 DNPRINTF(SWM_D_EVENT, "buttonpress: passing to window.\n");
9197                 /* Replay event to event window */
9198                 xcb_allow_events(conn, XCB_ALLOW_REPLAY_POINTER, e->time);
9199         } else {
9200                 DNPRINTF(SWM_D_EVENT, "buttonpress: handled.\n");
9201                 /* Unfreeze grab events. */
9202                 xcb_allow_events(conn, XCB_ALLOW_SYNC_POINTER, e->time);
9203         }
9204
9205         xcb_flush(conn);
9206 }
9207
9208 #ifdef SWM_DEBUG
9209 void
9210 print_win_geom(xcb_window_t w)
9211 {
9212         xcb_get_geometry_reply_t        *wa;
9213
9214         wa = xcb_get_geometry_reply(conn, xcb_get_geometry(conn, w), NULL);
9215         if (wa == NULL) {
9216                 DNPRINTF(SWM_D_MISC, "print_win_geom: window not found: %#x\n",
9217                     w);
9218                 return;
9219         }
9220
9221         DNPRINTF(SWM_D_MISC, "print_win_geom: win %#x, root: %#x, "
9222             "depth: %u, (x,y) w x h: (%d,%d) %d x %d, border: %d\n",
9223             w, wa->root, wa->depth, wa->x,  wa->y, wa->width, wa->height,
9224             wa->border_width);
9225
9226         free(wa);
9227 }
9228 #endif
9229
9230 #ifdef SWM_DEBUG
9231 char *
9232 get_stack_mode_name(uint8_t mode)
9233 {
9234         char    *name;
9235
9236         switch(mode) {
9237         case XCB_STACK_MODE_ABOVE:
9238                 name = "Above";
9239                 break;
9240         case XCB_STACK_MODE_BELOW:
9241                 name = "Below";
9242                 break;
9243         case XCB_STACK_MODE_TOP_IF:
9244                 name = "TopIf";
9245                 break;
9246         case XCB_STACK_MODE_BOTTOM_IF:
9247                 name = "BottomIf";
9248                 break;
9249         case XCB_STACK_MODE_OPPOSITE:
9250                 name = "Opposite";
9251                 break;
9252         default:
9253                 name = "Unknown";
9254         }
9255
9256         return name;
9257 }
9258 #endif
9259
9260 void
9261 configurerequest(xcb_configure_request_event_t *e)
9262 {
9263         struct ws_win           *win;
9264         struct swm_region       *r = NULL;
9265         int                     i = 0;
9266         uint32_t                wc[7] = {0};
9267         uint16_t                mask = 0;
9268         bool                    new = false;
9269
9270         if ((win = find_window(e->window)) == NULL)
9271                 if ((win = find_unmanaged_window(e->window)) == NULL)
9272                         new = true;
9273
9274 #ifdef SWM_DEBUG
9275         if (swm_debug & SWM_D_EVENT) {
9276                 print_win_geom(e->window);
9277
9278                 DNPRINTF(SWM_D_EVENT, "configurerequest: win %#x, "
9279                     "parent: %#x, new: %s, value_mask: %u { ", e->window,
9280                     e->parent, YESNO(new), e->value_mask);
9281                 if (e->value_mask & XCB_CONFIG_WINDOW_X)
9282                         DPRINTF("X: %d ", e->x);
9283                 if (e->value_mask & XCB_CONFIG_WINDOW_Y)
9284                         DPRINTF("Y: %d ", e->y);
9285                 if (e->value_mask & XCB_CONFIG_WINDOW_WIDTH)
9286                         DPRINTF("W: %u ", e->width);
9287                 if (e->value_mask & XCB_CONFIG_WINDOW_HEIGHT)
9288                         DPRINTF("H: %u ", e->height);
9289                 if (e->value_mask & XCB_CONFIG_WINDOW_BORDER_WIDTH)
9290                         DPRINTF("Border: %u ", e->border_width);
9291                 if (e->value_mask & XCB_CONFIG_WINDOW_SIBLING)
9292                         DPRINTF("Sibling: %#x ", e->sibling);
9293                 if (e->value_mask & XCB_CONFIG_WINDOW_STACK_MODE)
9294                         DPRINTF("StackMode: %s(%u) ",
9295                             get_stack_mode_name(e->stack_mode), e->stack_mode);
9296                 DPRINTF("}\n");
9297         }
9298 #endif
9299
9300         if (new) {
9301                 if (e->value_mask & XCB_CONFIG_WINDOW_X) {
9302                         mask |= XCB_CONFIG_WINDOW_X;
9303                         wc[i++] = e->x;
9304                 }
9305                 if (e->value_mask & XCB_CONFIG_WINDOW_Y) {
9306                         mask |= XCB_CONFIG_WINDOW_Y;
9307                         wc[i++] = e->y;
9308                 }
9309                 if (e->value_mask & XCB_CONFIG_WINDOW_WIDTH) {
9310                         mask |= XCB_CONFIG_WINDOW_WIDTH;
9311                         wc[i++] = e->width;
9312                 }
9313                 if (e->value_mask & XCB_CONFIG_WINDOW_HEIGHT) {
9314                         mask |= XCB_CONFIG_WINDOW_HEIGHT;
9315                         wc[i++] = e->height;
9316                 }
9317                 if (e->value_mask & XCB_CONFIG_WINDOW_BORDER_WIDTH) {
9318                         mask |= XCB_CONFIG_WINDOW_BORDER_WIDTH;
9319                         wc[i++] = e->border_width;
9320                 }
9321                 if (e->value_mask & XCB_CONFIG_WINDOW_SIBLING) {
9322                         mask |= XCB_CONFIG_WINDOW_SIBLING;
9323                         wc[i++] = e->sibling;
9324                 }
9325                 if (e->value_mask & XCB_CONFIG_WINDOW_STACK_MODE) {
9326                         mask |= XCB_CONFIG_WINDOW_STACK_MODE;
9327                         wc[i++] = e->stack_mode;
9328                 }
9329
9330                 if (mask != 0) {
9331                         xcb_configure_window(conn, e->window, mask, wc);
9332                         xcb_flush(conn);
9333                 }
9334         } else if ((!MANUAL(win) || win->quirks & SWM_Q_ANYWHERE) &&
9335             !FULLSCREEN(win) && !MAXIMIZED(win)) {
9336                 if (win->ws->r)
9337                         r = win->ws->r;
9338                 else if (win->ws->old_r)
9339                         r = win->ws->old_r;
9340
9341                 /* windows are centered unless ANYWHERE quirk is set. */
9342                 if (win->quirks & SWM_Q_ANYWHERE) {
9343                         if (e->value_mask & XCB_CONFIG_WINDOW_X) {
9344                                 win->g_float.x = e->x;
9345                                 if (r)
9346                                         win->g_float.x -= X(r);
9347                         }
9348
9349                         if (e->value_mask & XCB_CONFIG_WINDOW_Y) {
9350                                 win->g_float.y = e->y;
9351                                 if (r)
9352                                         win->g_float.y -= Y(r);
9353                         }
9354                 }
9355
9356                 if (e->value_mask & XCB_CONFIG_WINDOW_WIDTH)
9357                         win->g_float.w = e->width;
9358
9359                 if (e->value_mask & XCB_CONFIG_WINDOW_HEIGHT)
9360                         win->g_float.h = e->height;
9361
9362                 win->g_floatvalid = true;
9363
9364                 if (!MAXIMIZED(win) && !FULLSCREEN(win) &&
9365                     (TRANS(win) || (ABOVE(win) &&
9366                     win->ws->cur_layout != &layouts[SWM_MAX_STACK]))) {
9367                         WIDTH(win) = win->g_float.w;
9368                         HEIGHT(win) = win->g_float.h;
9369
9370                         if (r != NULL) {
9371                                 update_floater(win);
9372                                 focus_flush();
9373                         } else {
9374                                 config_win(win, e);
9375                                 xcb_flush(conn);
9376                         }
9377                 } else {
9378                         config_win(win, e);
9379                         xcb_flush(conn);
9380                 }
9381         } else {
9382                 config_win(win, e);
9383                 xcb_flush(conn);
9384         }
9385
9386         DNPRINTF(SWM_D_EVENT, "configurerequest: done.\n");
9387 }
9388
9389 void
9390 configurenotify(xcb_configure_notify_event_t *e)
9391 {
9392         struct ws_win           *win;
9393
9394         DNPRINTF(SWM_D_EVENT, "configurenotify: win %#x, event win: %#x, "
9395             "(x,y) WxH: (%d,%d) %ux%u, border: %u, above_sibling: %#x, "
9396             "override_redirect: %s\n", e->window, e->event, e->x, e->y,
9397             e->width, e->height, e->border_width, e->above_sibling,
9398             YESNO(e->override_redirect));
9399
9400         win = find_window(e->window);
9401         if (win) {
9402                 xcb_icccm_get_wm_normal_hints_reply(conn,
9403                     xcb_icccm_get_wm_normal_hints(conn, win->id),
9404                     &win->sh, NULL);
9405                 adjust_font(win);
9406                 if (font_adjusted) {
9407                         stack();
9408                         xcb_flush(conn);
9409                 }
9410         }
9411 }
9412
9413 void
9414 destroynotify(xcb_destroy_notify_event_t *e)
9415 {
9416         struct ws_win           *win;
9417
9418         DNPRINTF(SWM_D_EVENT, "destroynotify: win %#x\n", e->window);
9419
9420         if ((win = find_window(e->window)) == NULL) {
9421                 if ((win = find_unmanaged_window(e->window)) == NULL)
9422                         return;
9423                 free_window(win);
9424                 return;
9425         }
9426
9427         if (focus_mode != SWM_FOCUS_FOLLOW) {
9428                 /* If we were focused, make sure we focus on something else. */
9429                 if (win == win->ws->focus)
9430                         win->ws->focus_pending = get_focus_prev(win);
9431         }
9432
9433         unmanage_window(win);
9434         stack();
9435
9436         if (focus_mode != SWM_FOCUS_FOLLOW && WS_FOCUSED(win->ws)) {
9437                 if (win->ws->focus_pending) {
9438                         focus_win(win->ws->focus_pending);
9439                         win->ws->focus_pending = NULL;
9440                 } else if (win == win->ws->focus) {
9441                         xcb_set_input_focus(conn, XCB_INPUT_FOCUS_PARENT,
9442                             win->ws->r->id, XCB_CURRENT_TIME);
9443                 }
9444         }
9445
9446         free_window(win);
9447
9448         focus_flush();
9449 }
9450
9451 #ifdef SWM_DEBUG
9452 char *
9453 get_notify_detail_label(uint8_t detail)
9454 {
9455         char *label;
9456
9457         switch (detail) {
9458         case XCB_NOTIFY_DETAIL_ANCESTOR:
9459                 label = "Ancestor";
9460                 break;
9461         case XCB_NOTIFY_DETAIL_VIRTUAL:
9462                 label = "Virtual";
9463                 break;
9464         case XCB_NOTIFY_DETAIL_INFERIOR:
9465                 label = "Inferior";
9466                 break;
9467         case XCB_NOTIFY_DETAIL_NONLINEAR:
9468                 label = "Nonlinear";
9469                 break;
9470         case XCB_NOTIFY_DETAIL_NONLINEAR_VIRTUAL:
9471                 label = "NonlinearVirtual";
9472                 break;
9473         case XCB_NOTIFY_DETAIL_POINTER:
9474                 label = "Pointer";
9475                 break;
9476         case XCB_NOTIFY_DETAIL_POINTER_ROOT:
9477                 label = "PointerRoot";
9478                 break;
9479         case XCB_NOTIFY_DETAIL_NONE:
9480                 label = "None";
9481                 break;
9482         default:
9483                 label = "Unknown";
9484         }
9485
9486         return label;
9487 }
9488
9489 char *
9490 get_notify_mode_label(uint8_t mode)
9491 {
9492         char *label;
9493
9494         switch (mode) {
9495         case XCB_NOTIFY_MODE_NORMAL:
9496                 label = "Normal";
9497                 break;
9498         case XCB_NOTIFY_MODE_GRAB:
9499                 label = "Grab";
9500                 break;
9501         case XCB_NOTIFY_MODE_UNGRAB:
9502                 label = "Ungrab";
9503                 break;
9504         case XCB_NOTIFY_MODE_WHILE_GRABBED:
9505                 label = "WhileGrabbed";
9506                 break;
9507         default:
9508                 label = "Unknown";
9509         }
9510
9511         return label;
9512 }
9513 #endif
9514
9515 void
9516 enternotify(xcb_enter_notify_event_t *e)
9517 {
9518         struct ws_win           *win;
9519         struct swm_region       *r;
9520
9521         DNPRINTF(SWM_D_FOCUS, "enternotify: time: %u, win (x,y): %#x "
9522             "(%d,%d), mode: %s(%d), detail: %s(%d), root (x,y): %#x (%d,%d), "
9523             "child: %#x, same_screen_focus: %s, state: %d\n",
9524             e->time, e->event, e->event_x, e->event_y,
9525             get_notify_mode_label(e->mode), e->mode,
9526             get_notify_detail_label(e->detail), e->detail,
9527             e->root, e->root_x, e->root_y, e->child,
9528             YESNO(e->same_screen_focus), e->state);
9529
9530         if (focus_mode == SWM_FOCUS_MANUAL &&
9531             e->mode == XCB_NOTIFY_MODE_NORMAL) {
9532                 DNPRINTF(SWM_D_EVENT, "enternotify: manual focus; ignoring.\n");
9533                 return;
9534         }
9535
9536         last_event_time = e->time;
9537
9538         if ((win = find_window(e->event)) == NULL) {
9539                 if (e->event == e->root) {
9540                         /* If no windows on pointer region, then focus root. */
9541                         r = root_to_region(e->root, SWM_CK_POINTER);
9542                         if (r == NULL) {
9543                                 DNPRINTF(SWM_D_EVENT, "enternotify: "
9544                                     "NULL region; ignoring.\n");
9545                                 return;
9546                         }
9547
9548                         focus_region(r);
9549                 } else {
9550                         DNPRINTF(SWM_D_EVENT, "enternotify: window is NULL; "
9551                             "ignoring\n");
9552                         return;
9553                 }
9554         } else {
9555                 if (e->mode == XCB_NOTIFY_MODE_NORMAL &&
9556                     e->detail == XCB_NOTIFY_DETAIL_INFERIOR) {
9557                         DNPRINTF(SWM_D_EVENT, "enternotify: entering from "
9558                             "inferior; ignoring\n");
9559                         return;
9560                 }
9561
9562                 focus_win(get_focus_magic(win));
9563         }
9564
9565         xcb_flush(conn);
9566 }
9567
9568 #ifdef SWM_DEBUG
9569 void
9570 leavenotify(xcb_leave_notify_event_t *e)
9571 {
9572         DNPRINTF(SWM_D_FOCUS, "leavenotify: time: %u, win (x,y): %#x "
9573             "(%d,%d), mode: %s(%d), detail: %s(%d), root (x,y): %#x (%d,%d), "
9574             "child: %#x, same_screen_focus: %s, state: %d\n",
9575             e->time, e->event, e->event_x, e->event_y,
9576             get_notify_mode_label(e->mode), e->mode,
9577             get_notify_detail_label(e->detail), e->detail,
9578             e->root, e->root_x, e->root_y, e->child,
9579             YESNO(e->same_screen_focus), e->state);
9580 }
9581 #endif
9582
9583 void
9584 mapnotify(xcb_map_notify_event_t *e)
9585 {
9586         struct ws_win           *win, *parent = NULL;
9587         struct workspace        *ws;
9588
9589         DNPRINTF(SWM_D_EVENT, "mapnotify: win %#x\n", e->window);
9590
9591         if ((win = manage_window(e->window, spawn_position, true)) == NULL)
9592                 return;
9593         ws = win->ws;
9594
9595         /* Need to know if win was mapped due to ws switch. */
9596         if (ws->state == SWM_WS_STATE_MAPPED) {
9597                 if (ws->focus_pending && TRANS(ws->focus_pending))
9598                         parent = find_window(win->transient);
9599
9600                 /* If window's parent is maximized, don't clear it. */
9601                 if ((parent == NULL) || !MAXIMIZED(parent))
9602                         if (clear_maximized(ws) > 0)
9603                                 stack();
9604         }
9605
9606         win->mapped = true;
9607         set_win_state(win, XCB_ICCCM_WM_STATE_NORMAL);
9608
9609         if (focus_mode != SWM_FOCUS_FOLLOW && WS_FOCUSED(win->ws)) {
9610                 if (ws->focus_pending == win) {
9611                         focus_win(win);
9612                         ws->focus_pending = NULL;
9613                         center_pointer(win->ws->r);
9614                         focus_flush();
9615                 }
9616         }
9617
9618         xcb_flush(conn);
9619 }
9620
9621 void
9622 mappingnotify(xcb_mapping_notify_event_t *e)
9623 {
9624         struct ws_win   *w;
9625         int     i, j, num_screens;
9626
9627         xcb_refresh_keyboard_mapping(syms, e);
9628
9629         if (e->request == XCB_MAPPING_KEYBOARD) {
9630                 grabkeys();
9631
9632                 /* Regrab buttons on all managed windows. */
9633                 num_screens = get_screen_count();
9634                 for (i = 0; i < num_screens; i++)
9635                         for (j = 0; j < workspace_limit; j++)
9636                                 TAILQ_FOREACH(w, &screens[i].ws[j].winlist,
9637                                     entry)
9638                                         grabbuttons(w);
9639         }
9640 }
9641
9642 void
9643 maprequest(xcb_map_request_event_t *e)
9644 {
9645         struct ws_win           *win, *w = NULL;
9646         xcb_get_window_attributes_reply_t *war;
9647
9648         DNPRINTF(SWM_D_EVENT, "maprequest: win %#x\n",
9649             e->window);
9650
9651         war = xcb_get_window_attributes_reply(conn,
9652             xcb_get_window_attributes(conn, e->window),
9653             NULL);
9654         if (war == NULL) {
9655                 DNPRINTF(SWM_D_EVENT, "maprequest: window lost.\n");
9656                 goto out;
9657         }
9658
9659         if (war->override_redirect) {
9660                 DNPRINTF(SWM_D_EVENT, "maprequest: override_redirect; "
9661                     "skipping.\n");
9662                 goto out;
9663         }
9664
9665         win = manage_window(e->window, spawn_position,
9666             (war->map_state == XCB_MAP_STATE_VIEWABLE));
9667         if (win == NULL)
9668                 goto out;
9669
9670         /* The new window should get focus; prepare. */
9671         if (focus_mode != SWM_FOCUS_FOLLOW &&
9672             !(win->quirks & SWM_Q_NOFOCUSONMAP) &&
9673             (!(win->hints.flags & XCB_ICCCM_WM_HINT_INPUT) ||
9674              (win->hints.flags & XCB_ICCCM_WM_HINT_INPUT &&
9675               win->hints.input))) {
9676                 if (win->quirks & SWM_Q_FOCUSONMAP_SINGLE) {
9677                         /* See if other wins of same type are already mapped. */
9678                         TAILQ_FOREACH(w, &win->ws->winlist, entry) {
9679                                 if (w == win || !w->mapped)
9680                                         continue;
9681
9682                                 if (w->ch.class_name &&
9683                                     win->ch.class_name &&
9684                                     strcmp(w->ch.class_name,
9685                                     win->ch.class_name) == 0 &&
9686                                     w->ch.instance_name &&
9687                                     win->ch.instance_name &&
9688                                     strcmp(w->ch.instance_name,
9689                                     win->ch.instance_name) == 0)
9690                                         break;
9691                         }
9692                 }
9693
9694                 if (w == NULL)
9695                         win->ws->focus_pending = get_focus_magic(win);
9696         }
9697
9698         /* All windows need to be mapped if they are in the current workspace.*/
9699         if (win->ws->r)
9700                 stack();
9701
9702         /* Ignore EnterNotify to handle the mapnotify without interference. */
9703         if (focus_mode == SWM_FOCUS_DEFAULT)
9704                 event_drain(XCB_ENTER_NOTIFY);
9705 out:
9706         free(war);
9707         DNPRINTF(SWM_D_EVENT, "maprequest: done.\n");
9708 }
9709
9710 void
9711 motionnotify(xcb_motion_notify_event_t *e)
9712 {
9713         struct swm_region       *r = NULL;
9714         int                     i, num_screens;
9715
9716         DNPRINTF(SWM_D_FOCUS, "motionnotify: time: %u, win (x,y): %#x "
9717             "(%d,%d), detail: %s(%d), root (x,y): %#x (%d,%d), "
9718             "child: %#x, same_screen_focus: %s, state: %d\n",
9719             e->time, e->event, e->event_x, e->event_y,
9720             get_notify_detail_label(e->detail), e->detail,
9721             e->root, e->root_x, e->root_y, e->child,
9722             YESNO(e->same_screen), e->state);
9723
9724         last_event_time = e->time;
9725
9726         if (focus_mode == SWM_FOCUS_MANUAL)
9727                 return;
9728
9729         num_screens = get_screen_count();
9730         for (i = 0; i < num_screens; i++)
9731                 if (screens[i].root == e->root)
9732                         break;
9733
9734         TAILQ_FOREACH(r, &screens[i].rl, entry)
9735                 if (X(r) <= e->root_x && e->root_x < MAX_X(r) &&
9736                     Y(r) <= e->root_y && e->root_y < MAX_Y(r))
9737                         break;
9738
9739         focus_region(r);
9740 }
9741
9742 #ifdef SWM_DEBUG
9743 char *
9744 get_atom_name(xcb_atom_t atom)
9745 {
9746         char                            *name = NULL;
9747 #ifdef SWM_DEBUG_ATOM_NAMES
9748         /*
9749          * This should be disabled during most debugging since
9750          * xcb_get_* causes an xcb_flush.
9751          */
9752         size_t                          len;
9753         xcb_get_atom_name_reply_t       *r;
9754
9755         r = xcb_get_atom_name_reply(conn,
9756             xcb_get_atom_name(conn, atom),
9757             NULL);
9758         if (r) {
9759                 len = xcb_get_atom_name_name_length(r);
9760                 if (len > 0) {
9761                         name = malloc(len + 1);
9762                         if (name) {
9763                                 memcpy(name, xcb_get_atom_name_name(r), len);
9764                                 name[len] = '\0';
9765                         }
9766                 }
9767                 free(r);
9768         }
9769 #else
9770         (void)atom;
9771 #endif
9772         return (name);
9773 }
9774 #endif
9775
9776 void
9777 propertynotify(xcb_property_notify_event_t *e)
9778 {
9779         struct ws_win           *win;
9780         struct workspace        *ws;
9781 #ifdef SWM_DEBUG
9782         char                    *name;
9783
9784         name = get_atom_name(e->atom);
9785         DNPRINTF(SWM_D_EVENT, "propertynotify: win %#x, atom: %s(%u), "
9786             "time: %#x, state: %u\n", e->window, name, e->atom, e->time,
9787             e->state);
9788         free(name);
9789 #endif
9790         win = find_window(e->window);
9791         if (win == NULL)
9792                 return;
9793
9794         ws = win->ws;
9795
9796         last_event_time = e->time;
9797
9798         if (e->atom == a_state) {
9799                 /* State just changed, make sure it gets focused if mapped. */
9800                 if (e->state == XCB_PROPERTY_NEW_VALUE) {
9801                         if (focus_mode != SWM_FOCUS_FOLLOW && WS_FOCUSED(ws)) {
9802                                 if (win->mapped &&
9803                                     ws->focus_pending == win) {
9804                                         focus_win(ws->focus_pending);
9805                                         ws->focus_pending = NULL;
9806                                 }
9807                         }
9808                 }
9809         } else if (e->atom == XCB_ATOM_WM_CLASS ||
9810             e->atom == XCB_ATOM_WM_NAME) {
9811                 bar_draw();
9812         } else if (e->atom == a_prot) {
9813                 get_wm_protocols(win);
9814         }
9815
9816         xcb_flush(conn);
9817 }
9818
9819 void
9820 unmapnotify(xcb_unmap_notify_event_t *e)
9821 {
9822         struct ws_win           *win;
9823         struct workspace        *ws;
9824
9825         DNPRINTF(SWM_D_EVENT, "unmapnotify: win %#x\n", e->window);
9826
9827         /* If we aren't managing the window, then ignore. */
9828         win = find_window(e->window);
9829         if (win == NULL || win->id != e->window)
9830                 return;
9831
9832         /* Do nothing if already withdrawn. */
9833         if (!win->mapped && !ICONIC(win))
9834                 return;
9835
9836         ws = win->ws;
9837         win->mapped = false;
9838
9839         /* If win was focused, make sure to focus on something else. */
9840         if (win == ws->focus) {
9841                 if (focus_mode != SWM_FOCUS_FOLLOW) {
9842                         ws->focus_pending = get_focus_prev(win);
9843                         DNPRINTF(SWM_D_EVENT, "unmapnotify: "
9844                             "focus_pending: %#x\n",
9845                             WINID(ws->focus_pending));
9846                 }
9847
9848                 unfocus_win(win);
9849         }
9850
9851         if (ICONIC(win)) {
9852                 /* Iconify. */
9853                 set_win_state(win, XCB_ICCCM_WM_STATE_ICONIC);
9854         } else {
9855                 /* Withdraw. */
9856                 set_win_state(win, XCB_ICCCM_WM_STATE_WITHDRAWN);
9857                 unmanage_window(win);
9858         }
9859
9860         if (ws->r)
9861                 stack();
9862
9863         /* Update focus if ws is active. */
9864         if (WS_FOCUSED(ws)) {
9865                 if (focus_mode == SWM_FOCUS_FOLLOW) {
9866                         focus_win(get_pointer_win(ws->r->s->root));
9867                 } else if (ws->focus_pending) {
9868                         focus_win(ws->focus_pending);
9869                         ws->focus_pending = NULL;
9870                 } else if (ws->focus == NULL) {
9871                         xcb_set_input_focus(conn, XCB_INPUT_FOCUS_PARENT,
9872                             ws->r->id, XCB_CURRENT_TIME);
9873                 }
9874         }
9875
9876         center_pointer(ws->r);
9877         focus_flush();
9878 }
9879
9880 #ifdef SWM_DEBUG
9881 char *
9882 get_source_type_label(uint32_t type)
9883 {
9884         char *label;
9885
9886         switch (type) {
9887         case EWMH_SOURCE_TYPE_NONE:
9888                 label = "None";
9889                 break;
9890         case EWMH_SOURCE_TYPE_NORMAL:
9891                 label = "Normal";
9892                 break;
9893         case EWMH_SOURCE_TYPE_OTHER:
9894                 label = "Other";
9895                 break;
9896         default:
9897                 label = "Invalid";
9898         }
9899
9900         return label;
9901 }
9902 #endif
9903
9904 void
9905 clientmessage(xcb_client_message_event_t *e)
9906 {
9907         struct ws_win           *win;
9908         struct swm_region       *r = NULL;
9909         union arg               a;
9910         uint32_t                val[2];
9911         int                     num_screens, i;
9912         xcb_map_request_event_t mre;
9913 #ifdef SWM_DEBUG
9914         char                    *name;
9915
9916         name = get_atom_name(e->type);
9917         DNPRINTF(SWM_D_EVENT, "clientmessage: win %#x, atom: %s(%u)\n",
9918             e->window, name, e->type);
9919         free(name);
9920 #endif
9921
9922         if (e->type == ewmh[_NET_CURRENT_DESKTOP].atom) {
9923                 num_screens = get_screen_count();
9924                 for (i = 0; i < num_screens; i++)
9925                         if (screens[i].root == e->window) {
9926                                 r = screens[i].r_focus;
9927                                 break;
9928                         }
9929
9930                 if (r && e->data.data32[0] < (uint32_t)workspace_limit) {
9931                         a.id = e->data.data32[0];
9932                         switchws(r, &a);
9933                         focus_flush();
9934                 }
9935
9936                 return;
9937         }
9938
9939         win = find_window(e->window);
9940         if (win == NULL) {
9941                 if (e->type == ewmh[_NET_ACTIVE_WINDOW].atom) {
9942                         /* Manage the window with maprequest. */
9943                         DNPRINTF(SWM_D_EVENT, "clientmessage: request focus on "
9944                             "unmanaged window.\n");
9945                         mre.window = e->window;
9946                         maprequest(&mre);
9947                 }
9948                 return;
9949         }
9950
9951         if (e->type == ewmh[_NET_ACTIVE_WINDOW].atom) {
9952                 DNPRINTF(SWM_D_EVENT, "clientmessage: _NET_ACTIVE_WINDOW, "
9953                     "source_type: %s(%d)\n",
9954                     get_source_type_label(e->data.data32[0]),
9955                     e->data.data32[0]);
9956
9957                 /*
9958                  * Allow focus changes that are a result of direct user
9959                  * action and from applications that use the old EWMH spec.
9960                  */
9961                 if (e->data.data32[0] != EWMH_SOURCE_TYPE_NORMAL ||
9962                     win->quirks & SWM_Q_OBEYAPPFOCUSREQ) {
9963                         if (WS_FOCUSED(win->ws))
9964                                 focus_win(win);
9965                         else
9966                                 win->ws->focus_pending = win;
9967                 }
9968         } else if (e->type == ewmh[_NET_CLOSE_WINDOW].atom) {
9969                 DNPRINTF(SWM_D_EVENT, "clientmessage: _NET_CLOSE_WINDOW\n");
9970                 if (win->can_delete)
9971                         client_msg(win, a_delete, 0);
9972                 else
9973                         xcb_kill_client(conn, win->id);
9974         } else if (e->type == ewmh[_NET_MOVERESIZE_WINDOW].atom) {
9975                 DNPRINTF(SWM_D_EVENT,
9976                     "clientmessage: _NET_MOVERESIZE_WINDOW\n");
9977                 if (ABOVE(win)) {
9978                         if (e->data.data32[0] & (1<<8)) /* x */
9979                                 X(win) = e->data.data32[1];
9980                         if (e->data.data32[0] & (1<<9)) /* y */
9981                                 Y(win) = e->data.data32[2];
9982                         if (e->data.data32[0] & (1<<10)) /* width */
9983                                 WIDTH(win) = e->data.data32[3];
9984                         if (e->data.data32[0] & (1<<11)) /* height */
9985                                 HEIGHT(win) = e->data.data32[4];
9986
9987                         update_window(win);
9988                 } else {
9989                         /* Notify no change was made. */
9990                         config_win(win, NULL);
9991                         /* TODO: Change stack sizes */
9992                 }
9993         } else if (e->type == ewmh[_NET_RESTACK_WINDOW].atom) {
9994                 DNPRINTF(SWM_D_EVENT, "clientmessage: _NET_RESTACK_WINDOW\n");
9995                 val[0] = e->data.data32[1]; /* Sibling window. */
9996                 val[1] = e->data.data32[2]; /* Stack mode detail. */
9997
9998                 xcb_configure_window(conn, win->id, XCB_CONFIG_WINDOW_SIBLING |
9999                     XCB_CONFIG_WINDOW_STACK_MODE, val);
10000         } else  if (e->type == ewmh[_NET_WM_STATE].atom) {
10001                 DNPRINTF(SWM_D_EVENT, "clientmessage: _NET_WM_STATE\n");
10002                 ewmh_change_wm_state(win, e->data.data32[1], e->data.data32[0]);
10003                 if (e->data.data32[2])
10004                         ewmh_change_wm_state(win, e->data.data32[2],
10005                             e->data.data32[0]);
10006
10007                 ewmh_update_wm_state(win);
10008                 stack();
10009         } else if (e->type == ewmh[_NET_WM_DESKTOP].atom) {
10010                 DNPRINTF(SWM_D_EVENT, "clientmessage: _NET_WM_DESKTOP\n");
10011                 r = win->ws->r;
10012
10013                 win_to_ws(win, e->data.data32[0], true);
10014
10015                 /* Restack if either the source or destination ws is mapped. */
10016                 if (r != NULL || win->ws->r != NULL) {
10017                         if (FLOATING(win))
10018                                 load_float_geom(win);
10019
10020                         stack();
10021                 }
10022         }
10023
10024         focus_flush();
10025 }
10026
10027 void
10028 check_conn(void)
10029 {
10030         int      errcode = xcb_connection_has_error(conn);
10031 #ifdef XCB_CONN_ERROR
10032         char    *s;
10033         switch (errcode) {
10034         case XCB_CONN_ERROR:
10035                 s = "Socket error, pipe error or other stream error.";
10036                 break;
10037         case XCB_CONN_CLOSED_EXT_NOTSUPPORTED:
10038                 s = "Extension not supported.";
10039                 break;
10040         case XCB_CONN_CLOSED_MEM_INSUFFICIENT:
10041                 s = "Insufficient memory.";
10042                 break;
10043         case XCB_CONN_CLOSED_REQ_LEN_EXCEED:
10044                 s = "Request length was exceeded.";
10045                 break;
10046         case XCB_CONN_CLOSED_PARSE_ERR:
10047                 s = "Error parsing display string.";
10048                 break;
10049         default:
10050                 s = "Unknown error.";
10051         }
10052         if (errcode)
10053                 errx(errcode, "X CONNECTION ERROR: %s", s);
10054 #else
10055         if (errcode)
10056                 errx(errcode, "X CONNECTION ERROR");
10057 #endif
10058 }
10059
10060 int
10061 enable_wm(void)
10062 {
10063         int                     num_screens, i;
10064         const uint32_t          val = XCB_EVENT_MASK_SUBSTRUCTURE_REDIRECT |
10065             XCB_EVENT_MASK_ENTER_WINDOW;
10066         xcb_screen_t            *sc;
10067         xcb_void_cookie_t       wac;
10068         xcb_generic_error_t     *error;
10069
10070         /* this causes an error if some other window manager is running */
10071         num_screens = get_screen_count();
10072         for (i = 0; i < num_screens; i++) {
10073                 if ((sc = get_screen(i)) == NULL)
10074                         errx(1, "ERROR: can't get screen %d.", i);
10075                 DNPRINTF(SWM_D_INIT, "enable_wm: screen %d, root: %#x\n",
10076                     i, sc->root);
10077                 wac = xcb_change_window_attributes_checked(conn, sc->root,
10078                     XCB_CW_EVENT_MASK, &val);
10079                 if ((error = xcb_request_check(conn, wac))) {
10080                         DNPRINTF(SWM_D_INIT, "enable_wm: error_code: %u\n",
10081                             error->error_code);
10082                         free(error);
10083                         return 1;
10084                 }
10085
10086                 /* click to focus on empty region */
10087                 xcb_grab_button(conn, 1, sc->root, BUTTONMASK,
10088                     XCB_GRAB_MODE_SYNC, XCB_GRAB_MODE_ASYNC, XCB_WINDOW_NONE,
10089                     XCB_CURSOR_NONE, XCB_BUTTON_INDEX_1, XCB_BUTTON_MASK_ANY);
10090         }
10091
10092         return 0;
10093 }
10094
10095 void
10096 new_region(struct swm_screen *s, int x, int y, int w, int h)
10097 {
10098         struct swm_region       *r = NULL, *n;
10099         struct workspace        *ws = NULL;
10100         int                     i;
10101         uint32_t                wa[1];
10102
10103         DNPRINTF(SWM_D_MISC, "new region: screen[%d]:%dx%d+%d+%d\n",
10104              s->idx, w, h, x, y);
10105
10106         /* remove any conflicting regions */
10107         n = TAILQ_FIRST(&s->rl);
10108         while (n) {
10109                 r = n;
10110                 n = TAILQ_NEXT(r, entry);
10111                 if (X(r) < (x + w) && (X(r) + WIDTH(r)) > x &&
10112                     Y(r) < (y + h) && (Y(r) + HEIGHT(r)) > y) {
10113                         if (r->ws->r != NULL)
10114                                 r->ws->old_r = r->ws->r;
10115                         r->ws->r = NULL;
10116                         bar_cleanup(r);
10117                         xcb_destroy_window(conn, r->id);
10118                         TAILQ_REMOVE(&s->rl, r, entry);
10119                         TAILQ_INSERT_TAIL(&s->orl, r, entry);
10120                 }
10121         }
10122
10123         /* search old regions for one to reuse */
10124
10125         /* size + location match */
10126         TAILQ_FOREACH(r, &s->orl, entry)
10127                 if (X(r) == x && Y(r) == y &&
10128                     HEIGHT(r) == h && WIDTH(r) == w)
10129                         break;
10130
10131         /* size match */
10132         TAILQ_FOREACH(r, &s->orl, entry)
10133                 if (HEIGHT(r) == h && WIDTH(r) == w)
10134                         break;
10135
10136         if (r != NULL) {
10137                 TAILQ_REMOVE(&s->orl, r, entry);
10138                 /* try to use old region's workspace */
10139                 if (r->ws->r == NULL)
10140                         ws = r->ws;
10141         } else
10142                 if ((r = calloc(1, sizeof(struct swm_region))) == NULL)
10143                         err(1, "new_region: calloc: failed to allocate memory "
10144                             "for screen");
10145
10146         /* if we don't have a workspace already, find one */
10147         if (ws == NULL) {
10148                 for (i = 0; i < workspace_limit; i++)
10149                         if (s->ws[i].r == NULL) {
10150                                 ws = &s->ws[i];
10151                                 break;
10152                         }
10153         }
10154
10155         if (ws == NULL)
10156                 errx(1, "new_region: no free workspaces");
10157
10158         if (ws->state == SWM_WS_STATE_HIDDEN)
10159                 ws->state = SWM_WS_STATE_MAPPING;
10160
10161         X(r) = x;
10162         Y(r) = y;
10163         WIDTH(r) = w;
10164         HEIGHT(r) = h;
10165         r->s = s;
10166         r->ws = ws;
10167         r->ws_prior = NULL;
10168         ws->r = r;
10169         outputs++;
10170         TAILQ_INSERT_TAIL(&s->rl, r, entry);
10171
10172         /* Invisible region window to detect pointer events on empty regions. */
10173         r->id = xcb_generate_id(conn);
10174         wa[0] = XCB_EVENT_MASK_POINTER_MOTION |
10175             XCB_EVENT_MASK_POINTER_MOTION_HINT;
10176
10177         xcb_create_window(conn, XCB_COPY_FROM_PARENT, r->id, r->s->root,
10178             X(r), Y(r), WIDTH(r), HEIGHT(r), 0, XCB_WINDOW_CLASS_INPUT_ONLY,
10179             XCB_COPY_FROM_PARENT, XCB_CW_EVENT_MASK, wa);
10180
10181         /* Make sure region input is at the bottom. */
10182         wa[0] = XCB_STACK_MODE_BELOW;
10183         xcb_configure_window(conn, r->id, XCB_CONFIG_WINDOW_STACK_MODE, wa);
10184
10185         xcb_map_window(conn, r->id);
10186 }
10187
10188 void
10189 scan_randr(int idx)
10190 {
10191 #ifdef SWM_XRR_HAS_CRTC
10192         int                                             c;
10193         int                                             ncrtc = 0;
10194 #endif /* SWM_XRR_HAS_CRTC */
10195         struct swm_region                               *r;
10196         struct ws_win                                   *win;
10197         int                                             num_screens;
10198         xcb_randr_get_screen_resources_current_cookie_t src;
10199         xcb_randr_get_screen_resources_current_reply_t  *srr;
10200         xcb_randr_get_crtc_info_cookie_t                cic;
10201         xcb_randr_get_crtc_info_reply_t                 *cir = NULL;
10202         xcb_randr_crtc_t                                *crtc;
10203         xcb_screen_t                                    *screen;
10204
10205         DNPRINTF(SWM_D_MISC, "scan_randr: screen: %d\n", idx);
10206
10207         if ((screen = get_screen(idx)) == NULL)
10208                 errx(1, "ERROR: can't get screen %d.", idx);
10209
10210         num_screens = get_screen_count();
10211         if (idx >= num_screens)
10212                 errx(1, "scan_randr: invalid screen");
10213
10214         /* remove any old regions */
10215         while ((r = TAILQ_FIRST(&screens[idx].rl)) != NULL) {
10216                 r->ws->old_r = r->ws->r = NULL;
10217                 bar_cleanup(r);
10218                 xcb_destroy_window(conn, r->id);
10219                 TAILQ_REMOVE(&screens[idx].rl, r, entry);
10220                 TAILQ_INSERT_TAIL(&screens[idx].orl, r, entry);
10221         }
10222         outputs = 0;
10223
10224         /* map virtual screens onto physical screens */
10225 #ifdef SWM_XRR_HAS_CRTC
10226         if (randr_support) {
10227                 src = xcb_randr_get_screen_resources_current(conn,
10228                     screens[idx].root);
10229                 srr = xcb_randr_get_screen_resources_current_reply(conn, src,
10230                     NULL);
10231                 if (srr == NULL) {
10232                         new_region(&screens[idx], 0, 0,
10233                             screen->width_in_pixels,
10234                             screen->height_in_pixels);
10235                         goto out;
10236                 } else
10237                         ncrtc = srr->num_crtcs;
10238
10239                 crtc = xcb_randr_get_screen_resources_current_crtcs(srr);
10240                 for (c = 0; c < ncrtc; c++) {
10241                         cic = xcb_randr_get_crtc_info(conn, crtc[c],
10242                             XCB_CURRENT_TIME);
10243                         cir = xcb_randr_get_crtc_info_reply(conn, cic, NULL);
10244                         if (cir == NULL)
10245                                 continue;
10246                         if (cir->num_outputs == 0) {
10247                                 free(cir);
10248                                 continue;
10249                         }
10250
10251                         if (cir->mode == 0)
10252                                 new_region(&screens[idx], 0, 0,
10253                                     screen->width_in_pixels,
10254                                     screen->height_in_pixels);
10255                         else
10256                                 new_region(&screens[idx],
10257                                     cir->x, cir->y, cir->width, cir->height);
10258                         free(cir);
10259                 }
10260                 free(srr);
10261         }
10262 #endif /* SWM_XRR_HAS_CRTC */
10263
10264         /* If detection failed, create a single region that spans the screen. */
10265         if (TAILQ_EMPTY(&screens[idx].rl))
10266                 new_region(&screens[idx], 0, 0, screen->width_in_pixels,
10267                     screen->height_in_pixels);
10268
10269 out:
10270         /* Cleanup unused previously visible workspaces. */
10271         TAILQ_FOREACH(r, &screens[idx].orl, entry) {
10272                 TAILQ_FOREACH(win, &r->ws->winlist, entry)
10273                         unmap_window(win);
10274                 r->ws->state = SWM_WS_STATE_HIDDEN;
10275
10276                 /* The screen shouldn't focus on an unused region. */
10277                 if (screens[idx].r_focus == r)
10278                         screens[idx].r_focus = NULL;
10279         }
10280
10281         DNPRINTF(SWM_D_MISC, "scan_randr: done.\n");
10282 }
10283
10284 void
10285 screenchange(xcb_randr_screen_change_notify_event_t *e)
10286 {
10287         struct swm_region               *r;
10288         int                             i, num_screens;
10289
10290         DNPRINTF(SWM_D_EVENT, "screenchange: root: %#x\n", e->root);
10291
10292         num_screens = get_screen_count();
10293         /* silly event doesn't include the screen index */
10294         for (i = 0; i < num_screens; i++)
10295                 if (screens[i].root == e->root)
10296                         break;
10297         if (i >= num_screens)
10298                 errx(1, "screenchange: screen not found");
10299
10300         /* brute force for now, just re-enumerate the regions */
10301         scan_randr(i);
10302
10303 #ifdef SWM_DEBUG
10304         print_win_geom(e->root);
10305 #endif
10306         /* add bars to all regions */
10307         for (i = 0; i < num_screens; i++) {
10308                 TAILQ_FOREACH(r, &screens[i].rl, entry)
10309                         bar_setup(r);
10310         }
10311
10312         stack();
10313
10314         /* Make sure a region has focus on each screen. */
10315         for (i = 0; i < num_screens; i++) {
10316                 if (screens[i].r_focus == NULL) {
10317                         r = TAILQ_FIRST(&screens[i].rl);
10318                         if (r != NULL)
10319                                 focus_region(r);
10320                 }
10321         }
10322
10323         bar_draw();
10324         focus_flush();
10325
10326         /* Update workspace state on all regions. */
10327         for (i = 0; i < num_screens; i++)
10328                 TAILQ_FOREACH(r, &screens[i].rl, entry)
10329                         r->ws->state = SWM_WS_STATE_MAPPED;
10330 }
10331
10332 void
10333 grab_windows(void)
10334 {
10335         struct swm_region       *r = NULL;
10336         xcb_window_t            *wins = NULL, trans, *cwins = NULL;
10337         int                     i, j, k, n, no, num_screens;
10338         uint8_t                 state;
10339         bool                    manage, mapped;
10340
10341         xcb_query_tree_cookie_t                 qtc;
10342         xcb_query_tree_reply_t                  *qtr;
10343         xcb_get_window_attributes_cookie_t      gac;
10344         xcb_get_window_attributes_reply_t       *gar;
10345         xcb_get_property_cookie_t               pc;
10346         xcb_get_property_reply_t                *pr;
10347
10348         DNPRINTF(SWM_D_INIT, "grab_windows: begin\n");
10349         num_screens = get_screen_count();
10350         for (i = 0; i < num_screens; i++) {
10351                 qtc = xcb_query_tree(conn, screens[i].root);
10352                 qtr = xcb_query_tree_reply(conn, qtc, NULL);
10353                 if (qtr == NULL)
10354                         continue;
10355                 wins = xcb_query_tree_children(qtr);
10356                 no = xcb_query_tree_children_length(qtr);
10357
10358                 /* Try to sort windows according to _NET_CLIENT_LIST. */
10359                 pr = xcb_get_property_reply(conn, xcb_get_property(conn, 0,
10360                     screens[i].root, ewmh[_NET_CLIENT_LIST].atom,
10361                     XCB_ATOM_WINDOW, 0, UINT32_MAX), NULL);
10362                 if (pr != NULL) {
10363                         cwins = xcb_get_property_value(pr);
10364                         n = xcb_get_property_value_length(pr) /
10365                             sizeof(xcb_atom_t);
10366
10367                         for (j = 0; j < n; ++j) {
10368                                 for (k = j; k < no; ++k) {
10369                                         if (wins[k] == cwins[j]) {
10370                                                 /* Swap wins j and k. */
10371                                                 wins[k] = wins[j];
10372                                                 wins[j] = cwins[j];
10373                                         }
10374                                 }
10375                         }
10376
10377                         free(pr);
10378                 }
10379
10380                 /* attach windows to a region */
10381                 /* normal windows */
10382                 DNPRINTF(SWM_D_INIT, "grab_windows: grab top level windows.\n");
10383                 for (j = 0; j < no; j++) {
10384                         TAILQ_FOREACH(r, &screens[i].rl, entry) {
10385                                 if (r->id == wins[j]) {
10386                                         DNPRINTF(SWM_D_INIT, "grab_windows: "
10387                                             "skip %#x; region input window.\n",
10388                                             wins[j]);
10389                                         break;
10390                                 } else if (r->bar->id == wins[j]) {
10391                                         DNPRINTF(SWM_D_INIT, "grab_windows: "
10392                                             "skip %#x; region bar.\n",
10393                                             wins[j]);
10394                                         break;
10395                                 }
10396                         }
10397
10398                         if (r)
10399                                 continue;
10400
10401                         gac = xcb_get_window_attributes(conn, wins[j]);
10402                         gar = xcb_get_window_attributes_reply(conn, gac, NULL);
10403                         if (gar == NULL) {
10404                                 DNPRINTF(SWM_D_INIT, "grab_windows: skip %#x; "
10405                                     "doesn't exist.\n", wins[j]);
10406                                 continue;
10407                         }
10408
10409                         if (gar->override_redirect) {
10410                                 DNPRINTF(SWM_D_INIT, "grab_windows: skip %#x; "
10411                                     "override_redirect set.\n", wins[j]);
10412                                 free(gar);
10413                                 continue;
10414                         }
10415
10416                         pc = xcb_icccm_get_wm_transient_for(conn, wins[j]);
10417                         if (xcb_icccm_get_wm_transient_for_reply(conn, pc,
10418                             &trans, NULL)) {
10419                                 DNPRINTF(SWM_D_INIT, "grab_windows: skip %#x; "
10420                                     "is transient for %#x.\n", wins[j], trans);
10421                                 free(gar);
10422                                 continue;
10423                         }
10424
10425                         state = get_win_state(wins[j]);
10426                         manage = state != XCB_ICCCM_WM_STATE_WITHDRAWN;
10427                         mapped = gar->map_state == XCB_MAP_STATE_VIEWABLE;
10428                         if (mapped || manage)
10429                                 manage_window(wins[j], SWM_STACK_TOP, mapped);
10430                         free(gar);
10431                 }
10432                 /* transient windows */
10433                 DNPRINTF(SWM_D_INIT, "grab_windows: grab transient windows.\n");
10434                 for (j = 0; j < no; j++) {
10435                         gac = xcb_get_window_attributes(conn, wins[j]);
10436                         gar = xcb_get_window_attributes_reply(conn, gac, NULL);
10437                         if (gar == NULL) {
10438                                 DNPRINTF(SWM_D_INIT, "grab_windows: skip %#x; "
10439                                     "doesn't exist.\n", wins[j]);
10440                                 continue;
10441                         }
10442
10443                         if (gar->override_redirect) {
10444                                 DNPRINTF(SWM_D_INIT, "grab_windows: skip %#x; "
10445                                     "override_redirect set.\n", wins[j]);
10446                                 free(gar);
10447                                 continue;
10448                         }
10449
10450                         state = get_win_state(wins[j]);
10451                         manage = state != XCB_ICCCM_WM_STATE_WITHDRAWN;
10452                         mapped = gar->map_state == XCB_MAP_STATE_VIEWABLE;
10453                         pc = xcb_icccm_get_wm_transient_for(conn, wins[j]);
10454                         if (xcb_icccm_get_wm_transient_for_reply(conn, pc,
10455                             &trans, NULL) && manage)
10456                                 manage_window(wins[j], SWM_STACK_TOP, mapped);
10457                         free(gar);
10458                 }
10459                 free(qtr);
10460         }
10461         DNPRINTF(SWM_D_INIT, "grab_windows: done.\n");
10462 }
10463
10464 void
10465 setup_screens(void)
10466 {
10467         int                     i, j, k, num_screens;
10468         struct workspace        *ws;
10469         uint32_t                gcv[1], wa[1];
10470         const xcb_query_extension_reply_t *qep;
10471         xcb_screen_t                            *screen;
10472         xcb_randr_query_version_cookie_t        c;
10473         xcb_randr_query_version_reply_t         *r;
10474
10475         num_screens = get_screen_count();
10476         if ((screens = calloc(num_screens,
10477              sizeof(struct swm_screen))) == NULL)
10478                 err(1, "setup_screens: calloc: failed to allocate memory for "
10479                     "screens");
10480
10481         /* Initial RandR setup. */
10482         randr_support = false;
10483         qep = xcb_get_extension_data(conn, &xcb_randr_id);
10484         if (qep->present) {
10485                 c = xcb_randr_query_version(conn, 1, 1);
10486                 r = xcb_randr_query_version_reply(conn, c, NULL);
10487                 if (r) {
10488                         if (r->major_version >= 1) {
10489                                 randr_support = true;
10490                                 randr_eventbase = qep->first_event;
10491                         }
10492                         free(r);
10493                 }
10494         }
10495
10496         wa[0] = cursors[XC_LEFT_PTR].cid;
10497
10498         /* map physical screens */
10499         for (i = 0; i < num_screens; i++) {
10500                 DNPRINTF(SWM_D_WS, "setup_screens: init screen: %d\n", i);
10501                 screens[i].idx = i;
10502                 screens[i].r_focus = NULL;
10503
10504                 TAILQ_INIT(&screens[i].rl);
10505                 TAILQ_INIT(&screens[i].orl);
10506                 if ((screen = get_screen(i)) == NULL)
10507                         errx(1, "ERROR: can't get screen %d.", i);
10508                 screens[i].root = screen->root;
10509
10510                 /* set default colors */
10511                 setscreencolor("red", i, SWM_S_COLOR_FOCUS);
10512                 setscreencolor("rgb:88/88/88", i, SWM_S_COLOR_UNFOCUS);
10513                 setscreencolor("rgb:00/80/80", i, SWM_S_COLOR_BAR_BORDER);
10514                 setscreencolor("rgb:00/40/40", i,
10515                     SWM_S_COLOR_BAR_BORDER_UNFOCUS);
10516                 setscreencolor("black", i, SWM_S_COLOR_BAR);
10517                 setscreencolor("rgb:a0/a0/a0", i, SWM_S_COLOR_BAR_FONT);
10518                 setscreencolor("red", i, SWM_S_COLOR_FOCUS_MAXIMIZED);
10519                 setscreencolor("rgb:88/88/88", i,
10520                     SWM_S_COLOR_UNFOCUS_MAXIMIZED);
10521
10522                 /* create graphics context on screen */
10523                 screens[i].bar_gc = xcb_generate_id(conn);
10524                 gcv[0] = 0;
10525                 xcb_create_gc(conn, screens[i].bar_gc, screens[i].root,
10526                     XCB_GC_GRAPHICS_EXPOSURES, gcv);
10527
10528                 /* set default cursor */
10529                 xcb_change_window_attributes(conn, screens[i].root,
10530                     XCB_CW_CURSOR, wa);
10531
10532                 /* init all workspaces */
10533                 /* XXX these should be dynamically allocated too */
10534                 for (j = 0; j < SWM_WS_MAX; j++) {
10535                         ws = &screens[i].ws[j];
10536                         ws->idx = j;
10537                         ws->name = NULL;
10538                         ws->bar_enabled = true;
10539                         ws->focus = NULL;
10540                         ws->focus_prev = NULL;
10541                         ws->focus_pending = NULL;
10542                         ws->r = NULL;
10543                         ws->old_r = NULL;
10544                         ws->state = SWM_WS_STATE_HIDDEN;
10545                         TAILQ_INIT(&ws->stack);
10546                         TAILQ_INIT(&ws->winlist);
10547                         TAILQ_INIT(&ws->unmanagedlist);
10548
10549                         for (k = 0; layouts[k].l_stack != NULL; k++)
10550                                 if (layouts[k].l_config != NULL)
10551                                         layouts[k].l_config(ws,
10552                                             SWM_ARG_ID_STACKINIT);
10553                         ws->cur_layout = &layouts[0];
10554                         ws->cur_layout->l_string(ws);
10555                 }
10556
10557                 scan_randr(i);
10558
10559                 if (randr_support)
10560                         xcb_randr_select_input(conn, screens[i].root,
10561                             XCB_RANDR_NOTIFY_MASK_SCREEN_CHANGE);
10562         }
10563 }
10564
10565 void
10566 setup_globals(void)
10567 {
10568         if ((bar_fonts = strdup(SWM_BAR_FONTS)) == NULL)
10569                 err(1, "setup_globals: strdup: failed to allocate memory.");
10570
10571         if ((clock_format = strdup("%a %b %d %R %Z %Y")) == NULL)
10572                 err(1, "setup_globals: strdup: failed to allocate memory.");
10573
10574         if ((syms = xcb_key_symbols_alloc(conn)) == NULL)
10575                 errx(1, "unable to allocate key symbols");
10576
10577         a_state = get_atom_from_string("WM_STATE");
10578         a_prot = get_atom_from_string("WM_PROTOCOLS");
10579         a_delete = get_atom_from_string("WM_DELETE_WINDOW");
10580         a_net_supported = get_atom_from_string("_NET_SUPPORTED");
10581         a_net_wm_check = get_atom_from_string("_NET_SUPPORTING_WM_CHECK");
10582         a_takefocus = get_atom_from_string("WM_TAKE_FOCUS");
10583         a_utf8_string = get_atom_from_string("UTF8_STRING");
10584         a_swm_ws = get_atom_from_string("_SWM_WS");
10585 }
10586
10587 void
10588 shutdown_cleanup(void)
10589 {
10590         int                     i, num_screens;
10591
10592         /* disable alarm because the following code may not be interrupted */
10593         alarm(0);
10594         if (signal(SIGALRM, SIG_IGN) == SIG_ERR)
10595                 err(1, "can't disable alarm");
10596
10597         bar_extra_stop();
10598         unmap_all();
10599
10600         cursors_cleanup();
10601
10602         teardown_ewmh();
10603
10604         num_screens = get_screen_count();
10605         for (i = 0; i < num_screens; ++i) {
10606                 xcb_set_input_focus(conn, XCB_INPUT_FOCUS_POINTER_ROOT,
10607                     screens[i].root, XCB_CURRENT_TIME);
10608
10609                 if (screens[i].bar_gc != XCB_NONE)
10610                         xcb_free_gc(conn, screens[i].bar_gc);
10611                 if (!bar_font_legacy) {
10612                         XftColorFree(display, DefaultVisual(display, i),
10613                             DefaultColormap(display, i), &bar_font_color);
10614                         XftColorFree(display, DefaultVisual(display, i),
10615                             DefaultColormap(display, i), &search_font_color);
10616                 }
10617         }
10618
10619         if (bar_font_legacy)
10620                 XFreeFontSet(display, bar_fs);
10621         else {
10622                 XftFontClose(display, bar_font);
10623         }
10624
10625         xcb_key_symbols_free(syms);
10626         xcb_flush(conn);
10627         xcb_disconnect(conn);
10628 }
10629
10630 void
10631 event_error(xcb_generic_error_t *e)
10632 {
10633         (void)e;
10634
10635         DNPRINTF(SWM_D_EVENT, "event_error: %s(%u) from %s(%u), sequence: %u, "
10636             "resource_id: %u, minor_code: %u\n",
10637             xcb_event_get_error_label(e->error_code), e->error_code,
10638             xcb_event_get_request_label(e->major_code), e->major_code,
10639             e->sequence, e->resource_id, e->minor_code);
10640 }
10641
10642 void
10643 event_handle(xcb_generic_event_t *evt)
10644 {
10645         uint8_t                 type = XCB_EVENT_RESPONSE_TYPE(evt);
10646
10647         DNPRINTF(SWM_D_EVENT, "XCB Event: %s(%d), seq %u\n",
10648             xcb_event_get_label(XCB_EVENT_RESPONSE_TYPE(evt)),
10649             XCB_EVENT_RESPONSE_TYPE(evt), evt->sequence);
10650
10651         switch (type) {
10652 #define EVENT(type, callback) case type: callback((void *)evt); return
10653         EVENT(0, event_error);
10654         EVENT(XCB_BUTTON_PRESS, buttonpress);
10655         /*EVENT(XCB_BUTTON_RELEASE, buttonpress);*/
10656         /*EVENT(XCB_CIRCULATE_NOTIFY, );*/
10657         /*EVENT(XCB_CIRCULATE_REQUEST, );*/
10658         EVENT(XCB_CLIENT_MESSAGE, clientmessage);
10659         /*EVENT(XCB_COLORMAP_NOTIFY, );*/
10660         EVENT(XCB_CONFIGURE_NOTIFY, configurenotify);
10661         EVENT(XCB_CONFIGURE_REQUEST, configurerequest);
10662         /*EVENT(XCB_CREATE_NOTIFY, );*/
10663         EVENT(XCB_DESTROY_NOTIFY, destroynotify);
10664         EVENT(XCB_ENTER_NOTIFY, enternotify);
10665         EVENT(XCB_EXPOSE, expose);
10666 #ifdef SWM_DEBUG
10667         EVENT(XCB_FOCUS_IN, focusin);
10668         EVENT(XCB_FOCUS_OUT, focusout);
10669 #endif
10670         /*EVENT(XCB_GRAPHICS_EXPOSURE, );*/
10671         /*EVENT(XCB_GRAVITY_NOTIFY, );*/
10672         EVENT(XCB_KEY_PRESS, keypress);
10673         /*EVENT(XCB_KEY_RELEASE, keypress);*/
10674         /*EVENT(XCB_KEYMAP_NOTIFY, );*/
10675 #ifdef SWM_DEBUG
10676         EVENT(XCB_LEAVE_NOTIFY, leavenotify);
10677 #endif
10678         EVENT(XCB_MAP_NOTIFY, mapnotify);
10679         EVENT(XCB_MAP_REQUEST, maprequest);
10680         EVENT(XCB_MAPPING_NOTIFY, mappingnotify);
10681         EVENT(XCB_MOTION_NOTIFY, motionnotify);
10682         /*EVENT(XCB_NO_EXPOSURE, );*/
10683         EVENT(XCB_PROPERTY_NOTIFY, propertynotify);
10684         /*EVENT(XCB_REPARENT_NOTIFY, );*/
10685         /*EVENT(XCB_RESIZE_REQUEST, );*/
10686         /*EVENT(XCB_SELECTION_CLEAR, );*/
10687         /*EVENT(XCB_SELECTION_NOTIFY, );*/
10688         /*EVENT(XCB_SELECTION_REQUEST, );*/
10689         EVENT(XCB_UNMAP_NOTIFY, unmapnotify);
10690         /*EVENT(XCB_VISIBILITY_NOTIFY, );*/
10691 #undef EVENT
10692         }
10693         if (type - randr_eventbase == XCB_RANDR_SCREEN_CHANGE_NOTIFY)
10694                 screenchange((void *)evt);
10695 }
10696
10697 int
10698 main(int argc, char *argv[])
10699 {
10700         struct swm_region       *r;
10701         char                    conf[PATH_MAX], *cfile = NULL;
10702         struct stat             sb;
10703         int                     xfd, i, num_screens;
10704         struct sigaction        sact;
10705         xcb_generic_event_t     *evt;
10706         struct timeval          tv;
10707         fd_set                  rd;
10708         int                     rd_max;
10709         int                     num_readable;
10710         bool                    stdin_ready = false, startup = true;
10711
10712         /* suppress unused warning since var is needed */
10713         (void)argc;
10714
10715 #ifdef SWM_DEBUG
10716         time_started = time(NULL);
10717 #endif
10718
10719         start_argv = argv;
10720         warnx("Welcome to spectrwm V%s Build: %s", SPECTRWM_VERSION, buildstr);
10721         if (setlocale(LC_CTYPE, "") == NULL || setlocale(LC_TIME, "") == NULL)
10722                 warnx("no locale support");
10723
10724         /* handle some signals */
10725         bzero(&sact, sizeof(sact));
10726         sigemptyset(&sact.sa_mask);
10727         sact.sa_flags = 0;
10728         sact.sa_handler = sighdlr;
10729         sigaction(SIGINT, &sact, NULL);
10730         sigaction(SIGQUIT, &sact, NULL);
10731         sigaction(SIGTERM, &sact, NULL);
10732         sigaction(SIGHUP, &sact, NULL);
10733
10734         sact.sa_handler = sighdlr;
10735         sact.sa_flags = SA_NOCLDSTOP;
10736         sigaction(SIGCHLD, &sact, NULL);
10737
10738         if ((display = XOpenDisplay(0)) == NULL)
10739                 errx(1, "can not open display");
10740
10741         conn = XGetXCBConnection(display);
10742         if (xcb_connection_has_error(conn))
10743                 errx(1, "can not get XCB connection");
10744
10745         XSetEventQueueOwner(display, XCBOwnsEventQueue);
10746
10747         xcb_prefetch_extension_data(conn, &xcb_randr_id);
10748         xfd = xcb_get_file_descriptor(conn);
10749
10750         /* look for local and global conf file */
10751         pwd = getpwuid(getuid());
10752         if (pwd == NULL)
10753                 errx(1, "invalid user: %d", getuid());
10754
10755         xcb_grab_server(conn);
10756         xcb_aux_sync(conn);
10757
10758         /* flush all events */
10759         while ((evt = xcb_poll_for_event(conn))) {
10760                 if (XCB_EVENT_RESPONSE_TYPE(evt) == 0)
10761                         event_handle(evt);
10762                 free(evt);
10763         }
10764
10765         if (enable_wm())
10766                 errx(1, "another window manager is currently running");
10767
10768         /* Load Xcursors and/or cursorfont glyph cursors. */
10769         cursors_load();
10770
10771         xcb_aux_sync(conn);
10772
10773         setup_globals();
10774         setup_screens();
10775         setup_ewmh();
10776         setup_keys();
10777         setup_quirks();
10778         setup_spawn();
10779
10780         /* load config */
10781         for (i = 0; ; i++) {
10782                 conf[0] = '\0';
10783                 switch (i) {
10784                 case 0:
10785                         /* ~ */
10786                         snprintf(conf, sizeof conf, "%s/.%s",
10787                             pwd->pw_dir, SWM_CONF_FILE);
10788                         break;
10789                 case 1:
10790                         /* global */
10791                         snprintf(conf, sizeof conf, "/etc/%s",
10792                             SWM_CONF_FILE);
10793                         break;
10794                 case 2:
10795                         /* ~ compat */
10796                         snprintf(conf, sizeof conf, "%s/.%s",
10797                             pwd->pw_dir, SWM_CONF_FILE_OLD);
10798                         break;
10799                 case 3:
10800                         /* global compat */
10801                         snprintf(conf, sizeof conf, "/etc/%s",
10802                             SWM_CONF_FILE_OLD);
10803                         break;
10804                 default:
10805                         goto noconfig;
10806                 }
10807
10808                 if (strlen(conf) && stat(conf, &sb) != -1)
10809                         if (S_ISREG(sb.st_mode)) {
10810                                 cfile = conf;
10811                                 break;
10812                         }
10813         }
10814 noconfig:
10815
10816         /* load conf (if any) */
10817         if (cfile)
10818                 conf_load(cfile, SWM_CONF_DEFAULT);
10819
10820         validate_spawns();
10821
10822         if (getenv("SWM_STARTED") == NULL)
10823                 setenv("SWM_STARTED", "YES", 1);
10824
10825         /* setup all bars */
10826         num_screens = get_screen_count();
10827         for (i = 0; i < num_screens; i++)
10828                 TAILQ_FOREACH(r, &screens[i].rl, entry)
10829                         bar_setup(r);
10830
10831         /* Manage existing windows. */
10832         grab_windows();
10833
10834         grabkeys();
10835         stack();
10836         bar_draw();
10837
10838         xcb_ungrab_server(conn);
10839         xcb_flush(conn);
10840
10841         /* Update state of each newly mapped workspace. */
10842         for (i = 0; i < num_screens; i++)
10843                 TAILQ_FOREACH(r, &screens[i].rl, entry)
10844                         r->ws->state = SWM_WS_STATE_MAPPED;
10845
10846         rd_max = xfd > STDIN_FILENO ? xfd : STDIN_FILENO;
10847
10848         while (running) {
10849                 while ((evt = xcb_poll_for_event(conn))) {
10850                         if (!running)
10851                                 goto done;
10852                         event_handle(evt);
10853                         free(evt);
10854                 }
10855
10856                 /* If just (re)started, set default focus if needed. */
10857                 if (startup) {
10858                         startup = false;
10859
10860                         if (focus_mode != SWM_FOCUS_FOLLOW) {
10861                                 r = TAILQ_FIRST(&screens[0].rl);
10862                                 if (r) {
10863                                         focus_region(r);
10864                                         focus_flush();
10865                                 }
10866                                 continue;
10867                         }
10868                 }
10869
10870                 FD_ZERO(&rd);
10871
10872                 if (bar_extra)
10873                         FD_SET(STDIN_FILENO, &rd);
10874
10875                 FD_SET(xfd, &rd);
10876                 tv.tv_sec = 1;
10877                 tv.tv_usec = 0;
10878                 num_readable = select(rd_max + 1, &rd, NULL, NULL, &tv);
10879                 if (num_readable == -1 && errno != EINTR) {
10880                         DNPRINTF(SWM_D_MISC, "select failed");
10881                 } else if (num_readable > 0 && FD_ISSET(STDIN_FILENO, &rd)) {
10882                         stdin_ready = true;
10883                 }
10884
10885                 if (restart_wm)
10886                         restart(NULL, NULL);
10887
10888                 if (search_resp)
10889                         search_do_resp();
10890
10891                 if (!running)
10892                         goto done;
10893
10894                 if (stdin_ready) {
10895                         stdin_ready = false;
10896                         bar_extra_update();
10897                 }
10898
10899                 bar_draw();
10900                 xcb_flush(conn);
10901         }
10902 done:
10903         shutdown_cleanup();
10904
10905         return (0);
10906 }