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