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