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