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