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