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