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