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