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