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