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