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