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