JasonWoof Got questions, comments, patches, etc.? Contact Jason Woofenden
Add new key binding: bar_toggle_ws (M-S-b)
[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                 break;
2253         case SWM_ARG_ID_BAR_TOGGLE:
2254                 bar_enabled = !bar_enabled;
2255                 break;
2256         }
2257
2258         /* update bars as necessary */
2259         num_screens = xcb_setup_roots_length(xcb_get_setup(conn));
2260         for (i = 0; i < num_screens; i++)
2261                 TAILQ_FOREACH(tmpr, &screens[i].rl, entry)
2262                         if (tmpr->bar) {
2263                                 if (bar_enabled && tmpr->ws->bar_enabled)
2264                                         xcb_map_window(conn, tmpr->bar->id);
2265                                 else
2266                                         xcb_unmap_window(conn, tmpr->bar->id);
2267                         }
2268
2269         stack();
2270
2271         /* must be after stack */
2272         bar_update();
2273
2274         focus_flush();
2275 }
2276
2277 void
2278 bar_refresh(void)
2279 {
2280         struct swm_region       *r;
2281         uint32_t                wa[2];
2282         int                     i, num_screens;
2283
2284         /* do this here because the conf file is in memory */
2285         if (bar_extra && !bar_extra_running && bar_argv[0]) {
2286                 /* launch external status app */
2287                 bar_extra_running = 1;
2288                 if (pipe(bar_pipe) == -1)
2289                         err(1, "pipe error");
2290                 socket_setnonblock(bar_pipe[0]);
2291                 socket_setnonblock(bar_pipe[1]); /* XXX hmmm, really? */
2292                 if (dup2(bar_pipe[0], 0) == -1)
2293                         err(1, "dup2");
2294                 if (dup2(bar_pipe[1], 1) == -1)
2295                         err(1, "dup2");
2296                 if (signal(SIGPIPE, SIG_IGN) == SIG_ERR)
2297                         err(1, "could not disable SIGPIPE");
2298                 switch (bar_pid = fork()) {
2299                 case -1:
2300                         err(1, "cannot fork");
2301                         break;
2302                 case 0: /* child */
2303                         close(bar_pipe[0]);
2304                         execvp(bar_argv[0], bar_argv);
2305                         err(1, "%s external app failed", bar_argv[0]);
2306                         break;
2307                 default: /* parent */
2308                         close(bar_pipe[1]);
2309                         break;
2310                 }
2311         }
2312
2313         num_screens = xcb_setup_roots_length(xcb_get_setup(conn));
2314         for (i = 0; i < num_screens; i++)
2315                 TAILQ_FOREACH(r, &screens[i].rl, entry) {
2316                         if (r->bar == NULL)
2317                                 continue;
2318                         wa[0] = screens[i].c[SWM_S_COLOR_BAR].pixel;
2319                         wa[1] = screens[i].c[SWM_S_COLOR_BAR_BORDER].pixel;
2320                         xcb_change_window_attributes(conn, r->bar->id,
2321                             XCB_CW_BACK_PIXEL | XCB_CW_BORDER_PIXEL, wa);
2322                 }
2323         bar_update();
2324 }
2325
2326 int
2327 isxlfd(char *s)
2328 {
2329         int      count = 0;
2330
2331         while ((s = index(s, '-'))) {
2332                 ++count;
2333                 ++s;
2334         }
2335
2336         return (count == 14);
2337 }
2338
2339 void
2340 fontset_init(void)
2341 {
2342         char                    *default_string;
2343         char                    **missing_charsets;
2344         int                     num_missing_charsets = 0;
2345         int                     i;
2346
2347         if (bar_fs) {
2348                 XFreeFontSet(display, bar_fs);
2349                 bar_fs = NULL;
2350         }
2351
2352         DNPRINTF(SWM_D_INIT, "fontset_init: loading bar_fonts: %s\n", bar_fonts);
2353
2354         bar_fs = XCreateFontSet(display, bar_fonts, &missing_charsets,
2355             &num_missing_charsets, &default_string);
2356
2357         if (num_missing_charsets > 0) {
2358                 warnx("Unable to load charset(s):");
2359
2360                 for (i = 0; i < num_missing_charsets; ++i)
2361                         warnx("%s", missing_charsets[i]);
2362
2363                 XFreeStringList(missing_charsets);
2364
2365                 if (strcmp(default_string, ""))
2366                         warnx("Glyphs from those sets will be replaced "
2367                             "by '%s'.", default_string);
2368                 else
2369                         warnx("Glyphs from those sets won't be drawn.");
2370         }
2371
2372         if (bar_fs == NULL)
2373                 errx(1, "Error creating font set structure.");
2374
2375         bar_fs_extents = XExtentsOfFontSet(bar_fs);
2376
2377         bar_height = bar_fs_extents->max_logical_extent.height +
2378             2 * bar_border_width;
2379
2380         if (bar_height < 1)
2381                 bar_height = 1;
2382 }
2383
2384 void
2385 xft_init(struct swm_region *r)
2386 {
2387         char                    *font, *d, *search;
2388         XRenderColor            color;
2389
2390         if (bar_font == NULL) {
2391                 if ((d = strdup(bar_fonts)) == NULL)
2392                         errx(1, "insufficient memory.");
2393                 search = d;
2394                 while ((font = strsep(&search, ",")) != NULL) {
2395                         if (*font == '\0')
2396                                 continue;
2397
2398                         DNPRINTF(SWM_D_INIT, "xft_init: try font %s\n", font);
2399
2400                         if (isxlfd(font)) {
2401                                 bar_font = XftFontOpenXlfd(display, r->s->idx,
2402                                                 font);
2403                         } else {
2404                                 bar_font = XftFontOpenName(display, r->s->idx,
2405                                                 font);
2406                         }
2407
2408                         if (!bar_font) {
2409                                 warnx("unable to load font %s", font);
2410                                 continue;
2411                         } else {
2412                                 DNPRINTF(SWM_D_INIT, "successfully opened "
2413                                     "font %s\n", font);
2414                                 break;
2415                         }
2416                 }
2417                 free(d);
2418         }
2419
2420         if (bar_font == NULL)
2421                 errx(1, "unable to open a font");
2422
2423         PIXEL_TO_XRENDERCOLOR(r->s->c[SWM_S_COLOR_BAR_FONT].pixel, color);
2424
2425         if (!XftColorAllocValue(display, DefaultVisual(display, r->s->idx),
2426             DefaultColormap(display, r->s->idx), &color, &bar_font_color))
2427                 warn("Xft error: unable to allocate color.");
2428
2429         bar_height = bar_font->height + 2 * bar_border_width;
2430
2431         if (bar_height < 1)
2432                 bar_height = 1;
2433 }
2434
2435 void
2436 bar_setup(struct swm_region *r)
2437 {
2438         xcb_screen_t    *screen;
2439         uint32_t         wa[3];
2440
2441         DNPRINTF(SWM_D_BAR, "bar_setup: screen %d.\n",
2442             r->s->idx);
2443
2444         if ((screen = get_screen(r->s->idx)) == NULL)
2445                 errx(1, "ERROR: can't get screen %d.", r->s->idx);
2446
2447         if (r->bar != NULL)
2448                 return;
2449
2450         if ((r->bar = calloc(1, sizeof(struct swm_bar))) == NULL)
2451                 err(1, "bar_setup: calloc: failed to allocate memory.");
2452
2453         if (bar_font_legacy)
2454                 fontset_init();
2455         else
2456                 xft_init(r);
2457
2458         X(r->bar) = X(r);
2459         Y(r->bar) = bar_at_bottom ? (Y(r) + HEIGHT(r) - bar_height) : Y(r);
2460         WIDTH(r->bar) = WIDTH(r) - 2 * bar_border_width;
2461         HEIGHT(r->bar) = bar_height - 2 * bar_border_width;
2462
2463         r->bar->id = xcb_generate_id(conn);
2464         wa[0] = r->s->c[SWM_S_COLOR_BAR].pixel;
2465         wa[1] = r->s->c[SWM_S_COLOR_BAR_BORDER].pixel;
2466         wa[2] = XCB_EVENT_MASK_EXPOSURE;
2467
2468         xcb_create_window(conn, XCB_COPY_FROM_PARENT, r->bar->id, r->s->root,
2469             X(r->bar), Y(r->bar), WIDTH(r->bar), HEIGHT(r->bar),
2470             bar_border_width, XCB_WINDOW_CLASS_INPUT_OUTPUT,
2471             XCB_COPY_FROM_PARENT, XCB_CW_BACK_PIXEL | XCB_CW_BORDER_PIXEL
2472             | XCB_CW_EVENT_MASK, wa);
2473
2474         r->bar->buffer = xcb_generate_id(conn);
2475         xcb_create_pixmap(conn, screen->root_depth, r->bar->buffer, r->bar->id,
2476             WIDTH(r->bar), HEIGHT(r->bar));
2477
2478         if (xrandr_support)
2479                 xcb_randr_select_input(conn, r->bar->id,
2480                     XCB_RANDR_NOTIFY_MASK_OUTPUT_CHANGE);
2481
2482         if (bar_enabled)
2483                 xcb_map_window(conn, r->bar->id);
2484
2485         DNPRINTF(SWM_D_BAR, "bar_setup: window: 0x%x, (x,y) w x h: (%d,%d) "
2486             "%d x %d\n", WINID(r->bar), X(r->bar), Y(r->bar), WIDTH(r->bar),
2487             HEIGHT(r->bar));
2488
2489         if (signal(SIGALRM, bar_signal) == SIG_ERR)
2490                 err(1, "could not install bar_signal");
2491         bar_refresh();
2492 }
2493
2494 void
2495 bar_cleanup(struct swm_region *r)
2496 {
2497         if (r->bar == NULL)
2498                 return;
2499         xcb_destroy_window(conn, r->bar->id);
2500         xcb_free_pixmap(conn, r->bar->buffer);
2501         free(r->bar);
2502         r->bar = NULL;
2503 }
2504
2505 void
2506 set_win_state(struct ws_win *win, uint16_t state)
2507 {
2508         uint16_t                data[2] = { state, XCB_ATOM_NONE };
2509
2510         DNPRINTF(SWM_D_EVENT, "set_win_state: window: 0x%x, state: %u\n",
2511             win->id, state);
2512
2513         if (win == NULL)
2514                 return;
2515
2516         xcb_change_property(conn, XCB_PROP_MODE_REPLACE, win->id, a_state,
2517             a_state, 32, 2, data);
2518 }
2519
2520 uint32_t
2521 getstate(xcb_window_t w)
2522 {
2523         uint32_t                        result = 0;
2524         xcb_get_property_cookie_t       c;
2525         xcb_get_property_reply_t        *r;
2526
2527         c = xcb_get_property(conn, 0, w, a_state, a_state, 0L, 2L);
2528         r = xcb_get_property_reply(conn, c, NULL);
2529
2530         if (r) {
2531                 if (r->type == a_state && r->format == 32 && r->length == 2)
2532                         result = *((uint32_t *)xcb_get_property_value(r));
2533                 free(r);
2534         }
2535
2536         DNPRINTF(SWM_D_MISC, "getstate property: win 0x%x state %u\n", w,
2537             result);
2538         return (result);
2539 }
2540
2541 void
2542 version(struct swm_region *r, union arg *args)
2543 {
2544         /* suppress unused warnings since vars are needed */
2545         (void)r;
2546         (void)args;
2547
2548         bar_version = !bar_version;
2549         if (bar_version)
2550                 snprintf(bar_vertext, sizeof bar_vertext,
2551                     "Version: %s Build: %s", SPECTRWM_VERSION, buildstr);
2552         else
2553                 strlcpy(bar_vertext, "", sizeof bar_vertext);
2554         bar_update();
2555
2556         xcb_flush(conn);
2557 }
2558
2559 void
2560 client_msg(struct ws_win *win, xcb_atom_t a, xcb_timestamp_t t)
2561 {
2562         xcb_client_message_event_t      ev;
2563 #ifdef SWM_DEBUG
2564         char                            *name;
2565 #endif
2566
2567         if (win == NULL)
2568                 return;
2569 #ifdef SWM_DEBUG
2570         name = get_atom_name(a);
2571         DNPRINTF(SWM_D_EVENT, "client_msg: window: 0x%x, atom: %s(%u), "
2572             "time: %#x\n",
2573             win->id, name, a, t);
2574         free(name);
2575 #endif
2576
2577         bzero(&ev, sizeof ev);
2578         ev.response_type = XCB_CLIENT_MESSAGE;
2579         ev.window = win->id;
2580         ev.type = a_prot;
2581         ev.format = 32;
2582         ev.data.data32[0] = a;
2583         ev.data.data32[1] = t;
2584
2585         xcb_send_event(conn, 0, win->id,
2586             XCB_EVENT_MASK_NO_EVENT, (const char *)&ev);
2587 }
2588
2589 /* synthetic response to a ConfigureRequest when not making a change */
2590 void
2591 config_win(struct ws_win *win, xcb_configure_request_event_t *ev)
2592 {
2593         xcb_configure_notify_event_t ce;
2594
2595         if (win == NULL)
2596                 return;
2597
2598         /* send notification of unchanged state. */
2599         bzero(&ce, sizeof(ce));
2600         ce.response_type = XCB_CONFIGURE_NOTIFY;
2601         ce.x = X(win);
2602         ce.y = Y(win);
2603         ce.width = WIDTH(win);
2604         ce.height = HEIGHT(win);
2605         ce.override_redirect = 0;
2606
2607         if (ev == NULL) {
2608                 /* EWMH */
2609                 ce.event = win->id;
2610                 ce.window = win->id;
2611                 ce.border_width = BORDER(win);
2612                 ce.above_sibling = XCB_WINDOW_NONE;
2613         } else {
2614                 /* normal */
2615                 ce.event = ev->window;
2616                 ce.window = ev->window;
2617
2618                 /* make response appear more WM_SIZE_HINTS-compliant */
2619                 if (win->sh.flags) {
2620                         DNPRINTF(SWM_D_MISC, "config_win: hints: window: 0x%x,"
2621                             " sh.flags: %u, min: %d x %d, max: %d x %d, inc: "
2622                             "%d x %d\n", win->id, win->sh.flags, SH_MIN_W(win),
2623                             SH_MIN_H(win), SH_MAX_W(win), SH_MAX_H(win),
2624                             SH_INC_W(win), SH_INC_H(win));
2625                 }
2626
2627                 /* min size */
2628                 if (SH_MIN(win)) {
2629                         /* the hint may be set... to 0! */
2630                         if (SH_MIN_W(win) > 0 && ce.width < SH_MIN_W(win))
2631                                 ce.width = SH_MIN_W(win);
2632                         if (SH_MIN_H(win) > 0 && ce.height < SH_MIN_H(win))
2633                                 ce.height = SH_MIN_H(win);
2634                 }
2635
2636                 /* max size */
2637                 if (SH_MAX(win)) {
2638                         /* may also be advertized as 0 */
2639                         if (SH_MAX_W(win) > 0 && ce.width > SH_MAX_W(win))
2640                                 ce.width = SH_MAX_W(win);
2641                         if (SH_MAX_H(win) > 0 && ce.height > SH_MAX_H(win))
2642                                 ce.height = SH_MAX_H(win);
2643                 }
2644
2645                 /* resize increment. */
2646                 if (SH_INC(win)) {
2647                         if (SH_INC_W(win) > 1 && ce.width > SH_INC_W(win))
2648                                 ce.width -= (ce.width - SH_MIN_W(win)) %
2649                                     SH_INC_W(win);
2650                         if (SH_INC_H(win) > 1 && ce.height > SH_INC_H(win))
2651                                 ce.height -= (ce.height - SH_MIN_H(win)) %
2652                                     SH_INC_H(win);
2653                 }
2654
2655                 /* adjust x and y for requested border_width. */
2656                 ce.x += BORDER(win) - ev->border_width;
2657                 ce.y += BORDER(win) - ev->border_width;
2658                 ce.border_width = ev->border_width;
2659                 ce.above_sibling = ev->sibling;
2660         }
2661
2662         DNPRINTF(SWM_D_MISC, "config_win: ewmh: %s, window: 0x%x, (x,y) w x h: "
2663             "(%d,%d) %d x %d, border: %d\n", YESNO(ev == NULL), win->id, ce.x,
2664             ce.y, ce.width, ce.height, ce.border_width);
2665
2666         xcb_send_event(conn, 0, win->id, XCB_EVENT_MASK_STRUCTURE_NOTIFY,
2667             (char *)&ce);
2668 }
2669
2670 int
2671 count_win(struct workspace *ws, int count_transient)
2672 {
2673         struct ws_win           *win;
2674         int                     count = 0;
2675
2676         TAILQ_FOREACH(win, &ws->winlist, entry) {
2677                 if (!count_transient && win->floating)
2678                         continue;
2679                 if (!count_transient && win->transient)
2680                         continue;
2681                 if (win->iconic)
2682                         continue;
2683                 count++;
2684         }
2685         DNPRINTF(SWM_D_MISC, "count_win: %d\n", count);
2686
2687         return (count);
2688 }
2689
2690 void
2691 quit(struct swm_region *r, union arg *args)
2692 {
2693         /* suppress unused warnings since vars are needed */
2694         (void)r;
2695         (void)args;
2696
2697         DNPRINTF(SWM_D_MISC, "quit\n");
2698         running = 0;
2699 }
2700
2701 void
2702 map_window(struct ws_win *win)
2703 {
2704         uint32_t        val = XCB_STACK_MODE_ABOVE;
2705
2706         if (win == NULL)
2707                 return;
2708
2709         DNPRINTF(SWM_D_EVENT, "map_window: win 0x%x, mapped: %s\n", win->id,
2710             YESNO(win->mapped));
2711
2712         xcb_configure_window(conn, win->id,
2713             XCB_CONFIG_WINDOW_STACK_MODE, &val);
2714
2715         if (win->mapped)
2716                 return;
2717
2718         xcb_map_window(conn, win->id);
2719         set_win_state(win, XCB_ICCCM_WM_STATE_NORMAL);
2720         win->mapped = 1;
2721 }
2722
2723 void
2724 unmap_window(struct ws_win *win)
2725 {
2726         if (win == NULL)
2727                 return;
2728
2729         DNPRINTF(SWM_D_EVENT, "unmap_window: win 0x%x, mapped: %s\n", win->id,
2730             YESNO(win->mapped));
2731
2732         if (!win->mapped)
2733                 return;
2734
2735         xcb_unmap_window(conn, win->id);
2736         set_win_state(win, XCB_ICCCM_WM_STATE_ICONIC);
2737         win->mapped = 0;
2738 }
2739
2740 void
2741 unmap_all(void)
2742 {
2743         struct ws_win           *win;
2744         int                     i, j, num_screens;
2745
2746         num_screens = xcb_setup_roots_length(xcb_get_setup(conn));
2747         for (i = 0; i < num_screens; i++)
2748                 for (j = 0; j < workspace_limit; j++)
2749                         TAILQ_FOREACH(win, &screens[i].ws[j].winlist, entry)
2750                                 unmap_window(win);
2751 }
2752
2753 void
2754 fake_keypress(struct ws_win *win, xcb_keysym_t keysym, uint16_t modifiers)
2755 {
2756         xcb_key_press_event_t   event;
2757         xcb_keycode_t           *keycode;
2758
2759         if (win == NULL)
2760                 return;
2761
2762         keycode = xcb_key_symbols_get_keycode(syms, keysym);
2763
2764         DNPRINTF(SWM_D_MISC, "fake_keypress: win 0x%x keycode %u\n",
2765             win->id, *keycode);
2766
2767         bzero(&event, sizeof(event));
2768         event.event = win->id;
2769         event.root = win->s->root;
2770         event.child = XCB_WINDOW_NONE;
2771         event.time = XCB_CURRENT_TIME;
2772         event.event_x = X(win);
2773         event.event_y = Y(win);
2774         event.root_x = 1;
2775         event.root_y = 1;
2776         event.same_screen = 1;
2777         event.detail = *keycode;
2778         event.state = modifiers;
2779
2780         event.response_type = XCB_KEY_PRESS;
2781         xcb_send_event(conn, 1, win->id,
2782             XCB_EVENT_MASK_KEY_PRESS, (const char *)&event);
2783
2784         event.response_type = XCB_KEY_RELEASE;
2785         xcb_send_event(conn, 1, win->id,
2786             XCB_EVENT_MASK_KEY_RELEASE, (const char *)&event);
2787
2788         free(keycode);
2789 }
2790
2791 void
2792 restart(struct swm_region *r, union arg *args)
2793 {
2794         /* suppress unused warning since var is needed */
2795         (void)r;
2796         (void)args;
2797
2798         DNPRINTF(SWM_D_MISC, "restart: %s\n", start_argv[0]);
2799
2800         shutdown_cleanup();
2801
2802         execvp(start_argv[0], start_argv);
2803         warn("execvp failed");
2804         quit(NULL, NULL);
2805 }
2806
2807 struct ws_win *
2808 get_pointer_win(xcb_window_t root)
2809 {
2810         struct ws_win                   *win = NULL;
2811         xcb_query_pointer_reply_t       *r;
2812
2813         DNPRINTF(SWM_D_EVENT, "get_pointer_win: root: 0x%x.\n", root);
2814
2815         r = xcb_query_pointer_reply(conn, xcb_query_pointer(conn, root), NULL);
2816         if (r) {
2817                 win = find_window(r->child);
2818                 if (win) {
2819                         DNPRINTF(SWM_D_EVENT, "get_pointer_win: 0x%x.\n",
2820                             win->id);
2821                 } else {
2822                         DNPRINTF(SWM_D_EVENT, "get_pointer_win: none.\n");
2823                 }
2824                 free(r);
2825         }
2826
2827         return win;
2828 }
2829
2830 struct swm_region *
2831 root_to_region(xcb_window_t root, int check)
2832 {
2833         struct ws_win                   *cfw;
2834         struct swm_region               *r = NULL;
2835         int                             i, num_screens;
2836         xcb_query_pointer_reply_t       *qpr;
2837         xcb_get_input_focus_reply_t     *gifr;
2838
2839         DNPRINTF(SWM_D_MISC, "root_to_region: window: 0x%x\n", root);
2840
2841         num_screens = xcb_setup_roots_length(xcb_get_setup(conn));
2842         for (i = 0; i < num_screens; i++)
2843                 if (screens[i].root == root)
2844                         break;
2845
2846         if (check & SWM_CK_FOCUS) {
2847                 /* Try to find an actively focused window */
2848                 gifr = xcb_get_input_focus_reply(conn,
2849                     xcb_get_input_focus(conn), NULL);
2850                 if (gifr) {
2851                         cfw = find_window(gifr->focus);
2852                         if (cfw && cfw->ws->r)
2853                                 r = cfw->ws->r;
2854
2855                         free(gifr);
2856                 }
2857         }
2858
2859         if (r == NULL && check & SWM_CK_POINTER) {
2860                 /* No region with an active focus; try to use pointer. */
2861                 qpr = xcb_query_pointer_reply(conn, xcb_query_pointer(conn,
2862                     screens[i].root), NULL);
2863
2864                 if (qpr) {
2865                         DNPRINTF(SWM_D_MISC, "root_to_region: pointer: "
2866                             "(%d,%d)\n", qpr->root_x, qpr->root_y);
2867                         TAILQ_FOREACH(r, &screens[i].rl, entry)
2868                                 if (X(r) <= qpr->root_x &&
2869                                     qpr->root_x < MAX_X(r) &&
2870                                     Y(r) <= qpr->root_y &&
2871                                     qpr->root_y < MAX_Y(r))
2872                                         break;
2873                         free(qpr);
2874                 }
2875         }
2876
2877         /* Last resort. */
2878         if (r == NULL && check & SWM_CK_FALLBACK)
2879                 r = TAILQ_FIRST(&screens[i].rl);
2880
2881         return (r);
2882 }
2883
2884 struct ws_win *
2885 find_unmanaged_window(xcb_window_t id)
2886 {
2887         struct ws_win           *win;
2888         int                     i, j, num_screens;
2889
2890         num_screens = xcb_setup_roots_length(xcb_get_setup(conn));
2891         for (i = 0; i < num_screens; i++)
2892                 for (j = 0; j < workspace_limit; j++)
2893                         TAILQ_FOREACH(win, &screens[i].ws[j].unmanagedlist,
2894                             entry)
2895                                 if (id == win->id)
2896                                         return (win);
2897         return (NULL);
2898 }
2899
2900 struct ws_win *
2901 find_window(xcb_window_t id)
2902 {
2903         struct ws_win           *win;
2904         int                     i, j, num_screens;
2905         xcb_query_tree_reply_t  *r;
2906
2907         num_screens = xcb_setup_roots_length(xcb_get_setup(conn));
2908         for (i = 0; i < num_screens; i++)
2909                 for (j = 0; j < workspace_limit; j++)
2910                         TAILQ_FOREACH(win, &screens[i].ws[j].winlist, entry)
2911                                 if (id == win->id)
2912                                         return (win);
2913
2914         r = xcb_query_tree_reply(conn, xcb_query_tree(conn, id), NULL);
2915         if (!r)
2916                 return (NULL);
2917
2918         /* if we were looking for the parent return that window instead */
2919         if (r->parent == 0 || r->root == r->parent) {
2920                 free(r);
2921                 return (NULL);
2922         }
2923
2924         /* look for parent */
2925         for (i = 0; i < num_screens; i++)
2926                 for (j = 0; j < workspace_limit; j++)
2927                         TAILQ_FOREACH(win, &screens[i].ws[j].winlist, entry)
2928                                 if (r->parent == win->id) {
2929                                         free(r);
2930                                         return (win);
2931                                 }
2932
2933         free(r);
2934         return (NULL);
2935 }
2936
2937 void
2938 spawn(int ws_idx, union arg *args, int close_fd)
2939 {
2940         int                     fd;
2941         char                    *ret = NULL;
2942
2943         DNPRINTF(SWM_D_MISC, "spawn: %s\n", args->argv[0]);
2944
2945         close(xcb_get_file_descriptor(conn));
2946
2947         setenv("LD_PRELOAD", SWM_LIB, 1);
2948
2949         if (asprintf(&ret, "%d", ws_idx) == -1) {
2950                 warn("spawn: asprintf SWM_WS");
2951                 _exit(1);
2952         }
2953         setenv("_SWM_WS", ret, 1);
2954         free(ret);
2955         ret = NULL;
2956
2957         if (asprintf(&ret, "%d", getpid()) == -1) {
2958                 warn("spawn: asprintf _SWM_PID");
2959                 _exit(1);
2960         }
2961         setenv("_SWM_PID", ret, 1);
2962         free(ret);
2963         ret = NULL;
2964
2965         if (setsid() == -1) {
2966                 warn("spawn: setsid");
2967                 _exit(1);
2968         }
2969
2970         if (close_fd) {
2971                 /*
2972                  * close stdin and stdout to prevent interaction between apps
2973                  * and the baraction script
2974                  * leave stderr open to record errors
2975                 */
2976                 if ((fd = open(_PATH_DEVNULL, O_RDWR, 0)) == -1) {
2977                         warn("spawn: open");
2978                         _exit(1);
2979                 }
2980                 dup2(fd, STDIN_FILENO);
2981                 dup2(fd, STDOUT_FILENO);
2982                 if (fd > 2)
2983                         close(fd);
2984         }
2985
2986         execvp(args->argv[0], args->argv);
2987
2988         warn("spawn: execvp");
2989         _exit(1);
2990 }
2991
2992 void
2993 kill_refs(struct ws_win *win)
2994 {
2995         int                     i, x, num_screens;
2996         struct swm_region       *r;
2997         struct workspace        *ws;
2998
2999         if (win == NULL)
3000                 return;
3001
3002         num_screens = xcb_setup_roots_length(xcb_get_setup(conn));
3003         for (i = 0; i < num_screens; i++)
3004                 TAILQ_FOREACH(r, &screens[i].rl, entry)
3005                         for (x = 0; x < workspace_limit; x++) {
3006                                 ws = &r->s->ws[x];
3007                                 if (win == ws->focus)
3008                                         ws->focus = NULL;
3009                                 if (win == ws->focus_prev)
3010                                         ws->focus_prev = NULL;
3011                         }
3012 }
3013
3014 int
3015 validate_win(struct ws_win *testwin)
3016 {
3017         struct ws_win           *win;
3018         struct workspace        *ws;
3019         struct swm_region       *r;
3020         int                     i, x, num_screens;
3021
3022         if (testwin == NULL)
3023                 return (0);
3024
3025         num_screens = xcb_setup_roots_length(xcb_get_setup(conn));
3026         for (i = 0; i < num_screens; i++)
3027                 TAILQ_FOREACH(r, &screens[i].rl, entry)
3028                         for (x = 0; x < workspace_limit; x++) {
3029                                 ws = &r->s->ws[x];
3030                                 TAILQ_FOREACH(win, &ws->winlist, entry)
3031                                         if (win == testwin)
3032                                                 return (0);
3033                         }
3034         return (1);
3035 }
3036
3037 int
3038 validate_ws(struct workspace *testws)
3039 {
3040         struct swm_region       *r;
3041         struct workspace        *ws;
3042         int                     i, x, num_screens;
3043
3044         /* validate all ws */
3045         num_screens = xcb_setup_roots_length(xcb_get_setup(conn));
3046         for (i = 0; i < num_screens; i++)
3047                 TAILQ_FOREACH(r, &screens[i].rl, entry)
3048                         for (x = 0; x < workspace_limit; x++) {
3049                                 ws = &r->s->ws[x];
3050                                 if (ws == testws)
3051                                         return (0);
3052                         }
3053         return (1);
3054 }
3055
3056 void
3057 unfocus_win(struct ws_win *win)
3058 {
3059         xcb_window_t            none = XCB_WINDOW_NONE;
3060
3061         DNPRINTF(SWM_D_FOCUS, "unfocus_win: window: 0x%x\n", WINID(win));
3062
3063         if (win == NULL)
3064                 return;
3065         if (win->ws == NULL) {
3066                 DNPRINTF(SWM_D_FOCUS, "unfocus_win: NULL ws.\n");
3067                 return;
3068         }
3069
3070         if (validate_ws(win->ws)) {
3071                 DNPRINTF(SWM_D_FOCUS, "unfocus_win: invalid ws.\n");
3072                 return;
3073         }
3074
3075         if (win->ws->r == NULL) {
3076                 DNPRINTF(SWM_D_FOCUS, "unfocus_win: NULL region.\n");
3077                 return;
3078         }
3079
3080         if (validate_win(win)) {
3081                 DNPRINTF(SWM_D_FOCUS, "unfocus_win: invalid win.\n");
3082                 kill_refs(win);
3083                 return;
3084         }
3085
3086         if (win->ws->focus == win) {
3087                 win->ws->focus = NULL;
3088                 win->ws->focus_prev = win;
3089         }
3090
3091         if (validate_win(win->ws->focus)) {
3092                 kill_refs(win->ws->focus);
3093                 win->ws->focus = NULL;
3094         }
3095
3096         if (validate_win(win->ws->focus_prev)) {
3097                 kill_refs(win->ws->focus_prev);
3098                 win->ws->focus_prev = NULL;
3099         }
3100
3101         xcb_change_window_attributes(conn, win->id, XCB_CW_BORDER_PIXEL,
3102             &win->ws->r->s->c[SWM_S_COLOR_UNFOCUS].pixel);
3103
3104         xcb_change_property(conn, XCB_PROP_MODE_REPLACE, win->s->root,
3105             ewmh[_NET_ACTIVE_WINDOW].atom, XCB_ATOM_WINDOW, 32, 1, &none);
3106
3107         DNPRINTF(SWM_D_FOCUS, "unfocus_win: done.\n");
3108 }
3109
3110 void
3111 focus_win(struct ws_win *win)
3112 {
3113         struct ws_win                   *cfw = NULL, *parent = NULL, *w;
3114         struct workspace                *ws;
3115         xcb_get_input_focus_reply_t     *r;
3116
3117         DNPRINTF(SWM_D_FOCUS, "focus_win: window: 0x%x\n", WINID(win));
3118
3119         if (win == NULL)
3120                 goto out;
3121
3122         if (win->ws == NULL)
3123                 goto out;
3124
3125         ws = win->ws;
3126
3127         if (validate_ws(ws))
3128                 goto out;
3129
3130         if (validate_win(win)) {
3131                 kill_refs(win);
3132                 goto out;
3133         }
3134
3135         r = xcb_get_input_focus_reply(conn, xcb_get_input_focus(conn), NULL);
3136         if (r) {
3137                 cfw = find_window(r->focus);
3138                 if (cfw != win)
3139                         unfocus_win(cfw);
3140                 free(r);
3141         }
3142
3143         if (ws->focus != win) {
3144                 if (ws->focus && ws->focus != cfw)
3145                         unfocus_win(ws->focus);
3146                 ws->focus = win;
3147         }
3148
3149         /* If this window directs focus to a child window, then clear. */
3150         if (win->focus_child)
3151                 win->focus_child = NULL;
3152
3153         /* If transient, adjust parent's focus child for focus_magic. */
3154         if (win->transient) {
3155                 parent = find_window(win->transient);
3156                 if (parent && parent->focus_child != win)
3157                         parent->focus_child = win;
3158         }
3159
3160         if (cfw != win && ws->r != NULL) {
3161                 /* Set input focus if no input hint, or indicated by hint. */
3162                 if (!(win->hints.flags & XCB_ICCCM_WM_HINT_INPUT) ||
3163                     (win->hints.flags & XCB_ICCCM_WM_HINT_INPUT &&
3164                      win->hints.input))
3165                         xcb_set_input_focus(conn, XCB_INPUT_FOCUS_PARENT,
3166                                         win->id, last_event_time);
3167
3168                 /* Tell app it can adjust focus to a specific window. */
3169                 if (win->take_focus) {
3170                         /* java is special; always tell parent */
3171                         if (win->transient && win->java)
3172                                 client_msg(parent, a_takefocus,
3173                                     last_event_time);
3174                         else
3175                                 client_msg(win, a_takefocus, last_event_time);
3176                 }
3177
3178                 xcb_change_window_attributes(conn, win->id, XCB_CW_BORDER_PIXEL,
3179                     &ws->r->s->c[SWM_S_COLOR_FOCUS].pixel);
3180
3181                 if (ws->cur_layout->flags & SWM_L_MAPONFOCUS ||
3182                     ws->always_raise) {
3183                         /* If a parent exists, map it first. */
3184                         if (parent) {
3185                                 map_window(parent);
3186
3187                                 /* Map siblings next. */
3188                                 TAILQ_FOREACH(w, &ws->winlist, entry)
3189                                         if (w != win && !w->iconic &&
3190                                             w->transient == parent->id)
3191                                                 map_window(w);
3192                         }
3193
3194                         /* Map focused window. */
3195                         map_window(win);
3196
3197                         /* Finally, map children of focus window. */
3198                         TAILQ_FOREACH(w, &ws->winlist, entry)
3199                                 if (w->transient == win->id && !w->iconic)
3200                                         map_window(w);
3201
3202                 }
3203
3204                 xcb_change_property(conn, XCB_PROP_MODE_REPLACE, win->s->root,
3205                     ewmh[_NET_ACTIVE_WINDOW].atom, XCB_ATOM_WINDOW, 32, 1,
3206                     &win->id);
3207         }
3208
3209 out:
3210         bar_update();
3211
3212         DNPRINTF(SWM_D_FOCUS, "focus_win: done.\n");
3213 }
3214
3215 /* If a child window should have focus instead, return it. */
3216 struct ws_win *
3217 get_focus_magic(struct ws_win *win)
3218 {
3219         struct ws_win   *parent = NULL;
3220         struct ws_win   *child = NULL;
3221
3222         DNPRINTF(SWM_D_FOCUS, "get_focus_magic: window: 0x%x\n", WINID(win));
3223         if (win == NULL)
3224                 return win;
3225
3226         if (win->transient) {
3227                 parent = find_window(win->transient);
3228
3229                 /* If parent prefers focus elsewhere, then try to do so. */
3230                 if (parent && (child = parent->focus_child)) {
3231                         if (validate_win(child) == 0 && child->mapped)
3232                                 win = child;
3233                         else
3234                                 parent->focus_child = NULL;
3235                 }
3236         }
3237
3238         /* If this window prefers focus elsewhere, then try to do so. */
3239         if ((child = win->focus_child)) {
3240                 if (validate_win(child) == 0 && child->mapped)
3241                         win = child;
3242                 else
3243                         win->focus_child = NULL;
3244         }
3245
3246         return win;
3247 }
3248
3249 void
3250 event_drain(uint8_t rt)
3251 {
3252         xcb_generic_event_t     *evt;
3253
3254         /* ensure all pending requests have been processed before filtering. */
3255         xcb_aux_sync(conn);
3256         while ((evt = xcb_poll_for_event(conn))) {
3257                 if (XCB_EVENT_RESPONSE_TYPE(evt) != rt)
3258                         event_handle(evt);
3259
3260                 free(evt);
3261         }
3262 }
3263
3264 void
3265 switchws(struct swm_region *r, union arg *args)
3266 {
3267         int                     wsid = args->id, unmap_old = 0;
3268         struct swm_region       *this_r, *other_r;
3269         struct ws_win           *win;
3270         struct workspace        *new_ws, *old_ws;
3271
3272         if (!(r && r->s))
3273                 return;
3274
3275         if (wsid >= workspace_limit)
3276                 return;
3277
3278         this_r = r;
3279         old_ws = this_r->ws;
3280         new_ws = &this_r->s->ws[wsid];
3281
3282         DNPRINTF(SWM_D_WS, "switchws: screen[%d]:%dx%d+%d+%d: %d -> %d\n",
3283             r->s->idx, WIDTH(r), HEIGHT(r), X(r), Y(r), old_ws->idx, wsid);
3284
3285         if (new_ws == NULL || old_ws == NULL)
3286                 return;
3287         if (new_ws == old_ws)
3288                 return;
3289
3290         unfocus_win(old_ws->focus);
3291
3292         other_r = new_ws->r;
3293         if (other_r == NULL) {
3294                 /* the other workspace is hidden, hide this one */
3295                 old_ws->r = NULL;
3296                 unmap_old = 1;
3297         } else {
3298                 /* the other ws is visible in another region, exchange them */
3299                 other_r->ws_prior = new_ws;
3300                 other_r->ws = old_ws;
3301                 old_ws->r = other_r;
3302         }
3303         this_r->ws_prior = old_ws;
3304         this_r->ws = new_ws;
3305         new_ws->r = this_r;
3306
3307         /* Set focus_pending before stacking. */
3308         if (focus_mode != SWM_FOCUS_FOLLOW)
3309                 new_ws->focus_pending = get_region_focus(new_ws->r);
3310
3311         stack();
3312
3313         /* unmap old windows */
3314         if (unmap_old)
3315                 TAILQ_FOREACH(win, &old_ws->winlist, entry)
3316                         unmap_window(win);
3317
3318         /* if workspaces were swapped, then don't wait to set focus */
3319         if (old_ws->r && focus_mode != SWM_FOCUS_FOLLOW) {
3320                 if (new_ws->focus_pending) {
3321                         focus_win(new_ws->focus_pending);
3322                 } else {
3323                         /* Empty region, focus on root. */
3324                         xcb_set_input_focus(conn, XCB_INPUT_FOCUS_PARENT,
3325                             new_ws->r->s[new_ws->r->s->idx].root,
3326                             XCB_CURRENT_TIME);
3327                 }
3328         }
3329
3330         /* Clear bar if new ws is empty. */
3331         if (new_ws->focus_pending == NULL)
3332                 bar_update();
3333
3334         focus_flush();
3335
3336         DNPRINTF(SWM_D_WS, "switchws: done.\n");
3337 }
3338
3339 void
3340 cyclews(struct swm_region *r, union arg *args)
3341 {
3342         union                   arg a;
3343         struct swm_screen       *s = r->s;
3344         int                     cycle_all = 0;
3345
3346         DNPRINTF(SWM_D_WS, "cyclews: id: %d, screen[%d]:%dx%d+%d+%d, ws: %d\n",
3347             args->id, r->s->idx, WIDTH(r), HEIGHT(r), X(r), Y(r), r->ws->idx);
3348
3349         a.id = r->ws->idx;
3350         do {
3351                 switch (args->id) {
3352                 case SWM_ARG_ID_CYCLEWS_UP_ALL:
3353                         cycle_all = 1;
3354                         /* FALLTHROUGH */
3355                 case SWM_ARG_ID_CYCLEWS_UP:
3356                         if (a.id < workspace_limit - 1)
3357                                 a.id++;
3358                         else
3359                                 a.id = 0;
3360                         break;
3361                 case SWM_ARG_ID_CYCLEWS_DOWN_ALL:
3362                         cycle_all = 1;
3363                         /* FALLTHROUGH */
3364                 case SWM_ARG_ID_CYCLEWS_DOWN:
3365                         if (a.id > 0)
3366                                 a.id--;
3367                         else
3368                                 a.id = workspace_limit - 1;
3369                         break;
3370                 default:
3371                         return;
3372                 };
3373
3374                 if (!cycle_all &&
3375                     (!cycle_empty && TAILQ_EMPTY(&s->ws[a.id].winlist)))
3376                         continue;
3377                 if (!cycle_visible && s->ws[a.id].r != NULL)
3378                         continue;
3379
3380                 switchws(r, &a);
3381         } while (a.id != r->ws->idx);
3382 }
3383
3384 void
3385 priorws(struct swm_region *r, union arg *args)
3386 {
3387         union arg               a;
3388
3389         (void)args;
3390
3391         DNPRINTF(SWM_D_WS, "priorws: id: %d, screen[%d]:%dx%d+%d+%d, ws: %d\n",
3392             args->id, r->s->idx, WIDTH(r), HEIGHT(r), X(r), Y(r), r->ws->idx);
3393
3394         if (r->ws_prior == NULL)
3395                 return;
3396
3397         a.id = r->ws_prior->idx;
3398         switchws(r, &a);
3399 }
3400
3401 void
3402 cyclescr(struct swm_region *r, union arg *args)
3403 {
3404         struct ws_win           *nfw;
3405         struct swm_region       *rr = NULL;
3406         int                     i, num_screens;
3407
3408         num_screens = xcb_setup_roots_length(xcb_get_setup(conn));
3409         /* do nothing if we don't have more than one screen */
3410         if (!(num_screens > 1 || outputs > 1))
3411                 return;
3412
3413         i = r->s->idx;
3414         switch (args->id) {
3415         case SWM_ARG_ID_CYCLESC_UP:
3416                 rr = TAILQ_NEXT(r, entry);
3417                 if (rr == NULL)
3418                         rr = TAILQ_FIRST(&screens[i].rl);
3419                 break;
3420         case SWM_ARG_ID_CYCLESC_DOWN:
3421                 rr = TAILQ_PREV(r, swm_region_list, entry);
3422                 if (rr == NULL)
3423                         rr = TAILQ_LAST(&screens[i].rl, swm_region_list);
3424                 break;
3425         default:
3426                 return;
3427         };
3428         if (rr == NULL)
3429                 return;
3430
3431         nfw = get_region_focus(rr);
3432         if (nfw) {
3433                 focus_win(nfw);
3434         } else {
3435                 /* New region is empty; unfocus old region and warp pointer. */
3436                 unfocus_win(r->ws->focus);
3437                 xcb_set_input_focus(conn, XCB_INPUT_FOCUS_PARENT,
3438                                 rr->s[i].root, XCB_CURRENT_TIME);
3439
3440                 /* Clear bar since empty. */
3441                 bar_update();
3442         }
3443
3444         focus_flush();
3445 }
3446
3447 void
3448 sort_windows(struct ws_win_list *wl)
3449 {
3450         struct ws_win           *win, *parent, *nxt;
3451
3452         if (wl == NULL)
3453                 return;
3454
3455         for (win = TAILQ_FIRST(wl); win != TAILQ_END(wl); win = nxt) {
3456                 nxt = TAILQ_NEXT(win, entry);
3457                 if (win->transient) {
3458                         parent = find_window(win->transient);
3459                         if (parent == NULL) {
3460                                 warnx("not possible bug");
3461                                 continue;
3462                         }
3463                         TAILQ_REMOVE(wl, win, entry);
3464                         TAILQ_INSERT_AFTER(wl, parent, win, entry);
3465                 }
3466         }
3467
3468 }
3469
3470 void
3471 swapwin(struct swm_region *r, union arg *args)
3472 {
3473         struct ws_win           *target, *source;
3474         struct ws_win           *cur_focus;
3475         struct ws_win_list      *wl;
3476
3477         DNPRINTF(SWM_D_WS, "swapwin: id: %d, screen[%d]:%dx%d+%d+%d, ws: %d\n",
3478             args->id, r->s->idx, WIDTH(r), HEIGHT(r), X(r), Y(r), r->ws->idx);
3479
3480         cur_focus = r->ws->focus;
3481         if (cur_focus == NULL)
3482                 return;
3483
3484         source = cur_focus;
3485         wl = &source->ws->winlist;
3486
3487         switch (args->id) {
3488         case SWM_ARG_ID_SWAPPREV:
3489                 if (source->transient)
3490                         source = find_window(source->transient);
3491                 target = TAILQ_PREV(source, ws_win_list, entry);
3492                 if (target && target->transient)
3493                         target = find_window(target->transient);
3494                 TAILQ_REMOVE(wl, source, entry);
3495                 if (target == NULL)
3496                         TAILQ_INSERT_TAIL(wl, source, entry);
3497                 else
3498                         TAILQ_INSERT_BEFORE(target, source, entry);
3499                 break;
3500         case SWM_ARG_ID_SWAPNEXT:
3501                 target = TAILQ_NEXT(source, entry);
3502                 /* move the parent and let the sort handle the move */
3503                 if (source->transient)
3504                         source = find_window(source->transient);
3505                 TAILQ_REMOVE(wl, source, entry);
3506                 if (target == NULL)
3507                         TAILQ_INSERT_HEAD(wl, source, entry);
3508                 else
3509                         TAILQ_INSERT_AFTER(wl, target, source, entry);
3510                 break;
3511         case SWM_ARG_ID_SWAPMAIN:
3512                 target = TAILQ_FIRST(wl);
3513                 if (target == source) {
3514                         if (source->ws->focus_prev != NULL &&
3515                             source->ws->focus_prev != target)
3516                                 source = source->ws->focus_prev;
3517                         else
3518                                 return;
3519                 }
3520                 if (target == NULL || source == NULL)
3521                         return;
3522                 source->ws->focus_prev = target;
3523                 TAILQ_REMOVE(wl, target, entry);
3524                 TAILQ_INSERT_BEFORE(source, target, entry);
3525                 TAILQ_REMOVE(wl, source, entry);
3526                 TAILQ_INSERT_HEAD(wl, source, entry);
3527                 break;
3528         case SWM_ARG_ID_MOVELAST:
3529                 TAILQ_REMOVE(wl, source, entry);
3530                 TAILQ_INSERT_TAIL(wl, source, entry);
3531                 break;
3532         default:
3533                 DNPRINTF(SWM_D_MOVE, "swapwin: invalid id: %d\n", args->id);
3534                 return;
3535         }
3536
3537         sort_windows(wl);
3538
3539         stack();
3540
3541         focus_flush();
3542 }
3543
3544 struct ws_win *
3545 get_focus_prev(struct ws_win *win)
3546 {
3547         struct ws_win           *winfocus = NULL;
3548         struct ws_win           *cur_focus = NULL;
3549         struct ws_win_list      *wl = NULL;
3550         struct workspace        *ws = NULL;
3551
3552         if (!(win && win->ws))
3553                 return NULL;
3554
3555         ws = win->ws;
3556         wl = &ws->winlist;
3557         cur_focus = ws->focus;
3558
3559         DNPRINTF(SWM_D_FOCUS, "get_focus_prev: window: 0x%x, cur_focus: 0x%x\n",
3560             WINID(win), WINID(cur_focus));
3561
3562         /* pickle, just focus on whatever */
3563         if (cur_focus == NULL) {
3564                 /* use prev_focus if valid */
3565                 if (ws->focus_prev && ws->focus_prev != cur_focus &&
3566                     find_window(WINID(ws->focus_prev)))
3567                         winfocus = ws->focus_prev;
3568                 goto done;
3569         }
3570
3571         /* if transient focus on parent */
3572         if (cur_focus->transient) {
3573                 winfocus = find_window(cur_focus->transient);
3574                 goto done;
3575         }
3576
3577         /* if in max_stack try harder */
3578         if ((win->quirks & SWM_Q_FOCUSPREV) ||
3579             (ws->cur_layout->flags & SWM_L_FOCUSPREV)) {
3580                 if (cur_focus != ws->focus_prev)
3581                         winfocus = ws->focus_prev;
3582                 else
3583                         winfocus = TAILQ_PREV(win, ws_win_list, entry);
3584                 if (winfocus)
3585                         goto done;
3586         }
3587
3588         DNPRINTF(SWM_D_FOCUS, "get_focus_prev: focus_close: %d\n", focus_close);
3589
3590         if (winfocus == NULL || winfocus == win) {
3591                 switch (focus_close) {
3592                 case SWM_STACK_BOTTOM:
3593                         winfocus = TAILQ_FIRST(wl);
3594                         break;
3595                 case SWM_STACK_TOP:
3596                         winfocus = TAILQ_LAST(wl, ws_win_list);
3597                         break;
3598                 case SWM_STACK_ABOVE:
3599                         if ((winfocus = TAILQ_NEXT(cur_focus, entry)) == NULL) {
3600                                 if (focus_close_wrap)
3601                                         winfocus = TAILQ_FIRST(wl);
3602                                 else
3603                                         winfocus = TAILQ_PREV(cur_focus,
3604                                             ws_win_list, entry);
3605                         }
3606                         break;
3607                 case SWM_STACK_BELOW:
3608                         if ((winfocus = TAILQ_PREV(cur_focus, ws_win_list,
3609                             entry)) == NULL) {
3610                                 if (focus_close_wrap)
3611                                         winfocus = TAILQ_LAST(wl, ws_win_list);
3612                                 else
3613                                         winfocus = TAILQ_NEXT(cur_focus, entry);
3614                         }
3615                         break;
3616                 }
3617         }
3618 done:
3619         if (winfocus == NULL) {
3620                 if (focus_default == SWM_STACK_TOP)
3621                         winfocus = TAILQ_LAST(wl, ws_win_list);
3622                 else
3623                         winfocus = TAILQ_FIRST(wl);
3624         }
3625
3626         kill_refs(win);
3627
3628         return get_focus_magic(winfocus);
3629 }
3630
3631 struct ws_win *
3632 get_region_focus(struct swm_region *r)
3633 {
3634         struct ws_win           *winfocus = NULL;
3635
3636         if (!(r && r->ws))
3637                 return NULL;
3638
3639         if (r->ws->focus && !r->ws->focus->iconic)
3640                 winfocus = r->ws->focus;
3641         else if (r->ws->focus_prev && !r->ws->focus_prev->iconic)
3642                 winfocus = r->ws->focus_prev;
3643         else
3644                 TAILQ_FOREACH(winfocus, &r->ws->winlist, entry)
3645                         if (!winfocus->iconic)
3646                                 break;
3647
3648         return get_focus_magic(winfocus);
3649 }
3650
3651 void
3652 focus(struct swm_region *r, union arg *args)
3653 {
3654         struct ws_win           *head, *cur_focus = NULL, *winfocus = NULL;
3655         struct ws_win_list      *wl = NULL;
3656         struct workspace        *ws = NULL;
3657         int                     all_iconics;
3658
3659         if (!(r && r->ws))
3660                 return;
3661
3662         DNPRINTF(SWM_D_FOCUS, "focus: id: %d\n", args->id);
3663
3664         if ((cur_focus = r->ws->focus) == NULL)
3665                 return;
3666         ws = r->ws;
3667         wl = &ws->winlist;
3668         if (TAILQ_EMPTY(wl))
3669                 return;
3670         /* make sure there is at least one uniconified window */
3671         all_iconics = 1;
3672         TAILQ_FOREACH(winfocus, wl, entry)
3673                 if (!winfocus->iconic) {
3674                         all_iconics = 0;
3675                         break;
3676                 }
3677         if (all_iconics)
3678                 return;
3679
3680         switch (args->id) {
3681         case SWM_ARG_ID_FOCUSPREV:
3682                 head = TAILQ_PREV(cur_focus, ws_win_list, entry);
3683                 if (head == NULL)
3684                         head = TAILQ_LAST(wl, ws_win_list);
3685                 winfocus = head;
3686                 if (WINID(winfocus) == cur_focus->transient) {
3687                         head = TAILQ_PREV(winfocus, ws_win_list, entry);
3688                         if (head == NULL)
3689                                 head = TAILQ_LAST(wl, ws_win_list);
3690                         winfocus = head;
3691                 }
3692
3693                 /* skip iconics */
3694                 if (winfocus && winfocus->iconic) {
3695                         while (winfocus != cur_focus) {
3696                                 if (winfocus == NULL)
3697                                         winfocus = TAILQ_LAST(wl, ws_win_list);
3698                                 if (!winfocus->iconic)
3699                                         break;
3700                                 winfocus = TAILQ_PREV(winfocus, ws_win_list,
3701                                     entry);
3702                         }
3703                 }
3704                 break;
3705
3706         case SWM_ARG_ID_FOCUSNEXT:
3707                 head = TAILQ_NEXT(cur_focus, entry);
3708                 if (head == NULL)
3709                         head = TAILQ_FIRST(wl);
3710                 winfocus = head;
3711
3712                 /* skip iconics */
3713                 if (winfocus && winfocus->iconic) {
3714                         while (winfocus != cur_focus) {
3715                                 if (winfocus == NULL)
3716                                         winfocus = TAILQ_FIRST(wl);
3717                                 if (!winfocus->iconic)
3718                                         break;
3719                                 winfocus = TAILQ_NEXT(winfocus, entry);
3720                         }
3721                 }
3722                 break;
3723
3724         case SWM_ARG_ID_FOCUSMAIN:
3725                 winfocus = TAILQ_FIRST(wl);
3726                 if (winfocus == cur_focus)
3727                         winfocus = cur_focus->ws->focus_prev;
3728                 break;
3729
3730         default:
3731                 return;
3732         }
3733
3734         focus_win(get_focus_magic(winfocus));
3735
3736         focus_flush();
3737 }
3738
3739 void
3740 cycle_layout(struct swm_region *r, union arg *args)
3741 {
3742         struct workspace        *ws = r->ws;
3743
3744         /* suppress unused warning since var is needed */
3745         (void)args;
3746
3747         DNPRINTF(SWM_D_EVENT, "cycle_layout: workspace: %d\n", ws->idx);
3748
3749         ws->cur_layout++;
3750         if (ws->cur_layout->l_stack == NULL)
3751                 ws->cur_layout = &layouts[0];
3752
3753         stack();
3754         bar_update();
3755
3756         focus_win(get_region_focus(r));
3757
3758         focus_flush();
3759 }
3760
3761 void
3762 stack_config(struct swm_region *r, union arg *args)
3763 {
3764         struct workspace        *ws = r->ws;
3765
3766         DNPRINTF(SWM_D_STACK, "stack_config: id: %d workspace: %d\n",
3767             args->id, ws->idx);
3768
3769         if (ws->cur_layout->l_config != NULL)
3770                 ws->cur_layout->l_config(ws, args->id);
3771
3772         if (args->id != SWM_ARG_ID_STACKINIT)
3773                 stack();
3774         bar_update();
3775
3776         focus_flush();
3777 }
3778
3779 void
3780 stack(void) {
3781         struct swm_geometry     g;
3782         struct swm_region       *r;
3783         int                     i, num_screens;
3784 #ifdef SWM_DEBUG
3785         int j;
3786 #endif
3787
3788         DNPRINTF(SWM_D_STACK, "stack: begin\n");
3789
3790         num_screens = xcb_setup_roots_length(xcb_get_setup(conn));
3791         for (i = 0; i < num_screens; i++) {
3792 #ifdef SWM_DEBUG
3793                 j = 0;
3794 #endif
3795                 TAILQ_FOREACH(r, &screens[i].rl, entry) {
3796                         DNPRINTF(SWM_D_STACK, "stack: workspace: %d "
3797                             "(screen: %d, region: %d)\n", r->ws->idx, i, j++);
3798
3799                         /* start with screen geometry, adjust for bar */
3800                         g = r->g;
3801                         g.w -= 2 * border_width;
3802                         g.h -= 2 * border_width;
3803                         if (bar_enabled && r->ws->bar_enabled) {
3804                                 if (!bar_at_bottom)
3805                                         g.y += bar_height;
3806                                 g.h -= bar_height;
3807                         }
3808                         r->ws->cur_layout->l_stack(r->ws, &g);
3809                         r->ws->cur_layout->l_string(r->ws);
3810                         /* save r so we can track region changes */
3811                         r->ws->old_r = r;
3812                 }
3813         }
3814         if (font_adjusted)
3815                 font_adjusted--;
3816
3817         DNPRINTF(SWM_D_STACK, "stack: end\n");
3818 }
3819
3820 void
3821 store_float_geom(struct ws_win *win, struct swm_region *r)
3822 {
3823         if (win == NULL || r == NULL)
3824                 return;
3825
3826         /* retain window geom and region geom */
3827         win->g_float = win->g;
3828         win->g_float.x -= X(r);
3829         win->g_float.y -= Y(r);
3830         win->g_floatvalid = 1;
3831         DNPRINTF(SWM_D_MISC, "store_float_geom: window: 0x%x, g: (%d,%d)"
3832             " %d x %d, g_float: (%d,%d) %d x %d\n", win->id, X(win), Y(win),
3833             WIDTH(win), HEIGHT(win), win->g_float.x, win->g_float.y,
3834             win->g_float.w, win->g_float.h);
3835 }
3836
3837 void
3838 load_float_geom(struct ws_win *win, struct swm_region *r)
3839 {
3840         if (win == NULL || r == NULL)
3841                 return;
3842
3843         if (win->g_floatvalid) {
3844                 win->g = win->g_float;
3845                 X(win) += X(r);
3846                 Y(win) += Y(r);
3847                 DNPRINTF(SWM_D_MISC, "load_float_geom: window: 0x%x, g: (%d,%d)"
3848                     "%d x %d\n", win->id, X(win), Y(win), WIDTH(win),
3849                     HEIGHT(win));
3850         } else {
3851                 DNPRINTF(SWM_D_MISC, "load_float_geom: window: 0x%x, g_float "
3852                     "is not set.\n", win->id);
3853         }
3854 }
3855
3856 void
3857 stack_floater(struct ws_win *win, struct swm_region *r)
3858 {
3859         if (win == NULL)
3860                 return;
3861
3862         DNPRINTF(SWM_D_MISC, "stack_floater: window: 0x%x\n", win->id);
3863
3864         /*
3865          * to allow windows to change their size (e.g. mplayer fs) only retrieve
3866          * geom on ws switches or return from max mode
3867          */
3868         if (win->floatmaxed || (r != r->ws->old_r &&
3869             !(win->ewmh_flags & EWMH_F_FULLSCREEN))) {
3870                 /* update geometry for the new region */
3871                 load_float_geom(win, r);
3872         }
3873
3874         win->floatmaxed = 0;
3875
3876         /*
3877          * if set to fullscreen mode, configure window to maximum size.
3878          */
3879         if (win->ewmh_flags & EWMH_F_FULLSCREEN) {
3880                 if (!win->g_floatvalid)
3881                         store_float_geom(win, win->ws->r);
3882
3883                 win->g = r->g;
3884         }
3885
3886         /*
3887          * remove border on fullscreen floater when in fullscreen mode or when
3888          * the quirk is present.
3889          */
3890         if ((win->ewmh_flags & EWMH_F_FULLSCREEN) ||
3891             ((win->quirks & SWM_Q_FULLSCREEN) &&
3892              (WIDTH(win) >= WIDTH(r)) && (HEIGHT(win) >= HEIGHT(r)))) {
3893                 if (win->bordered) {
3894                         win->bordered = 0;
3895                         X(win) += border_width;
3896                         Y(win) += border_width;
3897                 }
3898         } else if (!win->bordered) {
3899                 win->bordered = 1;
3900                 X(win) -= border_width;
3901                 Y(win) -= border_width;
3902         }
3903
3904         if (win->transient && (win->quirks & SWM_Q_TRANSSZ)) {
3905                 WIDTH(win) = (double)WIDTH(r) * dialog_ratio;
3906                 HEIGHT(win) = (double)HEIGHT(r) * dialog_ratio;
3907         }
3908
3909         if (!win->manual && !(win->ewmh_flags & EWMH_F_FULLSCREEN) &&
3910             !(win->quirks & SWM_Q_ANYWHERE)) {
3911                 /*
3912                  * floaters and transients are auto-centred unless moved,
3913                  * resized or ANYWHERE quirk is set.
3914                  */
3915                 X(win) = X(r) + (WIDTH(r) - WIDTH(win)) /  2 - BORDER(win);
3916                 Y(win) = Y(r) + (HEIGHT(r) - HEIGHT(win)) / 2 - BORDER(win);
3917
3918                 store_float_geom(win, r);
3919         }
3920
3921         /* keep window within region bounds */
3922         constrain_window(win, r, 0);
3923
3924         update_window(win);
3925 }
3926
3927 /*
3928  * Send keystrokes to terminal to decrease/increase the font size as the
3929  * window size changes.
3930  */
3931 void
3932 adjust_font(struct ws_win *win)
3933 {
3934         if (!(win->quirks & SWM_Q_XTERM_FONTADJ) ||
3935             win->floating || win->transient)
3936                 return;
3937
3938         if (win->sh.width_inc && win->last_inc != win->sh.width_inc &&
3939             WIDTH(win) / win->sh.width_inc < term_width &&
3940             win->font_steps < SWM_MAX_FONT_STEPS) {
3941                 win->font_size_boundary[win->font_steps] =
3942                     (win->sh.width_inc * term_width) + win->sh.base_width;
3943                 win->font_steps++;
3944                 font_adjusted++;
3945                 win->last_inc = win->sh.width_inc;
3946                 fake_keypress(win, XK_KP_Subtract, XCB_MOD_MASK_SHIFT);
3947         } else if (win->font_steps && win->last_inc != win->sh.width_inc &&
3948             WIDTH(win) > win->font_size_boundary[win->font_steps - 1]) {
3949                 win->font_steps--;
3950                 font_adjusted++;
3951                 win->last_inc = win->sh.width_inc;
3952                 fake_keypress(win, XK_KP_Add, XCB_MOD_MASK_SHIFT);
3953         }
3954 }
3955
3956 #define SWAPXY(g)       do {                            \
3957         int tmp;                                        \
3958         tmp = (g)->y; (g)->y = (g)->x; (g)->x = tmp;    \
3959         tmp = (g)->h; (g)->h = (g)->w; (g)->w = tmp;    \
3960 } while (0)
3961 void
3962 stack_master(struct workspace *ws, struct swm_geometry *g, int rot, int flip)
3963 {
3964         struct swm_geometry     win_g, r_g = *g;
3965         struct ws_win           *win, *fs_win = NULL;
3966         int                     i, j, s, stacks;
3967         int                     w_inc = 1, h_inc, w_base = 1, h_base;
3968         int                     hrh, extra = 0, h_slice, last_h = 0;
3969         int                     split, colno, winno, mwin, msize, mscale;
3970         int                     remain, missing, v_slice, reconfigure = 0;
3971         int                     bordered = 1;
3972
3973         DNPRINTF(SWM_D_STACK, "stack_master: workspace: %d, rot: %s, "
3974             "flip: %s\n", ws->idx, YESNO(rot), YESNO(flip));
3975
3976         winno = count_win(ws, 0);
3977         if (winno == 0 && count_win(ws, 1) == 0)
3978                 return;
3979
3980         TAILQ_FOREACH(win, &ws->winlist, entry)
3981                 if (!win->transient && !win->floating && !win->iconic)
3982                         break;
3983
3984         if (win == NULL)
3985                 goto notiles;
3986
3987         if (rot) {
3988                 w_inc = win->sh.width_inc;
3989                 w_base = win->sh.base_width;
3990                 mwin = ws->l_state.horizontal_mwin;
3991                 mscale = ws->l_state.horizontal_msize;
3992                 stacks = ws->l_state.horizontal_stacks;
3993                 SWAPXY(&r_g);
3994         } else {
3995                 w_inc = win->sh.height_inc;
3996                 w_base = win->sh.base_height;
3997                 mwin = ws->l_state.vertical_mwin;
3998                 mscale = ws->l_state.vertical_msize;
3999                 stacks = ws->l_state.vertical_stacks;
4000         }
4001         win_g = r_g;
4002
4003         if (stacks > winno - mwin)
4004                 stacks = winno - mwin;
4005         if (stacks < 1)
4006                 stacks = 1;
4007
4008         h_slice = r_g.h / SWM_H_SLICE;
4009         if (mwin && winno > mwin) {
4010                 v_slice = r_g.w / SWM_V_SLICE;
4011
4012                 split = mwin;
4013                 colno = split;
4014                 win_g.w = v_slice * mscale;
4015
4016                 if (w_inc > 1 && w_inc < v_slice) {
4017                         /* adjust for window's requested size increment */
4018                         remain = (win_g.w - w_base) % w_inc;
4019                         win_g.w -= remain;
4020                 }
4021
4022                 msize = win_g.w;
4023                 if (flip)
4024                         win_g.x += r_g.w - msize;
4025         } else {
4026                 msize = -2;
4027                 colno = split = winno / stacks;
4028                 win_g.w = ((r_g.w - (stacks * 2 * border_width) +
4029                     2 * border_width) / stacks);
4030         }
4031         hrh = r_g.h / colno;
4032         extra = r_g.h - (colno * hrh);
4033         win_g.h = hrh - 2 * border_width;
4034
4035         /*  stack all the tiled windows */
4036         i = j = 0, s = stacks;
4037         TAILQ_FOREACH(win, &ws->winlist, entry) {
4038                 if (win->transient || win->floating)
4039                         continue;
4040                 if (win->iconic)
4041                         continue;
4042
4043                 if (win->ewmh_flags & EWMH_F_FULLSCREEN) {
4044                         fs_win = win;
4045                         continue;
4046                 }
4047
4048                 if (split && i == split) {
4049                         colno = (winno - mwin) / stacks;
4050                         if (s <= (winno - mwin) % stacks)
4051                                 colno++;
4052                         split = split + colno;
4053                         hrh = (r_g.h / colno);
4054                         extra = r_g.h - (colno * hrh);
4055                         if (flip)
4056                                 win_g.x = r_g.x;
4057                         else
4058                                 win_g.x += win_g.w + 2 * border_width;
4059                         win_g.w = (r_g.w - msize -
4060                             (stacks * 2 * border_width)) / stacks;
4061                         if (s == 1)
4062                                 win_g.w += (r_g.w - msize -
4063                                     (stacks * 2 * border_width)) % stacks;
4064                         s--;
4065                         j = 0;
4066                 }
4067                 win_g.h = hrh - 2 * border_width;
4068                 if (rot) {
4069                         h_inc = win->sh.width_inc;
4070                         h_base = win->sh.base_width;
4071                 } else {
4072                         h_inc = win->sh.height_inc;
4073                         h_base = win->sh.base_height;
4074                 }
4075                 if (j == colno - 1) {
4076                         win_g.h = hrh + extra;
4077                 } else if (h_inc > 1 && h_inc < h_slice) {
4078                         /* adjust for window's requested size increment */
4079                         remain = (win_g.h - h_base) % h_inc;
4080                         missing = h_inc - remain;
4081
4082                         if (missing <= extra || j == 0) {
4083                                 extra -= missing;
4084                                 win_g.h += missing;
4085                         } else {
4086                                 win_g.h -= remain;
4087                                 extra += remain;
4088                         }
4089                 }
4090
4091                 if (j == 0)
4092                         win_g.y = r_g.y;
4093                 else
4094                         win_g.y += last_h + 2 * border_width;
4095
4096                 if (disable_border && !(bar_enabled && ws->bar_enabled) &&
4097                     winno == 1){
4098                         bordered = 0;
4099                         win_g.w += 2 * border_width;
4100                         win_g.h += 2 * border_width;
4101                 } else {
4102                         bordered = 1;
4103                 }
4104                 if (rot) {
4105                         if (X(win) != win_g.y || Y(win) != win_g.x ||
4106                             WIDTH(win) != win_g.h || HEIGHT(win) != win_g.w) {
4107                                 reconfigure = 1;
4108                                 X(win) = win_g.y;
4109                                 Y(win) = win_g.x;
4110                                 WIDTH(win) = win_g.h;
4111                                 HEIGHT(win) = win_g.w;
4112                         }
4113                 } else {
4114                         if (X(win) != win_g.x || Y(win) != win_g.y ||
4115                             WIDTH(win) != win_g.w || HEIGHT(win) != win_g.h) {
4116                                 reconfigure = 1;
4117                                 X(win) = win_g.x;
4118                                 Y(win) = win_g.y;
4119                                 WIDTH(win) = win_g.w;
4120                                 HEIGHT(win) = win_g.h;
4121                         }
4122                 }
4123
4124                 if (bordered != win->bordered) {
4125                         reconfigure = 1;
4126                         win->bordered = bordered;
4127                 }
4128
4129                 if (reconfigure) {
4130                         adjust_font(win);
4131                         update_window(win);
4132                 }
4133
4134                 map_window(win);
4135
4136                 last_h = win_g.h;
4137                 i++;
4138                 j++;
4139         }
4140
4141 notiles:
4142         /* now, stack all the floaters and transients */
4143         TAILQ_FOREACH(win, &ws->winlist, entry) {
4144                 if (!win->transient && !win->floating)
4145                         continue;
4146                 if (win->iconic)
4147                         continue;
4148                 if (win->ewmh_flags & EWMH_F_FULLSCREEN) {
4149                         fs_win = win;
4150                         continue;
4151                 }
4152
4153                 stack_floater(win, ws->r);
4154                 map_window(win);
4155         }
4156
4157         /* Make sure fs_win is stacked last so it's on top. */
4158         if (fs_win) {
4159                 stack_floater(fs_win, ws->r);
4160                 map_window(fs_win);
4161         }
4162 }
4163
4164 void
4165 vertical_config(struct workspace *ws, int id)
4166 {
4167         DNPRINTF(SWM_D_STACK, "vertical_config: id: %d, workspace: %d\n",
4168             id, ws->idx);
4169
4170         switch (id) {
4171         case SWM_ARG_ID_STACKRESET:
4172         case SWM_ARG_ID_STACKINIT:
4173                 ws->l_state.vertical_msize = SWM_V_SLICE / 2;
4174                 ws->l_state.vertical_mwin = 1;
4175                 ws->l_state.vertical_stacks = 1;
4176                 break;
4177         case SWM_ARG_ID_MASTERSHRINK:
4178                 if (ws->l_state.vertical_msize > 1)
4179                         ws->l_state.vertical_msize--;
4180                 break;
4181         case SWM_ARG_ID_MASTERGROW:
4182                 if (ws->l_state.vertical_msize < SWM_V_SLICE - 1)
4183                         ws->l_state.vertical_msize++;
4184                 break;
4185         case SWM_ARG_ID_MASTERADD:
4186                 ws->l_state.vertical_mwin++;
4187                 break;
4188         case SWM_ARG_ID_MASTERDEL:
4189                 if (ws->l_state.vertical_mwin > 0)
4190                         ws->l_state.vertical_mwin--;
4191                 break;
4192         case SWM_ARG_ID_STACKINC:
4193                 ws->l_state.vertical_stacks++;
4194                 break;
4195         case SWM_ARG_ID_STACKDEC:
4196                 if (ws->l_state.vertical_stacks > 1)
4197                         ws->l_state.vertical_stacks--;
4198                 break;
4199         case SWM_ARG_ID_FLIPLAYOUT:
4200                 ws->l_state.vertical_flip = !ws->l_state.vertical_flip;
4201                 break;
4202         default:
4203                 return;
4204         }
4205 }
4206
4207 void
4208 vertical_stack(struct workspace *ws, struct swm_geometry *g)
4209 {
4210         DNPRINTF(SWM_D_STACK, "vertical_stack: workspace: %d\n", ws->idx);
4211
4212         stack_master(ws, g, 0, ws->l_state.vertical_flip);
4213 }
4214
4215 void
4216 horizontal_config(struct workspace *ws, int id)
4217 {
4218         DNPRINTF(SWM_D_STACK, "horizontal_config: workspace: %d\n", ws->idx);
4219
4220         switch (id) {
4221         case SWM_ARG_ID_STACKRESET:
4222         case SWM_ARG_ID_STACKINIT:
4223                 ws->l_state.horizontal_mwin = 1;
4224                 ws->l_state.horizontal_msize = SWM_H_SLICE / 2;
4225                 ws->l_state.horizontal_stacks = 1;
4226                 break;
4227         case SWM_ARG_ID_MASTERSHRINK:
4228                 if (ws->l_state.horizontal_msize > 1)
4229                         ws->l_state.horizontal_msize--;
4230                 break;
4231         case SWM_ARG_ID_MASTERGROW:
4232                 if (ws->l_state.horizontal_msize < SWM_H_SLICE - 1)
4233                         ws->l_state.horizontal_msize++;
4234                 break;
4235         case SWM_ARG_ID_MASTERADD:
4236                 ws->l_state.horizontal_mwin++;
4237                 break;
4238         case SWM_ARG_ID_MASTERDEL:
4239                 if (ws->l_state.horizontal_mwin > 0)
4240                         ws->l_state.horizontal_mwin--;
4241                 break;
4242         case SWM_ARG_ID_STACKINC:
4243                 ws->l_state.horizontal_stacks++;
4244                 break;
4245         case SWM_ARG_ID_STACKDEC:
4246                 if (ws->l_state.horizontal_stacks > 1)
4247                         ws->l_state.horizontal_stacks--;
4248                 break;
4249         case SWM_ARG_ID_FLIPLAYOUT:
4250                 ws->l_state.horizontal_flip = !ws->l_state.horizontal_flip;
4251                 break;
4252         default:
4253                 return;
4254         }
4255 }
4256
4257 void
4258 horizontal_stack(struct workspace *ws, struct swm_geometry *g)
4259 {
4260         DNPRINTF(SWM_D_STACK, "horizontal_stack: workspace: %d\n", ws->idx);
4261
4262         stack_master(ws, g, 1, ws->l_state.horizontal_flip);
4263 }
4264
4265 /* fullscreen view */
4266 void
4267 max_stack(struct workspace *ws, struct swm_geometry *g)
4268 {
4269         struct swm_geometry     gg = *g;
4270         struct ws_win           *w, *win = NULL, *parent = NULL;
4271         int                     winno, num_screens;
4272
4273         DNPRINTF(SWM_D_STACK, "max_stack: workspace: %d\n", ws->idx);
4274
4275         if (ws == NULL)
4276                 return;
4277
4278         winno = count_win(ws, 0);
4279         if (winno == 0 && count_win(ws, 1) == 0)
4280                 return;
4281
4282         /* Figure out which top level window should be visible. */
4283         if (ws->focus_pending)
4284                 win = ws->focus_pending;
4285         else if (ws->focus)
4286                 win = ws->focus;
4287         else
4288                 win = TAILQ_FIRST(&ws->winlist);
4289
4290         if (win->transient)
4291                 parent = find_window(win->transient);
4292
4293         DNPRINTF(SWM_D_STACK, "max_stack: win: 0x%x\n", win->id);
4294
4295         /* maximize all top level windows */
4296         num_screens = xcb_setup_roots_length(xcb_get_setup(conn));
4297         TAILQ_FOREACH(w, &ws->winlist, entry) {
4298                 if (w->transient || w->iconic)
4299                         continue;
4300
4301                 if (w->floating && !w->floatmaxed) {
4302                         /*
4303                          * retain geometry for retrieval on exit from
4304                          * max_stack mode
4305                          */
4306                         store_float_geom(w, ws->r);
4307                         w->floatmaxed = 1;
4308                 }
4309
4310                 /* only reconfigure if necessary */
4311                 if (X(w) != gg.x || Y(w) != gg.y || WIDTH(w) != gg.w ||
4312                     HEIGHT(w) != gg.h) {
4313                         w->g = gg;
4314                         if (bar_enabled && ws->bar_enabled){
4315                                 w->bordered = 1;
4316                         } else {
4317                                 w->bordered = 0;
4318                                 WIDTH(w) += 2 * border_width;
4319                                 HEIGHT(w) += 2 * border_width;
4320                         }
4321
4322                         update_window(w);
4323                 }
4324
4325                 /* Unmap unwanted windows if not multi-screen. */
4326                 if (!(num_screens > 1 || outputs > 1) && (w != win ||
4327                     w != parent || w->transient != win->id))
4328                         unmap_window(w);
4329         }
4330
4331         /* If a parent exists, map it first. */
4332         if (parent) {
4333                 map_window(parent);
4334
4335                 /* Map siblings next. */
4336                 TAILQ_FOREACH(w, &ws->winlist, entry)
4337                         if (w != win && !w->iconic &&
4338                             w->transient == parent->id) {
4339                                 stack_floater(w, ws->r);
4340                                 map_window(w);
4341                         }
4342         }
4343
4344         /* Map focused window. */
4345         map_window(win);
4346
4347         /* Finally, map children of focus window. */
4348         TAILQ_FOREACH(w, &ws->winlist, entry)
4349                 if (w->transient == win->id && !w->iconic) {
4350                         stack_floater(w, ws->r);
4351                         map_window(w);
4352                 }
4353 }
4354
4355 void
4356 send_to_ws(struct swm_region *r, union arg *args)
4357 {
4358         int                     wsid = args->id;
4359         struct ws_win           *win = NULL, *parent;
4360         struct workspace        *ws, *nws, *pws;
4361         char                    ws_idx_str[SWM_PROPLEN];
4362
4363         if (wsid >= workspace_limit)
4364                 return;
4365
4366         if (r && r->ws && r->ws->focus)
4367                 win = r->ws->focus;
4368         else
4369                 return;
4370
4371         if (win->ws->idx == wsid)
4372                 return;
4373
4374         DNPRINTF(SWM_D_MOVE, "send_to_ws: win 0x%x, ws %d -> %d\n", win->id,
4375             win->ws->idx, wsid);
4376
4377         ws = win->ws;
4378         nws = &win->s->ws[wsid];
4379
4380         /* Update the window's workspace property: _SWM_WS */
4381         if (snprintf(ws_idx_str, SWM_PROPLEN, "%d", nws->idx) < SWM_PROPLEN) {
4382                 if (focus_mode != SWM_FOCUS_FOLLOW)
4383                         ws->focus_pending = get_focus_prev(win);
4384
4385                 /* Move the parent if this is a transient window. */
4386                 if (win->transient) {
4387                         parent = find_window(win->transient);
4388                         if (parent) {
4389                                 pws = parent->ws;
4390                                 /* Set new focus in parent's ws if needed. */
4391                                 if (pws->focus == parent) {
4392                                         if (focus_mode != SWM_FOCUS_FOLLOW)
4393                                                 pws->focus_pending =
4394                                                     get_focus_prev(parent);
4395
4396                                         unfocus_win(parent);
4397
4398                                         if (focus_mode != SWM_FOCUS_FOLLOW)
4399                                                 pws->focus = pws->focus_pending;
4400
4401                                         if (focus_mode != SWM_FOCUS_FOLLOW)
4402                                                 pws->focus_pending = NULL;
4403                                 }
4404
4405                                 /* Don't unmap parent if new ws is visible */
4406                                 if (nws->r == NULL)
4407                                         unmap_window(parent);
4408
4409                                 /* Transfer */
4410                                 TAILQ_REMOVE(&ws->winlist, parent, entry);
4411                                 TAILQ_INSERT_TAIL(&nws->winlist, parent, entry);
4412                                 parent->ws = nws;
4413
4414                                 DNPRINTF(SWM_D_PROP, "send_to_ws: set "
4415                                     "property: _SWM_WS: %s\n", ws_idx_str);
4416                                 xcb_change_property(conn, XCB_PROP_MODE_REPLACE,
4417                                     parent->id, a_swm_ws, XCB_ATOM_STRING, 8,
4418                                     strlen(ws_idx_str), ws_idx_str);
4419                         }
4420                 }
4421
4422                 unfocus_win(win);
4423
4424                 /* Don't unmap if new ws is visible */
4425                 if (nws->r == NULL)
4426                         unmap_window(win);
4427
4428                 /* Transfer */
4429                 TAILQ_REMOVE(&ws->winlist, win, entry);
4430                 TAILQ_INSERT_TAIL(&nws->winlist, win, entry);
4431                 win->ws = nws;
4432
4433                 /* Set focus on new ws. */
4434                 unfocus_win(nws->focus);
4435                 nws->focus = win;
4436
4437                 DNPRINTF(SWM_D_PROP, "send_to_ws: set property: _SWM_WS: %s\n",
4438                     ws_idx_str);
4439                 xcb_change_property(conn, XCB_PROP_MODE_REPLACE, win->id,
4440                     a_swm_ws, XCB_ATOM_STRING, 8, strlen(ws_idx_str),
4441                     ws_idx_str);
4442
4443                 /* Restack and set new focus. */
4444                 stack();
4445
4446                 if (focus_mode != SWM_FOCUS_FOLLOW) {
4447                         focus_win(ws->focus_pending);
4448                         ws->focus_pending = NULL;
4449                 }
4450
4451                 focus_flush();
4452         }
4453
4454         DNPRINTF(SWM_D_MOVE, "send_to_ws: done.\n");
4455 }
4456
4457 void
4458 pressbutton(struct swm_region *r, union arg *args)
4459 {
4460         /* suppress unused warning since var is needed */
4461         (void)r;
4462
4463         xcb_test_fake_input(conn, XCB_BUTTON_PRESS, args->id,
4464             XCB_CURRENT_TIME, XCB_WINDOW_NONE, 0, 0, 0);
4465         xcb_test_fake_input(conn, XCB_BUTTON_RELEASE, args->id,
4466             XCB_CURRENT_TIME, XCB_WINDOW_NONE, 0, 0, 0);
4467 }
4468
4469 void
4470 raise_toggle(struct swm_region *r, union arg *args)
4471 {
4472         /* suppress unused warning since var is needed */
4473         (void)args;
4474
4475         if (r == NULL || r->ws == NULL)
4476                 return;
4477
4478         r->ws->always_raise = !r->ws->always_raise;
4479
4480         /* bring floaters back to top */
4481         if (!r->ws->always_raise)
4482                 stack();
4483
4484         focus_flush();
4485 }
4486
4487 void
4488 iconify(struct swm_region *r, union arg *args)
4489 {
4490         /* suppress unused warning since var is needed */
4491         (void)args;
4492
4493         if (r->ws->focus == NULL)
4494                 return;
4495
4496         set_swm_iconic(r->ws->focus, 1);
4497
4498         xcb_flush(conn);
4499 }
4500
4501 char *
4502 get_win_name(xcb_window_t win)
4503 {
4504         char                            *name = NULL;
4505         xcb_get_property_cookie_t       c;
4506         xcb_get_property_reply_t        *r;
4507
4508         /* First try _NET_WM_NAME for UTF-8. */
4509         c = xcb_get_property(conn, 0, win, a_netwmname,
4510             XCB_GET_PROPERTY_TYPE_ANY, 0, UINT_MAX);
4511         r = xcb_get_property_reply(conn, c, NULL);
4512
4513         if (r) {
4514                 if (r->type == XCB_NONE) {
4515                         free(r);
4516                         /* Use WM_NAME instead; no UTF-8. */
4517                         c = xcb_get_property(conn, 0, win, XCB_ATOM_WM_NAME,
4518                                 XCB_GET_PROPERTY_TYPE_ANY, 0, UINT_MAX);
4519                         r = xcb_get_property_reply(conn, c, NULL);
4520
4521                         if (!r)
4522                                 return (NULL);
4523                         if (r->type == XCB_NONE) {
4524                                 free(r);
4525                                 return (NULL);
4526                         }
4527                 }
4528                 if (r->length > 0)
4529                         name = strndup(xcb_get_property_value(r),
4530                                    xcb_get_property_value_length(r));
4531
4532                 free(r);
4533         }
4534
4535         return (name);
4536 }
4537
4538 void
4539 uniconify(struct swm_region *r, union arg *args)
4540 {
4541         struct ws_win           *win;
4542         FILE                    *lfile;
4543         char                    *name;
4544         int                     count = 0;
4545
4546         DNPRINTF(SWM_D_MISC, "uniconify\n");
4547
4548         if (r == NULL || r->ws == NULL)
4549                 return;
4550
4551         /* make sure we have anything to uniconify */
4552         TAILQ_FOREACH(win, &r->ws->winlist, entry) {
4553                 if (win->ws == NULL)
4554                         continue; /* should never happen */
4555                 if (!win->iconic)
4556                         continue;
4557                 count++;
4558         }
4559         if (count == 0)
4560                 return;
4561
4562         search_r = r;
4563         search_resp_action = SWM_SEARCH_UNICONIFY;
4564
4565         spawn_select(r, args, "search", &searchpid);
4566
4567         if ((lfile = fdopen(select_list_pipe[1], "w")) == NULL)
4568                 return;
4569
4570         TAILQ_FOREACH(win, &r->ws->winlist, entry) {
4571                 if (win->ws == NULL)
4572                         continue; /* should never happen */
4573                 if (!win->iconic)
4574                         continue;
4575
4576                 name = get_win_name(win->id);
4577                 if (name == NULL)
4578                         continue;
4579                 fprintf(lfile, "%s.%u\n", name, win->id);
4580                 free(name);
4581         }
4582
4583         fclose(lfile);
4584 }
4585
4586 void
4587 name_workspace(struct swm_region *r, union arg *args)
4588 {
4589         FILE                    *lfile;
4590
4591         DNPRINTF(SWM_D_MISC, "name_workspace\n");
4592
4593         if (r == NULL)
4594                 return;
4595
4596         search_r = r;
4597         search_resp_action = SWM_SEARCH_NAME_WORKSPACE;
4598
4599         spawn_select(r, args, "name_workspace", &searchpid);
4600
4601         if ((lfile = fdopen(select_list_pipe[1], "w")) == NULL)
4602                 return;
4603
4604         fprintf(lfile, "%s", "");
4605         fclose(lfile);
4606 }
4607
4608 void
4609 search_workspace(struct swm_region *r, union arg *args)
4610 {
4611         int                     i;
4612         struct workspace        *ws;
4613         FILE                    *lfile;
4614
4615         DNPRINTF(SWM_D_MISC, "search_workspace\n");
4616
4617         if (r == NULL)
4618                 return;
4619
4620         search_r = r;
4621         search_resp_action = SWM_SEARCH_SEARCH_WORKSPACE;
4622
4623         spawn_select(r, args, "search", &searchpid);
4624
4625         if ((lfile = fdopen(select_list_pipe[1], "w")) == NULL)
4626                 return;
4627
4628         for (i = 0; i < workspace_limit; i++) {
4629                 ws = &r->s->ws[i];
4630                 if (ws == NULL)
4631                         continue;
4632                 fprintf(lfile, "%d%s%s\n", ws->idx + 1,
4633                     (ws->name ? ":" : ""), (ws->name ? ws->name : ""));
4634         }
4635
4636         fclose(lfile);
4637 }
4638
4639 void
4640 search_win_cleanup(void)
4641 {
4642         struct search_window    *sw = NULL;
4643
4644         while ((sw = TAILQ_FIRST(&search_wl)) != NULL) {
4645                 xcb_destroy_window(conn, sw->indicator);
4646                 TAILQ_REMOVE(&search_wl, sw, entry);
4647                 free(sw);
4648         }
4649 }
4650
4651 void
4652 search_win(struct swm_region *r, union arg *args)
4653 {
4654         struct ws_win           *win = NULL;
4655         struct search_window    *sw = NULL;
4656         xcb_window_t            w;
4657         uint32_t                wa[2];
4658         int                     i, width, height;
4659         char                    s[8];
4660         FILE                    *lfile;
4661         size_t                  len;
4662         XftDraw                 *draw;
4663         XGlyphInfo              info;
4664         GC                      l_draw;
4665         XGCValues               l_gcv;
4666         XRectangle              l_ibox, l_lbox;
4667
4668         DNPRINTF(SWM_D_MISC, "search_win\n");
4669
4670         search_r = r;
4671         search_resp_action = SWM_SEARCH_SEARCH_WINDOW;
4672
4673         spawn_select(r, args, "search", &searchpid);
4674
4675         if ((lfile = fdopen(select_list_pipe[1], "w")) == NULL)
4676                 return;
4677
4678         TAILQ_INIT(&search_wl);
4679
4680         i = 1;
4681         TAILQ_FOREACH(win, &r->ws->winlist, entry) {
4682                 if (win->iconic)
4683                         continue;
4684
4685                 sw = calloc(1, sizeof(struct search_window));
4686                 if (sw == NULL) {
4687                         warn("search_win: calloc");
4688                         fclose(lfile);
4689                         search_win_cleanup();
4690                         return;
4691                 }
4692                 sw->idx = i;
4693                 sw->win = win;
4694
4695                 snprintf(s, sizeof s, "%d", i);
4696                 len = strlen(s);
4697
4698                 w = xcb_generate_id(conn);
4699                 wa[0] = r->s->c[SWM_S_COLOR_FOCUS].pixel;
4700                 wa[1] = r->s->c[SWM_S_COLOR_UNFOCUS].pixel;
4701
4702                 if (bar_font_legacy) {
4703                         XmbTextExtents(bar_fs, s, len, &l_ibox, &l_lbox);
4704                         width = l_lbox.width + 4;
4705                         height = bar_fs_extents->max_logical_extent.height + 4;
4706                 } else {
4707                         XftTextExtentsUtf8(display, bar_font, (FcChar8 *)s, len,
4708                             &info);
4709                         width = info.width + 4;
4710                         height = bar_font->height + 4;
4711                 }
4712
4713                 xcb_create_window(conn, XCB_COPY_FROM_PARENT, w, win->id, 0, 0,
4714                     width, height, 1, XCB_WINDOW_CLASS_INPUT_OUTPUT,
4715                     XCB_COPY_FROM_PARENT, XCB_CW_BACK_PIXEL |
4716                     XCB_CW_BORDER_PIXEL, wa);
4717
4718                 xcb_map_window(conn, w);
4719
4720                 sw->indicator = w;
4721                 TAILQ_INSERT_TAIL(&search_wl, sw, entry);
4722
4723                 if (bar_font_legacy) {
4724                         l_gcv.graphics_exposures = 0;
4725                         l_draw = XCreateGC(display, w, 0, &l_gcv);
4726
4727                         XSetForeground(display, l_draw,
4728                                 r->s->c[SWM_S_COLOR_BAR].pixel);
4729
4730                         DRAWSTRING(display, w, bar_fs, l_draw, 2,
4731                             (bar_fs_extents->max_logical_extent.height -
4732                             l_lbox.height) / 2 - l_lbox.y, s, len);
4733
4734                         XFreeGC(display, l_draw);
4735                 } else {
4736
4737                         draw = XftDrawCreate(display, w,
4738                             DefaultVisual(display, r->s->idx),
4739                             DefaultColormap(display, r->s->idx));
4740
4741                         XftDrawStringUtf8(draw, &bar_font_color, bar_font, 2,
4742                             (HEIGHT(r->bar) + bar_font->height) / 2 -
4743                             bar_font->descent, (FcChar8 *)s, len);
4744
4745                         XftDrawDestroy(draw);
4746                 }
4747
4748                 DNPRINTF(SWM_D_MISC, "search_win: mapped window: 0x%x\n", w);
4749
4750                 fprintf(lfile, "%d\n", i);
4751                 i++;
4752         }
4753
4754         fclose(lfile);
4755
4756         xcb_flush(conn);
4757 }
4758
4759 void
4760 search_resp_uniconify(const char *resp, unsigned long len)
4761 {
4762         char                    *name;
4763         struct ws_win           *win;
4764         char                    *s;
4765
4766         DNPRINTF(SWM_D_MISC, "search_resp_uniconify: resp: %s\n", resp);
4767
4768         TAILQ_FOREACH(win, &search_r->ws->winlist, entry) {
4769                 if (!win->iconic)
4770                         continue;
4771                 name = get_win_name(win->id);
4772                 if (name == NULL)
4773                         continue;
4774                 if (asprintf(&s, "%s.%u", name, win->id) == -1) {
4775                         free(name);
4776                         continue;
4777                 }
4778                 free(name);
4779                 if (strncmp(s, resp, len) == 0) {
4780                         /* XXX this should be a callback to generalize */
4781                         set_swm_iconic(win, 0);
4782                         free(s);
4783                         break;
4784                 }
4785                 free(s);
4786         }
4787 }
4788
4789 void
4790 search_resp_name_workspace(const char *resp, unsigned long len)
4791 {
4792         struct workspace        *ws;
4793
4794         DNPRINTF(SWM_D_MISC, "search_resp_name_workspace: resp: %s\n", resp);
4795
4796         if (search_r->ws == NULL)
4797                 return;
4798         ws = search_r->ws;
4799
4800         if (ws->name) {
4801                 free(search_r->ws->name);
4802                 search_r->ws->name = NULL;
4803         }
4804
4805         if (len > 1) {
4806                 ws->name = strdup(resp);
4807                 if (ws->name == NULL) {
4808                         DNPRINTF(SWM_D_MISC, "search_resp_name_workspace: "
4809                             "strdup: %s", strerror(errno));
4810                         return;
4811                 }
4812         }
4813 }
4814
4815 void
4816 search_resp_search_workspace(const char *resp)
4817 {
4818         char                    *p, *q;
4819         int                     ws_idx;
4820         const char              *errstr;
4821         union arg               a;
4822
4823         DNPRINTF(SWM_D_MISC, "search_resp_search_workspace: resp: %s\n", resp);
4824
4825         q = strdup(resp);
4826         if (!q) {
4827                 DNPRINTF(SWM_D_MISC, "search_resp_search_workspace: strdup: %s",
4828                     strerror(errno));
4829                 return;
4830         }
4831         p = strchr(q, ':');
4832         if (p != NULL)
4833                 *p = '\0';
4834         ws_idx = (int)strtonum(q, 1, workspace_limit, &errstr);
4835         if (errstr) {
4836                 DNPRINTF(SWM_D_MISC, "workspace idx is %s: %s",
4837                     errstr, q);
4838                 free(q);
4839                 return;
4840         }
4841         free(q);
4842         a.id = ws_idx - 1;
4843         switchws(search_r, &a);
4844 }
4845
4846 void
4847 search_resp_search_window(const char *resp)
4848 {
4849         char                    *s;
4850         int                     idx;
4851         const char              *errstr;
4852         struct search_window    *sw;
4853
4854         DNPRINTF(SWM_D_MISC, "search_resp_search_window: resp: %s\n", resp);
4855
4856         s = strdup(resp);
4857         if (!s) {
4858                 DNPRINTF(SWM_D_MISC, "search_resp_search_window: strdup: %s",
4859                     strerror(errno));
4860                 return;
4861         }
4862
4863         idx = (int)strtonum(s, 1, INT_MAX, &errstr);
4864         if (errstr) {
4865                 DNPRINTF(SWM_D_MISC, "window idx is %s: %s",
4866                     errstr, s);
4867                 free(s);
4868                 return;
4869         }
4870         free(s);
4871
4872         TAILQ_FOREACH(sw, &search_wl, entry)
4873                 if (idx == sw->idx) {
4874                         focus_win(sw->win);
4875                         break;
4876                 }
4877 }
4878
4879 #define MAX_RESP_LEN    1024
4880
4881 void
4882 search_do_resp(void)
4883 {
4884         ssize_t                 rbytes;
4885         char                    *resp;
4886         unsigned long           len;
4887
4888         DNPRINTF(SWM_D_MISC, "search_do_resp:\n");
4889
4890         search_resp = 0;
4891         searchpid = 0;
4892
4893         if ((resp = calloc(1, MAX_RESP_LEN + 1)) == NULL) {
4894                 warn("search: calloc");
4895                 goto done;
4896         }
4897
4898         rbytes = read(select_resp_pipe[0], resp, MAX_RESP_LEN);
4899         if (rbytes <= 0) {
4900                 warn("search: read error");
4901                 goto done;
4902         }
4903         resp[rbytes] = '\0';
4904
4905         /* XXX:
4906          * Older versions of dmenu (Atleast pre 4.4.1) do not send a
4907          * newline, so work around that by sanitizing the resp now.
4908          */
4909         resp[strcspn(resp, "\n")] = '\0';
4910         len = strlen(resp);
4911
4912         switch (search_resp_action) {
4913         case SWM_SEARCH_UNICONIFY:
4914                 search_resp_uniconify(resp, len);
4915                 break;
4916         case SWM_SEARCH_NAME_WORKSPACE:
4917                 search_resp_name_workspace(resp, len);
4918                 break;
4919         case SWM_SEARCH_SEARCH_WORKSPACE:
4920                 search_resp_search_workspace(resp);
4921                 break;
4922         case SWM_SEARCH_SEARCH_WINDOW:
4923                 search_resp_search_window(resp);
4924                 break;
4925         }
4926
4927 done:
4928         if (search_resp_action == SWM_SEARCH_SEARCH_WINDOW)
4929                 search_win_cleanup();
4930
4931         search_resp_action = SWM_SEARCH_NONE;
4932         close(select_resp_pipe[0]);
4933         free(resp);
4934
4935         xcb_flush(conn);
4936 }
4937
4938 void
4939 wkill(struct swm_region *r, union arg *args)
4940 {
4941         DNPRINTF(SWM_D_MISC, "wkill: id: %d\n", args->id);
4942
4943         if (r->ws->focus == NULL)
4944                 return;
4945
4946         if (args->id == SWM_ARG_ID_KILLWINDOW)
4947                 xcb_kill_client(conn, r->ws->focus->id);
4948         else
4949                 if (r->ws->focus->can_delete)
4950                         client_msg(r->ws->focus, a_delete, 0);
4951
4952         focus_flush();
4953 }
4954
4955 int
4956 floating_toggle_win(struct ws_win *win)
4957 {
4958         struct swm_region       *r;
4959
4960         if (win == NULL)
4961                 return (0);
4962
4963         if (!win->ws->r)
4964                 return (0);
4965
4966         r = win->ws->r;
4967
4968         /* reject floating toggles in max stack mode */
4969         if (win->ws->cur_layout == &layouts[SWM_MAX_STACK])
4970                 return (0);
4971
4972         if (win->floating) {
4973                 if (!win->floatmaxed) {
4974                         /* retain position for refloat */
4975                         store_float_geom(win, r);
4976                 }
4977                 win->floating = 0;
4978         } else {
4979                 load_float_geom(win, r);
4980                 win->floating = 1;
4981         }
4982
4983         ewmh_update_actions(win);
4984
4985         return (1);
4986 }
4987
4988 void
4989 floating_toggle(struct swm_region *r, union arg *args)
4990 {
4991         struct ws_win           *win = r->ws->focus;
4992
4993         /* suppress unused warning since var is needed */
4994         (void)args;
4995
4996         if (win == NULL)
4997                 return;
4998
4999         if (win->ewmh_flags & EWMH_F_FULLSCREEN)
5000                 return;
5001
5002         ewmh_update_win_state(win, ewmh[_NET_WM_STATE_ABOVE].atom,
5003             _NET_WM_STATE_TOGGLE);
5004
5005         stack();
5006
5007         if (win == win->ws->focus)
5008                 focus_win(win);
5009
5010         focus_flush();
5011 }
5012
5013 void
5014 constrain_window(struct ws_win *win, struct swm_region *r, int resizable)
5015 {
5016         if (MAX_X(win) + BORDER(win) > MAX_X(r)) {
5017                 if (resizable)
5018                         WIDTH(win) = MAX_X(r) - X(win) - BORDER(win);
5019                 else
5020                         X(win) = MAX_X(r)- WIDTH(win) - BORDER(win);
5021         }
5022
5023         if (X(win) + BORDER(win) < X(r)) {
5024                 if (resizable)
5025                         WIDTH(win) -= X(r) - X(win) - BORDER(win);
5026
5027                 X(win) = X(r) - BORDER(win);
5028         }
5029
5030         if (MAX_Y(win) + BORDER(win) > MAX_Y(r)) {
5031                 if (resizable)
5032                         HEIGHT(win) = MAX_Y(r) - Y(win) - BORDER(win);
5033                 else
5034                         Y(win) = MAX_Y(r) - HEIGHT(win) - BORDER(win);
5035         }
5036
5037         if (Y(win) + BORDER(win) < Y(r)) {
5038                 if (resizable)
5039                         HEIGHT(win) -= Y(r) - Y(win) - BORDER(win);
5040
5041                 Y(win) = Y(r) - BORDER(win);
5042         }
5043
5044         if (resizable) {
5045                 if (WIDTH(win) < 1)
5046                         WIDTH(win) = 1;
5047                 if (HEIGHT(win) < 1)
5048                         HEIGHT(win) = 1;
5049         }
5050 }
5051
5052 void
5053 update_window(struct ws_win *win)
5054 {
5055         uint16_t        mask;
5056         uint32_t        wc[5];
5057
5058         mask = XCB_CONFIG_WINDOW_X | XCB_CONFIG_WINDOW_Y |
5059             XCB_CONFIG_WINDOW_WIDTH | XCB_CONFIG_WINDOW_HEIGHT |
5060             XCB_CONFIG_WINDOW_BORDER_WIDTH;
5061         wc[0] = X(win);
5062         wc[1] = Y(win);
5063         wc[2] = WIDTH(win);
5064         wc[3] = HEIGHT(win);
5065         wc[4] = BORDER(win);
5066
5067         DNPRINTF(SWM_D_EVENT, "update_window: window: 0x%x, (x,y) w x h: "
5068             "(%d,%d) %d x %d, bordered: %s\n", win->id, wc[0], wc[1], wc[2],
5069             wc[3], YESNO(win->bordered));
5070
5071         xcb_configure_window(conn, win->id, mask, wc);
5072 }
5073
5074 #define SWM_RESIZE_STEPS        (50)
5075
5076 void
5077 resize(struct ws_win *win, union arg *args)
5078 {
5079         xcb_timestamp_t         timestamp = 0;
5080         struct swm_region       *r = NULL;
5081         int                     resize_stp = 0;
5082         struct swm_geometry     g;
5083         int                     top = 0, left = 0, resizing;
5084         int                     dx, dy;
5085         xcb_cursor_t                    cursor;
5086         xcb_query_pointer_reply_t       *xpr;
5087         xcb_generic_event_t             *evt;
5088         xcb_motion_notify_event_t       *mne;
5089
5090         if (win == NULL)
5091                 return;
5092         r = win->ws->r;
5093
5094         if (win->ewmh_flags & EWMH_F_FULLSCREEN)
5095                 return;
5096
5097         DNPRINTF(SWM_D_EVENT, "resize: window: 0x%x, floating: %s, "
5098             "transient: 0x%x\n", win->id, YESNO(win->floating),
5099             win->transient);
5100
5101         if (!win->transient && !win->floating)
5102                 return;
5103
5104         /* reject resizes in max mode for floaters (transient ok) */
5105         if (win->floatmaxed)
5106                 return;
5107
5108         win->manual = 1;
5109         ewmh_update_win_state(win, ewmh[_SWM_WM_STATE_MANUAL].atom,
5110             _NET_WM_STATE_ADD);
5111
5112         stack();
5113
5114         focus_flush();
5115
5116         switch (args->id) {
5117         case SWM_ARG_ID_WIDTHSHRINK:
5118                 WIDTH(win) -= SWM_RESIZE_STEPS;
5119                 resize_stp = 1;
5120                 break;
5121         case SWM_ARG_ID_WIDTHGROW:
5122                 WIDTH(win) += SWM_RESIZE_STEPS;
5123                 resize_stp = 1;
5124                 break;
5125         case SWM_ARG_ID_HEIGHTSHRINK:
5126                 HEIGHT(win) -= SWM_RESIZE_STEPS;
5127                 resize_stp = 1;
5128                 break;
5129         case SWM_ARG_ID_HEIGHTGROW:
5130                 HEIGHT(win) += SWM_RESIZE_STEPS;
5131                 resize_stp = 1;
5132                 break;
5133         default:
5134                 break;
5135         }
5136         if (resize_stp) {
5137                 constrain_window(win, r, 1);
5138                 update_window(win);
5139                 store_float_geom(win,r);
5140                 return;
5141         }
5142
5143         /* get cursor offset from window root */
5144         xpr = xcb_query_pointer_reply(conn, xcb_query_pointer(conn, win->id),
5145             NULL);
5146         if (!xpr)
5147                 return;
5148
5149         g = win->g;
5150
5151         if (xpr->win_x < WIDTH(win) / 2)
5152                 left = 1;
5153
5154         if (xpr->win_y < HEIGHT(win) / 2)
5155                 top = 1;
5156
5157         if (args->id == SWM_ARG_ID_CENTER)
5158                 cursor = cursors[XC_SIZING].cid;
5159         else if (top)
5160                 cursor = cursors[left ? XC_TOP_LEFT_CORNER :
5161                     XC_TOP_RIGHT_CORNER].cid;
5162         else
5163                 cursor = cursors[left ? XC_BOTTOM_LEFT_CORNER :
5164                     XC_BOTTOM_RIGHT_CORNER].cid;
5165
5166         xcb_grab_pointer(conn, 0, win->id, MOUSEMASK,
5167             XCB_GRAB_MODE_ASYNC, XCB_GRAB_MODE_ASYNC, XCB_WINDOW_NONE, cursor,
5168             XCB_CURRENT_TIME),
5169
5170         xcb_flush(conn);
5171         resizing = 1;
5172         while ((evt = xcb_wait_for_event(conn)) && resizing) {
5173                 switch (XCB_EVENT_RESPONSE_TYPE(evt)) {
5174                 case XCB_BUTTON_RELEASE:
5175                         DNPRINTF(SWM_D_EVENT, "resize: BUTTON_RELEASE\n");
5176                         resizing = 0;
5177                         break;
5178                 case XCB_MOTION_NOTIFY:
5179                         mne = (xcb_motion_notify_event_t *)evt;
5180                         /* cursor offset/delta from start of the operation */
5181                         dx = mne->root_x - xpr->root_x;
5182                         dy = mne->root_y - xpr->root_y;
5183
5184                         /* vertical */
5185                         if (top)
5186                                 dy = -dy;
5187
5188                         if (args->id == SWM_ARG_ID_CENTER) {
5189                                 if (g.h / 2 + dy < 1)
5190                                         dy = 1 - g.h / 2;
5191
5192                                 Y(win) = g.y - dy;
5193                                 HEIGHT(win) = g.h + 2 * dy;
5194                         } else {
5195                                 if (g.h + dy < 1)
5196                                         dy = 1 - g.h;
5197
5198                                 if (top)
5199                                         Y(win) = g.y - dy;
5200
5201                                 HEIGHT(win) = g.h + dy;
5202                         }
5203
5204                         /* horizontal */
5205                         if (left)
5206                                 dx = -dx;
5207
5208                         if (args->id == SWM_ARG_ID_CENTER) {
5209                                 if (g.w / 2 + dx < 1)
5210                                         dx = 1 - g.w / 2;
5211
5212                                 X(win) = g.x - dx;
5213                                 WIDTH(win) = g.w + 2 * dx;
5214                         } else {
5215                                 if (g.w + dx < 1)
5216                                         dx = 1 - g.w;
5217
5218                                 if (left)
5219                                         X(win) = g.x - dx;
5220
5221                                 WIDTH(win) = g.w + dx;
5222                         }
5223
5224                         constrain_window(win, r, 1);
5225
5226                         /* not free, don't sync more than 120 times / second */
5227                         if ((mne->time - timestamp) > (1000 / 120) ) {
5228                                 timestamp = mne->time;
5229                                 update_window(win);
5230                                 xcb_flush(conn);
5231                         }
5232                         break;
5233                 default:
5234                         event_handle(evt);
5235                         break;
5236                 }
5237                 free(evt);
5238         }
5239         if (timestamp) {
5240                 update_window(win);
5241                 xcb_flush(conn);
5242         }
5243         store_float_geom(win,r);
5244
5245         xcb_ungrab_pointer(conn, XCB_CURRENT_TIME);
5246         free(xpr);
5247         DNPRINTF(SWM_D_EVENT, "resize: done.\n");
5248 }
5249
5250 void
5251 resize_step(struct swm_region *r, union arg *args)
5252 {
5253         struct ws_win           *win = NULL;
5254
5255         if (r && r->ws && r->ws->focus)
5256                 win = r->ws->focus;
5257         else
5258                 return;
5259
5260         resize(win, args);
5261         focus_flush();
5262 }
5263
5264 #define SWM_MOVE_STEPS  (50)
5265
5266 void
5267 move(struct ws_win *win, union arg *args)
5268 {
5269         xcb_timestamp_t         timestamp = 0;
5270         int                     move_stp = 0, moving;
5271         struct swm_region       *r = NULL;
5272         xcb_query_pointer_reply_t       *qpr;
5273         xcb_generic_event_t             *evt;
5274         xcb_motion_notify_event_t       *mne;
5275
5276         if (win == NULL)
5277                 return;
5278         r = win->ws->r;
5279
5280         if (win->ewmh_flags & EWMH_F_FULLSCREEN)
5281                 return;
5282
5283         DNPRINTF(SWM_D_EVENT, "move: window: 0x%x, floating: %s, transient: "
5284             "0x%x\n", win->id, YESNO(win->floating), win->transient);
5285
5286         /* in max_stack mode should only move transients */
5287         if (win->ws->cur_layout == &layouts[SWM_MAX_STACK] && !win->transient)
5288                 return;
5289
5290         win->manual = 1;
5291         if (!win->floating && !win->transient) {
5292                 store_float_geom(win, r);
5293                 ewmh_update_win_state(win, ewmh[_NET_WM_STATE_ABOVE].atom,
5294                     _NET_WM_STATE_ADD);
5295         }
5296         ewmh_update_win_state(win, ewmh[_SWM_WM_STATE_MANUAL].atom,
5297             _NET_WM_STATE_ADD);
5298
5299         stack();
5300
5301         focus_flush();
5302
5303         move_stp = 0;
5304         switch (args->id) {
5305         case SWM_ARG_ID_MOVELEFT:
5306                 X(win) -= (SWM_MOVE_STEPS - border_width);
5307                 move_stp = 1;
5308                 break;
5309         case SWM_ARG_ID_MOVERIGHT:
5310                 X(win) += (SWM_MOVE_STEPS - border_width);
5311                 move_stp = 1;
5312                 break;
5313         case SWM_ARG_ID_MOVEUP:
5314                 Y(win) -= (SWM_MOVE_STEPS - border_width);
5315                 move_stp = 1;
5316                 break;
5317         case SWM_ARG_ID_MOVEDOWN:
5318                 Y(win) += (SWM_MOVE_STEPS - border_width);
5319                 move_stp = 1;
5320                 break;
5321         default:
5322                 break;
5323         }
5324         if (move_stp) {
5325                 constrain_window(win, r, 0);
5326                 update_window(win);
5327                 store_float_geom(win, r);
5328                 return;
5329         }
5330
5331         xcb_grab_pointer(conn, 0, win->id, MOUSEMASK,
5332             XCB_GRAB_MODE_ASYNC, XCB_GRAB_MODE_ASYNC,
5333             XCB_WINDOW_NONE, cursors[XC_FLEUR].cid, XCB_CURRENT_TIME);
5334
5335         /* get cursor offset from window root */
5336         qpr = xcb_query_pointer_reply(conn, xcb_query_pointer(conn, win->id),
5337                 NULL);
5338         if (!qpr) {
5339                 xcb_ungrab_pointer(conn, XCB_CURRENT_TIME);
5340                 return;
5341         }
5342
5343         xcb_flush(conn);
5344         moving = 1;
5345         while ((evt = xcb_wait_for_event(conn)) && moving) {
5346                 switch (XCB_EVENT_RESPONSE_TYPE(evt)) {
5347                 case XCB_BUTTON_RELEASE:
5348                         DNPRINTF(SWM_D_EVENT, "move: BUTTON_RELEASE\n");
5349                         moving = 0;
5350                         break;
5351                 case XCB_MOTION_NOTIFY:
5352                         mne = (xcb_motion_notify_event_t *)evt;
5353                         X(win) = mne->root_x - qpr->win_x - border_width;
5354                         Y(win) = mne->root_y - qpr->win_y - border_width;
5355
5356                         constrain_window(win, r, 0);
5357
5358                         /* not free, don't sync more than 120 times / second */
5359                         if ((mne->time - timestamp) > (1000 / 120) ) {
5360                                 timestamp = mne->time;
5361                                 update_window(win);
5362                                 xcb_flush(conn);
5363                         }
5364                         break;
5365                 default:
5366                         event_handle(evt);
5367                         break;
5368                 }
5369                 free(evt);
5370         }
5371         if (timestamp) {
5372                 update_window(win);
5373                 xcb_flush(conn);
5374         }
5375         store_float_geom(win, r);
5376         free(qpr);
5377         xcb_ungrab_pointer(conn, XCB_CURRENT_TIME);
5378         DNPRINTF(SWM_D_EVENT, "move: done.\n");
5379 }
5380
5381 void
5382 move_step(struct swm_region *r, union arg *args)
5383 {
5384         struct ws_win           *win = NULL;
5385
5386         if (r && r->ws && r->ws->focus)
5387                 win = r->ws->focus;
5388         else
5389                 return;
5390
5391         if (!win->transient && !win->floating)
5392                 return;
5393
5394         move(win, args);
5395         focus_flush();
5396 }
5397
5398 /* key definitions */
5399 struct keyfunc {
5400         char                    name[SWM_FUNCNAME_LEN];
5401         void                    (*func)(struct swm_region *r, union arg *);
5402         union arg               args;
5403 } keyfuncs[KF_INVALID + 1] = {
5404         /* name                 function        argument */
5405         { "bar_toggle",         bar_toggle,     {.id = SWM_ARG_ID_BAR_TOGGLE} },
5406         { "bar_toggle_ws",      bar_toggle,     {.id = SWM_ARG_ID_BAR_TOGGLE_WS} },
5407         { "button2",            pressbutton,    {2} },
5408         { "cycle_layout",       cycle_layout,   {0} },
5409         { "flip_layout",        stack_config,   {.id = SWM_ARG_ID_FLIPLAYOUT} },
5410         { "float_toggle",       floating_toggle,{0} },
5411         { "focus_main",         focus,          {.id = SWM_ARG_ID_FOCUSMAIN} },
5412         { "focus_next",         focus,          {.id = SWM_ARG_ID_FOCUSNEXT} },
5413         { "focus_prev",         focus,          {.id = SWM_ARG_ID_FOCUSPREV} },
5414         { "height_grow",        resize_step,    {.id = SWM_ARG_ID_HEIGHTGROW} },
5415         { "height_shrink",      resize_step,    {.id = SWM_ARG_ID_HEIGHTSHRINK} },
5416         { "iconify",            iconify,        {0} },
5417         { "master_shrink",      stack_config,   {.id = SWM_ARG_ID_MASTERSHRINK} },
5418         { "master_grow",        stack_config,   {.id = SWM_ARG_ID_MASTERGROW} },
5419         { "master_add",         stack_config,   {.id = SWM_ARG_ID_MASTERADD} },
5420         { "master_del",         stack_config,   {.id = SWM_ARG_ID_MASTERDEL} },
5421         { "move_down",          move_step,      {.id = SWM_ARG_ID_MOVEDOWN} },
5422         { "move_left",          move_step,      {.id = SWM_ARG_ID_MOVELEFT} },
5423         { "move_right",         move_step,      {.id = SWM_ARG_ID_MOVERIGHT} },
5424         { "move_up",            move_step,      {.id = SWM_ARG_ID_MOVEUP} },
5425         { "mvws_1",             send_to_ws,     {.id = 0} },
5426         { "mvws_2",             send_to_ws,     {.id = 1} },
5427         { "mvws_3",             send_to_ws,     {.id = 2} },
5428         { "mvws_4",             send_to_ws,     {.id = 3} },
5429         { "mvws_5",             send_to_ws,     {.id = 4} },
5430         { "mvws_6",             send_to_ws,     {.id = 5} },
5431         { "mvws_7",             send_to_ws,     {.id = 6} },
5432         { "mvws_8",             send_to_ws,     {.id = 7} },
5433         { "mvws_9",             send_to_ws,     {.id = 8} },
5434         { "mvws_10",            send_to_ws,     {.id = 9} },
5435         { "mvws_11",            send_to_ws,     {.id = 10} },
5436         { "mvws_12",            send_to_ws,     {.id = 11} },
5437         { "mvws_13",            send_to_ws,     {.id = 12} },
5438         { "mvws_14",            send_to_ws,     {.id = 13} },
5439         { "mvws_15",            send_to_ws,     {.id = 14} },
5440         { "mvws_16",            send_to_ws,     {.id = 15} },
5441         { "mvws_17",            send_to_ws,     {.id = 16} },
5442         { "mvws_18",            send_to_ws,     {.id = 17} },
5443         { "mvws_19",            send_to_ws,     {.id = 18} },
5444         { "mvws_20",            send_to_ws,     {.id = 19} },
5445         { "mvws_21",            send_to_ws,     {.id = 20} },
5446         { "mvws_22",            send_to_ws,     {.id = 21} },
5447         { "name_workspace",     name_workspace, {0} },
5448         { "quit",               quit,           {0} },
5449         { "raise_toggle",       raise_toggle,   {0} },
5450         { "restart",            restart,        {0} },
5451         { "screen_next",        cyclescr,       {.id = SWM_ARG_ID_CYCLESC_UP} },
5452         { "screen_prev",        cyclescr,       {.id = SWM_ARG_ID_CYCLESC_DOWN} },
5453         { "search_win",         search_win,     {0} },
5454         { "search_workspace",   search_workspace,       {0} },
5455         { "spawn_custom",       NULL,           {0} },
5456         { "stack_inc",          stack_config,   {.id = SWM_ARG_ID_STACKINC} },
5457         { "stack_dec",          stack_config,   {.id = SWM_ARG_ID_STACKDEC} },
5458         { "stack_reset",        stack_config,   {.id = SWM_ARG_ID_STACKRESET} },
5459         { "swap_main",          swapwin,        {.id = SWM_ARG_ID_SWAPMAIN} },
5460         { "swap_next",          swapwin,        {.id = SWM_ARG_ID_SWAPNEXT} },
5461         { "swap_prev",          swapwin,        {.id = SWM_ARG_ID_SWAPPREV} },
5462         { "uniconify",          uniconify,      {0} },
5463         { "version",            version,        {0} },
5464         { "width_grow",         resize_step,    {.id = SWM_ARG_ID_WIDTHGROW} },
5465         { "width_shrink",       resize_step,    {.id = SWM_ARG_ID_WIDTHSHRINK} },
5466         { "wind_del",           wkill,          {.id = SWM_ARG_ID_DELETEWINDOW} },
5467         { "wind_kill",          wkill,          {.id = SWM_ARG_ID_KILLWINDOW} },
5468         { "ws_1",               switchws,       {.id = 0} },
5469         { "ws_2",               switchws,       {.id = 1} },
5470         { "ws_3",               switchws,       {.id = 2} },
5471         { "ws_4",               switchws,       {.id = 3} },
5472         { "ws_5",               switchws,       {.id = 4} },
5473         { "ws_6",               switchws,       {.id = 5} },
5474         { "ws_7",               switchws,       {.id = 6} },
5475         { "ws_8",               switchws,       {.id = 7} },
5476         { "ws_9",               switchws,       {.id = 8} },
5477         { "ws_10",              switchws,       {.id = 9} },
5478         { "ws_11",              switchws,       {.id = 10} },
5479         { "ws_12",              switchws,       {.id = 11} },
5480         { "ws_13",              switchws,       {.id = 12} },
5481         { "ws_14",              switchws,       {.id = 13} },
5482         { "ws_15",              switchws,       {.id = 14} },
5483         { "ws_16",              switchws,       {.id = 15} },
5484         { "ws_17",              switchws,       {.id = 16} },
5485         { "ws_18",              switchws,       {.id = 17} },
5486         { "ws_19",              switchws,       {.id = 18} },
5487         { "ws_20",              switchws,       {.id = 19} },
5488         { "ws_21",              switchws,       {.id = 20} },
5489         { "ws_22",              switchws,       {.id = 21} },
5490         { "ws_next",            cyclews,        {.id = SWM_ARG_ID_CYCLEWS_UP} },
5491         { "ws_next_all",        cyclews,        {.id = SWM_ARG_ID_CYCLEWS_UP_ALL} },
5492         { "ws_prev",            cyclews,        {.id = SWM_ARG_ID_CYCLEWS_DOWN} },
5493         { "ws_prev_all",        cyclews,        {.id = SWM_ARG_ID_CYCLEWS_DOWN_ALL} },
5494         { "ws_prior",           priorws,        {0} },
5495         { "dumpwins",           dumpwins,       {0} }, /* MUST BE LAST */
5496         { "invalid key func",   NULL,           {0} },
5497 };
5498
5499 int
5500 key_cmp(struct key *kp1, struct key *kp2)
5501 {
5502         if (kp1->keysym < kp2->keysym)
5503                 return (-1);
5504         if (kp1->keysym > kp2->keysym)
5505                 return (1);
5506
5507         if (kp1->mod < kp2->mod)
5508                 return (-1);
5509         if (kp1->mod > kp2->mod)
5510                 return (1);
5511
5512         return (0);
5513 }
5514
5515 /* mouse */
5516 enum { client_click, root_click };
5517 struct button {
5518         unsigned int            action;
5519         unsigned int            mask;
5520         unsigned int            button;
5521         void                    (*func)(struct ws_win *, union arg *);
5522         union arg               args;
5523 } buttons[] = {
5524 #define MODKEY_SHIFT    MODKEY | XCB_MOD_MASK_SHIFT
5525           /* action     key             mouse button    func    args */
5526         { client_click, MODKEY,         XCB_BUTTON_INDEX_3,     resize, {.id = SWM_ARG_ID_DONTCENTER} },
5527         { client_click, MODKEY_SHIFT,   XCB_BUTTON_INDEX_3,     resize, {.id = SWM_ARG_ID_CENTER} },
5528         { client_click, MODKEY,         XCB_BUTTON_INDEX_1,     move,   {0} },
5529 #undef MODKEY_SHIFT
5530 };
5531
5532 void
5533 update_modkey(unsigned int mod)
5534 {
5535         int                     i;
5536         struct key              *kp;
5537
5538         mod_key = mod;
5539         RB_FOREACH(kp, key_tree, &keys)
5540                 if (kp->mod & XCB_MOD_MASK_SHIFT)
5541                         kp->mod = mod | XCB_MOD_MASK_SHIFT;
5542                 else
5543                         kp->mod = mod;
5544
5545         for (i = 0; i < LENGTH(buttons); i++)
5546                 if (buttons[i].mask & XCB_MOD_MASK_SHIFT)
5547                         buttons[i].mask = mod | XCB_MOD_MASK_SHIFT;
5548                 else
5549                         buttons[i].mask = mod;
5550 }
5551
5552 int
5553 spawn_expand(struct swm_region *r, union arg *args, const char *spawn_name,
5554     char ***ret_args)
5555 {
5556         struct spawn_prog       *prog = NULL;
5557         int                     i;
5558         char                    *ap, **real_args;
5559
5560         /* suppress unused warning since var is needed */
5561         (void)args;
5562
5563         DNPRINTF(SWM_D_SPAWN, "spawn_expand: %s\n", spawn_name);
5564
5565         /* find program */
5566         TAILQ_FOREACH(prog, &spawns, entry) {
5567                 if (!strcasecmp(spawn_name, prog->name))
5568                         break;
5569         }
5570         if (prog == NULL) {
5571                 warnx("spawn_custom: program %s not found", spawn_name);
5572                 return (-1);
5573         }
5574
5575         /* make room for expanded args */
5576         if ((real_args = calloc(prog->argc + 1, sizeof(char *))) == NULL)
5577                 err(1, "spawn_custom: calloc real_args");
5578
5579         /* expand spawn_args into real_args */
5580         for (i = 0; i < prog->argc; i++) {
5581                 ap = prog->argv[i];
5582                 DNPRINTF(SWM_D_SPAWN, "spawn_custom: raw arg: %s\n", ap);
5583                 if (!strcasecmp(ap, "$bar_border")) {
5584                         if ((real_args[i] =
5585                             strdup(r->s->c[SWM_S_COLOR_BAR_BORDER].name))
5586                             == NULL)
5587                                 err(1,  "spawn_custom border color");
5588                 } else if (!strcasecmp(ap, "$bar_color")) {
5589                         if ((real_args[i] =
5590                             strdup(r->s->c[SWM_S_COLOR_BAR].name))
5591                             == NULL)
5592                                 err(1, "spawn_custom bar color");
5593                 } else if (!strcasecmp(ap, "$bar_font")) {
5594                         if ((real_args[i] = strdup(bar_fonts))
5595                             == NULL)
5596                                 err(1, "spawn_custom bar fonts");
5597                 } else if (!strcasecmp(ap, "$bar_font_color")) {
5598                         if ((real_args[i] =
5599                             strdup(r->s->c[SWM_S_COLOR_BAR_FONT].name))
5600                             == NULL)
5601                                 err(1, "spawn_custom color font");
5602                 } else if (!strcasecmp(ap, "$color_focus")) {
5603                         if ((real_args[i] =
5604                             strdup(r->s->c[SWM_S_COLOR_FOCUS].name))
5605                             == NULL)
5606                                 err(1, "spawn_custom color focus");
5607                 } else if (!strcasecmp(ap, "$color_unfocus")) {
5608                         if ((real_args[i] =
5609                             strdup(r->s->c[SWM_S_COLOR_UNFOCUS].name))
5610                             == NULL)
5611                                 err(1, "spawn_custom color unfocus");
5612                 } else {
5613                         /* no match --> copy as is */
5614                         if ((real_args[i] = strdup(ap)) == NULL)
5615                                 err(1, "spawn_custom strdup(ap)");
5616                 }
5617                 DNPRINTF(SWM_D_SPAWN, "spawn_custom: cooked arg: %s\n",
5618                     real_args[i]);
5619         }
5620
5621 #ifdef SWM_DEBUG
5622         DNPRINTF(SWM_D_SPAWN, "spawn_custom: result: ");
5623         for (i = 0; i < prog->argc; i++)
5624                 DNPRINTF(SWM_D_SPAWN, "\"%s\" ", real_args[i]);
5625         DNPRINTF(SWM_D_SPAWN, "\n");
5626 #endif
5627         *ret_args = real_args;
5628         return (prog->argc);
5629 }
5630
5631 void
5632 spawn_custom(struct swm_region *r, union arg *args, const char *spawn_name)
5633 {
5634         union arg               a;
5635         char                    **real_args;
5636         int                     spawn_argc, i;
5637
5638         if ((spawn_argc = spawn_expand(r, args, spawn_name, &real_args)) < 0)
5639                 return;
5640         a.argv = real_args;
5641         if (fork() == 0)
5642                 spawn(r->ws->idx, &a, 1);
5643
5644         for (i = 0; i < spawn_argc; i++)
5645                 free(real_args[i]);
5646         free(real_args);
5647 }
5648
5649 void
5650 spawn_select(struct swm_region *r, union arg *args, const char *spawn_name,
5651     int *pid)
5652 {
5653         union arg               a;
5654         char                    **real_args;
5655         int                     i, spawn_argc;
5656
5657         if ((spawn_argc = spawn_expand(r, args, spawn_name, &real_args)) < 0)
5658                 return;
5659         a.argv = real_args;
5660
5661         if (pipe(select_list_pipe) == -1)
5662                 err(1, "pipe error");
5663         if (pipe(select_resp_pipe) == -1)
5664                 err(1, "pipe error");
5665
5666         if (signal(SIGPIPE, SIG_IGN) == SIG_ERR)
5667                 err(1, "could not disable SIGPIPE");
5668         switch (*pid = fork()) {
5669         case -1:
5670                 err(1, "cannot fork");
5671                 break;
5672         case 0: /* child */
5673                 if (dup2(select_list_pipe[0], 0) == -1)
5674                         err(1, "dup2");
5675                 if (dup2(select_resp_pipe[1], 1) == -1)
5676                         err(1, "dup2");
5677                 close(select_list_pipe[1]);
5678                 close(select_resp_pipe[0]);
5679                 spawn(r->ws->idx, &a, 0);
5680                 break;
5681         default: /* parent */
5682                 close(select_list_pipe[0]);
5683                 close(select_resp_pipe[1]);
5684                 break;
5685         }
5686
5687         for (i = 0; i < spawn_argc; i++)
5688                 free(real_args[i]);
5689         free(real_args);
5690 }
5691
5692 void
5693 spawn_insert(const char *name, const char *args)
5694 {
5695         char                    *arg, *cp, *ptr;
5696         struct spawn_prog       *sp;
5697
5698         DNPRINTF(SWM_D_SPAWN, "spawn_insert: %s\n", name);
5699
5700         if ((sp = calloc(1, sizeof *sp)) == NULL)
5701                 err(1, "spawn_insert: calloc");
5702         if ((sp->name = strdup(name)) == NULL)
5703                 err(1, "spawn_insert: strdup");
5704
5705         /* convert the arguments to an argument list */
5706         if ((ptr = cp = strdup(args)) == NULL)
5707                 err(1, "spawn_insert: strdup");
5708         while ((arg = strsep(&ptr, " \t")) != NULL) {
5709                 /* empty field; skip it */
5710                 if (*arg == '\0')
5711                         continue;
5712
5713                 sp->argc++;
5714                 if ((sp->argv = realloc(sp->argv, sp->argc *
5715                     sizeof *sp->argv)) == NULL)
5716                         err(1, "spawn_insert: realloc");
5717                 if ((sp->argv[sp->argc - 1] = strdup(arg)) == NULL)
5718                         err(1, "spawn_insert: strdup");
5719         }
5720         free(cp);
5721
5722         TAILQ_INSERT_TAIL(&spawns, sp, entry);
5723         DNPRINTF(SWM_D_SPAWN, "spawn_insert: leave\n");
5724 }
5725
5726 void
5727 spawn_remove(struct spawn_prog *sp)
5728 {
5729         int                     i;
5730
5731         DNPRINTF(SWM_D_SPAWN, "spawn_remove: %s\n", sp->name);
5732
5733         TAILQ_REMOVE(&spawns, sp, entry);
5734         for (i = 0; i < sp->argc; i++)
5735                 free(sp->argv[i]);
5736         free(sp->argv);
5737         free(sp->name);
5738         free(sp);
5739
5740         DNPRINTF(SWM_D_SPAWN, "spawn_remove: leave\n");
5741 }
5742
5743 void
5744 spawn_replace(struct spawn_prog *sp, const char *name, const char *args)
5745 {
5746         DNPRINTF(SWM_D_SPAWN, "spawn_replace: %s [%s]\n", sp->name, name);
5747
5748         spawn_remove(sp);
5749         spawn_insert(name, args);
5750
5751         DNPRINTF(SWM_D_SPAWN, "spawn_replace: leave\n");
5752 }
5753
5754 void
5755 setspawn(const char *name, const char *args)
5756 {
5757         struct spawn_prog       *sp;
5758
5759         DNPRINTF(SWM_D_SPAWN, "setspawn: %s\n", name);
5760
5761         if (name == NULL)
5762                 return;
5763
5764         TAILQ_FOREACH(sp, &spawns, entry) {
5765                 if (!strcmp(sp->name, name)) {
5766                         if (*args == '\0')
5767                                 spawn_remove(sp);
5768                         else
5769                                 spawn_replace(sp, name, args);
5770                         DNPRINTF(SWM_D_SPAWN, "setspawn: leave\n");
5771                         return;
5772                 }
5773         }
5774         if (*args == '\0') {
5775                 warnx("error: setspawn: cannot find program: %s", name);
5776                 return;
5777         }
5778
5779         spawn_insert(name, args);
5780         DNPRINTF(SWM_D_SPAWN, "setspawn: leave\n");
5781 }
5782
5783 int
5784 setconfspawn(char *selector, char *value, int flags)
5785 {
5786         char *args;
5787
5788         /* suppress unused warning since var is needed */
5789         (void)flags;
5790
5791         args = expand_tilde(value);
5792
5793         DNPRINTF(SWM_D_SPAWN, "setconfspawn: [%s] [%s]\n", selector, args);
5794
5795         setspawn(selector, args);
5796         free(args);
5797
5798         DNPRINTF(SWM_D_SPAWN, "setconfspawn: done.\n");
5799         return (0);
5800 }
5801
5802 void
5803 setup_spawn(void)
5804 {
5805         setconfspawn("term",            "xterm",                0);
5806         setconfspawn("spawn_term",      "xterm",                0);
5807         setconfspawn("screenshot_all",  "screenshot.sh full",   0);
5808         setconfspawn("screenshot_wind", "screenshot.sh window", 0);
5809         setconfspawn("lock",            "xlock",                0);
5810         setconfspawn("initscr",         "initscreen.sh",        0);
5811         setconfspawn("menu",            "dmenu_run"
5812                                         " -fn $bar_font"
5813                                         " -nb $bar_color"
5814                                         " -nf $bar_font_color"
5815                                         " -sb $bar_border"
5816                                         " -sf $bar_color",      0);
5817         setconfspawn("search",          "dmenu"
5818                                         " -i"
5819                                         " -fn $bar_font"
5820                                         " -nb $bar_color"
5821                                         " -nf $bar_font_color"
5822                                         " -sb $bar_border"
5823                                         " -sf $bar_color",      0);
5824         setconfspawn("name_workspace",  "dmenu"
5825                                         " -p Workspace"
5826                                         " -fn $bar_font"
5827                                         " -nb $bar_color"
5828                                         " -nf $bar_font_color"
5829                                         " -sb $bar_border"
5830                                         " -sf $bar_color",      0);
5831 }
5832
5833 /* key bindings */
5834 #define SWM_MODNAME_SIZE        32
5835 #define SWM_KEY_WS              "\n+ \t"
5836 int
5837 parsekeys(char *keystr, unsigned int currmod, unsigned int *mod, KeySym *ks)
5838 {
5839         char                    *cp, *name;
5840         KeySym                  uks;
5841         DNPRINTF(SWM_D_KEY, "parsekeys: enter [%s]\n", keystr);
5842         if (mod == NULL || ks == NULL) {
5843                 DNPRINTF(SWM_D_KEY, "parsekeys: no mod or key vars\n");
5844                 return (1);
5845         }
5846         if (keystr == NULL || strlen(keystr) == 0) {
5847                 DNPRINTF(SWM_D_KEY, "parsekeys: no keystr\n");
5848                 return (1);
5849         }
5850         cp = keystr;
5851         *ks = XCB_NO_SYMBOL;
5852         *mod = 0;
5853         while ((name = strsep(&cp, SWM_KEY_WS)) != NULL) {
5854                 DNPRINTF(SWM_D_KEY, "parsekeys: key [%s]\n", name);
5855                 if (cp)
5856                         cp += (long)strspn(cp, SWM_KEY_WS);
5857                 if (strncasecmp(name, "MOD", SWM_MODNAME_SIZE) == 0)
5858                         *mod |= currmod;
5859                 else if (!strncasecmp(name, "Mod1", SWM_MODNAME_SIZE))
5860                         *mod |= XCB_MOD_MASK_1;
5861                 else if (!strncasecmp(name, "Mod2", SWM_MODNAME_SIZE))
5862                         *mod += XCB_MOD_MASK_2;
5863                 else if (!strncmp(name, "Mod3", SWM_MODNAME_SIZE))
5864                         *mod |= XCB_MOD_MASK_3;
5865                 else if (!strncmp(name, "Mod4", SWM_MODNAME_SIZE))
5866                         *mod |= XCB_MOD_MASK_4;
5867                 else if (strncasecmp(name, "SHIFT", SWM_MODNAME_SIZE) == 0)
5868                         *mod |= XCB_MOD_MASK_SHIFT;
5869                 else if (strncasecmp(name, "CONTROL", SWM_MODNAME_SIZE) == 0)
5870                         *mod |= XCB_MOD_MASK_CONTROL;
5871                 else {
5872                         *ks = XStringToKeysym(name);
5873                         XConvertCase(*ks, ks, &uks);
5874                         if (ks == XCB_NO_SYMBOL) {
5875                                 DNPRINTF(SWM_D_KEY,
5876                                     "parsekeys: invalid key %s\n",
5877                                     name);
5878                                 return (1);
5879                         }
5880                 }
5881         }
5882         DNPRINTF(SWM_D_KEY, "parsekeys: leave ok\n");
5883         return (0);
5884 }
5885
5886 char *
5887 strdupsafe(const char *str)
5888 {
5889         if (str == NULL)
5890                 return (NULL);
5891         else
5892                 return (strdup(str));
5893 }
5894
5895 void
5896 key_insert(unsigned int mod, KeySym ks, enum keyfuncid kfid,
5897     const char *spawn_name)
5898 {
5899         struct key              *kp;
5900
5901         DNPRINTF(SWM_D_KEY, "key_insert: enter %s [%s]\n",
5902             keyfuncs[kfid].name, spawn_name);
5903
5904         if ((kp = malloc(sizeof *kp)) == NULL)
5905                 err(1, "key_insert: malloc");
5906
5907         kp->mod = mod;
5908         kp->keysym = ks;
5909         kp->funcid = kfid;
5910         kp->spawn_name = strdupsafe(spawn_name);
5911         RB_INSERT(key_tree, &keys, kp);
5912
5913         DNPRINTF(SWM_D_KEY, "key_insert: leave\n");
5914 }
5915
5916 struct key *
5917 key_lookup(unsigned int mod, KeySym ks)
5918 {
5919         struct key              kp;
5920
5921         kp.keysym = ks;
5922         kp.mod = mod;
5923
5924         return (RB_FIND(key_tree, &keys, &kp));
5925 }
5926
5927 void
5928 key_remove(struct key *kp)
5929 {
5930         DNPRINTF(SWM_D_KEY, "key_remove: %s\n", keyfuncs[kp->funcid].name);
5931
5932         RB_REMOVE(key_tree, &keys, kp);
5933         free(kp->spawn_name);
5934         free(kp);
5935
5936         DNPRINTF(SWM_D_KEY, "key_remove: leave\n");
5937 }
5938
5939 void
5940 key_replace(struct key *kp, unsigned int mod, KeySym ks, enum keyfuncid kfid,
5941     const char *spawn_name)
5942 {
5943         DNPRINTF(SWM_D_KEY, "key_replace: %s [%s]\n", keyfuncs[kp->funcid].name,
5944             spawn_name);
5945
5946         key_remove(kp);
5947         key_insert(mod, ks, kfid, spawn_name);
5948
5949         DNPRINTF(SWM_D_KEY, "key_replace: leave\n");
5950 }
5951
5952 void
5953 setkeybinding(unsigned int mod, KeySym ks, enum keyfuncid kfid,
5954     const char *spawn_name)
5955 {
5956         struct key              *kp;
5957
5958         DNPRINTF(SWM_D_KEY, "setkeybinding: enter %s [%s]\n",
5959             keyfuncs[kfid].name, spawn_name);
5960
5961         if ((kp = key_lookup(mod, ks)) != NULL) {
5962                 if (kfid == KF_INVALID)
5963                         key_remove(kp);
5964                 else
5965                         key_replace(kp, mod, ks, kfid, spawn_name);
5966                 DNPRINTF(SWM_D_KEY, "setkeybinding: leave\n");
5967                 return;
5968         }
5969         if (kfid == KF_INVALID) {
5970                 warnx("bind: Key combination already unbound.");
5971                 DNPRINTF(SWM_D_KEY, "setkeybinding: leave\n");
5972                 return;
5973         }
5974
5975         key_insert(mod, ks, kfid, spawn_name);
5976         DNPRINTF(SWM_D_KEY, "setkeybinding: leave\n");
5977 }
5978
5979 int
5980 setconfbinding(char *selector, char *value, int flags)
5981 {
5982         enum keyfuncid          kfid;
5983         unsigned int            mod;
5984         KeySym                  ks;
5985         struct spawn_prog       *sp;
5986
5987         /* suppress unused warning since var is needed */
5988         (void)flags;
5989
5990         DNPRINTF(SWM_D_KEY, "setconfbinding: enter\n");
5991         if (selector == NULL) {
5992                 DNPRINTF(SWM_D_KEY, "setconfbinding: unbind %s\n", value);
5993                 if (parsekeys(value, mod_key, &mod, &ks) == 0) {
5994                         kfid = KF_INVALID;
5995                         setkeybinding(mod, ks, kfid, NULL);
5996                         return (0);
5997                 } else
5998                         return (1);
5999         }
6000         /* search by key function name */
6001         for (kfid = 0; kfid < KF_INVALID; (kfid)++) {
6002                 if (strncasecmp(selector, keyfuncs[kfid].name,
6003                     SWM_FUNCNAME_LEN) == 0) {
6004                         DNPRINTF(SWM_D_KEY, "setconfbinding: %s: match\n",
6005                             selector);
6006                         if (parsekeys(value, mod_key, &mod, &ks) == 0) {
6007                                 setkeybinding(mod, ks, kfid, NULL);
6008                                 return (0);
6009                         } else
6010                                 return (1);
6011                 }
6012         }
6013         /* search by custom spawn name */
6014         TAILQ_FOREACH(sp, &spawns, entry) {
6015                 if (strcasecmp(selector, sp->name) == 0) {
6016                         DNPRINTF(SWM_D_KEY, "setconfbinding: %s: match\n",
6017                             selector);
6018                         if (parsekeys(value, mod_key, &mod, &ks) == 0) {
6019                                 setkeybinding(mod, ks, KF_SPAWN_CUSTOM,
6020                                     sp->name);
6021                                 return (0);
6022                         } else
6023                                 return (1);
6024                 }
6025         }
6026         DNPRINTF(SWM_D_KEY, "setconfbinding: no match\n");
6027         return (1);
6028 }
6029
6030 void
6031 setup_keys(void)
6032 {
6033 #define MODKEY_SHIFT    MODKEY | XCB_MOD_MASK_SHIFT
6034         setkeybinding(MODKEY,           XK_space,       KF_CYCLE_LAYOUT,NULL);
6035         setkeybinding(MODKEY_SHIFT,     XK_backslash,   KF_FLIP_LAYOUT, NULL);
6036         setkeybinding(MODKEY_SHIFT,     XK_space,       KF_STACK_RESET, NULL);
6037         setkeybinding(MODKEY,           XK_h,           KF_MASTER_SHRINK, NULL);
6038         setkeybinding(MODKEY,           XK_l,           KF_MASTER_GROW, NULL);
6039         setkeybinding(MODKEY,           XK_comma,       KF_MASTER_ADD,  NULL);
6040         setkeybinding(MODKEY,           XK_period,      KF_MASTER_DEL,  NULL);
6041         setkeybinding(MODKEY_SHIFT,     XK_comma,       KF_STACK_INC,   NULL);
6042         setkeybinding(MODKEY_SHIFT,     XK_period,      KF_STACK_DEC,   NULL);
6043         setkeybinding(MODKEY,           XK_Return,      KF_SWAP_MAIN,   NULL);
6044         setkeybinding(MODKEY,           XK_j,           KF_FOCUS_NEXT,  NULL);
6045         setkeybinding(MODKEY,           XK_k,           KF_FOCUS_PREV,  NULL);
6046         setkeybinding(MODKEY_SHIFT,     XK_j,           KF_SWAP_NEXT,   NULL);
6047         setkeybinding(MODKEY_SHIFT,     XK_k,           KF_SWAP_PREV,   NULL);
6048         setkeybinding(MODKEY_SHIFT,     XK_Return,      KF_SPAWN_CUSTOM,"term");
6049         setkeybinding(MODKEY,           XK_p,           KF_SPAWN_CUSTOM,"menu");
6050         setkeybinding(MODKEY_SHIFT,     XK_q,           KF_QUIT,        NULL);
6051         setkeybinding(MODKEY,           XK_q,           KF_RESTART,     NULL);
6052         setkeybinding(MODKEY,           XK_m,           KF_FOCUS_MAIN,  NULL);
6053         setkeybinding(MODKEY,           XK_1,           KF_WS_1,        NULL);
6054         setkeybinding(MODKEY,           XK_2,           KF_WS_2,        NULL);
6055         setkeybinding(MODKEY,           XK_3,           KF_WS_3,        NULL);
6056         setkeybinding(MODKEY,           XK_4,           KF_WS_4,        NULL);
6057         setkeybinding(MODKEY,           XK_5,           KF_WS_5,        NULL);
6058         setkeybinding(MODKEY,           XK_6,           KF_WS_6,        NULL);
6059         setkeybinding(MODKEY,           XK_7,           KF_WS_7,        NULL);
6060         setkeybinding(MODKEY,           XK_8,           KF_WS_8,        NULL);
6061         setkeybinding(MODKEY,           XK_9,           KF_WS_9,        NULL);
6062         setkeybinding(MODKEY,           XK_0,           KF_WS_10,       NULL);
6063         setkeybinding(MODKEY,           XK_F1,          KF_WS_11,       NULL);
6064         setkeybinding(MODKEY,           XK_F2,          KF_WS_12,       NULL);
6065         setkeybinding(MODKEY,           XK_F3,          KF_WS_13,       NULL);
6066         setkeybinding(MODKEY,           XK_F4,          KF_WS_14,       NULL);
6067         setkeybinding(MODKEY,           XK_F5,          KF_WS_15,       NULL);
6068         setkeybinding(MODKEY,           XK_F6,          KF_WS_16,       NULL);
6069         setkeybinding(MODKEY,           XK_F7,          KF_WS_17,       NULL);
6070         setkeybinding(MODKEY,           XK_F8,          KF_WS_18,       NULL);
6071         setkeybinding(MODKEY,           XK_F9,          KF_WS_19,       NULL);
6072         setkeybinding(MODKEY,           XK_F10,         KF_WS_20,       NULL);
6073         setkeybinding(MODKEY,           XK_F11,         KF_WS_21,       NULL);
6074         setkeybinding(MODKEY,           XK_F12,         KF_WS_22,       NULL);
6075         setkeybinding(MODKEY,           XK_Right,       KF_WS_NEXT,     NULL);
6076         setkeybinding(MODKEY,           XK_Left,        KF_WS_PREV,     NULL);
6077         setkeybinding(MODKEY,           XK_Up,          KF_WS_NEXT_ALL, NULL);
6078         setkeybinding(MODKEY,           XK_Down,        KF_WS_PREV_ALL, NULL);
6079         setkeybinding(MODKEY,           XK_a,           KF_WS_PRIOR,    NULL);
6080         setkeybinding(MODKEY_SHIFT,     XK_Right,       KF_SCREEN_NEXT, NULL);
6081         setkeybinding(MODKEY_SHIFT,     XK_Left,        KF_SCREEN_PREV, NULL);
6082         setkeybinding(MODKEY_SHIFT,     XK_1,           KF_MVWS_1,      NULL);
6083         setkeybinding(MODKEY_SHIFT,     XK_2,           KF_MVWS_2,      NULL);
6084         setkeybinding(MODKEY_SHIFT,     XK_3,           KF_MVWS_3,      NULL);
6085         setkeybinding(MODKEY_SHIFT,     XK_4,           KF_MVWS_4,      NULL);
6086         setkeybinding(MODKEY_SHIFT,     XK_5,           KF_MVWS_5,      NULL);
6087         setkeybinding(MODKEY_SHIFT,     XK_6,           KF_MVWS_6,      NULL);
6088         setkeybinding(MODKEY_SHIFT,     XK_7,           KF_MVWS_7,      NULL);
6089         setkeybinding(MODKEY_SHIFT,     XK_8,           KF_MVWS_8,      NULL);
6090         setkeybinding(MODKEY_SHIFT,     XK_9,           KF_MVWS_9,      NULL);
6091         setkeybinding(MODKEY_SHIFT,     XK_0,           KF_MVWS_10,     NULL);
6092         setkeybinding(MODKEY_SHIFT,     XK_F1,          KF_MVWS_11,     NULL);
6093         setkeybinding(MODKEY_SHIFT,     XK_F2,          KF_MVWS_12,     NULL);
6094         setkeybinding(MODKEY_SHIFT,     XK_F3,          KF_MVWS_13,     NULL);
6095         setkeybinding(MODKEY_SHIFT,     XK_F4,          KF_MVWS_14,     NULL);
6096         setkeybinding(MODKEY_SHIFT,     XK_F5,          KF_MVWS_15,     NULL);
6097         setkeybinding(MODKEY_SHIFT,     XK_F6,          KF_MVWS_16,     NULL);
6098         setkeybinding(MODKEY_SHIFT,     XK_F7,          KF_MVWS_17,     NULL);
6099         setkeybinding(MODKEY_SHIFT,     XK_F8,          KF_MVWS_18,     NULL);
6100         setkeybinding(MODKEY_SHIFT,     XK_F9,          KF_MVWS_19,     NULL);
6101         setkeybinding(MODKEY_SHIFT,     XK_F10,         KF_MVWS_20,     NULL);
6102         setkeybinding(MODKEY_SHIFT,     XK_F11,         KF_MVWS_21,     NULL);
6103         setkeybinding(MODKEY_SHIFT,     XK_F12,         KF_MVWS_22,     NULL);
6104         setkeybinding(MODKEY,           XK_b,           KF_BAR_TOGGLE,  NULL);
6105         setkeybinding(MODKEY_SHIFT,     XK_b,           KF_BAR_TOGGLE_WS,NULL);
6106         setkeybinding(MODKEY,           XK_Tab,         KF_FOCUS_NEXT,  NULL);
6107         setkeybinding(MODKEY_SHIFT,     XK_Tab,         KF_FOCUS_PREV,  NULL);
6108         setkeybinding(MODKEY_SHIFT,     XK_x,           KF_WIND_KILL,   NULL);
6109         setkeybinding(MODKEY,           XK_x,           KF_WIND_DEL,    NULL);
6110         setkeybinding(MODKEY,           XK_s,           KF_SPAWN_CUSTOM,"screenshot_all");
6111         setkeybinding(MODKEY_SHIFT,     XK_s,           KF_SPAWN_CUSTOM,"screenshot_wind");
6112         setkeybinding(MODKEY,           XK_t,           KF_FLOAT_TOGGLE,NULL);
6113         setkeybinding(MODKEY_SHIFT,     XK_v,           KF_VERSION,     NULL);
6114         setkeybinding(MODKEY_SHIFT,     XK_Delete,      KF_SPAWN_CUSTOM,"lock");
6115         setkeybinding(MODKEY_SHIFT,     XK_i,           KF_SPAWN_CUSTOM,"initscr");
6116         setkeybinding(MODKEY,           XK_w,           KF_ICONIFY,     NULL);
6117         setkeybinding(MODKEY_SHIFT,     XK_w,           KF_UNICONIFY,   NULL);
6118         setkeybinding(MODKEY_SHIFT,     XK_r,           KF_RAISE_TOGGLE,NULL);
6119         setkeybinding(MODKEY,           XK_v,           KF_BUTTON2,     NULL);
6120         setkeybinding(MODKEY,           XK_equal,       KF_WIDTH_GROW,  NULL);
6121         setkeybinding(MODKEY,           XK_minus,       KF_WIDTH_SHRINK,NULL);
6122         setkeybinding(MODKEY_SHIFT,     XK_equal,       KF_HEIGHT_GROW,NULL);
6123         setkeybinding(MODKEY_SHIFT,     XK_minus,       KF_HEIGHT_SHRINK,NULL);
6124         setkeybinding(MODKEY,           XK_bracketleft, KF_MOVE_LEFT,NULL);
6125         setkeybinding(MODKEY,           XK_bracketright,KF_MOVE_RIGHT,NULL);
6126         setkeybinding(MODKEY_SHIFT,     XK_bracketleft, KF_MOVE_UP,     NULL);
6127         setkeybinding(MODKEY_SHIFT,     XK_bracketright,KF_MOVE_DOWN,NULL);
6128         setkeybinding(MODKEY_SHIFT,     XK_slash,       KF_NAME_WORKSPACE,NULL);
6129         setkeybinding(MODKEY,           XK_slash,       KF_SEARCH_WORKSPACE,NULL);
6130         setkeybinding(MODKEY,           XK_f,           KF_SEARCH_WIN,  NULL);
6131 #ifdef SWM_DEBUG
6132         setkeybinding(MODKEY_SHIFT,     XK_d,           KF_DUMPWINS,    NULL);
6133 #endif
6134 #undef MODKEY_SHIFT
6135 }
6136
6137 void
6138 clear_keys(void)
6139 {
6140         struct key              *kp;
6141
6142         while (RB_EMPTY(&keys) == 0) {
6143                 kp = RB_ROOT(&keys);
6144                 key_remove(kp);
6145         }
6146 }
6147
6148 int
6149 setkeymapping(char *selector, char *value, int flags)
6150 {
6151         char                    keymapping_file[PATH_MAX];
6152
6153         /* suppress unused warnings since vars are needed */
6154         (void)selector;
6155         (void)flags;
6156
6157         DNPRINTF(SWM_D_KEY, "setkeymapping: enter\n");
6158         if (value[0] == '~')
6159                 snprintf(keymapping_file, sizeof keymapping_file, "%s/%s",
6160                     pwd->pw_dir, &value[1]);
6161         else
6162                 strlcpy(keymapping_file, value, sizeof keymapping_file);
6163         clear_keys();
6164         /* load new key bindings; if it fails, revert to default bindings */
6165         if (conf_load(keymapping_file, SWM_CONF_KEYMAPPING)) {
6166                 clear_keys();
6167                 setup_keys();
6168         }
6169         DNPRINTF(SWM_D_KEY, "setkeymapping: leave\n");
6170         return (0);
6171 }
6172
6173 void
6174 updatenumlockmask(void)
6175 {
6176         unsigned int                            i, j;
6177         xcb_get_modifier_mapping_reply_t        *modmap_r;
6178         xcb_keycode_t                           *modmap, kc, *keycode;
6179
6180         numlockmask = 0;
6181
6182         modmap_r = xcb_get_modifier_mapping_reply(conn,
6183             xcb_get_modifier_mapping(conn),
6184             NULL);
6185         if (modmap_r) {
6186                 modmap = xcb_get_modifier_mapping_keycodes(modmap_r);
6187                 for (i = 0; i < 8; i++) {
6188                         for (j = 0; j < modmap_r->keycodes_per_modifier; j++) {
6189                                 kc = modmap[i * modmap_r->keycodes_per_modifier
6190                                     + j];
6191                                 keycode = xcb_key_symbols_get_keycode(syms,
6192                                                 XK_Num_Lock);
6193                                 if (kc == *keycode)
6194                                         numlockmask = (1 << i);
6195                                 free(keycode);
6196                         }
6197                 }
6198                 free(modmap_r);
6199         }
6200         DNPRINTF(SWM_D_MISC, "updatenumlockmask: %d\n", numlockmask);
6201 }
6202
6203 void
6204 grabkeys(void)
6205 {
6206         struct key              *kp;
6207         int                     num_screens, k, j;
6208         unsigned int            modifiers[4];
6209         xcb_keycode_t           *code;
6210
6211         DNPRINTF(SWM_D_MISC, "grabkeys\n");
6212         updatenumlockmask();
6213
6214         modifiers[0] = 0;
6215         modifiers[1] = numlockmask;
6216         modifiers[2] = XCB_MOD_MASK_LOCK;
6217         modifiers[3] = numlockmask | XCB_MOD_MASK_LOCK;
6218
6219         num_screens = xcb_setup_roots_length(xcb_get_setup(conn));
6220         for (k = 0; k < num_screens; k++) {
6221                 if (TAILQ_EMPTY(&screens[k].rl))
6222                         continue;
6223                 xcb_ungrab_key(conn, XCB_GRAB_ANY, screens[k].root,
6224                         XCB_MOD_MASK_ANY);
6225                 RB_FOREACH(kp, key_tree, &keys) {
6226                         if ((code = xcb_key_symbols_get_keycode(syms,
6227                                         kp->keysym))) {
6228                                 for (j = 0; j < LENGTH(modifiers); j++)
6229                                         xcb_grab_key(conn, 1,
6230                                             screens[k].root,
6231                                             kp->mod | modifiers[j],
6232                                             *code, XCB_GRAB_MODE_SYNC,
6233                                             XCB_GRAB_MODE_ASYNC);
6234                                 free(code);
6235                         }
6236                 }
6237         }
6238 }
6239
6240 void
6241 grabbuttons(struct ws_win *win)
6242 {
6243         unsigned int    modifiers[4];
6244         int             i, j;
6245
6246         DNPRINTF(SWM_D_MOUSE, "grabbuttons: win 0x%x\n", win->id);
6247         updatenumlockmask();
6248
6249         modifiers[0] = 0;
6250         modifiers[1] = numlockmask;
6251         modifiers[2] = XCB_MOD_MASK_LOCK;
6252         modifiers[3] = numlockmask | XCB_MOD_MASK_LOCK;
6253
6254         for (i = 0; i < LENGTH(buttons); i++)
6255                 if (buttons[i].action == client_click)
6256                         for (j = 0; j < LENGTH(modifiers); ++j)
6257                                 xcb_grab_button(conn, 0, win->id, BUTTONMASK,
6258                                     XCB_GRAB_MODE_SYNC, XCB_GRAB_MODE_ASYNC,
6259                                     XCB_WINDOW_NONE, XCB_CURSOR_NONE,
6260                                     buttons[i].button, buttons[i].mask |
6261                                     modifiers[j]);
6262 }
6263
6264 const char *quirkname[] = {
6265         "NONE",         /* config string for "no value" */
6266         "FLOAT",
6267         "TRANSSZ",
6268         "ANYWHERE",
6269         "XTERM_FONTADJ",
6270         "FULLSCREEN",
6271         "FOCUSPREV",
6272 };
6273
6274 /* SWM_Q_WS: retain '|' for back compat for now (2009-08-11) */
6275 #define SWM_Q_WS                "\n|+ \t"
6276 int
6277 parsequirks(char *qstr, unsigned long *quirk)
6278 {
6279         char                    *cp, *name;
6280         int                     i;
6281
6282         if (quirk == NULL)
6283                 return (1);
6284
6285         cp = qstr;
6286         *quirk = 0;
6287         while ((name = strsep(&cp, SWM_Q_WS)) != NULL) {
6288                 if (cp)
6289                         cp += (long)strspn(cp, SWM_Q_WS);
6290                 for (i = 0; i < LENGTH(quirkname); i++) {
6291                         if (!strncasecmp(name, quirkname[i], SWM_QUIRK_LEN)) {
6292                                 DNPRINTF(SWM_D_QUIRK,
6293                                     "parsequirks: %s\n", name);
6294                                 if (i == 0) {
6295                                         *quirk = 0;
6296                                         return (0);
6297                                 }
6298                                 *quirk |= 1 << (i-1);
6299                                 break;
6300                         }
6301                 }
6302                 if (i >= LENGTH(quirkname)) {
6303                         DNPRINTF(SWM_D_QUIRK,
6304                             "parsequirks: invalid quirk [%s]\n", name);
6305                         return (1);
6306                 }
6307         }
6308         return (0);
6309 }
6310
6311 void
6312 quirk_insert(const char *class, const char *name, unsigned long quirk)
6313 {
6314         struct quirk            *qp;
6315
6316         DNPRINTF(SWM_D_QUIRK, "quirk_insert: %s:%s [%lu]\n", class, name,
6317             quirk);
6318
6319         if ((qp = malloc(sizeof *qp)) == NULL)
6320                 err(1, "quirk_insert: malloc");
6321         if ((qp->class = strdup(class)) == NULL)
6322                 err(1, "quirk_insert: strdup");
6323         if ((qp->name = strdup(name)) == NULL)
6324                 err(1, "quirk_insert: strdup");
6325
6326         qp->quirk = quirk;
6327         TAILQ_INSERT_TAIL(&quirks, qp, entry);
6328
6329         DNPRINTF(SWM_D_QUIRK, "quirk_insert: leave\n");
6330 }
6331
6332 void
6333 quirk_remove(struct quirk *qp)
6334 {
6335         DNPRINTF(SWM_D_QUIRK, "quirk_remove: %s:%s [%lu]\n", qp->class,
6336             qp->name, qp->quirk);
6337
6338         TAILQ_REMOVE(&quirks, qp, entry);
6339         free(qp->class);
6340         free(qp->name);
6341         free(qp);
6342
6343         DNPRINTF(SWM_D_QUIRK, "quirk_remove: leave\n");
6344 }
6345
6346 void
6347 quirk_replace(struct quirk *qp, const char *class, const char *name,
6348     unsigned long quirk)
6349 {
6350         DNPRINTF(SWM_D_QUIRK, "quirk_replace: %s:%s [%lu]\n", qp->class,
6351             qp->name, qp->quirk);
6352
6353         quirk_remove(qp);
6354         quirk_insert(class, name, quirk);
6355
6356         DNPRINTF(SWM_D_QUIRK, "quirk_replace: leave\n");
6357 }
6358
6359 void
6360 setquirk(const char *class, const char *name, unsigned long quirk)
6361 {
6362         struct quirk            *qp;
6363
6364         DNPRINTF(SWM_D_QUIRK, "setquirk: enter %s:%s [%lu]\n", class, name,
6365            quirk);
6366
6367         /* Remove/replace existing quirk. */
6368         TAILQ_FOREACH(qp, &quirks, entry) {
6369                 if (!strcmp(qp->class, class) && !strcmp(qp->name, name)) {
6370                         if (!quirk)
6371                                 quirk_remove(qp);
6372                         else
6373                                 quirk_replace(qp, class, name, quirk);
6374                         DNPRINTF(SWM_D_QUIRK, "setquirk: leave\n");
6375                         return;
6376                 }
6377         }
6378
6379         /* Only insert if quirk is not NONE. */
6380         if (quirk)
6381                 quirk_insert(class, name, quirk);
6382
6383         DNPRINTF(SWM_D_QUIRK, "setquirk: leave\n");
6384 }
6385
6386 int
6387 setconfquirk(char *selector, char *value, int flags)
6388 {
6389         char                    *cp, *class, *name;
6390         int                     retval;
6391         unsigned long           qrks;
6392
6393         /* suppress unused warning since var is needed */
6394         (void)flags;
6395
6396         if (selector == NULL)
6397                 return (0);
6398         if ((cp = strchr(selector, ':')) == NULL)
6399                 return (0);
6400         *cp = '\0';
6401         class = selector;
6402         name = cp + 1;
6403         if ((retval = parsequirks(value, &qrks)) == 0)
6404                 setquirk(class, name, qrks);
6405         return (retval);
6406 }
6407
6408 void
6409 setup_quirks(void)
6410 {
6411         setquirk("MPlayer",             "xv",           SWM_Q_FLOAT | SWM_Q_FULLSCREEN | SWM_Q_FOCUSPREV);
6412         setquirk("OpenOffice.org 3.2",  "VCLSalFrame",  SWM_Q_FLOAT);
6413         setquirk("Firefox-bin",         "firefox-bin",  SWM_Q_TRANSSZ);
6414         setquirk("Firefox",             "Dialog",       SWM_Q_FLOAT);
6415         setquirk("Gimp",                "gimp",         SWM_Q_FLOAT | SWM_Q_ANYWHERE);
6416         setquirk("XTerm",               "xterm",        SWM_Q_XTERM_FONTADJ);
6417         setquirk("xine",                "Xine Window",  SWM_Q_FLOAT | SWM_Q_ANYWHERE);
6418         setquirk("Xitk",                "Xitk Combo",   SWM_Q_FLOAT | SWM_Q_ANYWHERE);
6419         setquirk("xine",                "xine Panel",   SWM_Q_FLOAT | SWM_Q_ANYWHERE);
6420         setquirk("Xitk",                "Xine Window",  SWM_Q_FLOAT | SWM_Q_ANYWHERE);
6421         setquirk("xine",                "xine Video Fullscreen Window", SWM_Q_FULLSCREEN | SWM_Q_FLOAT);
6422         setquirk("pcb",                 "pcb",          SWM_Q_FLOAT);
6423         setquirk("SDL_App",             "SDL_App",      SWM_Q_FLOAT | SWM_Q_FULLSCREEN);
6424 }
6425
6426 /* conf file stuff */
6427 #define SWM_CONF_FILE           "spectrwm.conf"
6428 #define SWM_CONF_FILE_OLD       "scrotwm.conf"
6429
6430 enum {
6431         SWM_S_BAR_ACTION,
6432         SWM_S_BAR_AT_BOTTOM,
6433         SWM_S_BAR_BORDER_WIDTH,
6434         SWM_S_BAR_DELAY,
6435         SWM_S_BAR_ENABLED,
6436         SWM_S_BAR_FONT,
6437         SWM_S_BAR_FORMAT,
6438         SWM_S_BAR_JUSTIFY,
6439         SWM_S_BORDER_WIDTH,
6440         SWM_S_CLOCK_ENABLED,
6441         SWM_S_CLOCK_FORMAT,
6442         SWM_S_CYCLE_EMPTY,
6443         SWM_S_CYCLE_VISIBLE,
6444         SWM_S_DIALOG_RATIO,
6445         SWM_S_DISABLE_BORDER,
6446         SWM_S_FOCUS_CLOSE,
6447         SWM_S_FOCUS_CLOSE_WRAP,
6448         SWM_S_FOCUS_DEFAULT,
6449         SWM_S_FOCUS_MODE,
6450         SWM_S_SPAWN_ORDER,
6451         SWM_S_SPAWN_TERM,
6452         SWM_S_SS_APP,
6453         SWM_S_SS_ENABLED,
6454         SWM_S_STACK_ENABLED,
6455         SWM_S_TERM_WIDTH,
6456         SWM_S_TITLE_CLASS_ENABLED,
6457         SWM_S_TITLE_NAME_ENABLED,
6458         SWM_S_URGENT_ENABLED,
6459         SWM_S_VERBOSE_LAYOUT,
6460         SWM_S_WINDOW_NAME_ENABLED,
6461         SWM_S_WORKSPACE_LIMIT
6462 };
6463
6464 int
6465 setconfvalue(char *selector, char *value, int flags)
6466 {
6467         int     i;
6468         char    *b;
6469
6470         /* suppress unused warning since var is needed */
6471         (void)selector;
6472
6473         switch (flags) {
6474         case SWM_S_BAR_ACTION:
6475                 free(bar_argv[0]);
6476                 if ((bar_argv[0] = expand_tilde(value)) == NULL)
6477                         err(1, "setconfvalue: bar_action");
6478                 break;
6479         case SWM_S_BAR_AT_BOTTOM:
6480                 bar_at_bottom = atoi(value);
6481                 break;
6482         case SWM_S_BAR_BORDER_WIDTH:
6483                 bar_border_width = atoi(value);
6484                 if (bar_border_width < 0)
6485                         bar_border_width = 0;
6486                 break;
6487         case SWM_S_BAR_DELAY:
6488                 bar_delay = atoi(value);
6489                 break;
6490         case SWM_S_BAR_ENABLED:
6491                 bar_enabled = atoi(value);
6492                 break;
6493         case SWM_S_BAR_FONT:
6494                 b = bar_fonts;
6495                 if (asprintf(&bar_fonts, "%s,%s", value, bar_fonts) == -1)
6496                         err(1, "setconfvalue: asprintf: failed to allocate "
6497                                 "memory for bar_fonts.");
6498                 free(b);
6499
6500                 /* If already in xft mode, then we are done. */
6501                 if (!bar_font_legacy)
6502                         break;
6503
6504                 /* If there are any non-XLFD entries, switch to Xft mode. */
6505                 while ((b = strsep(&value, ",")) != NULL) {
6506                         if (*b == '\0')
6507                                 continue;
6508                         if (!isxlfd(b)) {
6509                                 bar_font_legacy = 0;
6510                                 break;
6511                         }
6512                 }
6513                 break;
6514         case SWM_S_BAR_FORMAT:
6515                 free(bar_format);
6516                 if ((bar_format = strdup(value)) == NULL)
6517                         err(1, "setconfvalue: bar_format");
6518                 break;
6519         case SWM_S_BAR_JUSTIFY:
6520                 if (!strcmp(value, "left"))
6521                         bar_justify = SWM_BAR_JUSTIFY_LEFT;
6522                 else if (!strcmp(value, "center"))
6523                         bar_justify = SWM_BAR_JUSTIFY_CENTER;
6524                 else if (!strcmp(value, "right"))
6525                         bar_justify = SWM_BAR_JUSTIFY_RIGHT;
6526                 else
6527                         errx(1, "invalid bar_justify");
6528                 break;
6529         case SWM_S_BORDER_WIDTH:
6530                 border_width = atoi(value);
6531                 if (border_width < 0)
6532                         border_width = 0;
6533                 break;
6534         case SWM_S_CLOCK_ENABLED:
6535                 clock_enabled = atoi(value);
6536                 break;
6537         case SWM_S_CLOCK_FORMAT:
6538 #ifndef SWM_DENY_CLOCK_FORMAT
6539                 free(clock_format);
6540                 if ((clock_format = strdup(value)) == NULL)
6541                         err(1, "setconfvalue: clock_format");
6542 #endif
6543                 break;
6544         case SWM_S_CYCLE_EMPTY:
6545                 cycle_empty = atoi(value);
6546                 break;
6547         case SWM_S_CYCLE_VISIBLE:
6548                 cycle_visible = atoi(value);
6549                 break;
6550         case SWM_S_DIALOG_RATIO:
6551                 dialog_ratio = atof(value);
6552                 if (dialog_ratio > 1.0 || dialog_ratio <= .3)
6553                         dialog_ratio = .6;
6554                 break;
6555         case SWM_S_DISABLE_BORDER:
6556                 disable_border = atoi(value);
6557                 break;
6558         case SWM_S_FOCUS_CLOSE:
6559                 if (!strcmp(value, "first"))
6560                         focus_close = SWM_STACK_BOTTOM;
6561                 else if (!strcmp(value, "last"))
6562                         focus_close = SWM_STACK_TOP;
6563                 else if (!strcmp(value, "next"))
6564                         focus_close = SWM_STACK_ABOVE;
6565                 else if (!strcmp(value, "previous"))
6566                         focus_close = SWM_STACK_BELOW;
6567                 else
6568                         errx(1, "focus_close");
6569                 break;
6570         case SWM_S_FOCUS_CLOSE_WRAP:
6571                 focus_close_wrap = atoi(value);
6572                 break;
6573         case SWM_S_FOCUS_DEFAULT:
6574                 if (!strcmp(value, "last"))
6575                         focus_default = SWM_STACK_TOP;
6576                 else if (!strcmp(value, "first"))
6577                         focus_default = SWM_STACK_BOTTOM;
6578                 else
6579                         errx(1, "focus_default");
6580                 break;
6581         case SWM_S_FOCUS_MODE:
6582                 if (!strcmp(value, "default"))
6583                         focus_mode = SWM_FOCUS_DEFAULT;
6584                 else if (!strcmp(value, "follow") ||
6585                     !strcmp(value, "follow_cursor"))
6586                         focus_mode = SWM_FOCUS_FOLLOW;
6587                 else if (!strcmp(value, "manual"))
6588                         focus_mode = SWM_FOCUS_MANUAL;
6589                 else
6590                         errx(1, "focus_mode");
6591                 break;
6592         case SWM_S_SPAWN_ORDER:
6593                 if (!strcmp(value, "first"))
6594                         spawn_position = SWM_STACK_BOTTOM;
6595                 else if (!strcmp(value, "last"))
6596                         spawn_position = SWM_STACK_TOP;
6597                 else if (!strcmp(value, "next"))
6598                         spawn_position = SWM_STACK_ABOVE;
6599                 else if (!strcmp(value, "previous"))
6600                         spawn_position = SWM_STACK_BELOW;
6601                 else
6602                         errx(1, "spawn_position");
6603                 break;
6604         case SWM_S_SPAWN_TERM:
6605                 setconfspawn("term", value, 0);
6606                 setconfspawn("spawn_term", value, 0);
6607                 break;
6608         case SWM_S_SS_APP:
6609                 break;
6610         case SWM_S_SS_ENABLED:
6611                 ss_enabled = atoi(value);
6612                 break;
6613         case SWM_S_STACK_ENABLED:
6614                 stack_enabled = atoi(value);
6615                 break;
6616         case SWM_S_TERM_WIDTH:
6617                 term_width = atoi(value);
6618                 if (term_width < 0)
6619                         term_width = 0;
6620                 break;
6621         case SWM_S_TITLE_CLASS_ENABLED:
6622                 title_class_enabled = atoi(value);
6623                 break;
6624         case SWM_S_TITLE_NAME_ENABLED:
6625                 title_name_enabled = atoi(value);
6626                 break;
6627         case SWM_S_URGENT_ENABLED:
6628                 urgent_enabled = atoi(value);
6629                 break;
6630         case SWM_S_VERBOSE_LAYOUT:
6631                 verbose_layout = atoi(value);
6632                 for (i = 0; layouts[i].l_stack != NULL; i++) {
6633                         if (verbose_layout)
6634                                 layouts[i].l_string = fancy_stacker;
6635                         else
6636                                 layouts[i].l_string = plain_stacker;
6637                 }
6638                 break;
6639         case SWM_S_WINDOW_NAME_ENABLED:
6640                 window_name_enabled = atoi(value);
6641                 break;
6642         case SWM_S_WORKSPACE_LIMIT:
6643                 workspace_limit = atoi(value);
6644                 if (workspace_limit > SWM_WS_MAX)
6645                         workspace_limit = SWM_WS_MAX;
6646                 else if (workspace_limit < 1)
6647                         workspace_limit = 1;
6648                 break;
6649         default:
6650                 return (1);
6651         }
6652         return (0);
6653 }
6654
6655 int
6656 setconfmodkey(char *selector, char *value, int flags)
6657 {
6658         /* suppress unused warnings since vars are needed */
6659         (void)selector;
6660         (void)flags;
6661
6662         if (!strncasecmp(value, "Mod1", strlen("Mod1")))
6663                 update_modkey(XCB_MOD_MASK_1);
6664         else if (!strncasecmp(value, "Mod2", strlen("Mod2")))
6665                 update_modkey(XCB_MOD_MASK_2);
6666         else if (!strncasecmp(value, "Mod3", strlen("Mod3")))
6667                 update_modkey(XCB_MOD_MASK_3);
6668         else if (!strncasecmp(value, "Mod4", strlen("Mod4")))
6669                 update_modkey(XCB_MOD_MASK_4);
6670         else
6671                 return (1);
6672         return (0);
6673 }
6674
6675 int
6676 setconfcolor(char *selector, char *value, int flags)
6677 {
6678         setscreencolor(value, ((selector == NULL)?-1:atoi(selector)), flags);
6679         return (0);
6680 }
6681
6682 int
6683 setconfregion(char *selector, char *value, int flags)
6684 {
6685         /* suppress unused warnings since vars are needed */
6686         (void)selector;
6687         (void)flags;
6688
6689         custom_region(value);
6690         return (0);
6691 }
6692
6693 int
6694 setautorun(char *selector, char *value, int flags)
6695 {
6696         int                     ws_id;
6697         char                    s[1024];
6698         char                    *ap, *sp;
6699         union arg               a;
6700         int                     argc = 0;
6701         pid_t                   pid;
6702         struct pid_e            *p;
6703
6704         /* suppress unused warnings since vars are needed */
6705         (void)selector;
6706         (void)flags;
6707
6708         if (getenv("SWM_STARTED"))
6709                 return (0);
6710
6711         bzero(s, sizeof s);
6712         if (sscanf(value, "ws[%d]:%1023c", &ws_id, s) != 2)
6713                 errx(1, "invalid autorun entry, should be 'ws[<idx>]:command'");
6714         ws_id--;
6715         if (ws_id < 0 || ws_id >= workspace_limit)
6716                 errx(1, "autorun: invalid workspace %d", ws_id + 1);
6717
6718         sp = expand_tilde((char *)&s);
6719
6720         /*
6721          * This is a little intricate
6722          *
6723          * If the pid already exists we simply reuse it because it means it was
6724          * used before AND not claimed by manage_window.  We get away with
6725          * altering it in the parent after INSERT because this can not be a race
6726          */
6727         a.argv = NULL;
6728         while ((ap = strsep(&sp, " \t")) != NULL) {
6729                 if (*ap == '\0')
6730                         continue;
6731                 DNPRINTF(SWM_D_SPAWN, "setautorun: arg [%s]\n", ap);
6732                 argc++;
6733                 if ((a.argv = realloc(a.argv, argc * sizeof(char *))) == NULL)
6734                         err(1, "setautorun: realloc");
6735                 a.argv[argc - 1] = ap;
6736         }
6737         free(sp);
6738
6739         if ((a.argv = realloc(a.argv, (argc + 1) * sizeof(char *))) == NULL)
6740                 err(1, "setautorun: realloc");
6741         a.argv[argc] = NULL;
6742
6743         if ((pid = fork()) == 0) {
6744                 spawn(ws_id, &a, 1);
6745                 /* NOTREACHED */
6746                 _exit(1);
6747         }
6748         free(a.argv);
6749
6750         /* parent */
6751         p = find_pid(pid);
6752         if (p == NULL) {
6753                 p = calloc(1, sizeof *p);
6754                 if (p == NULL)
6755                         return (1);
6756                 TAILQ_INSERT_TAIL(&pidlist, p, entry);
6757         }
6758
6759         p->pid = pid;
6760         p->ws = ws_id;
6761
6762         return (0);
6763 }
6764
6765 int
6766 setlayout(char *selector, char *value, int flags)
6767 {
6768         int                     ws_id, i, x, mg, ma, si, ar, f = 0;
6769         int                     st = SWM_V_STACK, num_screens;
6770         char                    s[1024];
6771         struct workspace        *ws;
6772
6773         /* suppress unused warnings since vars are needed */
6774         (void)selector;
6775         (void)flags;
6776
6777         if (getenv("SWM_STARTED"))
6778                 return (0);
6779
6780         bzero(s, sizeof s);
6781         if (sscanf(value, "ws[%d]:%d:%d:%d:%d:%1023c",
6782             &ws_id, &mg, &ma, &si, &ar, s) != 6)
6783                 errx(1, "invalid layout entry, should be 'ws[<idx>]:"
6784                     "<master_grow>:<master_add>:<stack_inc>:<always_raise>:"
6785                     "<type>'");
6786         ws_id--;
6787         if (ws_id < 0 || ws_id >= workspace_limit)
6788                 errx(1, "layout: invalid workspace %d", ws_id + 1);
6789
6790         if (!strcasecmp(s, "vertical"))
6791                 st = SWM_V_STACK;
6792         else if (!strcasecmp(s, "vertical_flip")) {
6793                 st = SWM_V_STACK;
6794                 f = 1;
6795         } else if (!strcasecmp(s, "horizontal"))
6796                 st = SWM_H_STACK;
6797         else if (!strcasecmp(s, "horizontal_flip")) {
6798                 st = SWM_H_STACK;
6799                 f = 1;
6800         } else if (!strcasecmp(s, "fullscreen"))
6801                 st = SWM_MAX_STACK;
6802         else
6803                 errx(1, "invalid layout entry, should be 'ws[<idx>]:"
6804                     "<master_grow>:<master_add>:<stack_inc>:<always_raise>:"
6805                     "<type>'");
6806
6807         num_screens = xcb_setup_roots_length(xcb_get_setup(conn));
6808         for (i = 0; i < num_screens; i++) {
6809                 ws = (struct workspace *)&screens[i].ws;
6810                 ws[ws_id].cur_layout = &layouts[st];
6811
6812                 ws[ws_id].always_raise = ar;
6813                 if (st == SWM_MAX_STACK)
6814                         continue;
6815
6816                 /* master grow */
6817                 for (x = 0; x < abs(mg); x++) {
6818                         ws[ws_id].cur_layout->l_config(&ws[ws_id],
6819                             mg >= 0 ?  SWM_ARG_ID_MASTERGROW :
6820                             SWM_ARG_ID_MASTERSHRINK);
6821                         stack();
6822                 }
6823                 /* master add */
6824                 for (x = 0; x < abs(ma); x++) {
6825                         ws[ws_id].cur_layout->l_config(&ws[ws_id],
6826                             ma >= 0 ?  SWM_ARG_ID_MASTERADD :
6827                             SWM_ARG_ID_MASTERDEL);
6828                         stack();
6829                 }
6830                 /* stack inc */
6831                 for (x = 0; x < abs(si); x++) {
6832                         ws[ws_id].cur_layout->l_config(&ws[ws_id],
6833                             si >= 0 ?  SWM_ARG_ID_STACKINC :
6834                             SWM_ARG_ID_STACKDEC);
6835                         stack();
6836                 }
6837                 /* Apply flip */
6838                 if (f) {
6839                         ws[ws_id].cur_layout->l_config(&ws[ws_id],
6840                             SWM_ARG_ID_FLIPLAYOUT);
6841                         stack();
6842                 }
6843         }
6844
6845         focus_flush();
6846
6847         return (0);
6848 }
6849
6850 /* config options */
6851 struct config_option {
6852         char                    *optname;
6853         int                     (*func)(char*, char*, int);
6854         int                     funcflags;
6855 };
6856 struct config_option configopt[] = {
6857         { "bar_enabled",                setconfvalue,   SWM_S_BAR_ENABLED },
6858         { "bar_at_bottom",              setconfvalue,   SWM_S_BAR_AT_BOTTOM },
6859         { "bar_border",                 setconfcolor,   SWM_S_COLOR_BAR_BORDER },
6860         { "bar_border_width",           setconfvalue,   SWM_S_BAR_BORDER_WIDTH },
6861         { "bar_color",                  setconfcolor,   SWM_S_COLOR_BAR },
6862         { "bar_font_color",             setconfcolor,   SWM_S_COLOR_BAR_FONT },
6863         { "bar_font",                   setconfvalue,   SWM_S_BAR_FONT },
6864         { "bar_action",                 setconfvalue,   SWM_S_BAR_ACTION },
6865         { "bar_delay",                  setconfvalue,   SWM_S_BAR_DELAY },
6866         { "bar_justify",                setconfvalue,   SWM_S_BAR_JUSTIFY },
6867         { "bar_format",                 setconfvalue,   SWM_S_BAR_FORMAT },
6868         { "keyboard_mapping",           setkeymapping,  0 },
6869         { "bind",                       setconfbinding, 0 },
6870         { "stack_enabled",              setconfvalue,   SWM_S_STACK_ENABLED },
6871         { "clock_enabled",              setconfvalue,   SWM_S_CLOCK_ENABLED },
6872         { "clock_format",               setconfvalue,   SWM_S_CLOCK_FORMAT },
6873         { "color_focus",                setconfcolor,   SWM_S_COLOR_FOCUS },
6874         { "color_unfocus",              setconfcolor,   SWM_S_COLOR_UNFOCUS },
6875         { "cycle_empty",                setconfvalue,   SWM_S_CYCLE_EMPTY },
6876         { "cycle_visible",              setconfvalue,   SWM_S_CYCLE_VISIBLE },
6877         { "workspace_limit",            setconfvalue,   SWM_S_WORKSPACE_LIMIT },
6878         { "dialog_ratio",               setconfvalue,   SWM_S_DIALOG_RATIO },
6879         { "verbose_layout",             setconfvalue,   SWM_S_VERBOSE_LAYOUT },
6880         { "modkey",                     setconfmodkey,  0 },
6881         { "program",                    setconfspawn,   0 },
6882         { "quirk",                      setconfquirk,   0 },
6883         { "region",                     setconfregion,  0 },
6884         { "spawn_term",                 setconfvalue,   SWM_S_SPAWN_TERM },
6885         { "screenshot_enabled",         setconfvalue,   SWM_S_SS_ENABLED },
6886         { "screenshot_app",             setconfvalue,   SWM_S_SS_APP },
6887         { "window_name_enabled",        setconfvalue,   SWM_S_WINDOW_NAME_ENABLED },
6888         { "urgent_enabled",             setconfvalue,   SWM_S_URGENT_ENABLED },
6889         { "term_width",                 setconfvalue,   SWM_S_TERM_WIDTH },
6890         { "title_class_enabled",        setconfvalue,   SWM_S_TITLE_CLASS_ENABLED },
6891         { "title_name_enabled",         setconfvalue,   SWM_S_TITLE_NAME_ENABLED },
6892         { "focus_mode",                 setconfvalue,   SWM_S_FOCUS_MODE },
6893         { "focus_close",                setconfvalue,   SWM_S_FOCUS_CLOSE },
6894         { "focus_close_wrap",           setconfvalue,   SWM_S_FOCUS_CLOSE_WRAP },
6895         { "focus_default",              setconfvalue,   SWM_S_FOCUS_DEFAULT },
6896         { "spawn_position",             setconfvalue,   SWM_S_SPAWN_ORDER },
6897         { "disable_border",             setconfvalue,   SWM_S_DISABLE_BORDER },
6898         { "border_width",               setconfvalue,   SWM_S_BORDER_WIDTH },
6899         { "autorun",                    setautorun,     0 },
6900         { "layout",                     setlayout,      0 },
6901 };
6902
6903 int
6904 conf_load(const char *filename, int keymapping)
6905 {
6906         FILE                    *config;
6907         char                    *line, *cp, *optsub, *optval;
6908         size_t                  linelen, lineno = 0;
6909         int                     wordlen, i, optidx;
6910         struct config_option    *opt = NULL;
6911
6912         DNPRINTF(SWM_D_CONF, "conf_load: begin\n");
6913
6914         if (filename == NULL) {
6915                 warnx("conf_load: no filename");
6916                 return (1);
6917         }
6918         if ((config = fopen(filename, "r")) == NULL) {
6919                 warn("conf_load: fopen: %s", filename);
6920                 return (1);
6921         }
6922
6923         while (!feof(config)) {
6924                 if ((line = fparseln(config, &linelen, &lineno, NULL, 0))
6925                     == NULL) {
6926                         if (ferror(config))
6927                                 err(1, "%s", filename);
6928                         else
6929                                 continue;
6930                 }
6931                 cp = line;
6932                 cp += strspn(cp, " \t\n"); /* eat whitespace */
6933                 if (cp[0] == '\0') {
6934                         /* empty line */
6935                         free(line);
6936                         continue;
6937                 }
6938                 /* get config option */
6939                 wordlen = strcspn(cp, "=[ \t\n");
6940                 if (wordlen == 0) {
6941                         warnx("%s: line %zd: no option found",
6942                             filename, lineno);
6943                         goto out;
6944                 }
6945                 optidx = -1;
6946                 for (i = 0; i < LENGTH(configopt); i++) {
6947                         opt = &configopt[i];
6948                         if (!strncasecmp(cp, opt->optname, wordlen) &&
6949                             (int)strlen(opt->optname) == wordlen) {
6950                                 optidx = i;
6951                                 break;
6952                         }
6953                 }
6954                 if (optidx == -1) {
6955                         warnx("%s: line %zd: unknown option %.*s",
6956                             filename, lineno, wordlen, cp);
6957                         goto out;
6958                 }
6959                 if (keymapping && opt && strcmp(opt->optname, "bind")) {
6960                         warnx("%s: line %zd: invalid option %.*s",
6961                             filename, lineno, wordlen, cp);
6962                         goto out;
6963                 }
6964                 cp += wordlen;
6965                 cp += strspn(cp, " \t\n"); /* eat whitespace */
6966                 /* get [selector] if any */
6967                 optsub = NULL;
6968                 if (*cp == '[') {
6969                         cp++;
6970                         wordlen = strcspn(cp, "]");
6971                         if (*cp != ']') {
6972                                 if (wordlen == 0) {
6973                                         warnx("%s: line %zd: syntax error",
6974                                             filename, lineno);
6975                                         goto out;
6976                                 }
6977
6978                                 if (asprintf(&optsub, "%.*s", wordlen, cp) ==
6979                                     -1) {
6980                                         warnx("%s: line %zd: unable to allocate"
6981                                             "memory for selector", filename,
6982                                             lineno);
6983                                         goto out;
6984                                 }
6985                         }
6986                         cp += wordlen;
6987                         cp += strspn(cp, "] \t\n"); /* eat trailing */
6988                 }
6989                 cp += strspn(cp, "= \t\n"); /* eat trailing */
6990                 /* get RHS value */
6991                 optval = strdup(cp);
6992                 /* call function to deal with it all */
6993                 if (configopt[optidx].func(optsub, optval,
6994                     configopt[optidx].funcflags) != 0)
6995                         errx(1, "%s: line %zd: invalid data for %s",
6996                             filename, lineno, configopt[optidx].optname);
6997                 free(optval);
6998                 free(optsub);
6999                 free(line);
7000         }
7001
7002         fclose(config);
7003         DNPRINTF(SWM_D_CONF, "conf_load: end\n");
7004
7005         return (0);
7006
7007 out:
7008         free(line);
7009         fclose(config);
7010         DNPRINTF(SWM_D_CONF, "conf_load: end with error.\n");
7011
7012         return (1);
7013 }
7014
7015 void
7016 set_child_transient(struct ws_win *win, xcb_window_t *trans)
7017 {
7018         struct ws_win           *parent, *w;
7019         struct swm_region       *r;
7020         struct workspace        *ws;
7021         xcb_icccm_wm_hints_t    wmh;
7022
7023         parent = find_window(win->transient);
7024         if (parent)
7025                 parent->focus_child = win;
7026         else {
7027                 DNPRINTF(SWM_D_MISC, "set_child_transient: parent doesn't exist"
7028                     " for 0x%x trans 0x%x\n", win->id, win->transient);
7029
7030                 r = root_to_region(win->wa->root, SWM_CK_ALL);
7031                 ws = r->ws;
7032                 /* parent doen't exist in our window list */
7033                 TAILQ_FOREACH(w, &ws->winlist, entry) {
7034                         if (xcb_icccm_get_wm_hints_reply(conn,
7035                             xcb_icccm_get_wm_hints(conn, w->id),
7036                             &wmh, NULL) != 1) {
7037                                 warnx("can't get hints for 0x%x", w->id);
7038                                 continue;
7039                         }
7040
7041                         if (win->hints.window_group != wmh.window_group)
7042                                 continue;
7043
7044                         w->focus_child = win;
7045                         win->transient = w->id;
7046                         *trans = w->id;
7047                         DNPRINTF(SWM_D_MISC, "set_child_transient: adjusting "
7048                             "transient to 0x%x\n", win->transient);
7049                         break;
7050                 }
7051         }
7052 }
7053
7054 pid_t
7055 window_get_pid(xcb_window_t win)
7056 {
7057         pid_t                           ret = 0;
7058         const char                      *errstr;
7059         xcb_atom_t                      apid;
7060         xcb_get_property_cookie_t       pc;
7061         xcb_get_property_reply_t        *pr;
7062
7063         apid = get_atom_from_string("_NET_WM_PID");
7064         if (apid == XCB_ATOM_NONE)
7065                 goto tryharder;
7066
7067         pc = xcb_get_property(conn, 0, win, apid, XCB_ATOM_CARDINAL, 0, 1);
7068         pr = xcb_get_property_reply(conn, pc, NULL);
7069         if (!pr)
7070                 goto tryharder;
7071         if (pr->type != XCB_ATOM_CARDINAL) {
7072                 free(pr);
7073                 goto tryharder;
7074         }
7075
7076         if (pr->type == apid && pr->format == 32)
7077                 ret = *((pid_t *)xcb_get_property_value(pr));
7078         free(pr);
7079
7080         return (ret);
7081
7082 tryharder:
7083         apid = get_atom_from_string("_SWM_PID");
7084         pc = xcb_get_property(conn, 0, win, apid, XCB_ATOM_STRING,
7085             0, SWM_PROPLEN);
7086         pr = xcb_get_property_reply(conn, pc, NULL);
7087         if (!pr)
7088                 return (0);
7089         if (pr->type != apid) {
7090                 free(pr);
7091                 return (0);
7092         }
7093
7094         ret = (pid_t)strtonum(xcb_get_property_value(pr), 0, INT_MAX, &errstr);
7095         free(pr);
7096
7097         return (ret);
7098 }
7099
7100 int
7101 get_ws_idx(xcb_window_t id)
7102 {
7103         int                     ws_idx = -1;
7104         char                    *prop = NULL;
7105         size_t                  proplen;
7106         const char              *errstr;
7107         xcb_get_property_reply_t        *gpr;
7108
7109         gpr = xcb_get_property_reply(conn,
7110                 xcb_get_property(conn, 0, id, a_swm_ws,
7111                     XCB_ATOM_STRING, 0, SWM_PROPLEN),
7112                 NULL);
7113         if (!gpr)
7114                 return (-1);
7115         if (gpr->type) {
7116                 proplen = xcb_get_property_value_length(gpr);
7117                 if (proplen > 0) {
7118                         prop = malloc(proplen + 1);
7119                         if (prop) {
7120                                 memcpy(prop,
7121                                     xcb_get_property_value(gpr),
7122                                     proplen);
7123                                 prop[proplen] = '\0';
7124                         }
7125                 }
7126         }
7127         free(gpr);
7128
7129         if (prop) {
7130                 DNPRINTF(SWM_D_PROP, "get_ws_idx: _SWM_WS: %s\n", prop);
7131                 ws_idx = (int)strtonum(prop, 0, workspace_limit - 1, &errstr);
7132                 if (errstr) {
7133                         DNPRINTF(SWM_D_PROP, "get_ws_idx: window: #%s: %s",
7134                             errstr, prop);
7135                 }
7136                 free(prop);
7137         }
7138
7139         return ws_idx;
7140 }
7141
7142 struct ws_win *
7143 manage_window(xcb_window_t id, uint16_t mapped)
7144 {
7145         xcb_window_t            trans = XCB_WINDOW_NONE;
7146         struct ws_win           *win, *ww;
7147         int                     ws_idx;
7148         char                    ws_idx_str[SWM_PROPLEN];
7149         struct swm_region       *r;
7150         struct pid_e            *p;
7151         struct quirk            *qp;
7152         uint32_t                i, wa[2];
7153         xcb_icccm_get_wm_protocols_reply_t      wpr;
7154
7155         if ((win = find_window(id)) != NULL) {
7156                 DNPRINTF(SWM_D_MISC, "manage_window: win 0x%x already "
7157                     "managed; skipping.)\n", id);
7158                 return (win);   /* Already managed. */
7159         }
7160
7161         /* See if window is on the unmanaged list. */
7162         if ((win = find_unmanaged_window(id)) != NULL) {
7163                 DNPRINTF(SWM_D_MISC, "manage_window: win 0x%x found on "
7164                     "unmanaged list.\n", id);
7165                 TAILQ_REMOVE(&win->ws->unmanagedlist, win, entry);
7166
7167                 if (win->transient)
7168                         set_child_transient(win, &trans);
7169
7170                 goto out;
7171         } else {
7172                 DNPRINTF(SWM_D_MISC, "manage_window: win 0x%x is new.\n", id);
7173         }
7174
7175         /* Create and initialize ws_win object. */
7176         if ((win = calloc(1, sizeof(struct ws_win))) == NULL)
7177                 err(1, "manage_window: calloc: failed to allocate memory for "
7178                     "new window");
7179
7180         win->id = id;
7181
7182         /* Get window geometry. */
7183         win->wa = xcb_get_geometry_reply(conn,
7184             xcb_get_geometry(conn, win->id),
7185             NULL);
7186
7187         /* Figure out which region the window belongs to. */
7188         r = root_to_region(win->wa->root, SWM_CK_ALL);
7189
7190         /* Ignore window border if there is one. */
7191         WIDTH(win) = win->wa->width;
7192         HEIGHT(win) = win->wa->height;
7193         X(win) = win->wa->x + win->wa->border_width - border_width;
7194         Y(win) = win->wa->y + win->wa->border_width - border_width;
7195         win->bordered = 1;
7196         win->mapped = mapped;
7197         win->floatmaxed = 0;
7198         win->ewmh_flags = 0;
7199         win->s = r->s;  /* this never changes */
7200
7201         store_float_geom(win, r);
7202
7203         /* Get WM_SIZE_HINTS. */
7204         xcb_icccm_get_wm_normal_hints_reply(conn,
7205             xcb_icccm_get_wm_normal_hints(conn, win->id),
7206             &win->sh, NULL);
7207
7208         /* Get WM_HINTS. */
7209         xcb_icccm_get_wm_hints_reply(conn,
7210             xcb_icccm_get_wm_hints(conn, win->id),
7211             &win->hints, NULL);
7212
7213         /* Get WM_TRANSIENT_FOR; see if window is a transient. */
7214         xcb_icccm_get_wm_transient_for_reply(conn,
7215             xcb_icccm_get_wm_transient_for(conn, win->id),
7216             &trans, NULL);
7217         if (trans) {
7218                 win->transient = trans;
7219                 set_child_transient(win, &win->transient);
7220         }
7221
7222         /* Get supported protocols. */
7223         if (xcb_icccm_get_wm_protocols_reply(conn,
7224             xcb_icccm_get_wm_protocols(conn, win->id, a_prot),
7225             &wpr, NULL)) {
7226                 for (i = 0; i < wpr.atoms_len; i++) {
7227                         if (wpr.atoms[i] == a_takefocus)
7228                                 win->take_focus = 1;
7229                         if (wpr.atoms[i] == a_delete)
7230                                 win->can_delete = 1;
7231                 }
7232                 xcb_icccm_get_wm_protocols_reply_wipe(&wpr);
7233         }
7234
7235         win->iconic = get_swm_iconic(win);
7236
7237         /* Figure out which workspace the window belongs to. */
7238         if ((p = find_pid(window_get_pid(win->id))) != NULL) {
7239                 win->ws = &r->s->ws[p->ws];
7240                 TAILQ_REMOVE(&pidlist, p, entry);
7241                 free(p);
7242                 p = NULL;
7243         } else if ((ws_idx = get_ws_idx(win->id)) != -1 &&
7244             !win->transient) {
7245                 /* _SWM_WS is set; use that. */
7246                 win->ws = &r->s->ws[ws_idx];
7247         } else if (trans && (ww = find_window(trans)) != NULL) {
7248                 /* Launch transients in the same ws as parent. */
7249                 win->ws = ww->ws;
7250         } else {
7251                 win->ws = r->ws;
7252         }
7253
7254         /* Set the _SWM_WS atom so we can remember this after reincarnation. */
7255         if (snprintf(ws_idx_str, SWM_PROPLEN, "%d", win->ws->idx) <
7256             SWM_PROPLEN) {
7257                 DNPRINTF(SWM_D_PROP, "manage_window: set _SWM_WS: %s\n",
7258                     ws_idx_str);
7259                 xcb_change_property(conn, XCB_PROP_MODE_REPLACE, win->id,
7260                     a_swm_ws, XCB_ATOM_STRING, 8, strlen(ws_idx_str),
7261                     ws_idx_str);
7262         }
7263
7264         /* Handle EWMH */
7265         ewmh_autoquirk(win);
7266
7267         /* Determine initial quirks. */
7268         if (xcb_icccm_get_wm_class_reply(conn,
7269             xcb_icccm_get_wm_class(conn, win->id),
7270             &win->ch, NULL)) {
7271                 DNPRINTF(SWM_D_CLASS, "manage_window: class: %s, name: %s\n",
7272                     win->ch.class_name, win->ch.instance_name);
7273
7274                 /* java is retarded so treat it special */
7275                 if (strstr(win->ch.instance_name, "sun-awt")) {
7276                         DNPRINTF(SWM_D_CLASS, "manage_window: java window "
7277                             "detected.\n");
7278                         win->java = 1;
7279                 }
7280
7281                 TAILQ_FOREACH(qp, &quirks, entry) {
7282                         if (!strcmp(win->ch.class_name, qp->class) &&
7283                             !strcmp(win->ch.instance_name, qp->name)) {
7284                                 DNPRINTF(SWM_D_CLASS, "manage_window: on quirks"
7285                                     "list; mask: 0x%lx\n", qp->quirk);
7286                                 if (qp->quirk & SWM_Q_FLOAT)
7287                                         win->floating = 1;
7288                                 win->quirks = qp->quirk;
7289                         }
7290                 }
7291         }
7292
7293         /* Alter window position if quirky */
7294         if (win->quirks & SWM_Q_ANYWHERE)
7295                 win->manual = 1;
7296
7297         /* Reset font sizes (the bruteforce way; no default keybinding). */
7298         if (win->quirks & SWM_Q_XTERM_FONTADJ) {
7299                 for (i = 0; i < SWM_MAX_FONT_STEPS; i++)
7300                         fake_keypress(win, XK_KP_Subtract, XCB_MOD_MASK_SHIFT);
7301                 for (i = 0; i < SWM_MAX_FONT_STEPS; i++)
7302                         fake_keypress(win, XK_KP_Add, XCB_MOD_MASK_SHIFT);
7303         }
7304
7305         /* Make sure window is positioned inside its region, if its active. */
7306         if (win->ws->r) {
7307                 constrain_window(win, win->ws->r, 0);
7308                 update_window(win);
7309         }
7310
7311         /* Select which X events to monitor and set border pixel color. */
7312         wa[0] = win->s->c[SWM_S_COLOR_UNFOCUS].pixel;
7313         wa[1] = XCB_EVENT_MASK_ENTER_WINDOW | XCB_EVENT_MASK_PROPERTY_CHANGE |
7314             XCB_EVENT_MASK_STRUCTURE_NOTIFY;
7315 #ifdef SWM_DEBUG
7316         wa[1] |= XCB_EVENT_MASK_LEAVE_WINDOW | XCB_EVENT_MASK_FOCUS_CHANGE;
7317 #endif
7318
7319         xcb_change_window_attributes(conn, win->id, XCB_CW_BORDER_PIXEL |
7320             XCB_CW_EVENT_MASK, wa);
7321
7322 out:
7323         /* Figure out where to stack the window in the workspace. */
7324         if (trans && (ww = find_window(trans)))
7325                 TAILQ_INSERT_AFTER(&win->ws->winlist, ww, win, entry);
7326         else if (win->ws->focus && spawn_position == SWM_STACK_ABOVE)
7327                 TAILQ_INSERT_AFTER(&win->ws->winlist, win->ws->focus, win,
7328                     entry);
7329         else if (win->ws->focus && spawn_position == SWM_STACK_BELOW)
7330                 TAILQ_INSERT_BEFORE(win->ws->focus, win, entry);
7331         else switch (spawn_position) {
7332         default:
7333         case SWM_STACK_TOP:
7334         case SWM_STACK_ABOVE:
7335                 TAILQ_INSERT_TAIL(&win->ws->winlist, win, entry);
7336                 break;
7337         case SWM_STACK_BOTTOM:
7338         case SWM_STACK_BELOW:
7339                 TAILQ_INSERT_HEAD(&win->ws->winlist, win, entry);
7340         }
7341
7342         /* Get initial _NET_WM_STATE */
7343         ewmh_get_win_state(win);
7344         /* Set initial _NET_WM_ALLOWED_ACTIONS */
7345         ewmh_update_actions(win);
7346
7347         grabbuttons(win);
7348
7349         DNPRINTF(SWM_D_MISC, "manage_window: done. window: 0x%x, (x,y) w x h: "
7350             "(%d,%d) %d x %d, ws: %d, iconic: %s, transient: 0x%x\n", win->id,
7351             X(win), Y(win), WIDTH(win), HEIGHT(win), win->ws->idx,
7352             YESNO(win->iconic), win->transient);
7353
7354         return (win);
7355 }
7356
7357 void
7358 free_window(struct ws_win *win)
7359 {
7360         DNPRINTF(SWM_D_MISC, "free_window: window: 0x%x\n", win->id);
7361
7362         if (win == NULL)
7363                 return;
7364
7365         TAILQ_REMOVE(&win->ws->unmanagedlist, win, entry);
7366
7367         if (win->wa)
7368                 free(win->wa);
7369
7370         xcb_icccm_get_wm_class_reply_wipe(&win->ch);
7371
7372         kill_refs(win);
7373
7374         /* paint memory */
7375         memset(win, 0xff, sizeof *win); /* XXX kill later */
7376
7377         free(win);
7378         DNPRINTF(SWM_D_MISC, "free_window: done.\n");
7379 }
7380
7381 void
7382 unmanage_window(struct ws_win *win)
7383 {
7384         struct ws_win           *parent;
7385
7386         if (win == NULL)
7387                 return;
7388
7389         DNPRINTF(SWM_D_MISC, "unmanage_window: window: 0x%x\n", win->id);
7390
7391         if (win->transient) {
7392                 parent = find_window(win->transient);
7393                 if (parent)
7394                         parent->focus_child = NULL;
7395         }
7396
7397         TAILQ_REMOVE(&win->ws->winlist, win, entry);
7398         TAILQ_INSERT_TAIL(&win->ws->unmanagedlist, win, entry);
7399 }
7400
7401 void
7402 expose(xcb_expose_event_t *e)
7403 {
7404         int                     i, num_screens;
7405         struct swm_region       *r;
7406
7407         DNPRINTF(SWM_D_EVENT, "expose: window: 0x%x\n", e->window);
7408
7409         num_screens = xcb_setup_roots_length(xcb_get_setup(conn));
7410         for (i = 0; i < num_screens; i++)
7411                 TAILQ_FOREACH(r, &screens[i].rl, entry)
7412                         if (e->window == WINID(r->bar))
7413                                 bar_update();
7414
7415         xcb_flush(conn);
7416 }
7417
7418 #ifdef SWM_DEBUG
7419 void
7420 focusin(xcb_focus_in_event_t *e)
7421 {
7422         DNPRINTF(SWM_D_EVENT, "focusin: window: 0x%x, mode: %s(%u), "
7423             "detail: %s(%u)\n", e->event, get_notify_mode_label(e->mode),
7424             e->mode, get_notify_detail_label(e->detail), e->detail);
7425 }
7426
7427 void
7428 focusout(xcb_focus_out_event_t *e)
7429 {
7430         DNPRINTF(SWM_D_EVENT, "focusout: window: 0x%x, mode: %s(%u), "
7431             "detail: %s(%u)\n", e->event, get_notify_mode_label(e->mode),
7432             e->mode, get_notify_detail_label(e->detail), e->detail);
7433 }
7434 #endif
7435
7436 void
7437 keypress(xcb_key_press_event_t *e)
7438 {
7439         xcb_keysym_t            keysym;
7440         struct key              *kp;
7441
7442         keysym = xcb_key_press_lookup_keysym(syms, e, 0);
7443
7444         DNPRINTF(SWM_D_EVENT, "keypress: %u %u\n", e->detail, keysym);
7445
7446         if ((kp = key_lookup(CLEANMASK(e->state), keysym)) == NULL)
7447                 return;
7448
7449         last_event_time = e->time;
7450
7451         if (kp->funcid == KF_SPAWN_CUSTOM)
7452                 spawn_custom(root_to_region(e->root, SWM_CK_ALL),
7453                     &(keyfuncs[kp->funcid].args), kp->spawn_name);
7454         else if (keyfuncs[kp->funcid].func)
7455                 keyfuncs[kp->funcid].func(root_to_region(e->root, SWM_CK_ALL),
7456                     &(keyfuncs[kp->funcid].args));
7457 }
7458
7459 void
7460 buttonpress(xcb_button_press_event_t *e)
7461 {
7462         struct ws_win           *win = NULL;
7463         struct swm_region       *r, *old_r;
7464         int                     i;
7465         int                     handled = 0;
7466
7467         DNPRINTF(SWM_D_EVENT, "buttonpress: win (x,y): 0x%x (%d,%d), "
7468             "detail: %u, time: %u, root (x,y): 0x%x (%d,%d), child: 0x%x, "
7469             "state: %u, same_screen: %s\n", e->event, e->event_x, e->event_y,
7470             e->detail, e->time, e->root, e->root_x, e->root_y, e->child,
7471             e->state, YESNO(e->same_screen));
7472
7473         if (e->event == e->root) {
7474                 if (e->child != 0) {
7475                         win = find_window(e->child);
7476                         /* Pass ButtonPress to window if it isn't managed. */
7477                         if (win == NULL)
7478                                 goto out;
7479                 } else {
7480                         /* Focus on empty region */
7481                         /* If no windows on region if its empty. */
7482                         r = root_to_region(e->root, SWM_CK_POINTER);
7483                         if (r == NULL) {
7484                                 DNPRINTF(SWM_D_EVENT, "buttonpress: "
7485                                     "NULL region; ignoring.\n");
7486                                 goto out;
7487                         }
7488
7489                         if (TAILQ_EMPTY(&r->ws->winlist)) {
7490                                 old_r = root_to_region(e->root, SWM_CK_FOCUS);
7491                                 if (old_r && old_r != r)
7492                                         unfocus_win(old_r->ws->focus);
7493
7494                                 xcb_set_input_focus(conn,
7495                                     XCB_INPUT_FOCUS_PARENT, e->root, e->time);
7496
7497                                 /* Clear bar since empty. */
7498                                 bar_update();
7499
7500                                 handled = 1;
7501                                 goto out;
7502                         }
7503                 }
7504         } else {
7505                 win = find_window(e->event);
7506         }
7507
7508         if (win == NULL)
7509                 goto out;
7510
7511         last_event_time = e->time;
7512
7513         focus_win(get_focus_magic(win));
7514
7515         for (i = 0; i < LENGTH(buttons); i++)
7516                 if (client_click == buttons[i].action && buttons[i].func &&
7517                     buttons[i].button == e->detail &&
7518                     CLEANMASK(buttons[i].mask) == CLEANMASK(e->state)) {
7519                         buttons[i].func(win, &buttons[i].args);
7520                         handled = 1;
7521                 }
7522
7523 out:
7524         if (!handled) {
7525                 DNPRINTF(SWM_D_EVENT, "buttonpress: passing to window.\n");
7526                 /* Replay event to event window */
7527                 xcb_allow_events(conn, XCB_ALLOW_REPLAY_POINTER, e->time);
7528         } else {
7529                 DNPRINTF(SWM_D_EVENT, "buttonpress: handled.\n");
7530                 /* Unfreeze grab events. */
7531                 xcb_allow_events(conn, XCB_ALLOW_SYNC_POINTER, e->time);
7532         }
7533
7534         xcb_flush(conn);
7535 }
7536
7537 #ifdef SWM_DEBUG
7538 void
7539 print_win_geom(xcb_window_t w)
7540 {
7541         xcb_get_geometry_reply_t        *wa;
7542
7543         wa = xcb_get_geometry_reply(conn, xcb_get_geometry(conn, w), NULL);
7544
7545         if (!wa) {
7546                 DNPRINTF(SWM_D_MISC, "print_win_geom: window not found: 0x%x\n",
7547                     w);
7548                 return;
7549         }
7550
7551         DNPRINTF(SWM_D_MISC, "print_win_geom: window: 0x%x, root: 0x%x, "
7552             "depth: %u, (x,y) w x h: (%d,%d) %d x %d, border: %d\n",
7553             w, wa->root, wa->depth, wa->x,  wa->y, wa->width, wa->height,
7554             wa->border_width);
7555
7556         free(wa);
7557 }
7558 #endif
7559
7560 #ifdef SWM_DEBUG
7561 char *
7562 get_stack_mode_name(uint8_t mode)
7563 {
7564         char    *name;
7565
7566         switch(mode) {
7567         case XCB_STACK_MODE_ABOVE:
7568                 name = "Above";
7569                 break;
7570         case XCB_STACK_MODE_BELOW:
7571                 name = "Below";
7572                 break;
7573         case XCB_STACK_MODE_TOP_IF:
7574                 name = "TopIf";
7575                 break;
7576         case XCB_STACK_MODE_BOTTOM_IF:
7577                 name = "BottomIf";
7578                 break;
7579         case XCB_STACK_MODE_OPPOSITE:
7580                 name = "Opposite";
7581                 break;
7582         default:
7583                 name = "Unknown";
7584         }
7585
7586         return name;
7587 }
7588 #endif
7589
7590 void
7591 configurerequest(xcb_configure_request_event_t *e)
7592 {
7593         struct ws_win           *win;
7594         struct swm_region       *r = NULL;
7595         int                     new = 0, i = 0;
7596         uint16_t                mask = 0;
7597         uint32_t                wc[7] = {0};
7598
7599         if ((win = find_window(e->window)) == NULL)
7600                 if ((win = find_unmanaged_window(e->window)) == NULL)
7601                         new = 1;
7602
7603 #ifdef SWM_DEBUG
7604         if (swm_debug & SWM_D_EVENT) {
7605                 print_win_geom(e->window);
7606
7607                 DNPRINTF(SWM_D_EVENT, "configurerequest: window: 0x%x, "
7608                     "parent: 0x%x, new: %s, value_mask: %u { ", e->window,
7609                     e->parent, YESNO(new), e->value_mask);
7610                 if (e->value_mask & XCB_CONFIG_WINDOW_X)
7611                         DPRINTF("X: %d ", e->x);
7612                 if (e->value_mask & XCB_CONFIG_WINDOW_Y)
7613                         DPRINTF("Y: %d ", e->y);
7614                 if (e->value_mask & XCB_CONFIG_WINDOW_WIDTH)
7615                         DPRINTF("W: %u ", e->width);
7616                 if (e->value_mask & XCB_CONFIG_WINDOW_HEIGHT)
7617                         DPRINTF("H: %u ", e->height);
7618                 if (e->value_mask & XCB_CONFIG_WINDOW_BORDER_WIDTH)
7619                         DPRINTF("Border: %u ", e->border_width);
7620                 if (e->value_mask & XCB_CONFIG_WINDOW_SIBLING)
7621                         DPRINTF("Sibling: 0x%x ", e->sibling);
7622                 if (e->value_mask & XCB_CONFIG_WINDOW_STACK_MODE)
7623                         DPRINTF("StackMode: %s(%u) ",
7624                             get_stack_mode_name(e->stack_mode), e->stack_mode);
7625                 DPRINTF("}\n");
7626         }
7627 #endif
7628
7629         if (new) {
7630                 if (e->value_mask & XCB_CONFIG_WINDOW_X) {
7631                         mask |= XCB_CONFIG_WINDOW_X;
7632                         wc[i++] = e->x;
7633                 }
7634                 if (e->value_mask & XCB_CONFIG_WINDOW_Y) {
7635                         mask |= XCB_CONFIG_WINDOW_Y;
7636                         wc[i++] = e->y;
7637                 }
7638                 if (e->value_mask & XCB_CONFIG_WINDOW_WIDTH) {
7639                         mask |= XCB_CONFIG_WINDOW_WIDTH;
7640                         wc[i++] = e->width;
7641                 }
7642                 if (e->value_mask & XCB_CONFIG_WINDOW_HEIGHT) {
7643                         mask |= XCB_CONFIG_WINDOW_HEIGHT;
7644                         wc[i++] = e->height;
7645                 }
7646                 if (e->value_mask & XCB_CONFIG_WINDOW_BORDER_WIDTH) {
7647                         mask |= XCB_CONFIG_WINDOW_BORDER_WIDTH;
7648                         wc[i++] = e->border_width;
7649                 }
7650                 if (e->value_mask & XCB_CONFIG_WINDOW_SIBLING) {
7651                         mask |= XCB_CONFIG_WINDOW_SIBLING;
7652                         wc[i++] = e->sibling;
7653                 }
7654                 if (e->value_mask & XCB_CONFIG_WINDOW_STACK_MODE) {
7655                         mask |= XCB_CONFIG_WINDOW_STACK_MODE;
7656                         wc[i++] = e->stack_mode;
7657                 }
7658
7659                 if (mask != 0) {
7660                         xcb_configure_window(conn, e->window, mask, wc);
7661                         xcb_flush(conn);
7662                 }
7663         } else if ((!win->manual || win->quirks & SWM_Q_ANYWHERE) &&
7664             !(win->ewmh_flags & EWMH_F_FULLSCREEN)) {
7665                 if (win->ws->r)
7666                         r = win->ws->r;
7667                 else if (win->ws->old_r)
7668                         r = win->ws->old_r;
7669
7670                 /* windows are centered unless ANYWHERE quirk is set. */
7671                 if (win->quirks & SWM_Q_ANYWHERE) {
7672                         if (e->value_mask & XCB_CONFIG_WINDOW_X) {
7673                                 win->g_float.x = e->x;
7674                                 if (r)
7675                                         win->g_float.x -= X(r);
7676                         }
7677
7678                         if (e->value_mask & XCB_CONFIG_WINDOW_Y) {
7679                                 win->g_float.y = e->y;
7680                                 if (r)
7681                                         win->g_float.y -= Y(r);
7682                         }
7683                 }
7684
7685                 if (e->value_mask & XCB_CONFIG_WINDOW_WIDTH)
7686                         win->g_float.w = e->width;
7687
7688                 if (e->value_mask & XCB_CONFIG_WINDOW_HEIGHT)
7689                         win->g_float.h = e->height;
7690
7691                 win->g_floatvalid = 1;
7692
7693                 if (win->floating && r && (win->transient ||
7694                     win->ws->cur_layout != &layouts[SWM_MAX_STACK])) {
7695                         WIDTH(win) = win->g_float.w;
7696                         HEIGHT(win) = win->g_float.h;
7697
7698                         if (r) {
7699                                 stack_floater(win, r);
7700                                 focus_flush();
7701                         }
7702                 } else {
7703                         config_win(win, e);
7704                         xcb_flush(conn);
7705                 }
7706         } else {
7707                 config_win(win, e);
7708                 xcb_flush(conn);
7709         }
7710
7711         DNPRINTF(SWM_D_EVENT, "configurerequest: done.\n");
7712 }
7713
7714 void
7715 configurenotify(xcb_configure_notify_event_t *e)
7716 {
7717         struct ws_win           *win;
7718
7719         DNPRINTF(SWM_D_EVENT, "configurenotify: win 0x%x, event win: 0x%x, "
7720             "(x,y) WxH: (%d,%d) %ux%u, border: %u, above_sibling: 0x%x, "
7721             "override_redirect: %s\n", e->window, e->event, e->x, e->y,
7722             e->width, e->height, e->border_width, e->above_sibling,
7723             YESNO(e->override_redirect));
7724
7725         win = find_window(e->window);
7726         if (win) {
7727                 xcb_icccm_get_wm_normal_hints_reply(conn,
7728                     xcb_icccm_get_wm_normal_hints(conn, win->id),
7729                     &win->sh, NULL);
7730                 adjust_font(win);
7731                 if (font_adjusted) {
7732                         stack();
7733                         xcb_flush(conn);
7734                 }
7735         }
7736 }
7737
7738 void
7739 destroynotify(xcb_destroy_notify_event_t *e)
7740 {
7741         struct ws_win           *win;
7742
7743         DNPRINTF(SWM_D_EVENT, "destroynotify: window: 0x%x\n", e->window);
7744
7745         if ((win = find_window(e->window)) == NULL) {
7746                 if ((win = find_unmanaged_window(e->window)) == NULL)
7747                         return;
7748                 free_window(win);
7749                 return;
7750         }
7751
7752         if (focus_mode != SWM_FOCUS_FOLLOW) {
7753                 /* If we were focused, make sure we focus on something else. */
7754                 if (win == win->ws->focus)
7755                         win->ws->focus_pending = get_focus_prev(win);
7756         }
7757
7758         unmanage_window(win);
7759         stack();
7760
7761         if (focus_mode != SWM_FOCUS_FOLLOW) {
7762                 if (win->ws->focus_pending) {
7763                         focus_win(win->ws->focus_pending);
7764                         win->ws->focus_pending = NULL;
7765                 }
7766         }
7767
7768         free_window(win);
7769
7770         focus_flush();
7771 }
7772
7773 #ifdef SWM_DEBUG
7774 char *
7775 get_notify_detail_label(uint8_t detail)
7776 {
7777         char *label;
7778
7779         switch (detail) {
7780         case XCB_NOTIFY_DETAIL_ANCESTOR:
7781                 label = "Ancestor";
7782                 break;
7783         case XCB_NOTIFY_DETAIL_VIRTUAL:
7784                 label = "Virtual";
7785                 break;
7786         case XCB_NOTIFY_DETAIL_INFERIOR:
7787                 label = "Inferior";
7788                 break;
7789         case XCB_NOTIFY_DETAIL_NONLINEAR:
7790                 label = "Nonlinear";
7791                 break;
7792         case XCB_NOTIFY_DETAIL_NONLINEAR_VIRTUAL:
7793                 label = "NonlinearVirtual";
7794                 break;
7795         case XCB_NOTIFY_DETAIL_POINTER:
7796                 label = "Pointer";
7797                 break;
7798         case XCB_NOTIFY_DETAIL_POINTER_ROOT:
7799                 label = "PointerRoot";
7800                 break;
7801         case XCB_NOTIFY_DETAIL_NONE:
7802                 label = "None";
7803                 break;
7804         default:
7805                 label = "Unknown";
7806         }
7807
7808         return label;
7809 }
7810
7811 char *
7812 get_notify_mode_label(uint8_t mode)
7813 {
7814         char *label;
7815
7816         switch (mode) {
7817         case XCB_NOTIFY_MODE_NORMAL:
7818                 label = "Normal";
7819                 break;
7820         case XCB_NOTIFY_MODE_GRAB:
7821                 label = "Grab";
7822                 break;
7823         case XCB_NOTIFY_MODE_UNGRAB:
7824                 label = "Ungrab";
7825                 break;
7826         case XCB_NOTIFY_MODE_WHILE_GRABBED:
7827                 label = "WhileGrabbed";
7828                 break;
7829         default:
7830                 label = "Unknown";
7831         }
7832
7833         return label;
7834 }
7835 #endif
7836
7837 void
7838 enternotify(xcb_enter_notify_event_t *e)
7839 {
7840         struct ws_win           *win;
7841         struct swm_region       *old_r, *r;
7842
7843         DNPRINTF(SWM_D_FOCUS, "enternotify: time: %u, win (x,y): 0x%x "
7844             "(%d,%d), mode: %s(%d), detail: %s(%d), root (x,y): 0x%x (%d,%d), "
7845             "child: 0x%x, same_screen_focus: %s, state: %d\n",
7846             e->time, e->event, e->event_x, e->event_y,
7847             get_notify_mode_label(e->mode), e->mode,
7848             get_notify_detail_label(e->detail), e->detail,
7849             e->root, e->root_x, e->root_y, e->child,
7850             YESNO(e->same_screen_focus), e->state);
7851
7852         if (focus_mode == SWM_FOCUS_MANUAL &&
7853             e->mode == XCB_NOTIFY_MODE_NORMAL) {
7854                 DNPRINTF(SWM_D_EVENT, "enternotify: manual focus; ignoring.\n");
7855                 return;
7856         }
7857
7858         last_event_time = e->time;
7859
7860         if ((win = find_window(e->event)) == NULL) {
7861                 if (e->event == e->root) {
7862                         /* If no windows on pointer region, then focus root. */
7863                         r = root_to_region(e->root, SWM_CK_POINTER);
7864                         if (r == NULL) {
7865                                 DNPRINTF(SWM_D_EVENT, "enterntoify: "
7866                                     "NULL region; ignoring.\n");
7867                                 return;
7868                         }
7869
7870                         if (TAILQ_EMPTY(&r->ws->winlist)) {
7871                                 old_r = root_to_region(e->root, SWM_CK_FOCUS);
7872                                 if (old_r && old_r != r)
7873                                         unfocus_win(old_r->ws->focus);
7874
7875                                 xcb_set_input_focus(conn,
7876                                     XCB_INPUT_FOCUS_PARENT, e->root, e->time);
7877
7878                                 /* Clear bar since empty. */
7879                                 bar_update();
7880
7881                                 focus_flush();
7882                         }
7883                 } else {
7884                         DNPRINTF(SWM_D_EVENT, "enternotify: window is NULL; "
7885                             "ignoring\n");
7886                 }
7887                 return;
7888         }
7889
7890         focus_win(get_focus_magic(win));
7891
7892         xcb_flush(conn);
7893 }
7894
7895 #ifdef SWM_DEBUG
7896 void
7897 leavenotify(xcb_leave_notify_event_t *e)
7898 {
7899         DNPRINTF(SWM_D_FOCUS, "leavenotify: time: %u, win (x,y): 0x%x "
7900             "(%d,%d), mode: %s(%d), detail: %s(%d), root (x,y): 0x%x (%d,%d), "
7901             "child: 0x%x, same_screen_focus: %s, state: %d\n",
7902             e->time, e->event, e->event_x, e->event_y,
7903             get_notify_mode_label(e->mode), e->mode,
7904             get_notify_detail_label(e->detail), e->detail,
7905             e->root, e->root_x, e->root_y, e->child,
7906             YESNO(e->same_screen_focus), e->state);
7907 }
7908 #endif
7909
7910 void
7911 mapnotify(xcb_map_notify_event_t *e)
7912 {
7913         struct ws_win           *win;
7914
7915         DNPRINTF(SWM_D_EVENT, "mapnotify: window: 0x%x\n", e->window);
7916
7917         if ((win = find_window(e->window)) == NULL)
7918                 win = manage_window(e->window, 1);
7919
7920         win->mapped = 1;
7921         set_win_state(win, XCB_ICCCM_WM_STATE_NORMAL);
7922
7923         if (focus_mode != SWM_FOCUS_FOLLOW) {
7924                 if (win->ws->focus_pending == win) {
7925                         focus_win(win);
7926                         win->ws->focus_pending = NULL;
7927                         focus_flush();
7928                 }
7929         }
7930
7931         xcb_flush(conn);
7932 }
7933
7934 void
7935 mappingnotify(xcb_mapping_notify_event_t *e)
7936 {
7937         xcb_refresh_keyboard_mapping(syms, e);
7938
7939         if (e->request == XCB_MAPPING_KEYBOARD)
7940                 grabkeys();
7941 }
7942
7943 void
7944 maprequest(xcb_map_request_event_t *e)
7945 {
7946         struct ws_win           *win;
7947         xcb_get_window_attributes_reply_t *war;
7948
7949         DNPRINTF(SWM_D_EVENT, "maprequest: win 0x%x\n",
7950             e->window);
7951
7952         war = xcb_get_window_attributes_reply(conn,
7953             xcb_get_window_attributes(conn, e->window),
7954             NULL);
7955         if (war == NULL) {
7956                 DNPRINTF(SWM_D_EVENT, "maprequest: window lost.\n");
7957                 goto out;
7958         }
7959
7960         if (war->override_redirect) {
7961                 DNPRINTF(SWM_D_EVENT, "maprequest: override_redirect; "
7962                     "skipping.\n");
7963                 goto out;
7964         }
7965
7966         win = manage_window(e->window,
7967             (war->map_state == XCB_MAP_STATE_VIEWABLE));
7968
7969         /* The new window should get focus; prepare. */
7970         if (focus_mode != SWM_FOCUS_FOLLOW)
7971                 win->ws->focus_pending = get_focus_magic(win);
7972
7973         /* All windows need to be mapped if they are in the current workspace.*/
7974         if (win->ws->r)
7975                 stack();
7976
7977         /* Ignore EnterNotify to handle the mapnotify without interference. */
7978         if (focus_mode == SWM_FOCUS_DEFAULT)
7979                 event_drain(XCB_ENTER_NOTIFY);
7980 out:
7981         free(war);
7982         DNPRINTF(SWM_D_EVENT, "maprequest: done.\n");
7983 }
7984
7985 #ifdef SWM_DEBUG
7986 char *
7987 get_atom_name(xcb_atom_t atom)
7988 {
7989         char                            *name = NULL;
7990 #if 0
7991         /*
7992          * This should be disabled during most debugging since
7993          * xcb_get_* causes an xcb_flush.
7994          */
7995         size_t                          len;
7996         xcb_get_atom_name_reply_t       *r;
7997
7998         r = xcb_get_atom_name_reply(conn,
7999             xcb_get_atom_name(conn, atom),
8000             NULL);
8001         if (r) {
8002                 len = xcb_get_atom_name_name_length(r);
8003                 if (len > 0) {
8004                         name = malloc(len + 1);
8005                         if (name) {
8006                                 memcpy(name, xcb_get_atom_name_name(r), len);
8007                                 name[len] = '\0';
8008                         }
8009                 }
8010                 free(r);
8011         }
8012 #else
8013         (void)atom;
8014 #endif
8015         return (name);
8016 }
8017 #endif
8018
8019 void
8020 propertynotify(xcb_property_notify_event_t *e)
8021 {
8022         struct ws_win           *win;
8023 #ifdef SWM_DEBUG
8024         char                    *name;
8025
8026         name = get_atom_name(e->atom);
8027         DNPRINTF(SWM_D_EVENT, "propertynotify: window: 0x%x, atom: %s(%u), "
8028             "time: %#x, state: %u\n", e->window, name, e->atom, e->time,
8029             e->state);
8030         free(name);
8031 #endif
8032         win = find_window(e->window);
8033         if (win == NULL)
8034                 return;
8035
8036         last_event_time = e->time;
8037
8038         if (e->atom == a_swm_iconic) {
8039                 if (e->state == XCB_PROPERTY_NEW_VALUE) {
8040                         if (focus_mode != SWM_FOCUS_FOLLOW)
8041                                 win->ws->focus_pending = get_focus_prev(win);
8042
8043                         unfocus_win(win);
8044                         unmap_window(win);
8045
8046                         if (win->ws->r) {
8047                                 stack();
8048                                 if (focus_mode != SWM_FOCUS_FOLLOW) {
8049                                         focus_win(win->ws->focus_pending);
8050                                         win->ws->focus_pending = NULL;
8051                                 }
8052                                 focus_flush();
8053                         }
8054                 } else if (e->state == XCB_PROPERTY_DELETE) {
8055                         /* The window is no longer iconic, restack ws. */
8056                         if (focus_mode != SWM_FOCUS_FOLLOW)
8057                                 win->ws->focus_pending = get_focus_magic(win);
8058
8059                         stack();
8060
8061                         /* Flush EnterNotify for mapnotify, if needed. */
8062                         focus_flush();
8063                 }
8064         } else if (e->atom == a_state) {
8065                 /* State just changed, make sure it gets focused if mapped. */
8066                 if (e->state == XCB_PROPERTY_NEW_VALUE) {
8067                         if (focus_mode != SWM_FOCUS_FOLLOW) {
8068                                 if (win->mapped &&
8069                                     win->ws->focus_pending == win) {
8070                                         focus_win(win->ws->focus_pending);
8071                                         win->ws->focus_pending = NULL;
8072                                 }
8073                         }
8074                 }
8075         } else if (e->atom == XCB_ATOM_WM_CLASS ||
8076             e->atom == XCB_ATOM_WM_NAME) {
8077                 bar_update();
8078         }
8079
8080         xcb_flush(conn);
8081 }
8082
8083 void
8084 unmapnotify(xcb_unmap_notify_event_t *e)
8085 {
8086         struct ws_win           *win;
8087         struct workspace        *ws;
8088
8089         DNPRINTF(SWM_D_EVENT, "unmapnotify: window: 0x%x\n", e->window);
8090
8091         /* If we aren't managing the window, then ignore. */
8092         win = find_window(e->window);
8093         if (win == NULL)
8094                 return;
8095
8096         ws = win->ws;
8097
8098         if (getstate(e->window) != XCB_ICCCM_WM_STATE_ICONIC)
8099                 set_win_state(win, XCB_ICCCM_WM_STATE_ICONIC);
8100
8101         if (win->mapped) {
8102                 /* window unmapped itself */
8103                 /* do unmap/unfocus/restack and unmanage */
8104                 win->mapped = 0;
8105
8106                 /* If win was focused, make sure to focus on something else. */
8107                 if (win == ws->focus) {
8108                         if (focus_mode != SWM_FOCUS_FOLLOW) {
8109                                 ws->focus_pending = get_focus_prev(win);
8110                                 DNPRINTF(SWM_D_EVENT, "unmapnotify: "
8111                                     "focus_pending: 0x%x\n",
8112                                     WINID(ws->focus_pending));
8113                         }
8114
8115                         unfocus_win(win);
8116                 }
8117
8118                 unmanage_window(win);
8119
8120                 if (ws->r)
8121                         stack();
8122
8123                 if (focus_mode == SWM_FOCUS_FOLLOW) {
8124                         if (ws->r)
8125                                 focus_win(get_pointer_win(ws->r->s->root));
8126                 } else {
8127                         if (ws->focus_pending) {
8128                                 focus_win(ws->focus_pending);
8129                                 ws->focus_pending = NULL;
8130                         }
8131                 }
8132         }
8133
8134         if (getstate(e->window) == XCB_ICCCM_WM_STATE_NORMAL)
8135                 set_win_state(win, XCB_ICCCM_WM_STATE_ICONIC);
8136
8137         focus_flush();
8138 }
8139
8140 #if 0
8141 void
8142 visibilitynotify(xcb_visibility_notify_event_t *e)
8143 {
8144         DNPRINTF(SWM_D_EVENT, "visibilitynotify: window: 0x%x\n",
8145             e->window);
8146 }
8147 #endif
8148
8149 void
8150 clientmessage(xcb_client_message_event_t *e)
8151 {
8152         struct ws_win *win;
8153         xcb_map_request_event_t mre;
8154 #ifdef SWM_DEBUG
8155         char                    *name;
8156
8157         name = get_atom_name(e->type);
8158         DNPRINTF(SWM_D_EVENT, "clientmessage: window: 0x%x, atom: %s(%u)\n",
8159             e->window, name, e->type);
8160         free(name);
8161 #endif
8162         win = find_window(e->window);
8163
8164         if (win == NULL) {
8165                 if (e->type == ewmh[_NET_ACTIVE_WINDOW].atom) {
8166                         /* Manage the window with maprequest. */
8167                         DNPRINTF(SWM_D_EVENT, "clientmessage: request focus on "
8168                             "unmanaged window.\n");
8169                         mre.window = e->window;
8170                         maprequest(&mre);
8171                 }
8172                 return;
8173         }
8174
8175         if (e->type == ewmh[_NET_ACTIVE_WINDOW].atom) {
8176                 DNPRINTF(SWM_D_EVENT, "clientmessage: _NET_ACTIVE_WINDOW\n");
8177                 focus_win(win);
8178         }
8179         if (e->type == ewmh[_NET_CLOSE_WINDOW].atom) {
8180                 DNPRINTF(SWM_D_EVENT, "clientmessage: _NET_CLOSE_WINDOW\n");
8181                 if (win->can_delete)
8182                         client_msg(win, a_delete, 0);
8183                 else
8184                         xcb_kill_client(conn, win->id);
8185         }
8186         if (e->type == ewmh[_NET_MOVERESIZE_WINDOW].atom) {
8187                 DNPRINTF(SWM_D_EVENT,
8188                     "clientmessage: _NET_MOVERESIZE_WINDOW\n");
8189                 if (win->floating) {
8190                         if (e->data.data32[0] & (1<<8)) /* x */
8191                                 X(win) = e->data.data32[1];
8192                         if (e->data.data32[0] & (1<<9)) /* y */
8193                                 Y(win) = e->data.data32[2];
8194                         if (e->data.data32[0] & (1<<10)) /* width */
8195                                 WIDTH(win) = e->data.data32[3];
8196                         if (e->data.data32[0] & (1<<11)) /* height */
8197                                 HEIGHT(win) = e->data.data32[4];
8198
8199                         update_window(win);
8200                 }
8201                 else {
8202                         /* TODO: Change stack sizes */
8203                         /* notify no change was made. */
8204                         config_win(win, NULL);
8205                 }
8206         }
8207         if (e->type == ewmh[_NET_WM_STATE].atom) {
8208                 DNPRINTF(SWM_D_EVENT, "clientmessage: _NET_WM_STATE\n");
8209                 ewmh_update_win_state(win, e->data.data32[1], e->data.data32[0]);
8210                 if (e->data.data32[2])
8211                         ewmh_update_win_state(win, e->data.data32[2],
8212                             e->data.data32[0]);
8213
8214                 stack();
8215         }
8216
8217         focus_flush();
8218 }
8219
8220 void
8221 check_conn(void)
8222 {
8223         int      errcode = xcb_connection_has_error(conn);
8224 #ifdef XCB_CONN_ERROR
8225         char    *s;
8226         switch (errcode) {
8227         case XCB_CONN_ERROR:
8228                 s = "Socket error, pipe error or other stream error.";
8229                 break;
8230         case XCB_CONN_CLOSED_EXT_NOTSUPPORTED:
8231                 s = "Extension not supported.";
8232                 break;
8233         case XCB_CONN_CLOSED_MEM_INSUFFICIENT:
8234                 s = "Insufficient memory.";
8235                 break;
8236         case XCB_CONN_CLOSED_REQ_LEN_EXCEED:
8237                 s = "Request length was exceeded.";
8238                 break;
8239         case XCB_CONN_CLOSED_PARSE_ERR:
8240                 s = "Error parsing display string.";
8241                 break;
8242         default:
8243                 s = "Unknown error.";
8244         }
8245         if (errcode)
8246                 errx(errcode, "X CONNECTION ERROR: %s", s);
8247 #else
8248         if (errcode)
8249                 errx(errcode, "X CONNECTION ERROR");
8250 #endif
8251 }
8252
8253 int
8254 enable_wm(void)
8255 {
8256         int                     num_screens, i;
8257         const uint32_t          val = XCB_EVENT_MASK_SUBSTRUCTURE_REDIRECT |
8258             XCB_EVENT_MASK_ENTER_WINDOW;
8259         xcb_screen_t            *sc;
8260         xcb_void_cookie_t       wac;
8261         xcb_generic_error_t     *error;
8262
8263         /* this causes an error if some other window manager is running */
8264         num_screens = xcb_setup_roots_length(xcb_get_setup(conn));
8265         for (i = 0; i < num_screens; i++) {
8266                 if ((sc = get_screen(i)) == NULL)
8267                         errx(1, "ERROR: can't get screen %d.", i);
8268                 DNPRINTF(SWM_D_INIT, "enable_wm: screen %d, root: 0x%x\n",
8269                     i, sc->root);
8270                 wac = xcb_change_window_attributes_checked(conn, sc->root,
8271                     XCB_CW_EVENT_MASK, &val);
8272                 if ((error = xcb_request_check(conn, wac))) {
8273                         DNPRINTF(SWM_D_INIT, "enable_wm: error_code: %u\n",
8274                             error->error_code);
8275                         free(error);
8276                         return 1;
8277                 }
8278
8279                 /* click to focus on empty region */
8280                 xcb_grab_button(conn, 1, sc->root, BUTTONMASK,
8281                     XCB_GRAB_MODE_SYNC, XCB_GRAB_MODE_ASYNC, XCB_WINDOW_NONE,
8282                     XCB_CURSOR_NONE, XCB_BUTTON_INDEX_1, XCB_BUTTON_MASK_ANY);
8283         }
8284
8285         return 0;
8286 }
8287
8288 void
8289 new_region(struct swm_screen *s, int x, int y, int w, int h)
8290 {
8291         struct swm_region       *r, *n;
8292         struct workspace        *ws = NULL;
8293         int                     i;
8294
8295         DNPRINTF(SWM_D_MISC, "new region: screen[%d]:%dx%d+%d+%d\n",
8296              s->idx, w, h, x, y);
8297
8298         /* remove any conflicting regions */
8299         n = TAILQ_FIRST(&s->rl);
8300         while (n) {
8301                 r = n;
8302                 n = TAILQ_NEXT(r, entry);
8303                 if (X(r) < (x + w) &&
8304                     (X(r) + WIDTH(r)) > x &&
8305                     Y(r) < (y + h) &&
8306                     (Y(r) + HEIGHT(r)) > y) {
8307                         if (r->ws->r != NULL)
8308                                 r->ws->old_r = r->ws->r;
8309                         r->ws->r = NULL;
8310                         bar_cleanup(r);
8311                         TAILQ_REMOVE(&s->rl, r, entry);
8312                         TAILQ_INSERT_TAIL(&s->orl, r, entry);
8313                 }
8314         }
8315
8316         /* search old regions for one to reuse */
8317
8318         /* size + location match */
8319         TAILQ_FOREACH(r, &s->orl, entry)
8320                 if (X(r) == x && Y(r) == y &&
8321                     HEIGHT(r) == h && WIDTH(r) == w)
8322                         break;
8323
8324         /* size match */
8325         TAILQ_FOREACH(r, &s->orl, entry)
8326                 if (HEIGHT(r) == h && WIDTH(r) == w)
8327                         break;
8328
8329         if (r != NULL) {
8330                 TAILQ_REMOVE(&s->orl, r, entry);
8331                 /* try to use old region's workspace */
8332                 if (r->ws->r == NULL)
8333                         ws = r->ws;
8334         } else
8335                 if ((r = calloc(1, sizeof(struct swm_region))) == NULL)
8336                         err(1, "new_region: calloc: failed to allocate memory "
8337                             "for screen");
8338
8339         /* if we don't have a workspace already, find one */
8340         if (ws == NULL) {
8341                 for (i = 0; i < workspace_limit; i++)
8342                         if (s->ws[i].r == NULL) {
8343                                 ws = &s->ws[i];
8344                                 break;
8345                         }
8346         }
8347
8348         if (ws == NULL)
8349                 errx(1, "new_region: no free workspaces");
8350
8351         X(r) = x;
8352         Y(r) = y;
8353         WIDTH(r) = w;
8354         HEIGHT(r) = h;
8355         r->s = s;
8356         r->ws = ws;
8357         r->ws_prior = NULL;
8358         ws->r = r;
8359         outputs++;
8360         TAILQ_INSERT_TAIL(&s->rl, r, entry);
8361 }
8362
8363 void
8364 scan_xrandr(int i)
8365 {
8366 #ifdef SWM_XRR_HAS_CRTC
8367         int                                             c;
8368         int                                             ncrtc = 0;
8369 #endif /* SWM_XRR_HAS_CRTC */
8370         struct swm_region                               *r;
8371         int                                             num_screens;
8372         xcb_randr_get_screen_resources_current_cookie_t src;
8373         xcb_randr_get_screen_resources_current_reply_t  *srr;
8374         xcb_randr_get_crtc_info_cookie_t                cic;
8375         xcb_randr_get_crtc_info_reply_t                 *cir = NULL;
8376         xcb_randr_crtc_t                                *crtc;
8377         xcb_screen_t                                    *screen;
8378
8379         DNPRINTF(SWM_D_MISC, "scan_xrandr: screen: %d\n", i);
8380
8381         if ((screen = get_screen(i)) == NULL)
8382                 errx(1, "ERROR: can't get screen %d.", i);
8383
8384         num_screens = xcb_setup_roots_length(xcb_get_setup(conn));
8385         if (i >= num_screens)
8386                 errx(1, "scan_xrandr: invalid screen");
8387
8388         /* remove any old regions */
8389         while ((r = TAILQ_FIRST(&screens[i].rl)) != NULL) {
8390                 r->ws->old_r = r->ws->r = NULL;
8391                 bar_cleanup(r);
8392                 TAILQ_REMOVE(&screens[i].rl, r, entry);
8393                 TAILQ_INSERT_TAIL(&screens[i].orl, r, entry);
8394         }
8395         outputs = 0;
8396
8397         /* map virtual screens onto physical screens */
8398 #ifdef SWM_XRR_HAS_CRTC
8399         if (xrandr_support) {
8400                 src = xcb_randr_get_screen_resources_current(conn,
8401                     screens[i].root);
8402                 srr = xcb_randr_get_screen_resources_current_reply(conn, src,
8403                     NULL);
8404                 if (srr == NULL) {
8405                         new_region(&screens[i], 0, 0,
8406                             screen->width_in_pixels,
8407                             screen->height_in_pixels);
8408                         goto out;
8409                 } else
8410                         ncrtc = srr->num_crtcs;
8411
8412                 crtc = xcb_randr_get_screen_resources_current_crtcs(srr);
8413                 for (c = 0; c < ncrtc; c++) {
8414                         cic = xcb_randr_get_crtc_info(conn, crtc[c],
8415                             XCB_CURRENT_TIME);
8416                         cir = xcb_randr_get_crtc_info_reply(conn, cic, NULL);
8417                         if (cir == NULL)
8418                                 continue;
8419                         if (cir->num_outputs == 0) {
8420                                 free(cir);
8421                                 continue;
8422                         }
8423
8424                         if (cir->mode == 0)
8425                                 new_region(&screens[i], 0, 0,
8426                                     screen->width_in_pixels,
8427                                     screen->height_in_pixels);
8428                         else
8429                                 new_region(&screens[i],
8430                                     cir->x, cir->y, cir->width, cir->height);
8431                         free(cir);
8432                 }
8433                 free(srr);
8434         }
8435 #endif /* SWM_XRR_HAS_CRTC */
8436
8437         /* If detection failed, create a single region that spans the screen. */
8438         if (TAILQ_EMPTY(&screens[i].rl))
8439                 new_region(&screens[i], 0, 0, screen->width_in_pixels,
8440                     screen->height_in_pixels);
8441
8442 out:
8443         DNPRINTF(SWM_D_MISC, "scan_xrandr: done.\n");
8444 }
8445
8446 void
8447 screenchange(xcb_randr_screen_change_notify_event_t *e)
8448 {
8449         struct swm_region               *r;
8450         int                             i, num_screens;
8451
8452         DNPRINTF(SWM_D_EVENT, "screenchange: root: 0x%x\n", e->root);
8453
8454         num_screens = xcb_setup_roots_length(xcb_get_setup(conn));
8455         /* silly event doesn't include the screen index */
8456         for (i = 0; i < num_screens; i++)
8457                 if (screens[i].root == e->root)
8458                         break;
8459         if (i >= num_screens)
8460                 errx(1, "screenchange: screen not found");
8461
8462         /* brute force for now, just re-enumerate the regions */
8463         scan_xrandr(i);
8464
8465 #ifdef SWM_DEBUG
8466         print_win_geom(e->root);
8467 #endif
8468         /* add bars to all regions */
8469         for (i = 0; i < num_screens; i++)
8470                 TAILQ_FOREACH(r, &screens[i].rl, entry)
8471                         bar_setup(r);
8472         stack();
8473 }
8474
8475 void
8476 grab_windows(void)
8477 {
8478         xcb_window_t            *wins = NULL, trans;
8479         int                     no;
8480         int                     i, j, num_screens;
8481         uint16_t                state, manage, mapped;
8482
8483         xcb_query_tree_cookie_t                 qtc;
8484         xcb_query_tree_reply_t                  *qtr;
8485         xcb_get_window_attributes_cookie_t      c;
8486         xcb_get_window_attributes_reply_t       *r;
8487         xcb_get_property_cookie_t               pc;
8488
8489         DNPRINTF(SWM_D_INIT, "grab_windows: begin\n");
8490         num_screens = xcb_setup_roots_length(xcb_get_setup(conn));
8491         for (i = 0; i < num_screens; i++) {
8492                 qtc = xcb_query_tree(conn, screens[i].root);
8493                 qtr = xcb_query_tree_reply(conn, qtc, NULL);
8494                 if (!qtr)
8495                         continue;
8496                 wins = xcb_query_tree_children(qtr);
8497                 no = xcb_query_tree_children_length(qtr);
8498                 /* attach windows to a region */
8499                 /* normal windows */
8500                 DNPRINTF(SWM_D_INIT, "grab_windows: grab top level windows.\n");
8501                 for (j = 0; j < no; j++) {
8502                         c = xcb_get_window_attributes(conn, wins[j]);
8503                         r = xcb_get_window_attributes_reply(conn, c, NULL);
8504                         if (!r) {
8505                                 DNPRINTF(SWM_D_INIT, "grab_windows: skip %#x; "
8506                                     "doesn't exist.\n", wins[j]);
8507                                 continue;
8508                         }
8509                         if (r->override_redirect) {
8510                                 DNPRINTF(SWM_D_INIT, "grab_windows: skip %#x; "
8511                                     "override_redirect set.\n", wins[j]);
8512                                 free(r);
8513                                 continue;
8514                         }
8515
8516                         pc = xcb_icccm_get_wm_transient_for(conn, wins[j]);
8517                         if (xcb_icccm_get_wm_transient_for_reply(conn, pc,
8518                             &trans, NULL)) {
8519                                 DNPRINTF(SWM_D_INIT, "grab_windows: skip %#x; "
8520                                     "is transient for %#x.\n", wins[j], trans);
8521                                 free(r);
8522                                 continue;
8523                         }
8524
8525                         state = getstate(wins[j]);
8526                         manage = state != XCB_ICCCM_WM_STATE_WITHDRAWN;
8527                         mapped = r->map_state != XCB_MAP_STATE_UNMAPPED;
8528                         if (mapped || manage)
8529                                 manage_window(wins[j], mapped);
8530                         free(r);
8531                 }
8532                 /* transient windows */
8533                 DNPRINTF(SWM_D_INIT, "grab_windows: grab transient windows.\n");
8534                 for (j = 0; j < no; j++) {
8535                         c = xcb_get_window_attributes(conn, wins[j]);
8536                         r = xcb_get_window_attributes_reply(conn, c, NULL);
8537                         if (!r) {
8538                                 DNPRINTF(SWM_D_INIT, "grab_windows: skip %#x; "
8539                                     "doesn't exist.\n", wins[j]);
8540                                 continue;
8541                         }
8542                         if (r->override_redirect) {
8543                                 DNPRINTF(SWM_D_INIT, "grab_windows: skip %#x; "
8544                                     "override_redirect set.\n", wins[j]);
8545                                 free(r);
8546                                 continue;
8547                         }
8548
8549                         state = getstate(wins[j]);
8550                         manage = state != XCB_ICCCM_WM_STATE_WITHDRAWN;
8551                         mapped = r->map_state != XCB_MAP_STATE_UNMAPPED;
8552                         pc = xcb_icccm_get_wm_transient_for(conn, wins[j]);
8553                         if (xcb_icccm_get_wm_transient_for_reply(conn, pc,
8554                             &trans, NULL) && manage)
8555                                 manage_window(wins[j], mapped);
8556                         free(r);
8557                 }
8558                 free(qtr);
8559         }
8560         DNPRINTF(SWM_D_INIT, "grab_windows: done.\n");
8561 }
8562
8563 void
8564 setup_screens(void)
8565 {
8566         int                     i, j, k, num_screens;
8567         struct workspace        *ws;
8568         uint32_t                gcv[1], wa[1];
8569         const xcb_query_extension_reply_t *qep;
8570         xcb_screen_t                            *screen;
8571         xcb_randr_query_version_cookie_t        c;
8572         xcb_randr_query_version_reply_t         *r;
8573
8574         num_screens = xcb_setup_roots_length(xcb_get_setup(conn));
8575         if ((screens = calloc(num_screens,
8576              sizeof(struct swm_screen))) == NULL)
8577                 err(1, "setup_screens: calloc: failed to allocate memory for "
8578                     "screens");
8579
8580         /* initial Xrandr setup */
8581         xrandr_support = 0;
8582         qep = xcb_get_extension_data(conn, &xcb_randr_id);
8583         if (qep->present) {
8584                 c = xcb_randr_query_version(conn, 1, 1);
8585                 r = xcb_randr_query_version_reply(conn, c, NULL);
8586                 if (r) {
8587                         if (r->major_version >= 1) {
8588                                 xrandr_support = 1;
8589                                 xrandr_eventbase = qep->first_event;
8590                         }
8591                         free(r);
8592                 }
8593         }
8594
8595         wa[0] = cursors[XC_LEFT_PTR].cid;
8596
8597         /* map physical screens */
8598         for (i = 0; i < num_screens; i++) {
8599                 DNPRINTF(SWM_D_WS, "setup_screens: init screen: %d\n", i);
8600                 screens[i].idx = i;
8601                 TAILQ_INIT(&screens[i].rl);
8602                 TAILQ_INIT(&screens[i].orl);
8603                 if ((screen = get_screen(i)) == NULL)
8604                         errx(1, "ERROR: can't get screen %d.", i);
8605                 screens[i].root = screen->root;
8606
8607                 /* set default colors */
8608                 setscreencolor("red", i + 1, SWM_S_COLOR_FOCUS);
8609                 setscreencolor("rgb:88/88/88", i + 1, SWM_S_COLOR_UNFOCUS);
8610                 setscreencolor("rgb:00/80/80", i + 1, SWM_S_COLOR_BAR_BORDER);
8611                 setscreencolor("black", i + 1, SWM_S_COLOR_BAR);
8612                 setscreencolor("rgb:a0/a0/a0", i + 1, SWM_S_COLOR_BAR_FONT);
8613
8614                 /* create graphics context on screen */
8615                 screens[i].bar_gc = xcb_generate_id(conn);
8616                 gcv[0] = 0;
8617                 xcb_create_gc(conn, screens[i].bar_gc, screens[i].root,
8618                     XCB_GC_GRAPHICS_EXPOSURES, gcv);
8619
8620                 /* set default cursor */
8621                 xcb_change_window_attributes(conn, screens[i].root,
8622                     XCB_CW_CURSOR, wa);
8623
8624                 /* init all workspaces */
8625                 /* XXX these should be dynamically allocated too */
8626                 for (j = 0; j < SWM_WS_MAX; j++) {
8627                         ws = &screens[i].ws[j];
8628                         ws->idx = j;
8629                         ws->name = NULL;
8630                         ws->bar_enabled = 1;
8631                         ws->focus = NULL;
8632                         ws->focus_prev = NULL;
8633                         ws->focus_pending = NULL;
8634                         ws->r = NULL;
8635                         ws->old_r = NULL;
8636                         TAILQ_INIT(&ws->winlist);
8637                         TAILQ_INIT(&ws->unmanagedlist);
8638
8639                         for (k = 0; layouts[k].l_stack != NULL; k++)
8640                                 if (layouts[k].l_config != NULL)
8641                                         layouts[k].l_config(ws,
8642                                             SWM_ARG_ID_STACKINIT);
8643                         ws->cur_layout = &layouts[0];
8644                         ws->cur_layout->l_string(ws);
8645                 }
8646
8647                 scan_xrandr(i);
8648
8649                 if (xrandr_support)
8650                         xcb_randr_select_input(conn, screens[i].root,
8651                             XCB_RANDR_NOTIFY_MASK_SCREEN_CHANGE);
8652         }
8653 }
8654
8655 void
8656 setup_globals(void)
8657 {
8658         if ((bar_fonts = strdup(SWM_BAR_FONTS)) == NULL)
8659                 err(1, "setup_globals: strdup: failed to allocate memory.");
8660
8661         if ((clock_format = strdup("%a %b %d %R %Z %Y")) == NULL)
8662                 err(1, "setup_globals: strdup: failed to allocate memory.");
8663
8664         if ((syms = xcb_key_symbols_alloc(conn)) == NULL)
8665                 errx(1, "unable to allocate key symbols");
8666
8667         a_state = get_atom_from_string("WM_STATE");
8668         a_prot = get_atom_from_string("WM_PROTOCOLS");
8669         a_delete = get_atom_from_string("WM_DELETE_WINDOW");
8670         a_takefocus = get_atom_from_string("WM_TAKE_FOCUS");
8671         a_wmname = get_atom_from_string("WM_NAME");
8672         a_netwmname = get_atom_from_string("_NET_WM_NAME");
8673         a_utf8_string = get_atom_from_string("UTF8_STRING");
8674         a_string = get_atom_from_string("STRING");
8675         a_swm_iconic = get_atom_from_string("_SWM_ICONIC");
8676         a_swm_ws = get_atom_from_string("_SWM_WS");
8677 }
8678
8679 void
8680 workaround(void)
8681 {
8682         int                     i, num_screens;
8683         xcb_atom_t              netwmcheck;
8684         xcb_window_t            root, win;
8685
8686         /* work around sun jdk bugs, code from wmname */
8687         netwmcheck = get_atom_from_string("_NET_SUPPORTING_WM_CHECK");
8688
8689         num_screens = xcb_setup_roots_length(xcb_get_setup(conn));
8690         for (i = 0; i < num_screens; i++) {
8691                 root = screens[i].root;
8692
8693                 win = xcb_generate_id(conn);
8694                 xcb_create_window(conn, XCB_COPY_FROM_PARENT, win, root,
8695                     0, 0, 1, 1, 0, XCB_WINDOW_CLASS_INPUT_OUTPUT,
8696                     XCB_COPY_FROM_PARENT, 0, NULL);
8697
8698                 xcb_change_property(conn, XCB_PROP_MODE_REPLACE, root,
8699                     netwmcheck, XCB_ATOM_WINDOW, 32, 1, &win);
8700                 xcb_change_property(conn, XCB_PROP_MODE_REPLACE, win,
8701                     netwmcheck, XCB_ATOM_WINDOW, 32, 1, &win);
8702                 xcb_change_property(conn, XCB_PROP_MODE_REPLACE, win,
8703                     a_netwmname, a_utf8_string, 8, strlen("LG3D"), "LG3D");
8704         }
8705 }
8706
8707 void
8708 shutdown_cleanup(void)
8709 {
8710         int i, num_screens;
8711
8712         /* disable alarm because the following code may not be interrupted */
8713         alarm(0);
8714         if (signal(SIGALRM, SIG_IGN) == SIG_ERR)
8715                 err(1, "can't disable alarm");
8716
8717         bar_extra_stop();
8718         bar_extra = 1;
8719         unmap_all();
8720
8721         cursors_cleanup();
8722
8723         teardown_ewmh();
8724
8725         num_screens = xcb_setup_roots_length(xcb_get_setup(conn));
8726         for (i = 0; i < num_screens; ++i) {
8727                 if (screens[i].bar_gc != 0)
8728                         xcb_free_gc(conn, screens[i].bar_gc);
8729                 if (!bar_font_legacy)
8730                         XftColorFree(display, DefaultVisual(display, i),
8731                             DefaultColormap(display, i), &bar_font_color);
8732         }
8733
8734         if (bar_font_legacy)
8735                 XFreeFontSet(display, bar_fs);
8736         else {
8737                 XftFontClose(display, bar_font);
8738         }
8739
8740         xcb_key_symbols_free(syms);
8741         xcb_flush(conn);
8742         xcb_disconnect(conn);
8743 }
8744
8745 void
8746 event_error(xcb_generic_error_t *e)
8747 {
8748         (void)e;
8749
8750         DNPRINTF(SWM_D_EVENT, "event_error: %s(%u) from %s(%u), sequence: %u, "
8751             "resource_id: %u, minor_code: %u\n",
8752             xcb_event_get_error_label(e->error_code), e->error_code,
8753             xcb_event_get_request_label(e->major_code), e->major_code,
8754             e->sequence, e->resource_id, e->minor_code);
8755 }
8756
8757 void
8758 event_handle(xcb_generic_event_t *evt)
8759 {
8760         uint8_t type = XCB_EVENT_RESPONSE_TYPE(evt);
8761
8762         DNPRINTF(SWM_D_EVENT, "XCB Event: %s(%d), seq %u\n",
8763             xcb_event_get_label(XCB_EVENT_RESPONSE_TYPE(evt)),
8764             XCB_EVENT_RESPONSE_TYPE(evt), evt->sequence);
8765
8766         switch (type) {
8767 #define EVENT(type, callback) case type: callback((void *)evt); return
8768         EVENT(0, event_error);
8769         EVENT(XCB_BUTTON_PRESS, buttonpress);
8770         /*EVENT(XCB_BUTTON_RELEASE, buttonpress);*/
8771         /*EVENT(XCB_CIRCULATE_NOTIFY, );*/
8772         /*EVENT(XCB_CIRCULATE_REQUEST, );*/
8773         EVENT(XCB_CLIENT_MESSAGE, clientmessage);
8774         /*EVENT(XCB_COLORMAP_NOTIFY, );*/
8775         EVENT(XCB_CONFIGURE_NOTIFY, configurenotify);
8776         EVENT(XCB_CONFIGURE_REQUEST, configurerequest);
8777         /*EVENT(XCB_CREATE_NOTIFY, );*/
8778         EVENT(XCB_DESTROY_NOTIFY, destroynotify);
8779         EVENT(XCB_ENTER_NOTIFY, enternotify);
8780         EVENT(XCB_EXPOSE, expose);
8781 #ifdef SWM_DEBUG
8782         EVENT(XCB_FOCUS_IN, focusin);
8783         EVENT(XCB_FOCUS_OUT, focusout);
8784 #endif
8785         /*EVENT(XCB_GRAPHICS_EXPOSURE, );*/
8786         /*EVENT(XCB_GRAVITY_NOTIFY, );*/
8787         EVENT(XCB_KEY_PRESS, keypress);
8788         /*EVENT(XCB_KEY_RELEASE, keypress);*/
8789         /*EVENT(XCB_KEYMAP_NOTIFY, );*/
8790 #ifdef SWM_DEBUG
8791         EVENT(XCB_LEAVE_NOTIFY, leavenotify);
8792 #endif
8793         EVENT(XCB_MAP_NOTIFY, mapnotify);
8794         EVENT(XCB_MAP_REQUEST, maprequest);
8795         EVENT(XCB_MAPPING_NOTIFY, mappingnotify);
8796         /*EVENT(XCB_MOTION_NOTIFY, );*/
8797         /*EVENT(XCB_NO_EXPOSURE, );*/
8798         EVENT(XCB_PROPERTY_NOTIFY, propertynotify);
8799         /*EVENT(XCB_REPARENT_NOTIFY, );*/
8800         /*EVENT(XCB_RESIZE_REQUEST, );*/
8801         /*EVENT(XCB_SELECTION_CLEAR, );*/
8802         /*EVENT(XCB_SELECTION_NOTIFY, );*/
8803         /*EVENT(XCB_SELECTION_REQUEST, );*/
8804         EVENT(XCB_UNMAP_NOTIFY, unmapnotify);
8805         /*EVENT(XCB_VISIBILITY_NOTIFY, visibilitynotify);*/
8806 #undef EVENT
8807         }
8808         if (type - xrandr_eventbase == XCB_RANDR_SCREEN_CHANGE_NOTIFY)
8809                 screenchange((void *)evt);
8810 }
8811
8812 int
8813 main(int argc, char *argv[])
8814 {
8815         struct swm_region       *r, *rr;
8816         struct ws_win           *winfocus = NULL;
8817         char                    conf[PATH_MAX], *cfile = NULL;
8818         struct stat             sb;
8819         int                     xfd, i, num_screens;
8820         struct sigaction        sact;
8821         xcb_generic_event_t     *evt;
8822         struct timeval          tv;
8823         fd_set                  rd;
8824
8825         /* suppress unused warning since var is needed */
8826         (void)argc;
8827
8828         time_started = time(NULL);
8829
8830         start_argv = argv;
8831         warnx("Welcome to spectrwm V%s Build: %s", SPECTRWM_VERSION, buildstr);
8832         if (!setlocale(LC_CTYPE, "") || !setlocale(LC_TIME, ""))
8833                 warnx("no locale support");
8834
8835         /* handle some signals */
8836         bzero(&sact, sizeof(sact));
8837         sigemptyset(&sact.sa_mask);
8838         sact.sa_flags = 0;
8839         sact.sa_handler = sighdlr;
8840         sigaction(SIGINT, &sact, NULL);
8841         sigaction(SIGQUIT, &sact, NULL);
8842         sigaction(SIGTERM, &sact, NULL);
8843         sigaction(SIGHUP, &sact, NULL);
8844
8845         sact.sa_handler = sighdlr;
8846         sact.sa_flags = SA_NOCLDSTOP;
8847         sigaction(SIGCHLD, &sact, NULL);
8848
8849         if (!(display = XOpenDisplay(0)))
8850                 errx(1, "can not open display");
8851
8852         conn = XGetXCBConnection(display);
8853         if (xcb_connection_has_error(conn))
8854                 errx(1, "can not get XCB connection");
8855
8856         XSetEventQueueOwner(display, XCBOwnsEventQueue);
8857
8858         xcb_prefetch_extension_data(conn, &xcb_randr_id);
8859         xfd = xcb_get_file_descriptor(conn);
8860
8861         /* look for local and global conf file */
8862         pwd = getpwuid(getuid());
8863         if (pwd == NULL)
8864                 errx(1, "invalid user: %d", getuid());
8865
8866         xcb_grab_server(conn);
8867         xcb_aux_sync(conn);
8868
8869         /* flush all events */
8870         while ((evt = xcb_poll_for_event(conn))) {
8871                 if (XCB_EVENT_RESPONSE_TYPE(evt) == 0)
8872                         event_handle(evt);
8873                 free(evt);
8874         }
8875
8876         if (enable_wm() != 0)
8877                 errx(1, "another window manager is currently running");
8878
8879         /* Load Xcursors and/or cursorfont glyph cursors. */
8880         cursors_load();
8881
8882         xcb_aux_sync(conn);
8883
8884         setup_globals();
8885         setup_screens();
8886         setup_keys();
8887         setup_quirks();
8888         setup_spawn();
8889
8890         /* load config */
8891         for (i = 0; ; i++) {
8892                 conf[0] = '\0';
8893                 switch (i) {
8894                 case 0:
8895                         /* ~ */
8896                         snprintf(conf, sizeof conf, "%s/.%s",
8897                             pwd->pw_dir, SWM_CONF_FILE);
8898                         break;
8899                 case 1:
8900                         /* global */
8901                         snprintf(conf, sizeof conf, "/etc/%s",
8902                             SWM_CONF_FILE);
8903                         break;
8904                 case 2:
8905                         /* ~ compat */
8906                         snprintf(conf, sizeof conf, "%s/.%s",
8907                             pwd->pw_dir, SWM_CONF_FILE_OLD);
8908                         break;
8909                 case 3:
8910                         /* global compat */
8911                         snprintf(conf, sizeof conf, "/etc/%s",
8912                             SWM_CONF_FILE_OLD);
8913                         break;
8914                 default:
8915                         goto noconfig;
8916                 }
8917
8918                 if (strlen(conf) && stat(conf, &sb) != -1)
8919                         if (S_ISREG(sb.st_mode)) {
8920                                 cfile = conf;
8921                                 break;
8922                         }
8923         }
8924 noconfig:
8925
8926         /* load conf (if any) */
8927         if (cfile)
8928                 conf_load(cfile, SWM_CONF_DEFAULT);
8929
8930         setup_ewmh();
8931         /* set some values to work around bad programs */
8932         workaround();
8933         /* grab existing windows (before we build the bars) */
8934         grab_windows();
8935
8936         if (getenv("SWM_STARTED") == NULL)
8937                 setenv("SWM_STARTED", "YES", 1);
8938
8939         /* setup all bars */
8940         num_screens = xcb_setup_roots_length(xcb_get_setup(conn));
8941         for (i = 0; i < num_screens; i++)
8942                 TAILQ_FOREACH(r, &screens[i].rl, entry) {
8943                         if (winfocus == NULL)
8944                                 winfocus = TAILQ_FIRST(&r->ws->winlist);
8945                         bar_setup(r);
8946                 }
8947
8948         grabkeys();
8949         stack();
8950
8951         xcb_ungrab_server(conn);
8952         xcb_flush(conn);
8953
8954         while (running) {
8955                 while ((evt = xcb_poll_for_event(conn))) {
8956                         if (!running)
8957                                 goto done;
8958                         event_handle(evt);
8959                         free(evt);
8960                 }
8961
8962                 /* If just (re)started, set default focus if needed. */
8963                 if (winfocus && focus_mode != SWM_FOCUS_FOLLOW) {
8964                         rr = winfocus->ws->r;
8965                         if (rr == NULL) {
8966                                 /* not a visible window */
8967                                 winfocus = NULL;
8968                                 continue;
8969                         }
8970
8971                         focus_win(get_region_focus(rr));
8972                         focus_flush();
8973                         winfocus = NULL;
8974                         continue;
8975                 }
8976
8977                 FD_ZERO(&rd);
8978                 FD_SET(xfd, &rd);
8979                 tv.tv_sec = 1;
8980                 tv.tv_usec = 0;
8981                 if (select(xfd + 1, &rd, NULL, NULL, &tv) == -1)
8982                         if (errno != EINTR) {
8983                                 DNPRINTF(SWM_D_MISC, "select failed");
8984                         }
8985                 if (restart_wm)
8986                         restart(NULL, NULL);
8987                 if (search_resp)
8988                         search_do_resp();
8989                 if (!running)
8990                         goto done;
8991                 if (bar_alarm) {
8992                         bar_alarm = 0;
8993                         bar_update();
8994                 }
8995         }
8996 done:
8997         shutdown_cleanup();
8998
8999         return (0);
9000 }