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