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