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