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