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