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