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