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