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