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