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