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