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