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