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