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