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