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