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