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