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