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