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