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