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