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