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