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