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