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