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