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