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