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