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