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