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