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