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