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