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