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