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