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