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