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