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