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