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