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