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