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