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