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