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