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