JasonWoof Got questions, comments, patches, etc.? Contact Jason Woofenden
71c7d9c46edd3cc2330828e450c1d007318bfb8a
[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         /* make sure bar gets updated if ws is empty */
2886         if (!new_ws->focus)
2887                 bar_update();
2888
2889         focus_flush();
2890
2891         DNPRINTF(SWM_D_WS, "switchws: done.\n");
2892 }
2893
2894 void
2895 cyclews(struct swm_region *r, union arg *args)
2896 {
2897         union                   arg a;
2898         struct swm_screen       *s = r->s;
2899         int                     cycle_all = 0;
2900
2901         DNPRINTF(SWM_D_WS, "cyclews: id: %d, screen[%d]:%dx%d+%d+%d, ws: %d\n",
2902             args->id, r->s->idx, WIDTH(r), HEIGHT(r), X(r), Y(r), r->ws->idx);
2903
2904         a.id = r->ws->idx;
2905         do {
2906                 switch (args->id) {
2907                 case SWM_ARG_ID_CYCLEWS_UP_ALL:
2908                         cycle_all = 1;
2909                         /* FALLTHROUGH */
2910                 case SWM_ARG_ID_CYCLEWS_UP:
2911                         if (a.id < workspace_limit - 1)
2912                                 a.id++;
2913                         else
2914                                 a.id = 0;
2915                         break;
2916                 case SWM_ARG_ID_CYCLEWS_DOWN_ALL:
2917                         cycle_all = 1;
2918                         /* FALLTHROUGH */
2919                 case SWM_ARG_ID_CYCLEWS_DOWN:
2920                         if (a.id > 0)
2921                                 a.id--;
2922                         else
2923                                 a.id = workspace_limit - 1;
2924                         break;
2925                 default:
2926                         return;
2927                 };
2928
2929                 if (!cycle_all &&
2930                     (cycle_empty == 0 && TAILQ_EMPTY(&s->ws[a.id].winlist)))
2931                         continue;
2932                 if (cycle_visible == 0 && s->ws[a.id].r != NULL)
2933                         continue;
2934
2935                 switchws(r, &a);
2936         } while (a.id != r->ws->idx);
2937 }
2938
2939 void
2940 priorws(struct swm_region *r, union arg *args)
2941 {
2942         union arg               a;
2943
2944         (void)args;
2945
2946         DNPRINTF(SWM_D_WS, "priorws: id: %d, screen[%d]:%dx%d+%d+%d, ws: %d\n",
2947             args->id, r->s->idx, WIDTH(r), HEIGHT(r), X(r), Y(r), r->ws->idx);
2948
2949         if (r->ws_prior == NULL)
2950                 return;
2951
2952         a.id = r->ws_prior->idx;
2953         switchws(r, &a);
2954 }
2955
2956 void
2957 cyclescr(struct swm_region *r, union arg *args)
2958 {
2959         struct swm_region       *rr = NULL;
2960         int                     i, x, y, num_screens;
2961
2962         num_screens = xcb_setup_roots_length(xcb_get_setup(conn));
2963         /* do nothing if we don't have more than one screen */
2964         if (!(num_screens > 1 || outputs > 1))
2965                 return;
2966
2967         i = r->s->idx;
2968         switch (args->id) {
2969         case SWM_ARG_ID_CYCLESC_UP:
2970                 rr = TAILQ_NEXT(r, entry);
2971                 if (rr == NULL)
2972                         rr = TAILQ_FIRST(&screens[i].rl);
2973                 break;
2974         case SWM_ARG_ID_CYCLESC_DOWN:
2975                 rr = TAILQ_PREV(r, swm_region_list, entry);
2976                 if (rr == NULL)
2977                         rr = TAILQ_LAST(&screens[i].rl, swm_region_list);
2978                 break;
2979         default:
2980                 return;
2981         };
2982         if (rr == NULL)
2983                 return;
2984
2985         /* move mouse to region */
2986         x = X(rr) + 1;
2987         y = Y(rr) + 1 + (bar_enabled ? bar_height : 0);
2988         xcb_warp_pointer(conn, XCB_WINDOW_NONE, rr->s[i].root, 0, 0, 0, 0,
2989             x, y);
2990
2991         rr->ws->focus = get_region_focus(rr);
2992
2993         if (rr->ws->focus) {
2994                 /* move to focus window */
2995                 x = X(rr->ws->focus) + 1;
2996                 y = Y(rr->ws->focus) + 1;
2997                 xcb_warp_pointer(conn, XCB_WINDOW_NONE, rr->s[i].root, 0, 0, 0,
2998                     0, x, y);
2999         }
3000
3001         focus_flush();
3002 }
3003
3004 void
3005 sort_windows(struct ws_win_list *wl)
3006 {
3007         struct ws_win           *win, *parent, *nxt;
3008
3009         if (wl == NULL)
3010                 return;
3011
3012         for (win = TAILQ_FIRST(wl); win != TAILQ_END(wl); win = nxt) {
3013                 nxt = TAILQ_NEXT(win, entry);
3014                 if (win->transient) {
3015                         parent = find_window(win->transient);
3016                         if (parent == NULL) {
3017                                 warnx("not possible bug");
3018                                 continue;
3019                         }
3020                         TAILQ_REMOVE(wl, win, entry);
3021                         TAILQ_INSERT_AFTER(wl, parent, win, entry);
3022                 }
3023         }
3024
3025 }
3026
3027 void
3028 swapwin(struct swm_region *r, union arg *args)
3029 {
3030         struct ws_win           *target, *source;
3031         struct ws_win           *cur_focus;
3032         struct ws_win_list      *wl;
3033
3034
3035         DNPRINTF(SWM_D_WS, "swapwin: id: %d, screen[%d]:%dx%d+%d+%d, ws: %d\n",
3036             args->id, r->s->idx, WIDTH(r), HEIGHT(r), X(r), Y(r), r->ws->idx);
3037
3038         cur_focus = r->ws->focus;
3039         if (cur_focus == NULL)
3040                 return;
3041
3042         source = cur_focus;
3043         wl = &source->ws->winlist;
3044
3045         switch (args->id) {
3046         case SWM_ARG_ID_SWAPPREV:
3047                 if (source->transient)
3048                         source = find_window(source->transient);
3049                 target = TAILQ_PREV(source, ws_win_list, entry);
3050                 if (target && target->transient)
3051                         target = find_window(target->transient);
3052                 TAILQ_REMOVE(wl, source, entry);
3053                 if (target == NULL)
3054                         TAILQ_INSERT_TAIL(wl, source, entry);
3055                 else
3056                         TAILQ_INSERT_BEFORE(target, source, entry);
3057                 break;
3058         case SWM_ARG_ID_SWAPNEXT:
3059                 target = TAILQ_NEXT(source, entry);
3060                 /* move the parent and let the sort handle the move */
3061                 if (source->transient)
3062                         source = find_window(source->transient);
3063                 TAILQ_REMOVE(wl, source, entry);
3064                 if (target == NULL)
3065                         TAILQ_INSERT_HEAD(wl, source, entry);
3066                 else
3067                         TAILQ_INSERT_AFTER(wl, target, source, entry);
3068                 break;
3069         case SWM_ARG_ID_SWAPMAIN:
3070                 target = TAILQ_FIRST(wl);
3071                 if (target == source) {
3072                         if (source->ws->focus_prev != NULL &&
3073                             source->ws->focus_prev != target)
3074                                 source = source->ws->focus_prev;
3075                         else
3076                                 return;
3077                 }
3078                 if (target == NULL || source == NULL)
3079                         return;
3080                 source->ws->focus_prev = target;
3081                 TAILQ_REMOVE(wl, target, entry);
3082                 TAILQ_INSERT_BEFORE(source, target, entry);
3083                 TAILQ_REMOVE(wl, source, entry);
3084                 TAILQ_INSERT_HEAD(wl, source, entry);
3085                 break;
3086         case SWM_ARG_ID_MOVELAST:
3087                 TAILQ_REMOVE(wl, source, entry);
3088                 TAILQ_INSERT_TAIL(wl, source, entry);
3089                 break;
3090         default:
3091                 DNPRINTF(SWM_D_MOVE, "swapwin: invalid id: %d\n", args->id);
3092                 return;
3093         }
3094
3095         sort_windows(wl);
3096
3097         stack();
3098
3099         focus_flush();
3100 }
3101
3102 struct ws_win *
3103 get_focus_prev(struct ws_win *win)
3104 {
3105         struct ws_win           *winfocus = NULL;
3106         struct ws_win           *cur_focus = NULL;
3107         struct ws_win_list      *wl = NULL;
3108         struct workspace        *ws = NULL;
3109
3110         if (!(win && win->ws))
3111                 return NULL;
3112
3113         ws = win->ws;
3114         wl = &ws->winlist;
3115         cur_focus = ws->focus;
3116
3117         DNPRINTF(SWM_D_FOCUS, "get_focus_prev: window: 0x%x, cur_focus: 0x%x\n",
3118             WINID(win), WINID(cur_focus));
3119
3120         /* pickle, just focus on whatever */
3121         if (cur_focus == NULL) {
3122                 /* use prev_focus if valid */
3123                 if (ws->focus_prev && ws->focus_prev != cur_focus &&
3124                     find_window(WINID(ws->focus_prev)))
3125                         winfocus = ws->focus_prev;
3126                 goto done;
3127         }
3128
3129         /* if transient focus on parent */
3130         if (cur_focus->transient) {
3131                 winfocus = find_window(cur_focus->transient);
3132                 goto done;
3133         }
3134
3135         /* if in max_stack try harder */
3136         if ((win->quirks & SWM_Q_FOCUSPREV) ||
3137             (ws->cur_layout->flags & SWM_L_FOCUSPREV)) {
3138                 if (cur_focus != ws->focus_prev)
3139                         winfocus = ws->focus_prev;
3140                 else
3141                         winfocus = TAILQ_PREV(win, ws_win_list, entry);
3142                 if (winfocus)
3143                         goto done;
3144         }
3145
3146         DNPRINTF(SWM_D_FOCUS, "get_focus_prev: focus_close: %d\n", focus_close);
3147
3148         if (winfocus == NULL || winfocus == win) {
3149                 switch (focus_close) {
3150                 case SWM_STACK_BOTTOM:
3151                         winfocus = TAILQ_FIRST(wl);
3152                         break;
3153                 case SWM_STACK_TOP:
3154                         winfocus = TAILQ_LAST(wl, ws_win_list);
3155                         break;
3156                 case SWM_STACK_ABOVE:
3157                         if ((winfocus = TAILQ_NEXT(cur_focus, entry)) == NULL) {
3158                                 if (focus_close_wrap)
3159                                         winfocus = TAILQ_FIRST(wl);
3160                                 else
3161                                         winfocus = TAILQ_PREV(cur_focus,
3162                                             ws_win_list, entry);
3163                         }
3164                         break;
3165                 case SWM_STACK_BELOW:
3166                         if ((winfocus = TAILQ_PREV(cur_focus, ws_win_list,
3167                             entry)) == NULL) {
3168                                 if (focus_close_wrap)
3169                                         winfocus = TAILQ_LAST(wl, ws_win_list);
3170                                 else
3171                                         winfocus = TAILQ_NEXT(cur_focus, entry);
3172                         }
3173                         break;
3174                 }
3175         }
3176 done:
3177         if (winfocus == NULL) {
3178                 if (focus_default == SWM_STACK_TOP)
3179                         winfocus = TAILQ_LAST(wl, ws_win_list);
3180                 else
3181                         winfocus = TAILQ_FIRST(wl);
3182         }
3183
3184         kill_refs(win);
3185
3186         return get_focus_magic(winfocus);
3187 }
3188
3189 struct ws_win *
3190 get_region_focus(struct swm_region *r)
3191 {
3192         struct ws_win           *winfocus = NULL;
3193
3194         if (!(r && r->ws))
3195                 return NULL;
3196
3197         if (r->ws->focus && !r->ws->focus->iconic)
3198                 winfocus = r->ws->focus;
3199         else if (r->ws->focus_prev && !r->ws->focus_prev->iconic)
3200                 winfocus = r->ws->focus_prev;
3201         else
3202                 TAILQ_FOREACH(winfocus, &r->ws->winlist, entry)
3203                         if (!winfocus->iconic)
3204                                 break;
3205
3206         return get_focus_magic(winfocus);
3207 }
3208
3209 void
3210 focus(struct swm_region *r, union arg *args)
3211 {
3212         struct ws_win           *head, *cur_focus = NULL, *winfocus = NULL;
3213         struct ws_win_list      *wl = NULL;
3214         struct workspace        *ws = NULL;
3215         int                     all_iconics;
3216
3217         if (!(r && r->ws))
3218                 return;
3219
3220         DNPRINTF(SWM_D_FOCUS, "focus: id: %d\n", args->id);
3221
3222         if ((cur_focus = r->ws->focus) == NULL)
3223                 return;
3224         ws = r->ws;
3225         wl = &ws->winlist;
3226         if (TAILQ_EMPTY(wl))
3227                 return;
3228         /* make sure there is at least one uniconified window */
3229         all_iconics = 1;
3230         TAILQ_FOREACH(winfocus, wl, entry)
3231                 if (winfocus->iconic == 0) {
3232                         all_iconics = 0;
3233                         break;
3234                 }
3235         if (all_iconics)
3236                 return;
3237
3238         switch (args->id) {
3239         case SWM_ARG_ID_FOCUSPREV:
3240                 head = TAILQ_PREV(cur_focus, ws_win_list, entry);
3241                 if (head == NULL)
3242                         head = TAILQ_LAST(wl, ws_win_list);
3243                 winfocus = head;
3244                 if (WINID(winfocus) == cur_focus->transient) {
3245                         head = TAILQ_PREV(winfocus, ws_win_list, entry);
3246                         if (head == NULL)
3247                                 head = TAILQ_LAST(wl, ws_win_list);
3248                         winfocus = head;
3249                 }
3250
3251                 /* skip iconics */
3252                 if (winfocus && winfocus->iconic) {
3253                         while (winfocus != cur_focus) {
3254                                 if (winfocus == NULL)
3255                                         winfocus = TAILQ_LAST(wl, ws_win_list);
3256                                 if (winfocus->iconic == 0)
3257                                         break;
3258                                 winfocus = TAILQ_PREV(winfocus, ws_win_list,
3259                                     entry);
3260                         }
3261                 }
3262                 break;
3263
3264         case SWM_ARG_ID_FOCUSNEXT:
3265                 head = TAILQ_NEXT(cur_focus, entry);
3266                 if (head == NULL)
3267                         head = TAILQ_FIRST(wl);
3268                 winfocus = head;
3269
3270                 /* skip iconics */
3271                 if (winfocus && winfocus->iconic) {
3272                         while (winfocus != cur_focus) {
3273                                 if (winfocus == NULL)
3274                                         winfocus = TAILQ_FIRST(wl);
3275                                 if (winfocus->iconic == 0)
3276                                         break;
3277                                 winfocus = TAILQ_NEXT(winfocus, entry);
3278                         }
3279                 }
3280                 break;
3281
3282         case SWM_ARG_ID_FOCUSMAIN:
3283                 winfocus = TAILQ_FIRST(wl);
3284                 if (winfocus == cur_focus)
3285                         winfocus = cur_focus->ws->focus_prev;
3286                 break;
3287
3288         default:
3289                 return;
3290         }
3291
3292         focus_win(get_focus_magic(winfocus));
3293
3294         xcb_flush(conn);
3295 }
3296
3297 void
3298 cycle_layout(struct swm_region *r, union arg *args)
3299 {
3300         struct workspace        *ws = r->ws;
3301
3302         /* suppress unused warning since var is needed */
3303         (void)args;
3304
3305         DNPRINTF(SWM_D_EVENT, "cycle_layout: workspace: %d\n", ws->idx);
3306
3307         ws->cur_layout++;
3308         if (ws->cur_layout->l_stack == NULL)
3309                 ws->cur_layout = &layouts[0];
3310
3311         stack();
3312         bar_update();
3313
3314         focus_win(get_region_focus(r));
3315
3316         focus_flush();
3317 }
3318
3319 void
3320 stack_config(struct swm_region *r, union arg *args)
3321 {
3322         struct workspace        *ws = r->ws;
3323
3324         DNPRINTF(SWM_D_STACK, "stack_config: id: %d workspace: %d\n",
3325             args->id, ws->idx);
3326
3327         if (ws->cur_layout->l_config != NULL)
3328                 ws->cur_layout->l_config(ws, args->id);
3329
3330         if (args->id != SWM_ARG_ID_STACKINIT)
3331                 stack();
3332         bar_update();
3333
3334         focus_flush();
3335 }
3336
3337 void
3338 stack(void) {
3339         struct swm_geometry     g;
3340         struct swm_region       *r;
3341         int                     i, num_screens;
3342 #ifdef SWM_DEBUG
3343         int j;
3344 #endif
3345
3346         DNPRINTF(SWM_D_STACK, "stack: begin\n");
3347
3348         num_screens = xcb_setup_roots_length(xcb_get_setup(conn));
3349         for (i = 0; i < num_screens; i++) {
3350 #ifdef SWM_DEBUG
3351                 j = 0;
3352 #endif
3353                 TAILQ_FOREACH(r, &screens[i].rl, entry) {
3354                         DNPRINTF(SWM_D_STACK, "stack: workspace: %d "
3355                             "(screen: %d, region: %d)\n", r->ws->idx, i, j++);
3356
3357                         /* start with screen geometry, adjust for bar */
3358                         g = r->g;
3359                         g.w -= 2 * border_width;
3360                         g.h -= 2 * border_width;
3361                         if (bar_enabled) {
3362                                 if (!bar_at_bottom)
3363                                         g.y += bar_height;
3364                                 g.h -= bar_height;
3365                         }
3366                         r->ws->cur_layout->l_stack(r->ws, &g);
3367                         r->ws->cur_layout->l_string(r->ws);
3368                         /* save r so we can track region changes */
3369                         r->ws->old_r = r;
3370                 }
3371         }
3372         if (font_adjusted)
3373                 font_adjusted--;
3374
3375         DNPRINTF(SWM_D_STACK, "stack: end\n");
3376 }
3377
3378 void
3379 store_float_geom(struct ws_win *win, struct swm_region *r)
3380 {
3381         if (win == NULL || r == NULL)
3382                 return;
3383
3384         /* retain window geom and region geom */
3385         win->g_float = win->g;
3386         win->g_float.x -= X(r);
3387         win->g_float.y -= Y(r);
3388         win->g_floatvalid = 1;
3389         DNPRINTF(SWM_D_MISC, "store_float_geom: window: 0x%x, g: (%d,%d)"
3390             " %d x %d, g_float: (%d,%d) %d x %d\n", win->id, X(win), Y(win),
3391             WIDTH(win), HEIGHT(win), win->g_float.x, win->g_float.y,
3392             win->g_float.w, win->g_float.h);
3393 }
3394
3395 void
3396 load_float_geom(struct ws_win *win, struct swm_region *r)
3397 {
3398         if (win == NULL || r == NULL)
3399                 return;
3400
3401         if (win->g_floatvalid) {
3402                 win->g = win->g_float;
3403                 X(win) += X(r);
3404                 Y(win) += Y(r);
3405                 DNPRINTF(SWM_D_MISC, "load_float_geom: window: 0x%x, g: (%d,%d)"
3406                     "%d x %d\n", win->id, X(win), Y(win), WIDTH(win),
3407                     HEIGHT(win));
3408         } else {
3409                 DNPRINTF(SWM_D_MISC, "load_float_geom: window: 0x%x, g_float "
3410                     "is not set.\n", win->id);
3411         }
3412 }
3413
3414 void
3415 stack_floater(struct ws_win *win, struct swm_region *r)
3416 {
3417         if (win == NULL)
3418                 return;
3419
3420         DNPRINTF(SWM_D_MISC, "stack_floater: window: 0x%x\n", win->id);
3421
3422         /*
3423          * to allow windows to change their size (e.g. mplayer fs) only retrieve
3424          * geom on ws switches or return from max mode
3425          */
3426         if (win->floatmaxed || (r != r->ws->old_r &&
3427             !(win->ewmh_flags & EWMH_F_FULLSCREEN))) {
3428                 /* update geometry for the new region */
3429                 load_float_geom(win, r);
3430         }
3431
3432         win->floatmaxed = 0;
3433
3434         /*
3435          * if set to fullscreen mode, configure window to maximum size.
3436          */
3437         if (win->ewmh_flags & EWMH_F_FULLSCREEN) {
3438                 if (!win->g_floatvalid)
3439                         store_float_geom(win, win->ws->r);
3440
3441                 win->g = r->g;
3442         }
3443
3444         /*
3445          * remove border on fullscreen floater when in fullscreen mode or when
3446          * the quirk is present.
3447          */
3448         if ((win->ewmh_flags & EWMH_F_FULLSCREEN) ||
3449             ((win->quirks & SWM_Q_FULLSCREEN) &&
3450              (WIDTH(win) >= WIDTH(r)) && (HEIGHT(win) >= HEIGHT(r)))) {
3451                 if (win->bordered) {
3452                         win->bordered = 0;
3453                         X(win) += border_width;
3454                         Y(win) += border_width;
3455                 }
3456         } else if (!win->bordered) {
3457                 win->bordered = 1;
3458                 X(win) -= border_width;
3459                 Y(win) -= border_width;
3460         }
3461
3462         if (win->transient && (win->quirks & SWM_Q_TRANSSZ)) {
3463                 WIDTH(win) = (double)WIDTH(r) * dialog_ratio;
3464                 HEIGHT(win) = (double)HEIGHT(r) * dialog_ratio;
3465         }
3466
3467         if (!win->manual && !(win->ewmh_flags & EWMH_F_FULLSCREEN) &&
3468             !(win->quirks & SWM_Q_ANYWHERE)) {
3469                 /*
3470                  * floaters and transients are auto-centred unless moved,
3471                  * resized or ANYWHERE quirk is set.
3472                  */
3473                 X(win) = X(r) + (WIDTH(r) - WIDTH(win)) /  2 - BORDER(win);
3474                 Y(win) = Y(r) + (HEIGHT(r) - HEIGHT(win)) / 2 - BORDER(win);
3475
3476                 store_float_geom(win, r);
3477         }
3478
3479         /* keep window within region bounds */
3480         constrain_window(win, r, 0);
3481
3482         update_window(win);
3483 }
3484
3485 /*
3486  * Send keystrokes to terminal to decrease/increase the font size as the
3487  * window size changes.
3488  */
3489 void
3490 adjust_font(struct ws_win *win)
3491 {
3492         if (!(win->quirks & SWM_Q_XTERM_FONTADJ) ||
3493             win->floating || win->transient)
3494                 return;
3495
3496         if (win->sh.width_inc && win->last_inc != win->sh.width_inc &&
3497             WIDTH(win) / win->sh.width_inc < term_width &&
3498             win->font_steps < SWM_MAX_FONT_STEPS) {
3499                 win->font_size_boundary[win->font_steps] =
3500                     (win->sh.width_inc * term_width) + win->sh.base_width;
3501                 win->font_steps++;
3502                 font_adjusted++;
3503                 win->last_inc = win->sh.width_inc;
3504                 fake_keypress(win, XK_KP_Subtract, XCB_MOD_MASK_SHIFT);
3505         } else if (win->font_steps && win->last_inc != win->sh.width_inc &&
3506             WIDTH(win) > win->font_size_boundary[win->font_steps - 1]) {
3507                 win->font_steps--;
3508                 font_adjusted++;
3509                 win->last_inc = win->sh.width_inc;
3510                 fake_keypress(win, XK_KP_Add, XCB_MOD_MASK_SHIFT);
3511         }
3512 }
3513
3514 #define SWAPXY(g)       do {                            \
3515         int tmp;                                        \
3516         tmp = (g)->y; (g)->y = (g)->x; (g)->x = tmp;    \
3517         tmp = (g)->h; (g)->h = (g)->w; (g)->w = tmp;    \
3518 } while (0)
3519 void
3520 stack_master(struct workspace *ws, struct swm_geometry *g, int rot, int flip)
3521 {
3522         struct swm_geometry     win_g, r_g = *g;
3523         struct ws_win           *win, *fs_win = NULL;
3524         int                     i, j, s, stacks;
3525         int                     w_inc = 1, h_inc, w_base = 1, h_base;
3526         int                     hrh, extra = 0, h_slice, last_h = 0;
3527         int                     split, colno, winno, mwin, msize, mscale;
3528         int                     remain, missing, v_slice, reconfigure;
3529         int                     bordered = 1;
3530
3531         DNPRINTF(SWM_D_STACK, "stack_master: workspace: %d, rot: %s, "
3532             "flip: %s\n", ws->idx, YESNO(rot), YESNO(flip));
3533
3534         winno = count_win(ws, 0);
3535         if (winno == 0 && count_win(ws, 1) == 0)
3536                 return;
3537
3538         TAILQ_FOREACH(win, &ws->winlist, entry)
3539                 if (win->transient == 0 && win->floating == 0
3540                     && win->iconic == 0)
3541                         break;
3542
3543         if (win == NULL)
3544                 goto notiles;
3545
3546         if (rot) {
3547                 w_inc = win->sh.width_inc;
3548                 w_base = win->sh.base_width;
3549                 mwin = ws->l_state.horizontal_mwin;
3550                 mscale = ws->l_state.horizontal_msize;
3551                 stacks = ws->l_state.horizontal_stacks;
3552                 SWAPXY(&r_g);
3553         } else {
3554                 w_inc = win->sh.height_inc;
3555                 w_base = win->sh.base_height;
3556                 mwin = ws->l_state.vertical_mwin;
3557                 mscale = ws->l_state.vertical_msize;
3558                 stacks = ws->l_state.vertical_stacks;
3559         }
3560         win_g = r_g;
3561
3562         if (stacks > winno - mwin)
3563                 stacks = winno - mwin;
3564         if (stacks < 1)
3565                 stacks = 1;
3566
3567         h_slice = r_g.h / SWM_H_SLICE;
3568         if (mwin && winno > mwin) {
3569                 v_slice = r_g.w / SWM_V_SLICE;
3570
3571                 split = mwin;
3572                 colno = split;
3573                 win_g.w = v_slice * mscale;
3574
3575                 if (w_inc > 1 && w_inc < v_slice) {
3576                         /* adjust for window's requested size increment */
3577                         remain = (win_g.w - w_base) % w_inc;
3578                         win_g.w -= remain;
3579                 }
3580
3581                 msize = win_g.w;
3582                 if (flip)
3583                         win_g.x += r_g.w - msize;
3584         } else {
3585                 msize = -2;
3586                 colno = split = winno / stacks;
3587                 win_g.w = ((r_g.w - (stacks * 2 * border_width) +
3588                     2 * border_width) / stacks);
3589         }
3590         hrh = r_g.h / colno;
3591         extra = r_g.h - (colno * hrh);
3592         win_g.h = hrh - 2 * border_width;
3593
3594         /*  stack all the tiled windows */
3595         i = j = 0, s = stacks;
3596         TAILQ_FOREACH(win, &ws->winlist, entry) {
3597                 if (win->transient != 0 || win->floating != 0)
3598                         continue;
3599                 if (win->iconic != 0)
3600                         continue;
3601
3602                 if (win->ewmh_flags & EWMH_F_FULLSCREEN) {
3603                         fs_win = win;
3604                         continue;
3605                 }
3606
3607                 if (split && i == split) {
3608                         colno = (winno - mwin) / stacks;
3609                         if (s <= (winno - mwin) % stacks)
3610                                 colno++;
3611                         split = split + colno;
3612                         hrh = (r_g.h / colno);
3613                         extra = r_g.h - (colno * hrh);
3614                         if (flip)
3615                                 win_g.x = r_g.x;
3616                         else
3617                                 win_g.x += win_g.w + 2 * border_width;
3618                         win_g.w = (r_g.w - msize -
3619                             (stacks * 2 * border_width)) / stacks;
3620                         if (s == 1)
3621                                 win_g.w += (r_g.w - msize -
3622                                     (stacks * 2 * border_width)) % stacks;
3623                         s--;
3624                         j = 0;
3625                 }
3626                 win_g.h = hrh - 2 * border_width;
3627                 if (rot) {
3628                         h_inc = win->sh.width_inc;
3629                         h_base = win->sh.base_width;
3630                 } else {
3631                         h_inc = win->sh.height_inc;
3632                         h_base = win->sh.base_height;
3633                 }
3634                 if (j == colno - 1) {
3635                         win_g.h = hrh + extra;
3636                 } else if (h_inc > 1 && h_inc < h_slice) {
3637                         /* adjust for window's requested size increment */
3638                         remain = (win_g.h - h_base) % h_inc;
3639                         missing = h_inc - remain;
3640
3641                         if (missing <= extra || j == 0) {
3642                                 extra -= missing;
3643                                 win_g.h += missing;
3644                         } else {
3645                                 win_g.h -= remain;
3646                                 extra += remain;
3647                         }
3648                 }
3649
3650                 if (j == 0)
3651                         win_g.y = r_g.y;
3652                 else
3653                         win_g.y += last_h + 2 * border_width;
3654
3655                 if (disable_border && bar_enabled == 0 && winno == 1){
3656                         bordered = 0;
3657                         win_g.w += 2 * border_width;
3658                         win_g.h += 2 * border_width;
3659                 } else {
3660                         bordered = 1;
3661                 }
3662                 if (rot) {
3663                         if (X(win) != win_g.y || Y(win) != win_g.x ||
3664                             WIDTH(win) != win_g.h || HEIGHT(win) != win_g.w) {
3665                                 reconfigure = 1;
3666                                 X(win) = win_g.y;
3667                                 Y(win) = win_g.x;
3668                                 WIDTH(win) = win_g.h;
3669                                 HEIGHT(win) = win_g.w;
3670                         }
3671                 } else {
3672                         if (X(win) != win_g.x || Y(win) != win_g.y ||
3673                             WIDTH(win) != win_g.w || HEIGHT(win) != win_g.h) {
3674                                 reconfigure = 1;
3675                                 X(win) = win_g.x;
3676                                 Y(win) = win_g.y;
3677                                 WIDTH(win) = win_g.w;
3678                                 HEIGHT(win) = win_g.h;
3679                         }
3680                 }
3681
3682                 if (bordered != win->bordered) {
3683                         reconfigure = 1;
3684                         win->bordered = bordered;
3685                 }
3686
3687                 if (reconfigure) {
3688                         adjust_font(win);
3689                         update_window(win);
3690                 }
3691
3692                 map_window(win);
3693
3694                 last_h = win_g.h;
3695                 i++;
3696                 j++;
3697         }
3698
3699 notiles:
3700         /* now, stack all the floaters and transients */
3701         TAILQ_FOREACH(win, &ws->winlist, entry) {
3702                 if (win->transient == 0 && win->floating == 0)
3703                         continue;
3704                 if (win->iconic == 1)
3705                         continue;
3706                 if (win->ewmh_flags & EWMH_F_FULLSCREEN) {
3707                         fs_win = win;
3708                         continue;
3709                 }
3710
3711                 stack_floater(win, ws->r);
3712                 map_window(win);
3713         }
3714
3715         if (fs_win) {
3716                 stack_floater(fs_win, ws->r);
3717                 map_window(fs_win);
3718         }
3719 }
3720
3721 void
3722 vertical_config(struct workspace *ws, int id)
3723 {
3724         DNPRINTF(SWM_D_STACK, "vertical_config: id: %d, workspace: %d\n",
3725             id, ws->idx);
3726
3727         switch (id) {
3728         case SWM_ARG_ID_STACKRESET:
3729         case SWM_ARG_ID_STACKINIT:
3730                 ws->l_state.vertical_msize = SWM_V_SLICE / 2;
3731                 ws->l_state.vertical_mwin = 1;
3732                 ws->l_state.vertical_stacks = 1;
3733                 break;
3734         case SWM_ARG_ID_MASTERSHRINK:
3735                 if (ws->l_state.vertical_msize > 1)
3736                         ws->l_state.vertical_msize--;
3737                 break;
3738         case SWM_ARG_ID_MASTERGROW:
3739                 if (ws->l_state.vertical_msize < SWM_V_SLICE - 1)
3740                         ws->l_state.vertical_msize++;
3741                 break;
3742         case SWM_ARG_ID_MASTERADD:
3743                 ws->l_state.vertical_mwin++;
3744                 break;
3745         case SWM_ARG_ID_MASTERDEL:
3746                 if (ws->l_state.vertical_mwin > 0)
3747                         ws->l_state.vertical_mwin--;
3748                 break;
3749         case SWM_ARG_ID_STACKINC:
3750                 ws->l_state.vertical_stacks++;
3751                 break;
3752         case SWM_ARG_ID_STACKDEC:
3753                 if (ws->l_state.vertical_stacks > 1)
3754                         ws->l_state.vertical_stacks--;
3755                 break;
3756         case SWM_ARG_ID_FLIPLAYOUT:
3757                 ws->l_state.vertical_flip = !ws->l_state.vertical_flip;
3758                 break;
3759         default:
3760                 return;
3761         }
3762 }
3763
3764 void
3765 vertical_stack(struct workspace *ws, struct swm_geometry *g)
3766 {
3767         DNPRINTF(SWM_D_STACK, "vertical_stack: workspace: %d\n", ws->idx);
3768
3769         stack_master(ws, g, 0, ws->l_state.vertical_flip);
3770 }
3771
3772 void
3773 horizontal_config(struct workspace *ws, int id)
3774 {
3775         DNPRINTF(SWM_D_STACK, "horizontal_config: workspace: %d\n", ws->idx);
3776
3777         switch (id) {
3778         case SWM_ARG_ID_STACKRESET:
3779         case SWM_ARG_ID_STACKINIT:
3780                 ws->l_state.horizontal_mwin = 1;
3781                 ws->l_state.horizontal_msize = SWM_H_SLICE / 2;
3782                 ws->l_state.horizontal_stacks = 1;
3783                 break;
3784         case SWM_ARG_ID_MASTERSHRINK:
3785                 if (ws->l_state.horizontal_msize > 1)
3786                         ws->l_state.horizontal_msize--;
3787                 break;
3788         case SWM_ARG_ID_MASTERGROW:
3789                 if (ws->l_state.horizontal_msize < SWM_H_SLICE - 1)
3790                         ws->l_state.horizontal_msize++;
3791                 break;
3792         case SWM_ARG_ID_MASTERADD:
3793                 ws->l_state.horizontal_mwin++;
3794                 break;
3795         case SWM_ARG_ID_MASTERDEL:
3796                 if (ws->l_state.horizontal_mwin > 0)
3797                         ws->l_state.horizontal_mwin--;
3798                 break;
3799         case SWM_ARG_ID_STACKINC:
3800                 ws->l_state.horizontal_stacks++;
3801                 break;
3802         case SWM_ARG_ID_STACKDEC:
3803                 if (ws->l_state.horizontal_stacks > 1)
3804                         ws->l_state.horizontal_stacks--;
3805                 break;
3806         case SWM_ARG_ID_FLIPLAYOUT:
3807                 ws->l_state.horizontal_flip = !ws->l_state.horizontal_flip;
3808                 break;
3809         default:
3810                 return;
3811         }
3812 }
3813
3814 void
3815 horizontal_stack(struct workspace *ws, struct swm_geometry *g)
3816 {
3817         DNPRINTF(SWM_D_STACK, "horizontal_stack: workspace: %d\n", ws->idx);
3818
3819         stack_master(ws, g, 1, ws->l_state.horizontal_flip);
3820 }
3821
3822 /* fullscreen view */
3823 void
3824 max_stack(struct workspace *ws, struct swm_geometry *g)
3825 {
3826         struct swm_geometry     gg = *g;
3827         struct ws_win           *win, *wintrans = NULL, *parent = NULL;
3828         int                     winno, num_screens;
3829
3830         DNPRINTF(SWM_D_STACK, "max_stack: workspace: %d\n", ws->idx);
3831
3832         if (ws == NULL)
3833                 return;
3834
3835         winno = count_win(ws, 0);
3836         if (winno == 0 && count_win(ws, 1) == 0)
3837                 return;
3838
3839         num_screens = xcb_setup_roots_length(xcb_get_setup(conn));
3840         TAILQ_FOREACH(win, &ws->winlist, entry) {
3841                 if (win->transient) {
3842                         wintrans = win;
3843                         parent = find_window(win->transient);
3844                         continue;
3845                 }
3846
3847                 if (win->floating && win->floatmaxed == 0 ) {
3848                         /*
3849                          * retain geometry for retrieval on exit from
3850                          * max_stack mode
3851                          */
3852                         store_float_geom(win, ws->r);
3853                         win->floatmaxed = 1;
3854                 }
3855
3856                 /* only reconfigure if necessary */
3857                 if (X(win) != gg.x || Y(win) != gg.y || WIDTH(win) != gg.w ||
3858                     HEIGHT(win) != gg.h) {
3859                         win->g = gg;
3860                         if (bar_enabled){
3861                                 win->bordered = 1;
3862                         } else {
3863                                 win->bordered = 0;
3864                                 WIDTH(win) += 2 * border_width;
3865                                 HEIGHT(win) += 2 * border_width;
3866                         }
3867
3868                         update_window(win);
3869                 }
3870                 /* unmap only if we don't have multi screen */
3871                 if (win != ws->focus)
3872                         if (!(num_screens > 1 || outputs > 1))
3873                                 unmap_window(win);
3874         }
3875
3876         /* put the last transient on top */
3877         if (wintrans) {
3878                 if (parent)
3879                         map_window(parent);
3880                 stack_floater(wintrans, ws->r);
3881                 ws->focus = get_focus_magic(wintrans);
3882         }
3883 }
3884
3885 void
3886 send_to_ws(struct swm_region *r, union arg *args)
3887 {
3888         int                     wsid = args->id;
3889         struct ws_win           *win = NULL, *parent;
3890         struct workspace        *ws, *nws;
3891         char                    ws_idx_str[SWM_PROPLEN];
3892         union arg               a;
3893
3894         if (wsid >= workspace_limit)
3895                 return;
3896
3897         if (r && r->ws && r->ws->focus)
3898                 win = r->ws->focus;
3899         else
3900                 return;
3901         if (win == NULL)
3902                 return;
3903         if (win->ws->idx == wsid)
3904                 return;
3905
3906         DNPRINTF(SWM_D_MOVE, "send_to_ws: window: 0x%x\n", win->id);
3907
3908         ws = win->ws;
3909         nws = &win->s->ws[wsid];
3910
3911         a.id = SWM_ARG_ID_FOCUSPREV;
3912         focus(r, &a);
3913         if (win->transient) {
3914                 parent = find_window(win->transient);
3915                 if (parent) {
3916                         unmap_window(parent);
3917                         TAILQ_REMOVE(&ws->winlist, parent, entry);
3918                         TAILQ_INSERT_TAIL(&nws->winlist, parent, entry);
3919                         parent->ws = nws;
3920                 }
3921         }
3922         unmap_window(win);
3923         TAILQ_REMOVE(&ws->winlist, win, entry);
3924         TAILQ_INSERT_TAIL(&nws->winlist, win, entry);
3925         if (TAILQ_EMPTY(&ws->winlist))
3926                 r->ws->focus = NULL;
3927         win->ws = nws;
3928
3929         /* Try to update the window's workspace property */
3930         if (snprintf(ws_idx_str, SWM_PROPLEN, "%d", nws->idx) < SWM_PROPLEN) {
3931                 DNPRINTF(SWM_D_PROP, "send_to_ws: set property: _SWM_WS: %s\n",
3932                     ws_idx_str);
3933                 xcb_change_property(conn, XCB_PROP_MODE_REPLACE, win->id,
3934                     a_swm_ws, XCB_ATOM_STRING, 8, strlen(ws_idx_str),
3935                     ws_idx_str);
3936         }
3937
3938         stack();
3939         bar_update();
3940
3941         focus_flush();
3942 }
3943
3944 void
3945 pressbutton(struct swm_region *r, union arg *args)
3946 {
3947         /* suppress unused warning since var is needed */
3948         (void)r;
3949
3950         xcb_test_fake_input(conn, XCB_BUTTON_PRESS, args->id,
3951             XCB_CURRENT_TIME, XCB_WINDOW_NONE, 0, 0, 0);
3952         xcb_test_fake_input(conn, XCB_BUTTON_RELEASE, args->id,
3953             XCB_CURRENT_TIME, XCB_WINDOW_NONE, 0, 0, 0);
3954 }
3955
3956 void
3957 raise_toggle(struct swm_region *r, union arg *args)
3958 {
3959         /* suppress unused warning since var is needed */
3960         (void)args;
3961
3962         if (r == NULL || r->ws == NULL)
3963                 return;
3964
3965         r->ws->always_raise = !r->ws->always_raise;
3966
3967         /* bring floaters back to top */
3968         if (r->ws->always_raise == 0)
3969                 stack();
3970
3971         focus_flush();
3972 }
3973
3974 void
3975 iconify(struct swm_region *r, union arg *args)
3976 {
3977         /* suppress unused warning since var is needed */
3978         (void)args;
3979
3980         if (r->ws->focus == NULL)
3981                 return;
3982
3983         update_iconic(r->ws->focus, 1);
3984
3985         xcb_flush(conn);
3986 }
3987
3988 char *
3989 get_win_name(xcb_window_t win)
3990 {
3991         char                            *name = NULL;
3992         xcb_get_property_cookie_t       c;
3993         xcb_get_property_reply_t        *r;
3994
3995         /* First try _NET_WM_NAME for UTF-8. */
3996         c = xcb_get_property(conn, 0, win, a_netwmname,
3997             XCB_GET_PROPERTY_TYPE_ANY, 0, UINT_MAX);
3998         r = xcb_get_property_reply(conn, c, NULL);
3999
4000         if (!r || r->type == XCB_NONE) {
4001                 free(r);
4002                 /* Use WM_NAME instead; no UTF-8. */
4003                 c = xcb_get_property(conn, 0, win, XCB_ATOM_WM_NAME,
4004                     XCB_GET_PROPERTY_TYPE_ANY, 0, UINT_MAX);
4005                 r = xcb_get_property_reply(conn, c, NULL);
4006
4007                 if(!r || r->type == XCB_NONE) {
4008                         free(r);
4009                         return NULL;
4010                 }
4011         }
4012
4013         if (r->length > 0)
4014                 name = strndup(xcb_get_property_value(r),
4015                     xcb_get_property_value_length(r));
4016
4017         free(r);
4018         return name;
4019 }
4020
4021 void
4022 uniconify(struct swm_region *r, union arg *args)
4023 {
4024         struct ws_win           *win;
4025         FILE                    *lfile;
4026         char                    *name;
4027         int                     count = 0;
4028
4029         DNPRINTF(SWM_D_MISC, "uniconify\n");
4030
4031         if (r == NULL || r->ws == NULL)
4032                 return;
4033
4034         /* make sure we have anything to uniconify */
4035         TAILQ_FOREACH(win, &r->ws->winlist, entry) {
4036                 if (win->ws == NULL)
4037                         continue; /* should never happen */
4038                 if (win->iconic == 0)
4039                         continue;
4040                 count++;
4041         }
4042         if (count == 0)
4043                 return;
4044
4045         search_r = r;
4046         search_resp_action = SWM_SEARCH_UNICONIFY;
4047
4048         spawn_select(r, args, "search", &searchpid);
4049
4050         if ((lfile = fdopen(select_list_pipe[1], "w")) == NULL)
4051                 return;
4052
4053         TAILQ_FOREACH(win, &r->ws->winlist, entry) {
4054                 if (win->ws == NULL)
4055                         continue; /* should never happen */
4056                 if (win->iconic == 0)
4057                         continue;
4058
4059                 name = get_win_name(win->id);
4060                 if (name == NULL)
4061                         continue;
4062                 fprintf(lfile, "%s.%u\n", name, win->id);
4063                 free(name);
4064         }
4065
4066         fclose(lfile);
4067 }
4068
4069 void
4070 name_workspace(struct swm_region *r, union arg *args)
4071 {
4072         FILE                    *lfile;
4073
4074         DNPRINTF(SWM_D_MISC, "name_workspace\n");
4075
4076         if (r == NULL)
4077                 return;
4078
4079         search_r = r;
4080         search_resp_action = SWM_SEARCH_NAME_WORKSPACE;
4081
4082         spawn_select(r, args, "name_workspace", &searchpid);
4083
4084         if ((lfile = fdopen(select_list_pipe[1], "w")) == NULL)
4085                 return;
4086
4087         fprintf(lfile, "%s", "");
4088         fclose(lfile);
4089 }
4090
4091 void
4092 search_workspace(struct swm_region *r, union arg *args)
4093 {
4094         int                     i;
4095         struct workspace        *ws;
4096         FILE                    *lfile;
4097
4098         DNPRINTF(SWM_D_MISC, "search_workspace\n");
4099
4100         if (r == NULL)
4101                 return;
4102
4103         search_r = r;
4104         search_resp_action = SWM_SEARCH_SEARCH_WORKSPACE;
4105
4106         spawn_select(r, args, "search", &searchpid);
4107
4108         if ((lfile = fdopen(select_list_pipe[1], "w")) == NULL)
4109                 return;
4110
4111         for (i = 0; i < workspace_limit; i++) {
4112                 ws = &r->s->ws[i];
4113                 if (ws == NULL)
4114                         continue;
4115                 fprintf(lfile, "%d%s%s\n", ws->idx + 1,
4116                     (ws->name ? ":" : ""), (ws->name ? ws->name : ""));
4117         }
4118
4119         fclose(lfile);
4120 }
4121
4122 void
4123 search_win_cleanup(void)
4124 {
4125         struct search_window    *sw = NULL;
4126
4127         while ((sw = TAILQ_FIRST(&search_wl)) != NULL) {
4128                 xcb_destroy_window(conn, sw->indicator);
4129                 TAILQ_REMOVE(&search_wl, sw, entry);
4130                 free(sw);
4131         }
4132 }
4133
4134 void
4135 search_win(struct swm_region *r, union arg *args)
4136 {
4137         struct ws_win           *win = NULL;
4138         struct search_window    *sw = NULL;
4139         xcb_window_t            w;
4140         uint32_t                wa[2];
4141         int                     i, width, height;
4142         char                    s[8];
4143         FILE                    *lfile;
4144         size_t                  len;
4145         XftDraw                 *draw;
4146         XGlyphInfo              info;
4147         GC                      l_draw;
4148         XGCValues               l_gcv;
4149         XRectangle              l_ibox, l_lbox;
4150
4151         DNPRINTF(SWM_D_MISC, "search_win\n");
4152
4153         search_r = r;
4154         search_resp_action = SWM_SEARCH_SEARCH_WINDOW;
4155
4156         spawn_select(r, args, "search", &searchpid);
4157
4158         if ((lfile = fdopen(select_list_pipe[1], "w")) == NULL)
4159                 return;
4160
4161         TAILQ_INIT(&search_wl);
4162
4163         i = 1;
4164         TAILQ_FOREACH(win, &r->ws->winlist, entry) {
4165                 if (win->iconic == 1)
4166                         continue;
4167
4168                 sw = calloc(1, sizeof(struct search_window));
4169                 if (sw == NULL) {
4170                         warn("search_win: calloc");
4171                         fclose(lfile);
4172                         search_win_cleanup();
4173                         return;
4174                 }
4175                 sw->idx = i;
4176                 sw->win = win;
4177
4178                 snprintf(s, sizeof s, "%d", i);
4179                 len = strlen(s);
4180
4181                 w = xcb_generate_id(conn);
4182                 wa[0] = r->s->c[SWM_S_COLOR_FOCUS].pixel;
4183                 wa[1] = r->s->c[SWM_S_COLOR_UNFOCUS].pixel;
4184
4185                 if (bar_font_legacy) {
4186                         XmbTextExtents(bar_fs, s, len, &l_ibox, &l_lbox);
4187                         width = l_lbox.width + 4;
4188                         height = bar_fs_extents->max_logical_extent.height + 4;
4189                 } else {
4190                         XftTextExtentsUtf8(display, bar_font, (FcChar8 *)s, len,
4191                             &info);
4192                         width = info.width + 4;
4193                         height = bar_font->height + 4;
4194                 }
4195
4196                 xcb_create_window(conn, XCB_COPY_FROM_PARENT, w, win->id, 0, 0,
4197                     width, height, 1, XCB_WINDOW_CLASS_INPUT_OUTPUT,
4198                     XCB_COPY_FROM_PARENT, XCB_CW_BACK_PIXEL |
4199                     XCB_CW_BORDER_PIXEL, wa);
4200
4201                 xcb_map_window(conn, w);
4202
4203                 sw->indicator = w;
4204                 TAILQ_INSERT_TAIL(&search_wl, sw, entry);
4205
4206                 if (bar_font_legacy) {
4207                         l_gcv.graphics_exposures = 0;
4208                         l_draw = XCreateGC(display, w, 0, &l_gcv);
4209
4210                         XSetForeground(display, l_draw,
4211                                 r->s->c[SWM_S_COLOR_BAR].pixel);
4212
4213                         DRAWSTRING(display, w, bar_fs, l_draw, 2,
4214                             (bar_fs_extents->max_logical_extent.height -
4215                             l_lbox.height) / 2 - l_lbox.y, s, len);
4216
4217                         XFreeGC(display, l_draw);
4218                 } else {
4219
4220                         draw = XftDrawCreate(display, w,
4221                             DefaultVisual(display, r->s->idx),
4222                             DefaultColormap(display, r->s->idx));
4223
4224                         XftDrawStringUtf8(draw, &bar_font_color, bar_font, 2,
4225                             (HEIGHT(r->bar) + bar_font->height) / 2 -
4226                             bar_font->descent, (FcChar8 *)s, len);
4227
4228                         XftDrawDestroy(draw);
4229                 }
4230
4231                 DNPRINTF(SWM_D_MISC, "search_win: mapped window: 0x%x\n", w);
4232
4233                 fprintf(lfile, "%d\n", i);
4234                 i++;
4235         }
4236
4237         fclose(lfile);
4238
4239         xcb_flush(conn);
4240 }
4241
4242 void
4243 search_resp_uniconify(char *resp, unsigned long len)
4244 {
4245         char                    *name;
4246         struct ws_win           *win;
4247         char                    *s;
4248
4249         DNPRINTF(SWM_D_MISC, "search_resp_uniconify: resp: %s\n", resp);
4250
4251         TAILQ_FOREACH(win, &search_r->ws->winlist, entry) {
4252                 if (win->iconic == 0)
4253                         continue;
4254                 name = get_win_name(win->id);
4255                 if (name == NULL)
4256                         continue;
4257                 if (asprintf(&s, "%s.%u", name, win->id) == -1) {
4258                         free(name);
4259                         continue;
4260                 }
4261                 free(name);
4262                 if (strncmp(s, resp, len) == 0) {
4263                         /* XXX this should be a callback to generalize */
4264                         update_iconic(win, 0);
4265                         xcb_flush(conn);
4266                         free(s);
4267                         break;
4268                 }
4269                 free(s);
4270         }
4271 }
4272
4273 void
4274 search_resp_name_workspace(char *resp, unsigned long len)
4275 {
4276         struct workspace        *ws;
4277
4278         DNPRINTF(SWM_D_MISC, "search_resp_name_workspace: resp: %s\n", resp);
4279
4280         if (search_r->ws == NULL)
4281                 return;
4282         ws = search_r->ws;
4283
4284         if (ws->name) {
4285                 free(search_r->ws->name);
4286                 search_r->ws->name = NULL;
4287         }
4288
4289         if (len > 1) {
4290                 ws->name = strdup(resp);
4291                 if (ws->name == NULL) {
4292                         DNPRINTF(SWM_D_MISC, "search_resp_name_workspace: "
4293                             "strdup: %s", strerror(errno));
4294                         return;
4295                 }
4296         }
4297 }
4298
4299 void
4300 search_resp_search_workspace(char *resp)
4301 {
4302         char                    *p, *q;
4303         int                     ws_idx;
4304         const char              *errstr;
4305         union arg               a;
4306
4307         DNPRINTF(SWM_D_MISC, "search_resp_search_workspace: resp: %s\n", resp);
4308
4309         q = strdup(resp);
4310         if (!q) {
4311                 DNPRINTF(SWM_D_MISC, "search_resp_search_workspace: strdup: %s",
4312                     strerror(errno));
4313                 return;
4314         }
4315         p = strchr(q, ':');
4316         if (p != NULL)
4317                 *p = '\0';
4318         ws_idx = (int)strtonum(q, 1, workspace_limit, &errstr);
4319         if (errstr) {
4320                 DNPRINTF(SWM_D_MISC, "workspace idx is %s: %s",
4321                     errstr, q);
4322                 free(q);
4323                 return;
4324         }
4325         free(q);
4326         a.id = ws_idx - 1;
4327         switchws(search_r, &a);
4328 }
4329
4330 void
4331 search_resp_search_window(char *resp)
4332 {
4333         char                    *s;
4334         int                     idx;
4335         const char              *errstr;
4336         struct search_window    *sw;
4337
4338         DNPRINTF(SWM_D_MISC, "search_resp_search_window: resp: %s\n", resp);
4339
4340         s = strdup(resp);
4341         if (!s) {
4342                 DNPRINTF(SWM_D_MISC, "search_resp_search_window: strdup: %s",
4343                     strerror(errno));
4344                 return;
4345         }
4346
4347         idx = (int)strtonum(s, 1, INT_MAX, &errstr);
4348         if (errstr) {
4349                 DNPRINTF(SWM_D_MISC, "window idx is %s: %s",
4350                     errstr, s);
4351                 free(s);
4352                 return;
4353         }
4354         free(s);
4355
4356         TAILQ_FOREACH(sw, &search_wl, entry)
4357                 if (idx == sw->idx) {
4358                         focus_win(sw->win);
4359                         break;
4360                 }
4361 }
4362
4363 #define MAX_RESP_LEN    1024
4364
4365 void
4366 search_do_resp(void)
4367 {
4368         ssize_t                 rbytes;
4369         char                    *resp;
4370         unsigned long           len;
4371
4372         DNPRINTF(SWM_D_MISC, "search_do_resp:\n");
4373
4374         search_resp = 0;
4375         searchpid = 0;
4376
4377         if ((resp = calloc(1, MAX_RESP_LEN + 1)) == NULL) {
4378                 warn("search: calloc");
4379                 goto done;
4380         }
4381
4382         rbytes = read(select_resp_pipe[0], resp, MAX_RESP_LEN);
4383         if (rbytes <= 0) {
4384                 warn("search: read error");
4385                 goto done;
4386         }
4387         resp[rbytes] = '\0';
4388
4389         /* XXX:
4390          * Older versions of dmenu (Atleast pre 4.4.1) do not send a
4391          * newline, so work around that by sanitizing the resp now.
4392          */
4393         resp[strcspn(resp, "\n")] = '\0';
4394         len = strlen(resp);
4395
4396         switch (search_resp_action) {
4397         case SWM_SEARCH_UNICONIFY:
4398                 search_resp_uniconify(resp, len);
4399                 break;
4400         case SWM_SEARCH_NAME_WORKSPACE:
4401                 search_resp_name_workspace(resp, len);
4402                 break;
4403         case SWM_SEARCH_SEARCH_WORKSPACE:
4404                 search_resp_search_workspace(resp);
4405                 break;
4406         case SWM_SEARCH_SEARCH_WINDOW:
4407                 search_resp_search_window(resp);
4408                 break;
4409         }
4410
4411 done:
4412         if (search_resp_action == SWM_SEARCH_SEARCH_WINDOW)
4413                 search_win_cleanup();
4414
4415         search_resp_action = SWM_SEARCH_NONE;
4416         close(select_resp_pipe[0]);
4417         free(resp);
4418
4419         xcb_flush(conn);
4420 }
4421
4422 void
4423 wkill(struct swm_region *r, union arg *args)
4424 {
4425         DNPRINTF(SWM_D_MISC, "wkill: id: %d\n", args->id);
4426
4427         if (r->ws->focus == NULL)
4428                 return;
4429
4430         if (args->id == SWM_ARG_ID_KILLWINDOW)
4431                 xcb_kill_client(conn, r->ws->focus->id);
4432         else
4433                 if (r->ws->focus->can_delete)
4434                         client_msg(r->ws->focus, a_delete, 0);
4435
4436         xcb_flush(conn);
4437 }
4438
4439
4440 int
4441 floating_toggle_win(struct ws_win *win)
4442 {
4443         struct swm_region       *r;
4444
4445         if (win == NULL)
4446                 return (0);
4447
4448         if (!win->ws->r)
4449                 return (0);
4450
4451         r = win->ws->r;
4452
4453         /* reject floating toggles in max stack mode */
4454         if (win->ws->cur_layout == &layouts[SWM_MAX_STACK])
4455                 return (0);
4456
4457         if (win->floating) {
4458                 if (!win->floatmaxed) {
4459                         /* retain position for refloat */
4460                         store_float_geom(win, r);
4461                 }
4462                 win->floating = 0;
4463         } else {
4464                 load_float_geom(win, r);
4465                 win->floating = 1;
4466         }
4467
4468         ewmh_update_actions(win);
4469
4470         return (1);
4471 }
4472
4473 void
4474 floating_toggle(struct swm_region *r, union arg *args)
4475 {
4476         struct ws_win           *win = r->ws->focus;
4477
4478         /* suppress unused warning since var is needed */
4479         (void)args;
4480
4481         if (win == NULL)
4482                 return;
4483
4484         if (win->ewmh_flags & EWMH_F_FULLSCREEN)
4485                 return;
4486
4487         ewmh_update_win_state(win, ewmh[_NET_WM_STATE_ABOVE].atom,
4488             _NET_WM_STATE_TOGGLE);
4489
4490         stack();
4491
4492         if (win == win->ws->focus)
4493                 focus_win(win);
4494
4495         focus_flush();
4496 }
4497
4498 void
4499 constrain_window(struct ws_win *win, struct swm_region *r, int resizable)
4500 {
4501         if (MAX_X(win) + BORDER(win) > MAX_X(r)) {
4502                 if (resizable)
4503                         WIDTH(win) = MAX_X(r) - X(win) - BORDER(win);
4504                 else
4505                         X(win) = MAX_X(r)- WIDTH(win) - BORDER(win);
4506         }
4507
4508         if (X(win) + BORDER(win) < X(r)) {
4509                 if (resizable)
4510                         WIDTH(win) -= X(r) - X(win) - BORDER(win);
4511
4512                 X(win) = X(r) - BORDER(win);
4513         }
4514
4515         if (MAX_Y(win) + BORDER(win) > MAX_Y(r)) {
4516                 if (resizable)
4517                         HEIGHT(win) = MAX_Y(r) - Y(win) - BORDER(win);
4518                 else
4519                         Y(win) = MAX_Y(r) - HEIGHT(win) - BORDER(win);
4520         }
4521
4522         if (Y(win) + BORDER(win) < Y(r)) {
4523                 if (resizable)
4524                         HEIGHT(win) -= Y(r) - Y(win) - BORDER(win);
4525
4526                 Y(win) = Y(r) - BORDER(win);
4527         }
4528
4529         if (resizable) {
4530                 if (WIDTH(win) < 1)
4531                         WIDTH(win) = 1;
4532                 if (HEIGHT(win) < 1)
4533                         HEIGHT(win) = 1;
4534         }
4535 }
4536
4537 void
4538 update_window(struct ws_win *win)
4539 {
4540         uint16_t        mask;
4541         uint32_t        wc[5];
4542
4543         mask = XCB_CONFIG_WINDOW_X | XCB_CONFIG_WINDOW_Y |
4544             XCB_CONFIG_WINDOW_WIDTH | XCB_CONFIG_WINDOW_HEIGHT |
4545             XCB_CONFIG_WINDOW_BORDER_WIDTH;
4546         wc[0] = X(win);
4547         wc[1] = Y(win);
4548         wc[2] = WIDTH(win);
4549         wc[3] = HEIGHT(win);
4550         wc[4] = BORDER(win);
4551
4552         DNPRINTF(SWM_D_EVENT, "update_window: window: 0x%x, (x,y) w x h: "
4553             "(%d,%d) %d x %d, bordered: %s\n", win->id, wc[0], wc[1], wc[2],
4554             wc[3], YESNO(win->bordered));
4555
4556         xcb_configure_window(conn, win->id, mask, wc);
4557 }
4558
4559 #define SWM_RESIZE_STEPS        (50)
4560
4561 void
4562 resize(struct ws_win *win, union arg *args)
4563 {
4564         xcb_timestamp_t         timestamp = 0;
4565         struct swm_region       *r = NULL;
4566         int                     resize_step = 0;
4567         struct swm_geometry     g;
4568         int                     top = 0, left = 0, resizing;
4569         int                     dx, dy;
4570         unsigned int            shape; /* cursor style */
4571         xcb_cursor_t            cursor;
4572         xcb_font_t              cursor_font;
4573         xcb_query_pointer_reply_t       *xpr;
4574         xcb_generic_event_t             *evt;
4575         xcb_motion_notify_event_t       *mne;
4576
4577         if (win == NULL)
4578                 return;
4579         r = win->ws->r;
4580
4581         if (win->ewmh_flags & EWMH_F_FULLSCREEN)
4582                 return;
4583
4584         DNPRINTF(SWM_D_EVENT, "resize: window: 0x%x, floating: %s, "
4585             "transient: 0x%x\n", win->id, YESNO(win->floating),
4586             win->transient);
4587
4588         if (!(win->transient != 0 || win->floating != 0))
4589                 return;
4590
4591         /* reject resizes in max mode for floaters (transient ok) */
4592         if (win->floatmaxed)
4593                 return;
4594
4595         win->manual = 1;
4596         ewmh_update_win_state(win, ewmh[_SWM_WM_STATE_MANUAL].atom,
4597             _NET_WM_STATE_ADD);
4598
4599         stack();
4600
4601         focus_flush();
4602
4603         switch (args->id) {
4604         case SWM_ARG_ID_WIDTHSHRINK:
4605                 WIDTH(win) -= SWM_RESIZE_STEPS;
4606                 resize_step = 1;
4607                 break;
4608         case SWM_ARG_ID_WIDTHGROW:
4609                 WIDTH(win) += SWM_RESIZE_STEPS;
4610                 resize_step = 1;
4611                 break;
4612         case SWM_ARG_ID_HEIGHTSHRINK:
4613                 HEIGHT(win) -= SWM_RESIZE_STEPS;
4614                 resize_step = 1;
4615                 break;
4616         case SWM_ARG_ID_HEIGHTGROW:
4617                 HEIGHT(win) += SWM_RESIZE_STEPS;
4618                 resize_step = 1;
4619                 break;
4620         default:
4621                 break;
4622         }
4623         if (resize_step) {
4624                 constrain_window(win, r, 1);
4625                 update_window(win);
4626                 store_float_geom(win,r);
4627                 return;
4628         }
4629
4630         /* get cursor offset from window root */
4631         xpr = xcb_query_pointer_reply(conn, xcb_query_pointer(conn, win->id),
4632             NULL);
4633         if (!xpr)
4634                 return;
4635
4636         g = win->g;
4637
4638         if (xpr->win_x < WIDTH(win) / 2)
4639                 left = 1;
4640
4641         if (xpr->win_y < HEIGHT(win) / 2)
4642                 top = 1;
4643
4644         if (args->id == SWM_ARG_ID_CENTER)
4645                 shape = XC_sizing;
4646         else if (top)
4647                 shape = (left) ? XC_top_left_corner : XC_top_right_corner;
4648         else
4649                 shape = (left) ? XC_bottom_left_corner : XC_bottom_right_corner;
4650
4651         cursor_font = xcb_generate_id(conn);
4652         xcb_open_font(conn, cursor_font, strlen("cursor"), "cursor");
4653
4654         cursor = xcb_generate_id(conn);
4655         xcb_create_glyph_cursor(conn, cursor, cursor_font, cursor_font,
4656             shape, shape + 1, 0, 0, 0, 0xffff, 0xffff, 0xffff);
4657
4658         xcb_grab_pointer(conn, 0, win->id, MOUSEMASK,
4659             XCB_GRAB_MODE_ASYNC, XCB_GRAB_MODE_ASYNC, XCB_WINDOW_NONE, cursor,
4660             XCB_CURRENT_TIME),
4661
4662         xcb_flush(conn);
4663         resizing = 1;
4664         while ((evt = xcb_wait_for_event(conn)) && resizing) {
4665                 switch (XCB_EVENT_RESPONSE_TYPE(evt)) {
4666                 case XCB_BUTTON_RELEASE:
4667                         DNPRINTF(SWM_D_EVENT, "resize: BUTTON_RELEASE\n");
4668                         resizing = 0;
4669                         break;
4670                 case XCB_MOTION_NOTIFY:
4671                         mne = (xcb_motion_notify_event_t *)evt;
4672                         /* cursor offset/delta from start of the operation */
4673                         dx = mne->root_x - xpr->root_x;
4674                         dy = mne->root_y - xpr->root_y;
4675
4676                         /* vertical */
4677                         if (top)
4678                                 dy = -dy;
4679
4680                         if (args->id == SWM_ARG_ID_CENTER) {
4681                                 if (g.h / 2 + dy < 1)
4682                                         dy = 1 - g.h / 2;
4683
4684                                 Y(win) = g.y - dy;
4685                                 HEIGHT(win) = g.h + 2 * dy;
4686                         } else {
4687                                 if (g.h + dy < 1)
4688                                         dy = 1 - g.h;
4689
4690                                 if (top)
4691                                         Y(win) = g.y - dy;
4692
4693                                 HEIGHT(win) = g.h + dy;
4694                         }
4695
4696                         /* horizontal */
4697                         if (left)
4698                                 dx = -dx;
4699
4700                         if (args->id == SWM_ARG_ID_CENTER) {
4701                                 if (g.w / 2 + dx < 1)
4702                                         dx = 1 - g.w / 2;
4703
4704                                 X(win) = g.x - dx;
4705                                 WIDTH(win) = g.w + 2 * dx;
4706                         } else {
4707                                 if (g.w + dx < 1)
4708                                         dx = 1 - g.w;
4709
4710                                 if (left)
4711                                         X(win) = g.x - dx;
4712
4713                                 WIDTH(win) = g.w + dx;
4714                         }
4715
4716                         constrain_window(win, r, 1);
4717
4718                         /* not free, don't sync more than 120 times / second */
4719                         if ((mne->time - timestamp) > (1000 / 120) ) {
4720                                 timestamp = mne->time;
4721                                 update_window(win);
4722                                 xcb_flush(conn);
4723                         }
4724                         break;
4725                 default:
4726                         event_handle(evt);
4727                         break;
4728                 }
4729                 free(evt);
4730         }
4731         if (timestamp) {
4732                 update_window(win);
4733                 xcb_flush(conn);
4734         }
4735         store_float_geom(win,r);
4736
4737         xcb_ungrab_pointer(conn, XCB_CURRENT_TIME);
4738         xcb_free_cursor(conn, cursor);
4739         xcb_close_font(conn, cursor_font);
4740         free(xpr);
4741         DNPRINTF(SWM_D_EVENT, "resize: done.\n");
4742 }
4743
4744 void
4745 resize_step(struct swm_region *r, union arg *args)
4746 {
4747         struct ws_win           *win = NULL;
4748
4749         if (r && r->ws && r->ws->focus)
4750                 win = r->ws->focus;
4751         else
4752                 return;
4753
4754         resize(win, args);
4755 }
4756
4757 #define SWM_MOVE_STEPS  (50)
4758
4759 void
4760 move(struct ws_win *win, union arg *args)
4761 {
4762         xcb_timestamp_t         timestamp = 0;
4763         int                     move_step = 0, moving;
4764         struct swm_region       *r = NULL;
4765         xcb_font_t                      cursor_font;
4766         xcb_cursor_t                    cursor;
4767         xcb_query_pointer_reply_t       *qpr;
4768         xcb_generic_event_t             *evt;
4769         xcb_motion_notify_event_t       *mne;
4770
4771         if (win == NULL)
4772                 return;
4773         r = win->ws->r;
4774
4775         if (win->ewmh_flags & EWMH_F_FULLSCREEN)
4776                 return;
4777
4778         DNPRINTF(SWM_D_EVENT, "move: window: 0x%x, floating: %s, transient: "
4779             "0x%x\n", win->id, YESNO(win->floating), win->transient);
4780
4781         /* in max_stack mode should only move transients */
4782         if (win->ws->cur_layout == &layouts[SWM_MAX_STACK] && !win->transient)
4783                 return;
4784
4785         win->manual = 1;
4786         if (win->floating == 0 && !win->transient) {
4787                 store_float_geom(win, r);
4788                 ewmh_update_win_state(win, ewmh[_NET_WM_STATE_ABOVE].atom,
4789                     _NET_WM_STATE_ADD);
4790         }
4791         ewmh_update_win_state(win, ewmh[_SWM_WM_STATE_MANUAL].atom,
4792             _NET_WM_STATE_ADD);
4793
4794         stack();
4795
4796         focus_flush();
4797
4798         move_step = 0;
4799         switch (args->id) {
4800         case SWM_ARG_ID_MOVELEFT:
4801                 X(win) -= (SWM_MOVE_STEPS - border_width);
4802                 move_step = 1;
4803                 break;
4804         case SWM_ARG_ID_MOVERIGHT:
4805                 X(win) += (SWM_MOVE_STEPS - border_width);
4806                 move_step = 1;
4807                 break;
4808         case SWM_ARG_ID_MOVEUP:
4809                 Y(win) -= (SWM_MOVE_STEPS - border_width);
4810                 move_step = 1;
4811                 break;
4812         case SWM_ARG_ID_MOVEDOWN:
4813                 Y(win) += (SWM_MOVE_STEPS - border_width);
4814                 move_step = 1;
4815                 break;
4816         default:
4817                 break;
4818         }
4819         if (move_step) {
4820                 constrain_window(win, r, 0);
4821                 update_window(win);
4822                 store_float_geom(win, r);
4823                 return;
4824         }
4825
4826         cursor_font = xcb_generate_id(conn);
4827         xcb_open_font(conn, cursor_font, strlen("cursor"), "cursor");
4828
4829         cursor = xcb_generate_id(conn);
4830         xcb_create_glyph_cursor(conn, cursor, cursor_font, cursor_font,
4831                 XC_fleur, XC_fleur + 1, 0, 0, 0, 0xffff, 0xffff, 0xffff);
4832
4833         xcb_grab_pointer(conn, 0, win->id, MOUSEMASK,
4834             XCB_GRAB_MODE_ASYNC, XCB_GRAB_MODE_ASYNC,
4835             XCB_WINDOW_NONE, cursor, XCB_CURRENT_TIME);
4836
4837         /* get cursor offset from window root */
4838         qpr = xcb_query_pointer_reply(conn, xcb_query_pointer(conn, win->id),
4839                 NULL);
4840         if (!qpr) {
4841                 xcb_ungrab_pointer(conn, XCB_CURRENT_TIME);
4842                 xcb_free_cursor(conn, cursor);
4843                 xcb_close_font(conn, cursor_font);
4844                 return;
4845         }
4846
4847         xcb_flush(conn);
4848         moving = 1;
4849         while ((evt = xcb_wait_for_event(conn)) && moving) {
4850                 switch (XCB_EVENT_RESPONSE_TYPE(evt)) {
4851                 case XCB_BUTTON_RELEASE:
4852                         DNPRINTF(SWM_D_EVENT, "move: BUTTON_RELEASE\n");
4853                         moving = 0;
4854                         break;
4855                 case XCB_MOTION_NOTIFY:
4856                         mne = (xcb_motion_notify_event_t *)evt;
4857                         X(win) = mne->root_x - qpr->win_x - border_width;
4858                         Y(win) = mne->root_y - qpr->win_y - border_width;
4859
4860                         constrain_window(win, r, 0);
4861
4862                         /* not free, don't sync more than 120 times / second */
4863                         if ((mne->time - timestamp) > (1000 / 120) ) {
4864                                 timestamp = mne->time;
4865                                 update_window(win);
4866                                 xcb_flush(conn);
4867                         }
4868                         break;
4869                 default:
4870                         event_handle(evt);
4871                         break;
4872                 }
4873                 free(evt);
4874         }
4875         if (timestamp) {
4876                 update_window(win);
4877                 xcb_flush(conn);
4878         }
4879         store_float_geom(win, r);
4880         free(qpr);
4881         xcb_free_cursor(conn, cursor);
4882         xcb_close_font(conn, cursor_font);
4883         xcb_ungrab_pointer(conn, XCB_CURRENT_TIME);
4884         DNPRINTF(SWM_D_EVENT, "move: done.\n");
4885 }
4886
4887 void
4888 move_step(struct swm_region *r, union arg *args)
4889 {
4890         struct ws_win           *win = NULL;
4891
4892         if (r && r->ws && r->ws->focus)
4893                 win = r->ws->focus;
4894         else
4895                 return;
4896
4897         if (!(win->transient != 0 || win->floating != 0))
4898                 return;
4899
4900         move(win, args);
4901 }
4902
4903
4904 /* user/key callable function IDs */
4905 enum keyfuncid {
4906         KF_BAR_TOGGLE,
4907         KF_BUTTON2,
4908         KF_CYCLE_LAYOUT,
4909         KF_FLIP_LAYOUT,
4910         KF_FLOAT_TOGGLE,
4911         KF_FOCUS_MAIN,
4912         KF_FOCUS_NEXT,
4913         KF_FOCUS_PREV,
4914         KF_HEIGHT_GROW,
4915         KF_HEIGHT_SHRINK,
4916         KF_ICONIFY,
4917         KF_MASTER_SHRINK,
4918         KF_MASTER_GROW,
4919         KF_MASTER_ADD,
4920         KF_MASTER_DEL,
4921         KF_MOVE_DOWN,
4922         KF_MOVE_LEFT,
4923         KF_MOVE_RIGHT,
4924         KF_MOVE_UP,
4925         KF_MVWS_1,
4926         KF_MVWS_2,
4927         KF_MVWS_3,
4928         KF_MVWS_4,
4929         KF_MVWS_5,
4930         KF_MVWS_6,
4931         KF_MVWS_7,
4932         KF_MVWS_8,
4933         KF_MVWS_9,
4934         KF_MVWS_10,
4935         KF_MVWS_11,
4936         KF_MVWS_12,
4937         KF_MVWS_13,
4938         KF_MVWS_14,
4939         KF_MVWS_15,
4940         KF_MVWS_16,
4941         KF_MVWS_17,
4942         KF_MVWS_18,
4943         KF_MVWS_19,
4944         KF_MVWS_20,
4945         KF_MVWS_21,
4946         KF_MVWS_22,
4947         KF_NAME_WORKSPACE,
4948         KF_QUIT,
4949         KF_RAISE_TOGGLE,
4950         KF_RESTART,
4951         KF_SCREEN_NEXT,
4952         KF_SCREEN_PREV,
4953         KF_SEARCH_WIN,
4954         KF_SEARCH_WORKSPACE,
4955         KF_SPAWN_CUSTOM,
4956         KF_STACK_INC,
4957         KF_STACK_DEC,
4958         KF_STACK_RESET,
4959         KF_SWAP_MAIN,
4960         KF_SWAP_NEXT,
4961         KF_SWAP_PREV,
4962         KF_UNICONIFY,
4963         KF_VERSION,
4964         KF_WIDTH_GROW,
4965         KF_WIDTH_SHRINK,
4966         KF_WIND_DEL,
4967         KF_WIND_KILL,
4968         KF_WS_1,
4969         KF_WS_2,
4970         KF_WS_3,
4971         KF_WS_4,
4972         KF_WS_5,
4973         KF_WS_6,
4974         KF_WS_7,
4975         KF_WS_8,
4976         KF_WS_9,
4977         KF_WS_10,
4978         KF_WS_11,
4979         KF_WS_12,
4980         KF_WS_13,
4981         KF_WS_14,
4982         KF_WS_15,
4983         KF_WS_16,
4984         KF_WS_17,
4985         KF_WS_18,
4986         KF_WS_19,
4987         KF_WS_20,
4988         KF_WS_21,
4989         KF_WS_22,
4990         KF_WS_NEXT,
4991         KF_WS_NEXT_ALL,
4992         KF_WS_PREV,
4993         KF_WS_PREV_ALL,
4994         KF_WS_PRIOR,
4995         KF_DUMPWINS, /* MUST BE LAST */
4996         KF_INVALID
4997 };
4998
4999 /* key definitions */
5000 struct keyfunc {
5001         char                    name[SWM_FUNCNAME_LEN];
5002         void                    (*func)(struct swm_region *r, union arg *);
5003         union arg               args;
5004 } keyfuncs[KF_INVALID + 1] = {
5005         /* name                 function        argument */
5006         { "bar_toggle",         bar_toggle,     {0} },
5007         { "button2",            pressbutton,    {2} },
5008         { "cycle_layout",       cycle_layout,   {0} },
5009         { "flip_layout",        stack_config,   {.id = SWM_ARG_ID_FLIPLAYOUT} },
5010         { "float_toggle",       floating_toggle,{0} },
5011         { "focus_main",         focus,          {.id = SWM_ARG_ID_FOCUSMAIN} },
5012         { "focus_next",         focus,          {.id = SWM_ARG_ID_FOCUSNEXT} },
5013         { "focus_prev",         focus,          {.id = SWM_ARG_ID_FOCUSPREV} },
5014         { "height_grow",        resize_step,    {.id = SWM_ARG_ID_HEIGHTGROW} },
5015         { "height_shrink",      resize_step,    {.id = SWM_ARG_ID_HEIGHTSHRINK} },
5016         { "iconify",            iconify,        {0} },
5017         { "master_shrink",      stack_config,   {.id = SWM_ARG_ID_MASTERSHRINK} },
5018         { "master_grow",        stack_config,   {.id = SWM_ARG_ID_MASTERGROW} },
5019         { "master_add",         stack_config,   {.id = SWM_ARG_ID_MASTERADD} },
5020         { "master_del",         stack_config,   {.id = SWM_ARG_ID_MASTERDEL} },
5021         { "move_down",          move_step,      {.id = SWM_ARG_ID_MOVEDOWN} },
5022         { "move_left",          move_step,      {.id = SWM_ARG_ID_MOVELEFT} },
5023         { "move_right",         move_step,      {.id = SWM_ARG_ID_MOVERIGHT} },
5024         { "move_up",            move_step,      {.id = SWM_ARG_ID_MOVEUP} },
5025         { "mvws_1",             send_to_ws,     {.id = 0} },
5026         { "mvws_2",             send_to_ws,     {.id = 1} },
5027         { "mvws_3",             send_to_ws,     {.id = 2} },
5028         { "mvws_4",             send_to_ws,     {.id = 3} },
5029         { "mvws_5",             send_to_ws,     {.id = 4} },
5030         { "mvws_6",             send_to_ws,     {.id = 5} },
5031         { "mvws_7",             send_to_ws,     {.id = 6} },
5032         { "mvws_8",             send_to_ws,     {.id = 7} },
5033         { "mvws_9",             send_to_ws,     {.id = 8} },
5034         { "mvws_10",            send_to_ws,     {.id = 9} },
5035         { "mvws_11",            send_to_ws,     {.id = 10} },
5036         { "mvws_12",            send_to_ws,     {.id = 11} },
5037         { "mvws_13",            send_to_ws,     {.id = 12} },
5038         { "mvws_14",            send_to_ws,     {.id = 13} },
5039         { "mvws_15",            send_to_ws,     {.id = 14} },
5040         { "mvws_16",            send_to_ws,     {.id = 15} },
5041         { "mvws_17",            send_to_ws,     {.id = 16} },
5042         { "mvws_18",            send_to_ws,     {.id = 17} },
5043         { "mvws_19",            send_to_ws,     {.id = 18} },
5044         { "mvws_20",            send_to_ws,     {.id = 19} },
5045         { "mvws_21",            send_to_ws,     {.id = 20} },
5046         { "mvws_22",            send_to_ws,     {.id = 21} },
5047         { "name_workspace",     name_workspace, {0} },
5048         { "quit",               quit,           {0} },
5049         { "raise_toggle",       raise_toggle,   {0} },
5050         { "restart",            restart,        {0} },
5051         { "screen_next",        cyclescr,       {.id = SWM_ARG_ID_CYCLESC_UP} },
5052         { "screen_prev",        cyclescr,       {.id = SWM_ARG_ID_CYCLESC_DOWN} },
5053         { "search_win",         search_win,     {0} },
5054         { "search_workspace",   search_workspace,       {0} },
5055         { "spawn_custom",       NULL,           {0} },
5056         { "stack_inc",          stack_config,   {.id = SWM_ARG_ID_STACKINC} },
5057         { "stack_dec",          stack_config,   {.id = SWM_ARG_ID_STACKDEC} },
5058         { "stack_reset",        stack_config,   {.id = SWM_ARG_ID_STACKRESET} },
5059         { "swap_main",          swapwin,        {.id = SWM_ARG_ID_SWAPMAIN} },
5060         { "swap_next",          swapwin,        {.id = SWM_ARG_ID_SWAPNEXT} },
5061         { "swap_prev",          swapwin,        {.id = SWM_ARG_ID_SWAPPREV} },
5062         { "uniconify",          uniconify,      {0} },
5063         { "version",            version,        {0} },
5064         { "width_grow",         resize_step,    {.id = SWM_ARG_ID_WIDTHGROW} },
5065         { "width_shrink",       resize_step,    {.id = SWM_ARG_ID_WIDTHSHRINK} },
5066         { "wind_del",           wkill,          {.id = SWM_ARG_ID_DELETEWINDOW} },
5067         { "wind_kill",          wkill,          {.id = SWM_ARG_ID_KILLWINDOW} },
5068         { "ws_1",               switchws,       {.id = 0} },
5069         { "ws_2",               switchws,       {.id = 1} },
5070         { "ws_3",               switchws,       {.id = 2} },
5071         { "ws_4",               switchws,       {.id = 3} },
5072         { "ws_5",               switchws,       {.id = 4} },
5073         { "ws_6",               switchws,       {.id = 5} },
5074         { "ws_7",               switchws,       {.id = 6} },
5075         { "ws_8",               switchws,       {.id = 7} },
5076         { "ws_9",               switchws,       {.id = 8} },
5077         { "ws_10",              switchws,       {.id = 9} },
5078         { "ws_11",              switchws,       {.id = 10} },
5079         { "ws_12",              switchws,       {.id = 11} },
5080         { "ws_13",              switchws,       {.id = 12} },
5081         { "ws_14",              switchws,       {.id = 13} },
5082         { "ws_15",              switchws,       {.id = 14} },
5083         { "ws_16",              switchws,       {.id = 15} },
5084         { "ws_17",              switchws,       {.id = 16} },
5085         { "ws_18",              switchws,       {.id = 17} },
5086         { "ws_19",              switchws,       {.id = 18} },
5087         { "ws_20",              switchws,       {.id = 19} },
5088         { "ws_21",              switchws,       {.id = 20} },
5089         { "ws_22",              switchws,       {.id = 21} },
5090         { "ws_next",            cyclews,        {.id = SWM_ARG_ID_CYCLEWS_UP} },
5091         { "ws_next_all",        cyclews,        {.id = SWM_ARG_ID_CYCLEWS_UP_ALL} },
5092         { "ws_prev",            cyclews,        {.id = SWM_ARG_ID_CYCLEWS_DOWN} },
5093         { "ws_prev_all",        cyclews,        {.id = SWM_ARG_ID_CYCLEWS_DOWN_ALL} },
5094         { "ws_prior",           priorws,        {0} },
5095         { "dumpwins",           dumpwins,       {0} }, /* MUST BE LAST */
5096         { "invalid key func",   NULL,           {0} },
5097 };
5098 struct key {
5099         RB_ENTRY(key)           entry;
5100         unsigned int            mod;
5101         KeySym                  keysym;
5102         enum keyfuncid          funcid;
5103         char                    *spawn_name;
5104 };
5105 RB_HEAD(key_tree, key);
5106
5107 int
5108 key_cmp(struct key *kp1, struct key *kp2)
5109 {
5110         if (kp1->keysym < kp2->keysym)
5111                 return (-1);
5112         if (kp1->keysym > kp2->keysym)
5113                 return (1);
5114
5115         if (kp1->mod < kp2->mod)
5116                 return (-1);
5117         if (kp1->mod > kp2->mod)
5118                 return (1);
5119
5120         return (0);
5121 }
5122
5123 RB_GENERATE(key_tree, key, entry, key_cmp);
5124 struct key_tree                 keys;
5125
5126 /* mouse */
5127 enum { client_click, root_click };
5128 struct button {
5129         unsigned int            action;
5130         unsigned int            mask;
5131         unsigned int            button;
5132         void                    (*func)(struct ws_win *, union arg *);
5133         union arg               args;
5134 } buttons[] = {
5135 #define MODKEY_SHIFT    MODKEY | XCB_MOD_MASK_SHIFT
5136           /* action     key             mouse button    func    args */
5137         { client_click, MODKEY,         XCB_BUTTON_INDEX_3,     resize, {.id = SWM_ARG_ID_DONTCENTER} },
5138         { client_click, MODKEY_SHIFT,   XCB_BUTTON_INDEX_3,     resize, {.id = SWM_ARG_ID_CENTER} },
5139         { client_click, MODKEY,         XCB_BUTTON_INDEX_1,     move,   {0} },
5140 #undef MODKEY_SHIFT
5141 };
5142
5143 void
5144 update_modkey(unsigned int mod)
5145 {
5146         int                     i;
5147         struct key              *kp;
5148
5149         mod_key = mod;
5150         RB_FOREACH(kp, key_tree, &keys)
5151                 if (kp->mod & XCB_MOD_MASK_SHIFT)
5152                         kp->mod = mod | XCB_MOD_MASK_SHIFT;
5153                 else
5154                         kp->mod = mod;
5155
5156         for (i = 0; i < LENGTH(buttons); i++)
5157                 if (buttons[i].mask & XCB_MOD_MASK_SHIFT)
5158                         buttons[i].mask = mod | XCB_MOD_MASK_SHIFT;
5159                 else
5160                         buttons[i].mask = mod;
5161 }
5162
5163 /* spawn */
5164 struct spawn_prog {
5165         TAILQ_ENTRY(spawn_prog) entry;
5166         char                    *name;
5167         int                     argc;
5168         char                    **argv;
5169 };
5170 TAILQ_HEAD(spawn_list, spawn_prog);
5171 struct spawn_list               spawns = TAILQ_HEAD_INITIALIZER(spawns);
5172
5173 int
5174 spawn_expand(struct swm_region *r, union arg *args, char *spawn_name,
5175     char ***ret_args)
5176 {
5177         struct spawn_prog       *prog = NULL;
5178         int                     i;
5179         char                    *ap, **real_args;
5180
5181         /* suppress unused warning since var is needed */
5182         (void)args;
5183
5184         DNPRINTF(SWM_D_SPAWN, "spawn_expand: %s\n", spawn_name);
5185
5186         /* find program */
5187         TAILQ_FOREACH(prog, &spawns, entry) {
5188                 if (!strcasecmp(spawn_name, prog->name))
5189                         break;
5190         }
5191         if (prog == NULL) {
5192                 warnx("spawn_custom: program %s not found", spawn_name);
5193                 return (-1);
5194         }
5195
5196         /* make room for expanded args */
5197         if ((real_args = calloc(prog->argc + 1, sizeof(char *))) == NULL)
5198                 err(1, "spawn_custom: calloc real_args");
5199
5200         /* expand spawn_args into real_args */
5201         for (i = 0; i < prog->argc; i++) {
5202                 ap = prog->argv[i];
5203                 DNPRINTF(SWM_D_SPAWN, "spawn_custom: raw arg: %s\n", ap);
5204                 if (!strcasecmp(ap, "$bar_border")) {
5205                         if ((real_args[i] =
5206                             strdup(r->s->c[SWM_S_COLOR_BAR_BORDER].name))
5207                             == NULL)
5208                                 err(1,  "spawn_custom border color");
5209                 } else if (!strcasecmp(ap, "$bar_color")) {
5210                         if ((real_args[i] =
5211                             strdup(r->s->c[SWM_S_COLOR_BAR].name))
5212                             == NULL)
5213                                 err(1, "spawn_custom bar color");
5214                 } else if (!strcasecmp(ap, "$bar_font")) {
5215                         if ((real_args[i] = strdup(bar_fonts))
5216                             == NULL)
5217                                 err(1, "spawn_custom bar fonts");
5218                 } else if (!strcasecmp(ap, "$bar_font_color")) {
5219                         if ((real_args[i] =
5220                             strdup(r->s->c[SWM_S_COLOR_BAR_FONT].name))
5221                             == NULL)
5222                                 err(1, "spawn_custom color font");
5223                 } else if (!strcasecmp(ap, "$color_focus")) {
5224                         if ((real_args[i] =
5225                             strdup(r->s->c[SWM_S_COLOR_FOCUS].name))
5226                             == NULL)
5227                                 err(1, "spawn_custom color focus");
5228                 } else if (!strcasecmp(ap, "$color_unfocus")) {
5229                         if ((real_args[i] =
5230                             strdup(r->s->c[SWM_S_COLOR_UNFOCUS].name))
5231                             == NULL)
5232                                 err(1, "spawn_custom color unfocus");
5233                 } else {
5234                         /* no match --> copy as is */
5235                         if ((real_args[i] = strdup(ap)) == NULL)
5236                                 err(1, "spawn_custom strdup(ap)");
5237                 }
5238                 DNPRINTF(SWM_D_SPAWN, "spawn_custom: cooked arg: %s\n",
5239                     real_args[i]);
5240         }
5241
5242 #ifdef SWM_DEBUG
5243         DNPRINTF(SWM_D_SPAWN, "spawn_custom: result: ");
5244         for (i = 0; i < prog->argc; i++)
5245                 DNPRINTF(SWM_D_SPAWN, "\"%s\" ", real_args[i]);
5246         DNPRINTF(SWM_D_SPAWN, "\n");
5247 #endif
5248         *ret_args = real_args;
5249         return (prog->argc);
5250 }
5251
5252 void
5253 spawn_custom(struct swm_region *r, union arg *args, char *spawn_name)
5254 {
5255         union arg               a;
5256         char                    **real_args;
5257         int                     spawn_argc, i;
5258
5259         if ((spawn_argc = spawn_expand(r, args, spawn_name, &real_args)) < 0)
5260                 return;
5261         a.argv = real_args;
5262         if (fork() == 0)
5263                 spawn(r->ws->idx, &a, 1);
5264
5265         for (i = 0; i < spawn_argc; i++)
5266                 free(real_args[i]);
5267         free(real_args);
5268 }
5269
5270 void
5271 spawn_select(struct swm_region *r, union arg *args, char *spawn_name, int *pid)
5272 {
5273         union arg               a;
5274         char                    **real_args;
5275         int                     i, spawn_argc;
5276
5277         if ((spawn_argc = spawn_expand(r, args, spawn_name, &real_args)) < 0)
5278                 return;
5279         a.argv = real_args;
5280
5281         if (pipe(select_list_pipe) == -1)
5282                 err(1, "pipe error");
5283         if (pipe(select_resp_pipe) == -1)
5284                 err(1, "pipe error");
5285
5286         if (signal(SIGPIPE, SIG_IGN) == SIG_ERR)
5287                 err(1, "could not disable SIGPIPE");
5288         switch (*pid = fork()) {
5289         case -1:
5290                 err(1, "cannot fork");
5291                 break;
5292         case 0: /* child */
5293                 if (dup2(select_list_pipe[0], 0) == -1)
5294                         err(1, "dup2");
5295                 if (dup2(select_resp_pipe[1], 1) == -1)
5296                         err(1, "dup2");
5297                 close(select_list_pipe[1]);
5298                 close(select_resp_pipe[0]);
5299                 spawn(r->ws->idx, &a, 0);
5300                 break;
5301         default: /* parent */
5302                 close(select_list_pipe[0]);
5303                 close(select_resp_pipe[1]);
5304                 break;
5305         }
5306
5307         for (i = 0; i < spawn_argc; i++)
5308                 free(real_args[i]);
5309         free(real_args);
5310 }
5311
5312 void
5313 spawn_insert(char *name, char *args)
5314 {
5315         char                    *arg, *cp, *ptr;
5316         struct spawn_prog       *sp;
5317
5318         DNPRINTF(SWM_D_SPAWN, "spawn_insert: %s\n", name);
5319
5320         if ((sp = calloc(1, sizeof *sp)) == NULL)
5321                 err(1, "spawn_insert: calloc");
5322         if ((sp->name = strdup(name)) == NULL)
5323                 err(1, "spawn_insert: strdup");
5324
5325         /* convert the arguments to an argument list */
5326         if ((ptr = cp = strdup(args)) == NULL)
5327                 err(1, "spawn_insert: strdup");
5328         while ((arg = strsep(&ptr, " \t")) != NULL) {
5329                 /* empty field; skip it */
5330                 if (*arg == '\0')
5331                         continue;
5332
5333                 sp->argc++;
5334                 if ((sp->argv = realloc(sp->argv, sp->argc *
5335                     sizeof *sp->argv)) == NULL)
5336                         err(1, "spawn_insert: realloc");
5337                 if ((sp->argv[sp->argc - 1] = strdup(arg)) == NULL)
5338                         err(1, "spawn_insert: strdup");
5339         }
5340         free(cp);
5341
5342         TAILQ_INSERT_TAIL(&spawns, sp, entry);
5343         DNPRINTF(SWM_D_SPAWN, "spawn_insert: leave\n");
5344 }
5345
5346 void
5347 spawn_remove(struct spawn_prog *sp)
5348 {
5349         int                     i;
5350
5351         DNPRINTF(SWM_D_SPAWN, "spawn_remove: %s\n", sp->name);
5352
5353         TAILQ_REMOVE(&spawns, sp, entry);
5354         for (i = 0; i < sp->argc; i++)
5355                 free(sp->argv[i]);
5356         free(sp->argv);
5357         free(sp->name);
5358         free(sp);
5359
5360         DNPRINTF(SWM_D_SPAWN, "spawn_remove: leave\n");
5361 }
5362
5363 void
5364 spawn_replace(struct spawn_prog *sp, char *name, char *args)
5365 {
5366         DNPRINTF(SWM_D_SPAWN, "spawn_replace: %s [%s]\n", sp->name, name);
5367
5368         spawn_remove(sp);
5369         spawn_insert(name, args);
5370
5371         DNPRINTF(SWM_D_SPAWN, "spawn_replace: leave\n");
5372 }
5373
5374 void
5375 setspawn(char *name, char *args)
5376 {
5377         struct spawn_prog       *sp;
5378
5379         DNPRINTF(SWM_D_SPAWN, "setspawn: %s\n", name);
5380
5381         if (name == NULL)
5382                 return;
5383
5384         TAILQ_FOREACH(sp, &spawns, entry) {
5385                 if (!strcmp(sp->name, name)) {
5386                         if (*args == '\0')
5387                                 spawn_remove(sp);
5388                         else
5389                                 spawn_replace(sp, name, args);
5390                         DNPRINTF(SWM_D_SPAWN, "setspawn: leave\n");
5391                         return;
5392                 }
5393         }
5394         if (*args == '\0') {
5395                 warnx("error: setspawn: cannot find program: %s", name);
5396                 return;
5397         }
5398
5399         spawn_insert(name, args);
5400         DNPRINTF(SWM_D_SPAWN, "setspawn: leave\n");
5401 }
5402
5403 int
5404 setconfspawn(char *selector, char *value, int flags)
5405 {
5406         char *args;
5407
5408         /* suppress unused warning since var is needed */
5409         (void)flags;
5410
5411         args = expand_tilde(value);
5412
5413         DNPRINTF(SWM_D_SPAWN, "setconfspawn: [%s] [%s]\n", selector, args);
5414
5415         setspawn(selector, args);
5416         free(args);
5417
5418         DNPRINTF(SWM_D_SPAWN, "setconfspawn: done.\n");
5419         return (0);
5420 }
5421
5422 void
5423 setup_spawn(void)
5424 {
5425         setconfspawn("term",            "xterm",                0);
5426         setconfspawn("spawn_term",      "xterm",                0);
5427         setconfspawn("screenshot_all",  "screenshot.sh full",   0);
5428         setconfspawn("screenshot_wind", "screenshot.sh window", 0);
5429         setconfspawn("lock",            "xlock",                0);
5430         setconfspawn("initscr",         "initscreen.sh",        0);
5431         setconfspawn("menu",            "dmenu_run"
5432                                         " -fn $bar_font"
5433                                         " -nb $bar_color"
5434                                         " -nf $bar_font_color"
5435                                         " -sb $bar_border"
5436                                         " -sf $bar_color",      0);
5437         setconfspawn("search",          "dmenu"
5438                                         " -i"
5439                                         " -fn $bar_font"
5440                                         " -nb $bar_color"
5441                                         " -nf $bar_font_color"
5442                                         " -sb $bar_border"
5443                                         " -sf $bar_color",      0);
5444         setconfspawn("name_workspace",  "dmenu"
5445                                         " -p Workspace"
5446                                         " -fn $bar_font"
5447                                         " -nb $bar_color"
5448                                         " -nf $bar_font_color"
5449                                         " -sb $bar_border"
5450                                         " -sf $bar_color",      0);
5451 }
5452
5453 /* key bindings */
5454 #define SWM_MODNAME_SIZE        32
5455 #define SWM_KEY_WS              "\n+ \t"
5456 int
5457 parsekeys(char *keystr, unsigned int currmod, unsigned int *mod, KeySym *ks)
5458 {
5459         char                    *cp, *name;
5460         KeySym                  uks;
5461         DNPRINTF(SWM_D_KEY, "parsekeys: enter [%s]\n", keystr);
5462         if (mod == NULL || ks == NULL) {
5463                 DNPRINTF(SWM_D_KEY, "parsekeys: no mod or key vars\n");
5464                 return (1);
5465         }
5466         if (keystr == NULL || strlen(keystr) == 0) {
5467                 DNPRINTF(SWM_D_KEY, "parsekeys: no keystr\n");
5468                 return (1);
5469         }
5470         cp = keystr;
5471         *ks = XCB_NO_SYMBOL;
5472         *mod = 0;
5473         while ((name = strsep(&cp, SWM_KEY_WS)) != NULL) {
5474                 DNPRINTF(SWM_D_KEY, "parsekeys: key [%s]\n", name);
5475                 if (cp)
5476                         cp += (long)strspn(cp, SWM_KEY_WS);
5477                 if (strncasecmp(name, "MOD", SWM_MODNAME_SIZE) == 0)
5478                         *mod |= currmod;
5479                 else if (!strncasecmp(name, "Mod1", SWM_MODNAME_SIZE))
5480                         *mod |= XCB_MOD_MASK_1;
5481                 else if (!strncasecmp(name, "Mod2", SWM_MODNAME_SIZE))
5482                         *mod += XCB_MOD_MASK_2;
5483                 else if (!strncmp(name, "Mod3", SWM_MODNAME_SIZE))
5484                         *mod |= XCB_MOD_MASK_3;
5485                 else if (!strncmp(name, "Mod4", SWM_MODNAME_SIZE))
5486                         *mod |= XCB_MOD_MASK_4;
5487                 else if (strncasecmp(name, "SHIFT", SWM_MODNAME_SIZE) == 0)
5488                         *mod |= XCB_MOD_MASK_SHIFT;
5489                 else if (strncasecmp(name, "CONTROL", SWM_MODNAME_SIZE) == 0)
5490                         *mod |= XCB_MOD_MASK_CONTROL;
5491                 else {
5492                         *ks = XStringToKeysym(name);
5493                         XConvertCase(*ks, ks, &uks);
5494                         if (ks == XCB_NO_SYMBOL) {
5495                                 DNPRINTF(SWM_D_KEY,
5496                                     "parsekeys: invalid key %s\n",
5497                                     name);
5498                                 return (1);
5499                         }
5500                 }
5501         }
5502         DNPRINTF(SWM_D_KEY, "parsekeys: leave ok\n");
5503         return (0);
5504 }
5505
5506 char *
5507 strdupsafe(char *str)
5508 {
5509         if (str == NULL)
5510                 return (NULL);
5511         else
5512                 return (strdup(str));
5513 }
5514
5515 void
5516 key_insert(unsigned int mod, KeySym ks, enum keyfuncid kfid, char *spawn_name)
5517 {
5518         struct key              *kp;
5519
5520         DNPRINTF(SWM_D_KEY, "key_insert: enter %s [%s]\n",
5521             keyfuncs[kfid].name, spawn_name);
5522
5523         if ((kp = malloc(sizeof *kp)) == NULL)
5524                 err(1, "key_insert: malloc");
5525
5526         kp->mod = mod;
5527         kp->keysym = ks;
5528         kp->funcid = kfid;
5529         kp->spawn_name = strdupsafe(spawn_name);
5530         RB_INSERT(key_tree, &keys, kp);
5531
5532         DNPRINTF(SWM_D_KEY, "key_insert: leave\n");
5533 }
5534
5535 struct key *
5536 key_lookup(unsigned int mod, KeySym ks)
5537 {
5538         struct key              kp;
5539
5540         kp.keysym = ks;
5541         kp.mod = mod;
5542
5543         return (RB_FIND(key_tree, &keys, &kp));
5544 }
5545
5546 void
5547 key_remove(struct key *kp)
5548 {
5549         DNPRINTF(SWM_D_KEY, "key_remove: %s\n", keyfuncs[kp->funcid].name);
5550
5551         RB_REMOVE(key_tree, &keys, kp);
5552         free(kp->spawn_name);
5553         free(kp);
5554
5555         DNPRINTF(SWM_D_KEY, "key_remove: leave\n");
5556 }
5557
5558 void
5559 key_replace(struct key *kp, unsigned int mod, KeySym ks, enum keyfuncid kfid,
5560     char *spawn_name)
5561 {
5562         DNPRINTF(SWM_D_KEY, "key_replace: %s [%s]\n", keyfuncs[kp->funcid].name,
5563             spawn_name);
5564
5565         key_remove(kp);
5566         key_insert(mod, ks, kfid, spawn_name);
5567
5568         DNPRINTF(SWM_D_KEY, "key_replace: leave\n");
5569 }
5570
5571 void
5572 setkeybinding(unsigned int mod, KeySym ks, enum keyfuncid kfid,
5573     char *spawn_name)
5574 {
5575         struct key              *kp;
5576
5577         DNPRINTF(SWM_D_KEY, "setkeybinding: enter %s [%s]\n",
5578             keyfuncs[kfid].name, spawn_name);
5579
5580         if ((kp = key_lookup(mod, ks)) != NULL) {
5581                 if (kfid == KF_INVALID)
5582                         key_remove(kp);
5583                 else
5584                         key_replace(kp, mod, ks, kfid, spawn_name);
5585                 DNPRINTF(SWM_D_KEY, "setkeybinding: leave\n");
5586                 return;
5587         }
5588         if (kfid == KF_INVALID) {
5589                 warnx("error: setkeybinding: cannot find mod/key combination");
5590                 DNPRINTF(SWM_D_KEY, "setkeybinding: leave\n");
5591                 return;
5592         }
5593
5594         key_insert(mod, ks, kfid, spawn_name);
5595         DNPRINTF(SWM_D_KEY, "setkeybinding: leave\n");
5596 }
5597
5598 int
5599 setconfbinding(char *selector, char *value, int flags)
5600 {
5601         enum keyfuncid          kfid;
5602         unsigned int            mod;
5603         KeySym                  ks;
5604         struct spawn_prog       *sp;
5605
5606         /* suppress unused warning since var is needed */
5607         (void)flags;
5608
5609         DNPRINTF(SWM_D_KEY, "setconfbinding: enter\n");
5610         if (selector == NULL) {
5611                 DNPRINTF(SWM_D_KEY, "setconfbinding: unbind %s\n", value);
5612                 if (parsekeys(value, mod_key, &mod, &ks) == 0) {
5613                         kfid = KF_INVALID;
5614                         setkeybinding(mod, ks, kfid, NULL);
5615                         return (0);
5616                 } else
5617                         return (1);
5618         }
5619         /* search by key function name */
5620         for (kfid = 0; kfid < KF_INVALID; (kfid)++) {
5621                 if (strncasecmp(selector, keyfuncs[kfid].name,
5622                     SWM_FUNCNAME_LEN) == 0) {
5623                         DNPRINTF(SWM_D_KEY, "setconfbinding: %s: match\n",
5624                             selector);
5625                         if (parsekeys(value, mod_key, &mod, &ks) == 0) {
5626                                 setkeybinding(mod, ks, kfid, NULL);
5627                                 return (0);
5628                         } else
5629                                 return (1);
5630                 }
5631         }
5632         /* search by custom spawn name */
5633         TAILQ_FOREACH(sp, &spawns, entry) {
5634                 if (strcasecmp(selector, sp->name) == 0) {
5635                         DNPRINTF(SWM_D_KEY, "setconfbinding: %s: match\n",
5636                             selector);
5637                         if (parsekeys(value, mod_key, &mod, &ks) == 0) {
5638                                 setkeybinding(mod, ks, KF_SPAWN_CUSTOM,
5639                                     sp->name);
5640                                 return (0);
5641                         } else
5642                                 return (1);
5643                 }
5644         }
5645         DNPRINTF(SWM_D_KEY, "setconfbinding: no match\n");
5646         return (1);
5647 }
5648
5649 void
5650 setup_keys(void)
5651 {
5652 #define MODKEY_SHIFT    MODKEY | XCB_MOD_MASK_SHIFT
5653         setkeybinding(MODKEY,           XK_space,       KF_CYCLE_LAYOUT,NULL);
5654         setkeybinding(MODKEY_SHIFT,     XK_backslash,   KF_FLIP_LAYOUT, NULL);
5655         setkeybinding(MODKEY_SHIFT,     XK_space,       KF_STACK_RESET, NULL);
5656         setkeybinding(MODKEY,           XK_h,           KF_MASTER_SHRINK, NULL);
5657         setkeybinding(MODKEY,           XK_l,           KF_MASTER_GROW, NULL);
5658         setkeybinding(MODKEY,           XK_comma,       KF_MASTER_ADD,  NULL);
5659         setkeybinding(MODKEY,           XK_period,      KF_MASTER_DEL,  NULL);
5660         setkeybinding(MODKEY_SHIFT,     XK_comma,       KF_STACK_INC,   NULL);
5661         setkeybinding(MODKEY_SHIFT,     XK_period,      KF_STACK_DEC,   NULL);
5662         setkeybinding(MODKEY,           XK_Return,      KF_SWAP_MAIN,   NULL);
5663         setkeybinding(MODKEY,           XK_j,           KF_FOCUS_NEXT,  NULL);
5664         setkeybinding(MODKEY,           XK_k,           KF_FOCUS_PREV,  NULL);
5665         setkeybinding(MODKEY_SHIFT,     XK_j,           KF_SWAP_NEXT,   NULL);
5666         setkeybinding(MODKEY_SHIFT,     XK_k,           KF_SWAP_PREV,   NULL);
5667         setkeybinding(MODKEY_SHIFT,     XK_Return,      KF_SPAWN_CUSTOM,"term");
5668         setkeybinding(MODKEY,           XK_p,           KF_SPAWN_CUSTOM,"menu");
5669         setkeybinding(MODKEY_SHIFT,     XK_q,           KF_QUIT,        NULL);
5670         setkeybinding(MODKEY,           XK_q,           KF_RESTART,     NULL);
5671         setkeybinding(MODKEY,           XK_m,           KF_FOCUS_MAIN,  NULL);
5672         setkeybinding(MODKEY,           XK_1,           KF_WS_1,        NULL);
5673         setkeybinding(MODKEY,           XK_2,           KF_WS_2,        NULL);
5674         setkeybinding(MODKEY,           XK_3,           KF_WS_3,        NULL);
5675         setkeybinding(MODKEY,           XK_4,           KF_WS_4,        NULL);
5676         setkeybinding(MODKEY,           XK_5,           KF_WS_5,        NULL);
5677         setkeybinding(MODKEY,           XK_6,           KF_WS_6,        NULL);
5678         setkeybinding(MODKEY,           XK_7,           KF_WS_7,        NULL);
5679         setkeybinding(MODKEY,           XK_8,           KF_WS_8,        NULL);
5680         setkeybinding(MODKEY,           XK_9,           KF_WS_9,        NULL);
5681         setkeybinding(MODKEY,           XK_0,           KF_WS_10,       NULL);
5682         setkeybinding(MODKEY,           XK_F1,          KF_WS_11,       NULL);
5683         setkeybinding(MODKEY,           XK_F2,          KF_WS_12,       NULL);
5684         setkeybinding(MODKEY,           XK_F3,          KF_WS_13,       NULL);
5685         setkeybinding(MODKEY,           XK_F4,          KF_WS_14,       NULL);
5686         setkeybinding(MODKEY,           XK_F5,          KF_WS_15,       NULL);
5687         setkeybinding(MODKEY,           XK_F6,          KF_WS_16,       NULL);
5688         setkeybinding(MODKEY,           XK_F7,          KF_WS_17,       NULL);
5689         setkeybinding(MODKEY,           XK_F8,          KF_WS_18,       NULL);
5690         setkeybinding(MODKEY,           XK_F9,          KF_WS_19,       NULL);
5691         setkeybinding(MODKEY,           XK_F10,         KF_WS_20,       NULL);
5692         setkeybinding(MODKEY,           XK_F11,         KF_WS_21,       NULL);
5693         setkeybinding(MODKEY,           XK_F12,         KF_WS_22,       NULL);
5694         setkeybinding(MODKEY,           XK_Right,       KF_WS_NEXT,     NULL);
5695         setkeybinding(MODKEY,           XK_Left,        KF_WS_PREV,     NULL);
5696         setkeybinding(MODKEY,           XK_Up,          KF_WS_NEXT_ALL, NULL);
5697         setkeybinding(MODKEY,           XK_Down,        KF_WS_PREV_ALL, NULL);
5698         setkeybinding(MODKEY,           XK_a,           KF_WS_PRIOR,    NULL);
5699         setkeybinding(MODKEY_SHIFT,     XK_Right,       KF_SCREEN_NEXT, NULL);
5700         setkeybinding(MODKEY_SHIFT,     XK_Left,        KF_SCREEN_PREV, NULL);
5701         setkeybinding(MODKEY_SHIFT,     XK_1,           KF_MVWS_1,      NULL);
5702         setkeybinding(MODKEY_SHIFT,     XK_2,           KF_MVWS_2,      NULL);
5703         setkeybinding(MODKEY_SHIFT,     XK_3,           KF_MVWS_3,      NULL);
5704         setkeybinding(MODKEY_SHIFT,     XK_4,           KF_MVWS_4,      NULL);
5705         setkeybinding(MODKEY_SHIFT,     XK_5,           KF_MVWS_5,      NULL);
5706         setkeybinding(MODKEY_SHIFT,     XK_6,           KF_MVWS_6,      NULL);
5707         setkeybinding(MODKEY_SHIFT,     XK_7,           KF_MVWS_7,      NULL);
5708         setkeybinding(MODKEY_SHIFT,     XK_8,           KF_MVWS_8,      NULL);
5709         setkeybinding(MODKEY_SHIFT,     XK_9,           KF_MVWS_9,      NULL);
5710         setkeybinding(MODKEY_SHIFT,     XK_0,           KF_MVWS_10,     NULL);
5711         setkeybinding(MODKEY_SHIFT,     XK_F1,          KF_MVWS_11,     NULL);
5712         setkeybinding(MODKEY_SHIFT,     XK_F2,          KF_MVWS_12,     NULL);
5713         setkeybinding(MODKEY_SHIFT,     XK_F3,          KF_MVWS_13,     NULL);
5714         setkeybinding(MODKEY_SHIFT,     XK_F4,          KF_MVWS_14,     NULL);
5715         setkeybinding(MODKEY_SHIFT,     XK_F5,          KF_MVWS_15,     NULL);
5716         setkeybinding(MODKEY_SHIFT,     XK_F6,          KF_MVWS_16,     NULL);
5717         setkeybinding(MODKEY_SHIFT,     XK_F7,          KF_MVWS_17,     NULL);
5718         setkeybinding(MODKEY_SHIFT,     XK_F8,          KF_MVWS_18,     NULL);
5719         setkeybinding(MODKEY_SHIFT,     XK_F9,          KF_MVWS_19,     NULL);
5720         setkeybinding(MODKEY_SHIFT,     XK_F10,         KF_MVWS_20,     NULL);
5721         setkeybinding(MODKEY_SHIFT,     XK_F11,         KF_MVWS_21,     NULL);
5722         setkeybinding(MODKEY_SHIFT,     XK_F12,         KF_MVWS_22,     NULL);
5723         setkeybinding(MODKEY,           XK_b,           KF_BAR_TOGGLE,  NULL);
5724         setkeybinding(MODKEY,           XK_Tab,         KF_FOCUS_NEXT,  NULL);
5725         setkeybinding(MODKEY_SHIFT,     XK_Tab,         KF_FOCUS_PREV,  NULL);
5726         setkeybinding(MODKEY_SHIFT,     XK_x,           KF_WIND_KILL,   NULL);
5727         setkeybinding(MODKEY,           XK_x,           KF_WIND_DEL,    NULL);
5728         setkeybinding(MODKEY,           XK_s,           KF_SPAWN_CUSTOM,"screenshot_all");
5729         setkeybinding(MODKEY_SHIFT,     XK_s,           KF_SPAWN_CUSTOM,"screenshot_wind");
5730         setkeybinding(MODKEY,           XK_t,           KF_FLOAT_TOGGLE,NULL);
5731         setkeybinding(MODKEY_SHIFT,     XK_v,           KF_VERSION,     NULL);
5732         setkeybinding(MODKEY_SHIFT,     XK_Delete,      KF_SPAWN_CUSTOM,"lock");
5733         setkeybinding(MODKEY_SHIFT,     XK_i,           KF_SPAWN_CUSTOM,"initscr");
5734         setkeybinding(MODKEY,           XK_w,           KF_ICONIFY,     NULL);
5735         setkeybinding(MODKEY_SHIFT,     XK_w,           KF_UNICONIFY,   NULL);
5736         setkeybinding(MODKEY_SHIFT,     XK_r,           KF_RAISE_TOGGLE,NULL);
5737         setkeybinding(MODKEY,           XK_v,           KF_BUTTON2,     NULL);
5738         setkeybinding(MODKEY,           XK_equal,       KF_WIDTH_GROW,  NULL);
5739         setkeybinding(MODKEY,           XK_minus,       KF_WIDTH_SHRINK,NULL);
5740         setkeybinding(MODKEY_SHIFT,     XK_equal,       KF_HEIGHT_GROW,NULL);
5741         setkeybinding(MODKEY_SHIFT,     XK_minus,       KF_HEIGHT_SHRINK,NULL);
5742         setkeybinding(MODKEY,           XK_bracketleft, KF_MOVE_LEFT,NULL);
5743         setkeybinding(MODKEY,           XK_bracketright,KF_MOVE_RIGHT,NULL);
5744         setkeybinding(MODKEY_SHIFT,     XK_bracketleft, KF_MOVE_UP,     NULL);
5745         setkeybinding(MODKEY_SHIFT,     XK_bracketright,KF_MOVE_DOWN,NULL);
5746         setkeybinding(MODKEY_SHIFT,     XK_slash,       KF_NAME_WORKSPACE,NULL);
5747         setkeybinding(MODKEY,           XK_slash,       KF_SEARCH_WORKSPACE,NULL);
5748         setkeybinding(MODKEY,           XK_f,           KF_SEARCH_WIN,  NULL);
5749 #ifdef SWM_DEBUG
5750         setkeybinding(MODKEY_SHIFT,     XK_d,           KF_DUMPWINS,    NULL);
5751 #endif
5752 #undef MODKEY_SHIFT
5753 }
5754
5755 void
5756 clear_keys(void)
5757 {
5758         struct key              *kp;
5759
5760         while (RB_EMPTY(&keys) == 0) {
5761                 kp = RB_ROOT(&keys);
5762                 key_remove(kp);
5763         }
5764 }
5765
5766 int
5767 setkeymapping(char *selector, char *value, int flags)
5768 {
5769         char                    keymapping_file[PATH_MAX];
5770
5771         /* suppress unused warnings since vars are needed */
5772         (void)selector;
5773         (void)flags;
5774
5775         DNPRINTF(SWM_D_KEY, "setkeymapping: enter\n");
5776         if (value[0] == '~')
5777                 snprintf(keymapping_file, sizeof keymapping_file, "%s/%s",
5778                     pwd->pw_dir, &value[1]);
5779         else
5780                 strlcpy(keymapping_file, value, sizeof keymapping_file);
5781         clear_keys();
5782         /* load new key bindings; if it fails, revert to default bindings */
5783         if (conf_load(keymapping_file, SWM_CONF_KEYMAPPING)) {
5784                 clear_keys();
5785                 setup_keys();
5786         }
5787         DNPRINTF(SWM_D_KEY, "setkeymapping: leave\n");
5788         return (0);
5789 }
5790
5791 void
5792 updatenumlockmask(void)
5793 {
5794         unsigned int                            i, j;
5795         xcb_get_modifier_mapping_reply_t        *modmap_r;
5796         xcb_keycode_t                           *modmap, kc, *keycode;
5797
5798         numlockmask = 0;
5799
5800         modmap_r = xcb_get_modifier_mapping_reply(conn,
5801             xcb_get_modifier_mapping(conn),
5802             NULL);
5803         if (modmap_r) {
5804                 modmap = xcb_get_modifier_mapping_keycodes(modmap_r);
5805                 for (i = 0; i < 8; i++) {
5806                         for (j = 0; j < modmap_r->keycodes_per_modifier; j++) {
5807                                 kc = modmap[i * modmap_r->keycodes_per_modifier
5808                                     + j];
5809                                 keycode = xcb_key_symbols_get_keycode(syms,
5810                                                 XK_Num_Lock);
5811                                 if (kc == *keycode)
5812                                         numlockmask = (1 << i);
5813                                 free(keycode);
5814                         }
5815                 }
5816                 free(modmap_r);
5817         }
5818         DNPRINTF(SWM_D_MISC, "updatenumlockmask: %d\n", numlockmask);
5819 }
5820
5821 void
5822 grabkeys(void)
5823 {
5824         struct key              *kp;
5825         int                     num_screens, k, j;
5826         unsigned int            modifiers[3];
5827         xcb_keycode_t           *code;
5828
5829         DNPRINTF(SWM_D_MISC, "grabkeys\n");
5830         updatenumlockmask();
5831
5832         modifiers[0] = 0;
5833         modifiers[1] = numlockmask;
5834         modifiers[2] = numlockmask | XCB_MOD_MASK_LOCK;
5835
5836         num_screens = xcb_setup_roots_length(xcb_get_setup(conn));
5837         for (k = 0; k < num_screens; k++) {
5838                 if (TAILQ_EMPTY(&screens[k].rl))
5839                         continue;
5840                 xcb_ungrab_key(conn, XCB_GRAB_ANY, screens[k].root,
5841                         XCB_MOD_MASK_ANY);
5842                 RB_FOREACH(kp, key_tree, &keys) {
5843                         if ((code = xcb_key_symbols_get_keycode(syms,
5844                                         kp->keysym))) {
5845                                 for (j = 0; j < LENGTH(modifiers); j++)
5846                                         xcb_grab_key(conn, 1,
5847                                             screens[k].root,
5848                                             kp->mod | modifiers[j],
5849                                             *code, XCB_GRAB_MODE_SYNC,
5850                                             XCB_GRAB_MODE_ASYNC);
5851                                 free(code);
5852                         }
5853                 }
5854         }
5855 }
5856
5857 void
5858 grabbuttons(struct ws_win *win)
5859 {
5860         int             i;
5861
5862         DNPRINTF(SWM_D_MOUSE, "grabbuttons: win 0x%x\n", win->id);
5863
5864         for (i = 0; i < LENGTH(buttons); i++)
5865                 if (buttons[i].action == client_click)
5866                         xcb_grab_button(conn, 0, win->id, BUTTONMASK,
5867                             XCB_GRAB_MODE_SYNC, XCB_GRAB_MODE_ASYNC,
5868                             XCB_WINDOW_NONE, XCB_CURSOR_NONE,
5869                             buttons[i].button, buttons[i].mask);
5870
5871         /* click to focus */
5872         xcb_grab_button(conn, 0, win->id, BUTTONMASK, XCB_GRAB_MODE_SYNC,
5873             XCB_GRAB_MODE_ASYNC, XCB_WINDOW_NONE, XCB_CURSOR_NONE,
5874             XCB_BUTTON_INDEX_1, XCB_BUTTON_MASK_ANY);
5875 }
5876
5877 const char *quirkname[] = {
5878         "NONE",         /* config string for "no value" */
5879         "FLOAT",
5880         "TRANSSZ",
5881         "ANYWHERE",
5882         "XTERM_FONTADJ",
5883         "FULLSCREEN",
5884         "FOCUSPREV",
5885 };
5886
5887 /* SWM_Q_WS: retain '|' for back compat for now (2009-08-11) */
5888 #define SWM_Q_WS                "\n|+ \t"
5889 int
5890 parsequirks(char *qstr, unsigned long *quirk)
5891 {
5892         char                    *cp, *name;
5893         int                     i;
5894
5895         if (quirk == NULL)
5896                 return (1);
5897
5898         cp = qstr;
5899         *quirk = 0;
5900         while ((name = strsep(&cp, SWM_Q_WS)) != NULL) {
5901                 if (cp)
5902                         cp += (long)strspn(cp, SWM_Q_WS);
5903                 for (i = 0; i < LENGTH(quirkname); i++) {
5904                         if (!strncasecmp(name, quirkname[i], SWM_QUIRK_LEN)) {
5905                                 DNPRINTF(SWM_D_QUIRK,
5906                                     "parsequirks: %s\n", name);
5907                                 if (i == 0) {
5908                                         *quirk = 0;
5909                                         return (0);
5910                                 }
5911                                 *quirk |= 1 << (i-1);
5912                                 break;
5913                         }
5914                 }
5915                 if (i >= LENGTH(quirkname)) {
5916                         DNPRINTF(SWM_D_QUIRK,
5917                             "parsequirks: invalid quirk [%s]\n", name);
5918                         return (1);
5919                 }
5920         }
5921         return (0);
5922 }
5923
5924 void
5925 quirk_insert(const char *class, const char *name, unsigned long quirk)
5926 {
5927         struct quirk            *qp;
5928
5929         DNPRINTF(SWM_D_QUIRK, "quirk_insert: %s:%s [%lu]\n", class, name,
5930             quirk);
5931
5932         if ((qp = malloc(sizeof *qp)) == NULL)
5933                 err(1, "quirk_insert: malloc");
5934         if ((qp->class = strdup(class)) == NULL)
5935                 err(1, "quirk_insert: strdup");
5936         if ((qp->name = strdup(name)) == NULL)
5937                 err(1, "quirk_insert: strdup");
5938
5939         qp->quirk = quirk;
5940         TAILQ_INSERT_TAIL(&quirks, qp, entry);
5941
5942         DNPRINTF(SWM_D_QUIRK, "quirk_insert: leave\n");
5943 }
5944
5945 void
5946 quirk_remove(struct quirk *qp)
5947 {
5948         DNPRINTF(SWM_D_QUIRK, "quirk_remove: %s:%s [%lu]\n", qp->class,
5949             qp->name, qp->quirk);
5950
5951         TAILQ_REMOVE(&quirks, qp, entry);
5952         free(qp->class);
5953         free(qp->name);
5954         free(qp);
5955
5956         DNPRINTF(SWM_D_QUIRK, "quirk_remove: leave\n");
5957 }
5958
5959 void
5960 quirk_replace(struct quirk *qp, const char *class, const char *name,
5961     unsigned long quirk)
5962 {
5963         DNPRINTF(SWM_D_QUIRK, "quirk_replace: %s:%s [%lu]\n", qp->class,
5964             qp->name, qp->quirk);
5965
5966         quirk_remove(qp);
5967         quirk_insert(class, name, quirk);
5968
5969         DNPRINTF(SWM_D_QUIRK, "quirk_replace: leave\n");
5970 }
5971
5972 void
5973 setquirk(const char *class, const char *name, unsigned long quirk)
5974 {
5975         struct quirk            *qp;
5976
5977         DNPRINTF(SWM_D_QUIRK, "setquirk: enter %s:%s [%lu]\n", class, name,
5978            quirk);
5979
5980         TAILQ_FOREACH(qp, &quirks, entry) {
5981                 if (!strcmp(qp->class, class) && !strcmp(qp->name, name)) {
5982                         if (!quirk)
5983                                 quirk_remove(qp);
5984                         else
5985                                 quirk_replace(qp, class, name, quirk);
5986                         DNPRINTF(SWM_D_QUIRK, "setquirk: leave\n");
5987                         return;
5988                 }
5989         }
5990         if (!quirk) {
5991                 warnx("error: setquirk: cannot find class/name combination");
5992                 return;
5993         }
5994
5995         quirk_insert(class, name, quirk);
5996         DNPRINTF(SWM_D_QUIRK, "setquirk: leave\n");
5997 }
5998
5999 int
6000 setconfquirk(char *selector, char *value, int flags)
6001 {
6002         char                    *cp, *class, *name;
6003         int                     retval;
6004         unsigned long           qrks;
6005
6006         /* suppress unused warning since var is needed */
6007         (void)flags;
6008
6009         if (selector == NULL)
6010                 return (0);
6011         if ((cp = strchr(selector, ':')) == NULL)
6012                 return (0);
6013         *cp = '\0';
6014         class = selector;
6015         name = cp + 1;
6016         if ((retval = parsequirks(value, &qrks)) == 0)
6017                 setquirk(class, name, qrks);
6018         return (retval);
6019 }
6020
6021 void
6022 setup_quirks(void)
6023 {
6024         setquirk("MPlayer",             "xv",           SWM_Q_FLOAT | SWM_Q_FULLSCREEN | SWM_Q_FOCUSPREV);
6025         setquirk("OpenOffice.org 3.2",  "VCLSalFrame",  SWM_Q_FLOAT);
6026         setquirk("Firefox-bin",         "firefox-bin",  SWM_Q_TRANSSZ);
6027         setquirk("Firefox",             "Dialog",       SWM_Q_FLOAT);
6028         setquirk("Gimp",                "gimp",         SWM_Q_FLOAT | SWM_Q_ANYWHERE);
6029         setquirk("XTerm",               "xterm",        SWM_Q_XTERM_FONTADJ);
6030         setquirk("xine",                "Xine Window",  SWM_Q_FLOAT | SWM_Q_ANYWHERE);
6031         setquirk("Xitk",                "Xitk Combo",   SWM_Q_FLOAT | SWM_Q_ANYWHERE);
6032         setquirk("xine",                "xine Panel",   SWM_Q_FLOAT | SWM_Q_ANYWHERE);
6033         setquirk("Xitk",                "Xine Window",  SWM_Q_FLOAT | SWM_Q_ANYWHERE);
6034         setquirk("xine",                "xine Video Fullscreen Window", SWM_Q_FULLSCREEN | SWM_Q_FLOAT);
6035         setquirk("pcb",                 "pcb",          SWM_Q_FLOAT);
6036         setquirk("SDL_App",             "SDL_App",      SWM_Q_FLOAT | SWM_Q_FULLSCREEN);
6037 }
6038
6039 /* conf file stuff */
6040 #define SWM_CONF_FILE           "spectrwm.conf"
6041 #define SWM_CONF_FILE_OLD       "scrotwm.conf"
6042
6043 enum {
6044         SWM_S_BAR_ACTION,
6045         SWM_S_BAR_AT_BOTTOM,
6046         SWM_S_BAR_BORDER_WIDTH,
6047         SWM_S_BAR_DELAY,
6048         SWM_S_BAR_ENABLED,
6049         SWM_S_BAR_FONT,
6050         SWM_S_BAR_FORMAT,
6051         SWM_S_BAR_JUSTIFY,
6052         SWM_S_BORDER_WIDTH,
6053         SWM_S_CLOCK_ENABLED,
6054         SWM_S_CLOCK_FORMAT,
6055         SWM_S_CYCLE_EMPTY,
6056         SWM_S_CYCLE_VISIBLE,
6057         SWM_S_DIALOG_RATIO,
6058         SWM_S_DISABLE_BORDER,
6059         SWM_S_FOCUS_CLOSE,
6060         SWM_S_FOCUS_CLOSE_WRAP,
6061         SWM_S_FOCUS_DEFAULT,
6062         SWM_S_FOCUS_MODE,
6063         SWM_S_SPAWN_ORDER,
6064         SWM_S_SPAWN_TERM,
6065         SWM_S_SS_APP,
6066         SWM_S_SS_ENABLED,
6067         SWM_S_STACK_ENABLED,
6068         SWM_S_TERM_WIDTH,
6069         SWM_S_TITLE_CLASS_ENABLED,
6070         SWM_S_TITLE_NAME_ENABLED,
6071         SWM_S_URGENT_ENABLED,
6072         SWM_S_VERBOSE_LAYOUT,
6073         SWM_S_WINDOW_NAME_ENABLED,
6074         SWM_S_WORKSPACE_LIMIT
6075 };
6076
6077 int
6078 setconfvalue(char *selector, char *value, int flags)
6079 {
6080         int     i;
6081         char    *b;
6082
6083         /* suppress unused warning since var is needed */
6084         (void)selector;
6085
6086         switch (flags) {
6087         case SWM_S_BAR_ACTION:
6088                 free(bar_argv[0]);
6089                 if ((bar_argv[0] = expand_tilde(value)) == NULL)
6090                         err(1, "setconfvalue: bar_action");
6091                 break;
6092         case SWM_S_BAR_AT_BOTTOM:
6093                 bar_at_bottom = atoi(value);
6094                 break;
6095         case SWM_S_BAR_BORDER_WIDTH:
6096                 bar_border_width = atoi(value);
6097                 if (bar_border_width < 0)
6098                         bar_border_width = 0;
6099                 break;
6100         case SWM_S_BAR_DELAY:
6101                 bar_delay = atoi(value);
6102                 break;
6103         case SWM_S_BAR_ENABLED:
6104                 bar_enabled = atoi(value);
6105                 break;
6106         case SWM_S_BAR_FONT:
6107                 b = bar_fonts;
6108                 if (asprintf(&bar_fonts, "%s,%s", value, bar_fonts) == -1)
6109                         err(1, "setconfvalue: asprintf: failed to allocate "
6110                                 "memory for bar_fonts.");
6111                 free(b);
6112
6113                 /* If already in xft mode, then we are done. */
6114                 if (!bar_font_legacy)
6115                         break;
6116
6117                 /* If there are any non-XLFD entries, switch to Xft mode. */
6118                 while ((b = strsep(&value, ",")) != NULL) {
6119                         if (*b == '\0')
6120                                 continue;
6121                         if (!isxlfd(b)) {
6122                                 bar_font_legacy = 0;
6123                                 break;
6124                         }
6125                 }
6126                 break;
6127         case SWM_S_BAR_FORMAT:
6128                 free(bar_format);
6129                 if ((bar_format = strdup(value)) == NULL)
6130                         err(1, "setconfvalue: bar_format");
6131                 break;
6132         case SWM_S_BAR_JUSTIFY:
6133                 if (!strcmp(value, "left"))
6134                         bar_justify = SWM_BAR_JUSTIFY_LEFT;
6135                 else if (!strcmp(value, "center"))
6136                         bar_justify = SWM_BAR_JUSTIFY_CENTER;
6137                 else if (!strcmp(value, "right"))
6138                         bar_justify = SWM_BAR_JUSTIFY_RIGHT;
6139                 else
6140                         errx(1, "invalid bar_justify");
6141                 break;
6142         case SWM_S_BORDER_WIDTH:
6143                 border_width = atoi(value);
6144                 if (border_width < 0)
6145                         border_width = 0;
6146                 break;
6147         case SWM_S_CLOCK_ENABLED:
6148                 clock_enabled = atoi(value);
6149                 break;
6150         case SWM_S_CLOCK_FORMAT:
6151 #ifndef SWM_DENY_CLOCK_FORMAT
6152                 free(clock_format);
6153                 if ((clock_format = strdup(value)) == NULL)
6154                         err(1, "setconfvalue: clock_format");
6155 #endif
6156                 break;
6157         case SWM_S_CYCLE_EMPTY:
6158                 cycle_empty = atoi(value);
6159                 break;
6160         case SWM_S_CYCLE_VISIBLE:
6161                 cycle_visible = atoi(value);
6162                 break;
6163         case SWM_S_DIALOG_RATIO:
6164                 dialog_ratio = atof(value);
6165                 if (dialog_ratio > 1.0 || dialog_ratio <= .3)
6166                         dialog_ratio = .6;
6167                 break;
6168         case SWM_S_DISABLE_BORDER:
6169                 disable_border = atoi(value);
6170                 break;
6171         case SWM_S_FOCUS_CLOSE:
6172                 if (!strcmp(value, "first"))
6173                         focus_close = SWM_STACK_BOTTOM;
6174                 else if (!strcmp(value, "last"))
6175                         focus_close = SWM_STACK_TOP;
6176                 else if (!strcmp(value, "next"))
6177                         focus_close = SWM_STACK_ABOVE;
6178                 else if (!strcmp(value, "previous"))
6179                         focus_close = SWM_STACK_BELOW;
6180                 else
6181                         errx(1, "focus_close");
6182                 break;
6183         case SWM_S_FOCUS_CLOSE_WRAP:
6184                 focus_close_wrap = atoi(value);
6185                 break;
6186         case SWM_S_FOCUS_DEFAULT:
6187                 if (!strcmp(value, "last"))
6188                         focus_default = SWM_STACK_TOP;
6189                 else if (!strcmp(value, "first"))
6190                         focus_default = SWM_STACK_BOTTOM;
6191                 else
6192                         errx(1, "focus_default");
6193                 break;
6194         case SWM_S_FOCUS_MODE:
6195                 if (!strcmp(value, "default"))
6196                         focus_mode = SWM_FOCUS_DEFAULT;
6197                 else if (!strcmp(value, "follow_cursor"))
6198                         focus_mode = SWM_FOCUS_FOLLOW;
6199                 else if (!strcmp(value, "manual"))
6200                         focus_mode = SWM_FOCUS_MANUAL;
6201                 else
6202                         errx(1, "focus_mode");
6203                 break;
6204         case SWM_S_SPAWN_ORDER:
6205                 if (!strcmp(value, "first"))
6206                         spawn_position = SWM_STACK_BOTTOM;
6207                 else if (!strcmp(value, "last"))
6208                         spawn_position = SWM_STACK_TOP;
6209                 else if (!strcmp(value, "next"))
6210                         spawn_position = SWM_STACK_ABOVE;
6211                 else if (!strcmp(value, "previous"))
6212                         spawn_position = SWM_STACK_BELOW;
6213                 else
6214                         errx(1, "spawn_position");
6215                 break;
6216         case SWM_S_SPAWN_TERM:
6217                 setconfspawn("term", value, 0);
6218                 setconfspawn("spawn_term", value, 0);
6219                 break;
6220         case SWM_S_SS_APP:
6221                 break;
6222         case SWM_S_SS_ENABLED:
6223                 ss_enabled = atoi(value);
6224                 break;
6225         case SWM_S_STACK_ENABLED:
6226                 stack_enabled = atoi(value);
6227                 break;
6228         case SWM_S_TERM_WIDTH:
6229                 term_width = atoi(value);
6230                 if (term_width < 0)
6231                         term_width = 0;
6232                 break;
6233         case SWM_S_TITLE_CLASS_ENABLED:
6234                 title_class_enabled = atoi(value);
6235                 break;
6236         case SWM_S_TITLE_NAME_ENABLED:
6237                 title_name_enabled = atoi(value);
6238                 break;
6239         case SWM_S_URGENT_ENABLED:
6240                 urgent_enabled = atoi(value);
6241                 break;
6242         case SWM_S_VERBOSE_LAYOUT:
6243                 verbose_layout = atoi(value);
6244                 for (i = 0; layouts[i].l_stack != NULL; i++) {
6245                         if (verbose_layout)
6246                                 layouts[i].l_string = fancy_stacker;
6247                         else
6248                                 layouts[i].l_string = plain_stacker;
6249                 }
6250                 break;
6251         case SWM_S_WINDOW_NAME_ENABLED:
6252                 window_name_enabled = atoi(value);
6253                 break;
6254         case SWM_S_WORKSPACE_LIMIT:
6255                 workspace_limit = atoi(value);
6256                 if (workspace_limit > SWM_WS_MAX)
6257                         workspace_limit = SWM_WS_MAX;
6258                 else if (workspace_limit < 1)
6259                         workspace_limit = 1;
6260                 break;
6261         default:
6262                 return (1);
6263         }
6264         return (0);
6265 }
6266
6267 int
6268 setconfmodkey(char *selector, char *value, int flags)
6269 {
6270         /* suppress unused warnings since vars are needed */
6271         (void)selector;
6272         (void)flags;
6273
6274         if (!strncasecmp(value, "Mod1", strlen("Mod1")))
6275                 update_modkey(XCB_MOD_MASK_1);
6276         else if (!strncasecmp(value, "Mod2", strlen("Mod2")))
6277                 update_modkey(XCB_MOD_MASK_2);
6278         else if (!strncasecmp(value, "Mod3", strlen("Mod3")))
6279                 update_modkey(XCB_MOD_MASK_3);
6280         else if (!strncasecmp(value, "Mod4", strlen("Mod4")))
6281                 update_modkey(XCB_MOD_MASK_4);
6282         else
6283                 return (1);
6284         return (0);
6285 }
6286
6287 int
6288 setconfcolor(char *selector, char *value, int flags)
6289 {
6290         setscreencolor(value, ((selector == NULL)?-1:atoi(selector)), flags);
6291         return (0);
6292 }
6293
6294 int
6295 setconfregion(char *selector, char *value, int flags)
6296 {
6297         /* suppress unused warnings since vars are needed */
6298         (void)selector;
6299         (void)flags;
6300
6301         custom_region(value);
6302         return (0);
6303 }
6304
6305 int
6306 setautorun(char *selector, char *value, int flags)
6307 {
6308         int                     ws_id;
6309         char                    s[1024];
6310         char                    *ap, *sp = s;
6311         union arg               a;
6312         int                     argc = 0;
6313         pid_t                   pid;
6314         struct pid_e            *p;
6315
6316         /* suppress unused warnings since vars are needed */
6317         (void)selector;
6318         (void)flags;
6319
6320         if (getenv("SWM_STARTED"))
6321                 return (0);
6322
6323         bzero(s, sizeof s);
6324         if (sscanf(value, "ws[%d]:%1023c", &ws_id, s) != 2)
6325                 errx(1, "invalid autorun entry, should be 'ws[<idx>]:command'");
6326         ws_id--;
6327         if (ws_id < 0 || ws_id >= workspace_limit)
6328                 errx(1, "autorun: invalid workspace %d", ws_id + 1);
6329
6330         /*
6331          * This is a little intricate
6332          *
6333          * If the pid already exists we simply reuse it because it means it was
6334          * used before AND not claimed by manage_window.  We get away with
6335          * altering it in the parent after INSERT because this can not be a race
6336          */
6337         a.argv = NULL;
6338         while ((ap = strsep(&sp, " \t")) != NULL) {
6339                 if (*ap == '\0')
6340                         continue;
6341                 DNPRINTF(SWM_D_SPAWN, "setautorun: arg [%s]\n", ap);
6342                 argc++;
6343                 if ((a.argv = realloc(a.argv, argc * sizeof(char *))) == NULL)
6344                         err(1, "setautorun: realloc");
6345                 a.argv[argc - 1] = ap;
6346         }
6347
6348         if ((a.argv = realloc(a.argv, (argc + 1) * sizeof(char *))) == NULL)
6349                 err(1, "setautorun: realloc");
6350         a.argv[argc] = NULL;
6351
6352         if ((pid = fork()) == 0) {
6353                 spawn(ws_id, &a, 1);
6354                 /* NOTREACHED */
6355                 _exit(1);
6356         }
6357         free(a.argv);
6358
6359         /* parent */
6360         p = find_pid(pid);
6361         if (p == NULL) {
6362                 p = calloc(1, sizeof *p);
6363                 if (p == NULL)
6364                         return (1);
6365                 TAILQ_INSERT_TAIL(&pidlist, p, entry);
6366         }
6367
6368         p->pid = pid;
6369         p->ws = ws_id;
6370
6371         return (0);
6372 }
6373
6374 int
6375 setlayout(char *selector, char *value, int flags)
6376 {
6377         int                     ws_id, i, x, mg, ma, si, ar, f = 0;
6378         int                     st = SWM_V_STACK, num_screens;
6379         char                    s[1024];
6380         struct workspace        *ws;
6381
6382         /* suppress unused warnings since vars are needed */
6383         (void)selector;
6384         (void)flags;
6385
6386         if (getenv("SWM_STARTED"))
6387                 return (0);
6388
6389         bzero(s, sizeof s);
6390         if (sscanf(value, "ws[%d]:%d:%d:%d:%d:%1023c",
6391             &ws_id, &mg, &ma, &si, &ar, s) != 6)
6392                 errx(1, "invalid layout entry, should be 'ws[<idx>]:"
6393                     "<master_grow>:<master_add>:<stack_inc>:<always_raise>:"
6394                     "<type>'");
6395         ws_id--;
6396         if (ws_id < 0 || ws_id >= workspace_limit)
6397                 errx(1, "layout: invalid workspace %d", ws_id + 1);
6398
6399         if (!strcasecmp(s, "vertical"))
6400                 st = SWM_V_STACK;
6401         else if (!strcasecmp(s, "vertical_flip")) {
6402                 st = SWM_V_STACK;
6403                 f = 1;
6404         } else if (!strcasecmp(s, "horizontal"))
6405                 st = SWM_H_STACK;
6406         else if (!strcasecmp(s, "horizontal_flip")) {
6407                 st = SWM_H_STACK;
6408                 f = 1;
6409         } else if (!strcasecmp(s, "fullscreen"))
6410                 st = SWM_MAX_STACK;
6411         else
6412                 errx(1, "invalid layout entry, should be 'ws[<idx>]:"
6413                     "<master_grow>:<master_add>:<stack_inc>:<always_raise>:"
6414                     "<type>'");
6415
6416         num_screens = xcb_setup_roots_length(xcb_get_setup(conn));
6417         for (i = 0; i < num_screens; i++) {
6418                 ws = (struct workspace *)&screens[i].ws;
6419                 ws[ws_id].cur_layout = &layouts[st];
6420
6421                 ws[ws_id].always_raise = ar;
6422                 if (st == SWM_MAX_STACK)
6423                         continue;
6424
6425                 /* master grow */
6426                 for (x = 0; x < abs(mg); x++) {
6427                         ws[ws_id].cur_layout->l_config(&ws[ws_id],
6428                             mg >= 0 ?  SWM_ARG_ID_MASTERGROW :
6429                             SWM_ARG_ID_MASTERSHRINK);
6430                         stack();
6431                 }
6432                 /* master add */
6433                 for (x = 0; x < abs(ma); x++) {
6434                         ws[ws_id].cur_layout->l_config(&ws[ws_id],
6435                             ma >= 0 ?  SWM_ARG_ID_MASTERADD :
6436                             SWM_ARG_ID_MASTERDEL);
6437                         stack();
6438                 }
6439                 /* stack inc */
6440                 for (x = 0; x < abs(si); x++) {
6441                         ws[ws_id].cur_layout->l_config(&ws[ws_id],
6442                             si >= 0 ?  SWM_ARG_ID_STACKINC :
6443                             SWM_ARG_ID_STACKDEC);
6444                         stack();
6445                 }
6446                 /* Apply flip */
6447                 if (f) {
6448                         ws[ws_id].cur_layout->l_config(&ws[ws_id],
6449                             SWM_ARG_ID_FLIPLAYOUT);
6450                         stack();
6451                 }
6452         }
6453
6454         focus_flush();
6455
6456         return (0);
6457 }
6458
6459 /* config options */
6460 struct config_option {
6461         char                    *optname;
6462         int                     (*func)(char*, char*, int);
6463         int                     funcflags;
6464 };
6465 struct config_option configopt[] = {
6466         { "bar_enabled",                setconfvalue,   SWM_S_BAR_ENABLED },
6467         { "bar_at_bottom",              setconfvalue,   SWM_S_BAR_AT_BOTTOM },
6468         { "bar_border",                 setconfcolor,   SWM_S_COLOR_BAR_BORDER },
6469         { "bar_border_width",           setconfvalue,   SWM_S_BAR_BORDER_WIDTH },
6470         { "bar_color",                  setconfcolor,   SWM_S_COLOR_BAR },
6471         { "bar_font_color",             setconfcolor,   SWM_S_COLOR_BAR_FONT },
6472         { "bar_font",                   setconfvalue,   SWM_S_BAR_FONT },
6473         { "bar_action",                 setconfvalue,   SWM_S_BAR_ACTION },
6474         { "bar_delay",                  setconfvalue,   SWM_S_BAR_DELAY },
6475         { "bar_justify",                setconfvalue,   SWM_S_BAR_JUSTIFY },
6476         { "bar_format",                 setconfvalue,   SWM_S_BAR_FORMAT },
6477         { "keyboard_mapping",           setkeymapping,  0 },
6478         { "bind",                       setconfbinding, 0 },
6479         { "stack_enabled",              setconfvalue,   SWM_S_STACK_ENABLED },
6480         { "clock_enabled",              setconfvalue,   SWM_S_CLOCK_ENABLED },
6481         { "clock_format",               setconfvalue,   SWM_S_CLOCK_FORMAT },
6482         { "color_focus",                setconfcolor,   SWM_S_COLOR_FOCUS },
6483         { "color_unfocus",              setconfcolor,   SWM_S_COLOR_UNFOCUS },
6484         { "cycle_empty",                setconfvalue,   SWM_S_CYCLE_EMPTY },
6485         { "cycle_visible",              setconfvalue,   SWM_S_CYCLE_VISIBLE },
6486         { "workspace_limit",            setconfvalue,   SWM_S_WORKSPACE_LIMIT },
6487         { "dialog_ratio",               setconfvalue,   SWM_S_DIALOG_RATIO },
6488         { "verbose_layout",             setconfvalue,   SWM_S_VERBOSE_LAYOUT },
6489         { "modkey",                     setconfmodkey,  0 },
6490         { "program",                    setconfspawn,   0 },
6491         { "quirk",                      setconfquirk,   0 },
6492         { "region",                     setconfregion,  0 },
6493         { "spawn_term",                 setconfvalue,   SWM_S_SPAWN_TERM },
6494         { "screenshot_enabled",         setconfvalue,   SWM_S_SS_ENABLED },
6495         { "screenshot_app",             setconfvalue,   SWM_S_SS_APP },
6496         { "window_name_enabled",        setconfvalue,   SWM_S_WINDOW_NAME_ENABLED },
6497         { "urgent_enabled",             setconfvalue,   SWM_S_URGENT_ENABLED },
6498         { "term_width",                 setconfvalue,   SWM_S_TERM_WIDTH },
6499         { "title_class_enabled",        setconfvalue,   SWM_S_TITLE_CLASS_ENABLED },
6500         { "title_name_enabled",         setconfvalue,   SWM_S_TITLE_NAME_ENABLED },
6501         { "focus_mode",                 setconfvalue,   SWM_S_FOCUS_MODE },
6502         { "focus_close",                setconfvalue,   SWM_S_FOCUS_CLOSE },
6503         { "focus_close_wrap",           setconfvalue,   SWM_S_FOCUS_CLOSE_WRAP },
6504         { "focus_default",              setconfvalue,   SWM_S_FOCUS_DEFAULT },
6505         { "spawn_position",             setconfvalue,   SWM_S_SPAWN_ORDER },
6506         { "disable_border",             setconfvalue,   SWM_S_DISABLE_BORDER },
6507         { "border_width",               setconfvalue,   SWM_S_BORDER_WIDTH },
6508         { "autorun",                    setautorun,     0 },
6509         { "layout",                     setlayout,      0 },
6510 };
6511
6512
6513 int
6514 conf_load(char *filename, int keymapping)
6515 {
6516         FILE                    *config;
6517         char                    *line, *cp, *optsub, *optval;
6518         size_t                  linelen, lineno = 0;
6519         int                     wordlen, i, optidx;
6520         struct config_option    *opt;
6521
6522         DNPRINTF(SWM_D_CONF, "conf_load: begin\n");
6523
6524         if (filename == NULL) {
6525                 warnx("conf_load: no filename");
6526                 return (1);
6527         }
6528         if ((config = fopen(filename, "r")) == NULL) {
6529                 warn("conf_load: fopen: %s", filename);
6530                 return (1);
6531         }
6532
6533         while (!feof(config)) {
6534                 if ((line = fparseln(config, &linelen, &lineno, NULL, 0))
6535                     == NULL) {
6536                         if (ferror(config))
6537                                 err(1, "%s", filename);
6538                         else
6539                                 continue;
6540                 }
6541                 cp = line;
6542                 cp += strspn(cp, " \t\n"); /* eat whitespace */
6543                 if (cp[0] == '\0') {
6544                         /* empty line */
6545                         free(line);
6546                         continue;
6547                 }
6548                 /* get config option */
6549                 wordlen = strcspn(cp, "=[ \t\n");
6550                 if (wordlen == 0) {
6551                         warnx("%s: line %zd: no option found",
6552                             filename, lineno);
6553                         goto out;
6554                 }
6555                 optidx = -1;
6556                 for (i = 0; i < LENGTH(configopt); i++) {
6557                         opt = &configopt[i];
6558                         if (!strncasecmp(cp, opt->optname, wordlen) &&
6559                             (int)strlen(opt->optname) == wordlen) {
6560                                 optidx = i;
6561                                 break;
6562                         }
6563                 }
6564                 if (optidx == -1) {
6565                         warnx("%s: line %zd: unknown option %.*s",
6566                             filename, lineno, wordlen, cp);
6567                         goto out;
6568                 }
6569                 if (keymapping && strcmp(opt->optname, "bind")) {
6570                         warnx("%s: line %zd: invalid option %.*s",
6571                             filename, lineno, wordlen, cp);
6572                         goto out;
6573                 }
6574                 cp += wordlen;
6575                 cp += strspn(cp, " \t\n"); /* eat whitespace */
6576                 /* get [selector] if any */
6577                 optsub = NULL;
6578                 if (*cp == '[') {
6579                         cp++;
6580                         wordlen = strcspn(cp, "]");
6581                         if (*cp != ']') {
6582                                 if (wordlen == 0) {
6583                                         warnx("%s: line %zd: syntax error",
6584                                             filename, lineno);
6585                                         goto out;
6586                                 }
6587
6588                                 if (asprintf(&optsub, "%.*s", wordlen, cp) ==
6589                                     -1) {
6590                                         warnx("%s: line %zd: unable to allocate"
6591                                             "memory for selector", filename,
6592                                             lineno);
6593                                         goto out;
6594                                 }
6595                         }
6596                         cp += wordlen;
6597                         cp += strspn(cp, "] \t\n"); /* eat trailing */
6598                 }
6599                 cp += strspn(cp, "= \t\n"); /* eat trailing */
6600                 /* get RHS value */
6601                 optval = strdup(cp);
6602                 /* call function to deal with it all */
6603                 if (configopt[optidx].func(optsub, optval,
6604                     configopt[optidx].funcflags) != 0)
6605                         errx(1, "%s: line %zd: invalid data for %s",
6606                             filename, lineno, configopt[optidx].optname);
6607                 free(optval);
6608                 free(optsub);
6609                 free(line);
6610         }
6611
6612         fclose(config);
6613         DNPRINTF(SWM_D_CONF, "conf_load: end\n");
6614
6615         return (0);
6616
6617 out:
6618         free(line);
6619         fclose(config);
6620         DNPRINTF(SWM_D_CONF, "conf_load: end with error.\n");
6621
6622         return (1);
6623 }
6624
6625 void
6626 set_child_transient(struct ws_win *win, xcb_window_t *trans)
6627 {
6628         struct ws_win           *parent, *w;
6629         struct swm_region       *r;
6630         struct workspace        *ws;
6631         xcb_icccm_wm_hints_t    wmh;
6632
6633         parent = find_window(win->transient);
6634         if (parent)
6635                 parent->focus_child = win;
6636         else {
6637                 DNPRINTF(SWM_D_MISC, "set_child_transient: parent doesn't exist"
6638                     " for 0x%x trans 0x%x\n", win->id, win->transient);
6639
6640                 r = root_to_region(win->wa->root);
6641                 ws = r->ws;
6642                 /* parent doen't exist in our window list */
6643                 TAILQ_FOREACH(w, &ws->winlist, entry) {
6644                         if (xcb_icccm_get_wm_hints_reply(conn,
6645                             xcb_icccm_get_wm_hints(conn, w->id),
6646                             &wmh, NULL) != 1) {
6647                                 warnx("can't get hints for 0x%x", w->id);
6648                                 continue;
6649                         }
6650
6651                         if (win->hints.window_group != wmh.window_group)
6652                                 continue;
6653
6654                         w->focus_child = win;
6655                         win->transient = w->id;
6656                         *trans = w->id;
6657                         DNPRINTF(SWM_D_MISC, "set_child_transient: adjusting "
6658                             "transient to 0x%x\n", win->transient);
6659                         break;
6660                 }
6661         }
6662 }
6663
6664 pid_t
6665 window_get_pid(xcb_window_t win)
6666 {
6667         pid_t                           ret = 0;
6668         const char                      *errstr;
6669         xcb_atom_t                      apid;
6670         xcb_get_property_cookie_t       pc;
6671         xcb_get_property_reply_t        *pr;
6672
6673         apid = get_atom_from_string("_NET_WM_PID");
6674         if (apid == XCB_ATOM_NONE)
6675                 goto tryharder;
6676
6677         pc = xcb_get_property(conn, 0, win, apid, XCB_ATOM_CARDINAL, 0, 1);
6678         pr = xcb_get_property_reply(conn, pc, NULL);
6679         if (!pr)
6680                 goto tryharder;
6681         if (pr->type != XCB_ATOM_CARDINAL) {
6682                 free(pr);
6683                 goto tryharder;
6684         }
6685
6686         if (pr->type == apid && pr->format == 32)
6687                 ret = *((pid_t *)xcb_get_property_value(pr));
6688         free(pr);
6689
6690         return (ret);
6691
6692 tryharder:
6693         apid = get_atom_from_string("_SWM_PID");
6694         pc = xcb_get_property(conn, 0, win, apid, XCB_ATOM_STRING,
6695             0, SWM_PROPLEN);
6696         pr = xcb_get_property_reply(conn, pc, NULL);
6697         if (!pr)
6698                 return (0);
6699         if (pr->type != apid) {
6700                 free(pr);
6701                 return (0);
6702         }
6703
6704         ret = (pid_t)strtonum(xcb_get_property_value(pr), 0, INT_MAX, &errstr);
6705         free(pr);
6706
6707         return (ret);
6708 }
6709
6710 int
6711 get_ws_idx(xcb_window_t id)
6712 {
6713         int                     ws_idx = -1;
6714         char                    *prop = NULL;
6715         size_t                  proplen;
6716         const char              *errstr;
6717         xcb_get_property_reply_t        *gpr;
6718
6719         gpr = xcb_get_property_reply(conn,
6720                 xcb_get_property(conn, 0, id, a_swm_ws,
6721                     XCB_ATOM_STRING, 0, SWM_PROPLEN),
6722                 NULL);
6723         if (!gpr)
6724                 return (-1);
6725         if (gpr->type) {
6726                 proplen = xcb_get_property_value_length(gpr);
6727                 if (proplen > 0) {
6728                         prop = malloc(proplen + 1);
6729                         if (prop) {
6730                                 memcpy(prop,
6731                                     xcb_get_property_value(gpr),
6732                                     proplen);
6733                                 prop[proplen] = '\0';
6734                         }
6735                 }
6736         }
6737         free(gpr);
6738
6739         if (prop) {
6740                 DNPRINTF(SWM_D_PROP, "get_ws_idx: _SWM_WS: %s\n", prop);
6741                 ws_idx = (int)strtonum(prop, 0, workspace_limit - 1, &errstr);
6742                 if (errstr) {
6743                         DNPRINTF(SWM_D_PROP, "get_ws_idx: window: #%s: %s",
6744                             errstr, prop);
6745                 }
6746                 free(prop);
6747         }
6748
6749         return ws_idx;
6750 }
6751
6752 struct ws_win *
6753 manage_window(xcb_window_t id, uint16_t mapped)
6754 {
6755         xcb_window_t            trans = XCB_WINDOW_NONE;
6756         struct ws_win           *win, *ww;
6757         int                     ws_idx, border_me = 0;
6758         char                    ws_idx_str[SWM_PROPLEN];
6759         struct swm_region       *r;
6760         struct pid_e            *p;
6761         struct quirk            *qp;
6762         uint32_t                event_mask, i;
6763         xcb_icccm_get_wm_protocols_reply_t      wpr;
6764
6765         if ((win = find_window(id)) != NULL) {
6766                 DNPRINTF(SWM_D_MISC, "manage_window: win 0x%x already "
6767                     "managed; skipping.)\n", id);
6768                 return (win);   /* Already managed. */
6769         }
6770
6771         /* See if window is on the unmanaged list. */
6772         if ((win = find_unmanaged_window(id)) != NULL) {
6773                 DNPRINTF(SWM_D_MISC, "manage_window: win 0x%x found on "
6774                     "unmanaged list.\n", id);
6775                 TAILQ_REMOVE(&win->ws->unmanagedlist, win, entry);
6776
6777                 if (win->transient)
6778                         set_child_transient(win, &trans);
6779
6780                 goto out;
6781         } else {
6782                 DNPRINTF(SWM_D_MISC, "manage_window: win 0x%x is new.\n", id);
6783         }
6784
6785         /* Create and initialize ws_win object. */
6786         if ((win = calloc(1, sizeof(struct ws_win))) == NULL)
6787                 err(1, "manage_window: calloc: failed to allocate memory for "
6788                     "new window");
6789
6790         win->id = id;
6791
6792         /* Get window geometry. */
6793         win->wa = xcb_get_geometry_reply(conn,
6794             xcb_get_geometry(conn, win->id),
6795             NULL);
6796
6797         /* Figure out which region the window belongs to. */
6798         r = root_to_region(win->wa->root);
6799
6800         /* Ignore window border if there is one. */
6801         WIDTH(win) = win->wa->width;
6802         HEIGHT(win) = win->wa->height;
6803         X(win) = win->wa->x + win->wa->border_width;
6804         Y(win) = win->wa->y + win->wa->border_width;
6805         win->bordered = 0;
6806         win->mapped = mapped;
6807         win->floatmaxed = 0;
6808         win->ewmh_flags = 0;
6809         win->s = r->s;  /* this never changes */
6810
6811         store_float_geom(win, r);
6812
6813         /* Get WM_SIZE_HINTS. */
6814         xcb_icccm_get_wm_normal_hints_reply(conn,
6815             xcb_icccm_get_wm_normal_hints(conn, win->id),
6816             &win->sh, NULL);
6817
6818         /* Get WM_HINTS. */
6819         xcb_icccm_get_wm_hints_reply(conn,
6820             xcb_icccm_get_wm_hints(conn, win->id),
6821             &win->hints, NULL);
6822
6823         /* Get WM_TRANSIENT_FOR; see if window is a transient. */
6824         xcb_icccm_get_wm_transient_for_reply(conn,
6825             xcb_icccm_get_wm_transient_for(conn, win->id),
6826             &trans, NULL);
6827         if (trans) {
6828                 win->transient = trans;
6829                 set_child_transient(win, &win->transient);
6830         }
6831
6832         /* Get supported protocols. */
6833         if (xcb_icccm_get_wm_protocols_reply(conn,
6834             xcb_icccm_get_wm_protocols(conn, win->id, a_prot),
6835             &wpr, NULL)) {
6836                 for (i = 0; i < wpr.atoms_len; i++) {
6837                         if (wpr.atoms[i] == a_takefocus)
6838                                 win->take_focus = 1;
6839                         if (wpr.atoms[i] == a_delete)
6840                                 win->can_delete = 1;
6841                 }
6842                 xcb_icccm_get_wm_protocols_reply_wipe(&wpr);
6843         }
6844
6845         win->iconic = get_swm_iconic(win);
6846
6847         /* Figure out which workspace the window belongs to. */
6848         if ((p = find_pid(window_get_pid(win->id))) != NULL) {
6849                 win->ws = &r->s->ws[p->ws];
6850                 TAILQ_REMOVE(&pidlist, p, entry);
6851                 free(p);
6852                 p = NULL;
6853         } else if ((ws_idx = get_ws_idx(win->id)) != -1 &&
6854             win->transient == 0) {
6855                 /* _SWM_WS is set; use that. */
6856                 win->ws = &r->s->ws[ws_idx];
6857         } else if (trans && (ww = find_window(trans)) != NULL) {
6858                 /* Launch transients in the same ws as parent. */
6859                 win->ws = ww->ws;
6860                 border_me = 1;
6861         } else {
6862                 win->ws = r->ws;
6863         }
6864
6865         /* Set the _SWM_WS atom so we can remember this after reincarnation. */
6866         if (snprintf(ws_idx_str, SWM_PROPLEN, "%d", win->ws->idx) <
6867             SWM_PROPLEN) {
6868                 DNPRINTF(SWM_D_PROP, "manage_window: set _SWM_WS: %s\n",
6869                     ws_idx_str);
6870                 xcb_change_property(conn, XCB_PROP_MODE_REPLACE, win->id,
6871                     a_swm_ws, XCB_ATOM_STRING, 8, strlen(ws_idx_str),
6872                     ws_idx_str);
6873         }
6874
6875         /* Handle EWMH */
6876         ewmh_autoquirk(win);
6877
6878         /* Determine initial quirks. */
6879         if (xcb_icccm_get_wm_class_reply(conn,
6880             xcb_icccm_get_wm_class(conn, win->id),
6881             &win->ch, NULL)) {
6882                 DNPRINTF(SWM_D_CLASS, "manage_window: class: %s, name: %s\n",
6883                     win->ch.class_name, win->ch.instance_name);
6884
6885                 /* java is retarded so treat it special */
6886                 if (strstr(win->ch.instance_name, "sun-awt")) {
6887                         DNPRINTF(SWM_D_CLASS, "manage_window: java window "
6888                             "detected.\n");
6889                         win->java = 1;
6890                         border_me = 1;
6891                 }
6892
6893                 TAILQ_FOREACH(qp, &quirks, entry) {
6894                         if (!strcmp(win->ch.class_name, qp->class) &&
6895                             !strcmp(win->ch.instance_name, qp->name)) {
6896                                 DNPRINTF(SWM_D_CLASS, "manage_window: on quirks"
6897                                     "list; mask: 0x%lx\n", qp->quirk);
6898                                 if (qp->quirk & SWM_Q_FLOAT) {
6899                                         win->floating = 1;
6900                                         border_me = 1;
6901                                 }
6902                                 win->quirks = qp->quirk;
6903                         }
6904                 }
6905         }
6906
6907         /* Alter window position if quirky */
6908         if (win->quirks & SWM_Q_ANYWHERE) {
6909                 win->manual = 1;
6910                 border_me = 1;
6911         }
6912
6913         /* Reset font sizes (the bruteforce way; no default keybinding). */
6914         if (win->quirks & SWM_Q_XTERM_FONTADJ) {
6915                 for (i = 0; i < SWM_MAX_FONT_STEPS; i++)
6916                         fake_keypress(win, XK_KP_Subtract, XCB_MOD_MASK_SHIFT);
6917                 for (i = 0; i < SWM_MAX_FONT_STEPS; i++)
6918                         fake_keypress(win, XK_KP_Add, XCB_MOD_MASK_SHIFT);
6919         }
6920
6921         if (border_me) {
6922                 win->bordered = 1;
6923                 X(win) -= border_width;
6924                 Y(win) -= border_width;
6925         }
6926
6927         /* Make sure window is positioned inside its region, if its active. */
6928         if (win->ws->r)
6929                 constrain_window(win, win->ws->r, 0);
6930
6931         if (win->ws->r || border_me)
6932                 update_window(win);
6933
6934         /* Select which X events to monitor. */
6935         event_mask = XCB_EVENT_MASK_ENTER_WINDOW | XCB_EVENT_MASK_FOCUS_CHANGE |
6936             XCB_EVENT_MASK_PROPERTY_CHANGE | XCB_EVENT_MASK_STRUCTURE_NOTIFY;
6937 #ifdef SWM_DEBUG
6938         event_mask |= XCB_EVENT_MASK_LEAVE_WINDOW;
6939 #endif
6940
6941         xcb_change_window_attributes(conn, win->id, XCB_CW_EVENT_MASK,
6942             &event_mask);
6943
6944 out:
6945         /* Figure out where to stack the window in the workspace. */
6946         if (trans && (ww = find_window(trans)))
6947                 TAILQ_INSERT_AFTER(&win->ws->winlist, ww, win, entry);
6948         else if (win->ws->focus && spawn_position == SWM_STACK_ABOVE)
6949                 TAILQ_INSERT_AFTER(&win->ws->winlist, win->ws->focus, win,
6950                     entry);
6951         else if (win->ws->focus && spawn_position == SWM_STACK_BELOW)
6952                 TAILQ_INSERT_BEFORE(win->ws->focus, win, entry);
6953         else switch (spawn_position) {
6954         default:
6955         case SWM_STACK_TOP:
6956         case SWM_STACK_ABOVE:
6957                 TAILQ_INSERT_TAIL(&win->ws->winlist, win, entry);
6958                 break;
6959         case SWM_STACK_BOTTOM:
6960         case SWM_STACK_BELOW:
6961                 TAILQ_INSERT_HEAD(&win->ws->winlist, win, entry);
6962         }
6963
6964         /* Get initial _NET_WM_STATE */
6965         ewmh_get_win_state(win);
6966         /* Set initial _NET_WM_ALLOWED_ACTIONS */
6967         ewmh_update_actions(win);
6968
6969         grabbuttons(win);
6970
6971         DNPRINTF(SWM_D_MISC, "manage_window: done. window: 0x%x, (x,y) w x h: "
6972             "(%d,%d) %d x %d, ws: %d, iconic: %s, transient: 0x%x\n", win->id,
6973             X(win), Y(win), WIDTH(win), HEIGHT(win), win->ws->idx,
6974             YESNO(win->iconic), win->transient);
6975
6976         return (win);
6977 }
6978
6979 void
6980 free_window(struct ws_win *win)
6981 {
6982         DNPRINTF(SWM_D_MISC, "free_window: window: 0x%x\n", win->id);
6983
6984         if (win == NULL)
6985                 return;
6986
6987         TAILQ_REMOVE(&win->ws->unmanagedlist, win, entry);
6988
6989         if (win->wa)
6990                 free(win->wa);
6991
6992         xcb_icccm_get_wm_class_reply_wipe(&win->ch);
6993
6994         kill_refs(win);
6995
6996         /* paint memory */
6997         memset(win, 0xff, sizeof *win); /* XXX kill later */
6998
6999         free(win);
7000         DNPRINTF(SWM_D_MISC, "free_window: done.\n");
7001 }
7002
7003 void
7004 unmanage_window(struct ws_win *win)
7005 {
7006         struct ws_win           *parent;
7007
7008         if (win == NULL)
7009                 return;
7010
7011         DNPRINTF(SWM_D_MISC, "unmanage_window: window: 0x%x\n", win->id);
7012
7013         if (win->transient) {
7014                 parent = find_window(win->transient);
7015                 if (parent)
7016                         parent->focus_child = NULL;
7017         }
7018
7019         focus_win(get_focus_prev(win));
7020
7021         TAILQ_REMOVE(&win->ws->winlist, win, entry);
7022         TAILQ_INSERT_TAIL(&win->ws->unmanagedlist, win, entry);
7023 }
7024
7025 void
7026 expose(xcb_expose_event_t *e)
7027 {
7028         int                     i, num_screens;
7029         struct swm_region       *r;
7030
7031         DNPRINTF(SWM_D_EVENT, "expose: window: 0x%x\n", e->window);
7032
7033         num_screens = xcb_setup_roots_length(xcb_get_setup(conn));
7034         for (i = 0; i < num_screens; i++)
7035                 TAILQ_FOREACH(r, &screens[i].rl, entry)
7036                         if (e->window == WINID(r->bar))
7037                                 bar_update();
7038
7039         xcb_flush(conn);
7040 }
7041
7042 #ifdef SWM_DEBUG
7043 void
7044 focusin(xcb_focus_in_event_t *e)
7045 {
7046         DNPRINTF(SWM_D_EVENT, "focusin: window: 0x%x, mode: %s(%u), "
7047             "detail: %s(%u)\n", e->event, get_notify_mode_label(e->mode),
7048             e->mode, get_notify_detail_label(e->detail), e->detail);
7049 }
7050
7051 void
7052 focusout(xcb_focus_out_event_t *e)
7053 {
7054         DNPRINTF(SWM_D_EVENT, "focusout: window: 0x%x, mode: %s(%u), "
7055             "detail: %s(%u)\n", e->event, get_notify_mode_label(e->mode),
7056             e->mode, get_notify_detail_label(e->detail), e->detail);
7057 }
7058 #endif
7059
7060 void
7061 keypress(xcb_key_press_event_t *e)
7062 {
7063         xcb_keysym_t            keysym;
7064         struct key              *kp;
7065
7066         keysym = xcb_key_press_lookup_keysym(syms, e, 0);
7067
7068         DNPRINTF(SWM_D_EVENT, "keypress: %u %u\n", e->detail, keysym);
7069
7070         if ((kp = key_lookup(CLEANMASK(e->state), keysym)) == NULL)
7071                 return;
7072
7073         last_event_time = e->time;
7074
7075         if (kp->funcid == KF_SPAWN_CUSTOM)
7076                 spawn_custom(root_to_region(e->root),
7077                     &(keyfuncs[kp->funcid].args), kp->spawn_name);
7078         else if (keyfuncs[kp->funcid].func)
7079                 keyfuncs[kp->funcid].func(root_to_region(e->root),
7080                     &(keyfuncs[kp->funcid].args));
7081 }
7082
7083 void
7084 buttonpress(xcb_button_press_event_t *e)
7085 {
7086         struct ws_win           *win;
7087         int                     i;
7088         int                     handled = 0;
7089
7090         DNPRINTF(SWM_D_EVENT, "buttonpress: window 0x%x, detail: %u\n",
7091             e->event, e->detail);
7092
7093         if ((win = find_window(e->event)) == NULL)
7094                 return;
7095
7096         last_event_time = e->time;
7097
7098         focus_win(get_focus_magic(win));
7099
7100         for (i = 0; i < LENGTH(buttons); i++)
7101                 if (client_click == buttons[i].action && buttons[i].func &&
7102                     buttons[i].button == e->detail &&
7103                     CLEANMASK(buttons[i].mask) == CLEANMASK(e->state)) {
7104                         buttons[i].func(win, &buttons[i].args);
7105                         handled = 1;
7106                 }
7107
7108         if (!handled) {
7109                 DNPRINTF(SWM_D_EVENT, "buttonpress: passing to window.\n");
7110                 xcb_allow_events(conn, XCB_ALLOW_REPLAY_POINTER, e->time);
7111         } else {
7112                 DNPRINTF(SWM_D_EVENT, "buttonpress: handled.\n");
7113         }
7114
7115         xcb_flush(conn);
7116 }
7117
7118 #ifdef SWM_DEBUG
7119 void
7120 print_win_geom(xcb_window_t w)
7121 {
7122         xcb_get_geometry_reply_t        *wa;
7123
7124         wa = xcb_get_geometry_reply(conn, xcb_get_geometry(conn, w), NULL);
7125
7126         if (!wa) {
7127                 DNPRINTF(SWM_D_MISC, "print_win_geom: window not found: 0x%x\n",
7128                     w);
7129                 return;
7130         }
7131
7132         DNPRINTF(SWM_D_MISC, "print_win_geom: window: 0x%x, root: 0x%x, "
7133             "depth: %u, (x,y) w x h: (%d,%d) %d x %d, border: %d\n",
7134             w, wa->root, wa->depth, wa->x,  wa->y, wa->width, wa->height,
7135             wa->border_width);
7136
7137         free(wa);
7138 }
7139 #endif
7140
7141 #ifdef SWM_DEBUG
7142 char *
7143 get_stack_mode_name(uint8_t mode)
7144 {
7145         char    *name;
7146
7147         switch(mode) {
7148         case XCB_STACK_MODE_ABOVE:
7149                 name = "Above";
7150                 break;
7151         case XCB_STACK_MODE_BELOW:
7152                 name = "Below";
7153                 break;
7154         case XCB_STACK_MODE_TOP_IF:
7155                 name = "TopIf";
7156                 break;
7157         case XCB_STACK_MODE_BOTTOM_IF:
7158                 name = "BottomIf";
7159                 break;
7160         case XCB_STACK_MODE_OPPOSITE:
7161                 name = "Opposite";
7162                 break;
7163         default:
7164                 name = "Unknown";
7165         }
7166
7167         return name;
7168 }
7169 #endif
7170
7171 void
7172 configurerequest(xcb_configure_request_event_t *e)
7173 {
7174         struct ws_win           *win;
7175         struct swm_region       *r = NULL;
7176         int                     new = 0, i = 0;
7177         uint16_t                mask = 0;
7178         uint32_t                wc[7] = {0};
7179
7180         if ((win = find_window(e->window)) == NULL)
7181                 if ((win = find_unmanaged_window(e->window)) == NULL)
7182                         new = 1;
7183
7184 #ifdef SWM_DEBUG
7185         if (swm_debug & SWM_D_EVENT) {
7186                 print_win_geom(e->window);
7187
7188                 DNPRINTF(SWM_D_EVENT, "configurerequest: window: 0x%x, "
7189                     "parent: 0x%x, new: %s, value_mask: %u { ", e->window,
7190                     e->parent, YESNO(new), e->value_mask);
7191                 if (e->value_mask & XCB_CONFIG_WINDOW_X)
7192                         DPRINTF("X: %d ", e->x);
7193                 if (e->value_mask & XCB_CONFIG_WINDOW_Y)
7194                         DPRINTF("Y: %d ", e->y);
7195                 if (e->value_mask & XCB_CONFIG_WINDOW_WIDTH)
7196                         DPRINTF("W: %u ", e->width);
7197                 if (e->value_mask & XCB_CONFIG_WINDOW_HEIGHT)
7198                         DPRINTF("H: %u ", e->height);
7199                 if (e->value_mask & XCB_CONFIG_WINDOW_BORDER_WIDTH)
7200                         DPRINTF("Border: %u ", e->border_width);
7201                 if (e->value_mask & XCB_CONFIG_WINDOW_SIBLING)
7202                         DPRINTF("Sibling: 0x%x ", e->sibling);
7203                 if (e->value_mask & XCB_CONFIG_WINDOW_STACK_MODE)
7204                         DPRINTF("StackMode: %s(%u) ",
7205                             get_stack_mode_name(e->stack_mode), e->stack_mode);
7206                 DPRINTF("}\n");
7207         }
7208 #endif
7209
7210         if (new) {
7211                 if (e->value_mask & XCB_CONFIG_WINDOW_X) {
7212                         mask |= XCB_CONFIG_WINDOW_X;
7213                         wc[i++] = e->x;
7214                 }
7215                 if (e->value_mask & XCB_CONFIG_WINDOW_Y) {
7216                         mask |= XCB_CONFIG_WINDOW_Y;
7217                         wc[i++] = e->y;
7218                 }
7219                 if (e->value_mask & XCB_CONFIG_WINDOW_WIDTH) {
7220                         mask |= XCB_CONFIG_WINDOW_WIDTH;
7221                         wc[i++] = e->width;
7222                 }
7223                 if (e->value_mask & XCB_CONFIG_WINDOW_HEIGHT) {
7224                         mask |= XCB_CONFIG_WINDOW_HEIGHT;
7225                         wc[i++] = e->height;
7226                 }
7227                 if (e->value_mask & XCB_CONFIG_WINDOW_BORDER_WIDTH) {
7228                         mask |= XCB_CONFIG_WINDOW_BORDER_WIDTH;
7229                         wc[i++] = e->border_width;
7230                 }
7231                 if (e->value_mask & XCB_CONFIG_WINDOW_SIBLING) {
7232                         mask |= XCB_CONFIG_WINDOW_SIBLING;
7233                         wc[i++] = e->sibling;
7234                 }
7235                 if (e->value_mask & XCB_CONFIG_WINDOW_STACK_MODE) {
7236                         mask |= XCB_CONFIG_WINDOW_STACK_MODE;
7237                         wc[i++] = e->stack_mode;
7238                 }
7239
7240                 if (mask != 0)
7241                         xcb_configure_window(conn, e->window, mask, wc);
7242         } else if ((!win->manual || win->quirks & SWM_Q_ANYWHERE) &&
7243             !(win->ewmh_flags & EWMH_F_FULLSCREEN)) {
7244                 if (win->ws->r)
7245                         r = win->ws->r;
7246                 else if (win->ws->old_r)
7247                         r = win->ws->old_r;
7248
7249                 /* windows are centered unless ANYWHERE quirk is set. */
7250                 if (win->quirks & SWM_Q_ANYWHERE) {
7251                         if (e->value_mask & XCB_CONFIG_WINDOW_X) {
7252                                 win->g_float.x = e->x;
7253                                 if (r)
7254                                         win->g_float.x -= X(r);
7255                         }
7256
7257                         if (e->value_mask & XCB_CONFIG_WINDOW_Y) {
7258                                 win->g_float.y = e->y;
7259                                 if (r)
7260                                         win->g_float.y -= Y(r);
7261                         }
7262                 }
7263
7264                 if (e->value_mask & XCB_CONFIG_WINDOW_WIDTH)
7265                         win->g_float.w = e->width;
7266
7267                 if (e->value_mask & XCB_CONFIG_WINDOW_HEIGHT)
7268                         win->g_float.h = e->height;
7269
7270                 win->g_floatvalid = 1;
7271
7272                 if (win->floating && r) {
7273                         WIDTH(win) = win->g_float.w;
7274                         HEIGHT(win) = win->g_float.h;
7275
7276                         stack_floater(win, win->ws->r);
7277
7278                         focus_flush();
7279                 } else {
7280                         config_win(win, e);
7281                         xcb_flush(conn);
7282                 }
7283         } else {
7284                 config_win(win, e);
7285                 xcb_flush(conn);
7286         }
7287 }
7288
7289 void
7290 configurenotify(xcb_configure_notify_event_t *e)
7291 {
7292         struct ws_win           *win;
7293
7294         DNPRINTF(SWM_D_EVENT, "configurenotify: window: 0x%x\n",
7295             e->window);
7296
7297         win = find_window(e->window);
7298         if (win) {
7299                 xcb_icccm_get_wm_normal_hints_reply(conn,
7300                     xcb_icccm_get_wm_normal_hints(conn, win->id),
7301                     &win->sh, NULL);
7302                 adjust_font(win);
7303                 if (font_adjusted) {
7304                         stack();
7305                         xcb_flush(conn);
7306                 }
7307         }
7308 }
7309
7310 void
7311 destroynotify(xcb_destroy_notify_event_t *e)
7312 {
7313         struct ws_win           *win;
7314
7315         DNPRINTF(SWM_D_EVENT, "destroynotify: window: 0x%x\n", e->window);
7316
7317         if ((win = find_window(e->window)) == NULL) {
7318                 if ((win = find_unmanaged_window(e->window)) == NULL)
7319                         return;
7320                 free_window(win);
7321                 return;
7322         }
7323
7324         /* make sure we focus on something */
7325         win->floating = 0;
7326
7327         unmanage_window(win);
7328         free_window(win);
7329
7330         stack();
7331
7332         focus_flush();
7333 }
7334
7335 #ifdef SWM_DEBUG
7336 char *
7337 get_notify_detail_label(uint8_t detail)
7338 {
7339         char *label;
7340
7341         switch (detail) {
7342         case XCB_NOTIFY_DETAIL_ANCESTOR:
7343                 label = "Ancestor";
7344                 break;
7345         case XCB_NOTIFY_DETAIL_VIRTUAL:
7346                 label = "Virtual";
7347                 break;
7348         case XCB_NOTIFY_DETAIL_INFERIOR:
7349                 label = "Inferior";
7350                 break;
7351         case XCB_NOTIFY_DETAIL_NONLINEAR:
7352                 label = "Nonlinear";
7353                 break;
7354         case XCB_NOTIFY_DETAIL_NONLINEAR_VIRTUAL:
7355                 label = "NonlinearVirtual";
7356                 break;
7357         case XCB_NOTIFY_DETAIL_POINTER:
7358                 label = "Pointer";
7359                 break;
7360         case XCB_NOTIFY_DETAIL_POINTER_ROOT:
7361                 label = "PointerRoot";
7362                 break;
7363         case XCB_NOTIFY_DETAIL_NONE:
7364                 label = "None";
7365                 break;
7366         default:
7367                 label = "Unknown";
7368         }
7369
7370         return label;
7371 }
7372
7373 char *
7374 get_notify_mode_label(uint8_t mode)
7375 {
7376         char *label;
7377
7378         switch (mode) {
7379         case XCB_NOTIFY_MODE_NORMAL:
7380                 label = "Normal";
7381                 break;
7382         case XCB_NOTIFY_MODE_GRAB:
7383                 label = "Grab";
7384                 break;
7385         case XCB_NOTIFY_MODE_UNGRAB:
7386                 label = "Ungrab";
7387                 break;
7388         case XCB_NOTIFY_MODE_WHILE_GRABBED:
7389                 label = "WhileGrabbed";
7390                 break;
7391         default:
7392                 label = "Unknown";
7393         }
7394
7395         return label;
7396 }
7397 #endif
7398
7399 void
7400 enternotify(xcb_enter_notify_event_t *e)
7401 {
7402         struct ws_win           *win;
7403
7404         DNPRINTF(SWM_D_FOCUS, "enternotify: time: %u, win (x,y): 0x%x "
7405             "(%d,%d), mode: %s(%d), detail: %s(%d), root (x,y): 0x%x (%d,%d), "
7406             "child: 0x%x, same_screen_focus: %s, state: %d\n",
7407             e->time, e->event, e->event_x, e->event_y,
7408             get_notify_mode_label(e->mode), e->mode,
7409             get_notify_detail_label(e->detail), e->detail,
7410             e->root, e->root_x, e->root_y, e->child,
7411             YESNO(e->same_screen_focus), e->state);
7412
7413         if (focus_mode == SWM_FOCUS_MANUAL &&
7414             e->mode == XCB_NOTIFY_MODE_NORMAL) {
7415                 DNPRINTF(SWM_D_EVENT, "enternotify: manual focus; ignoring.\n");
7416                 return;
7417         }
7418
7419         if ((win = find_window(e->event)) == NULL) {
7420                 DNPRINTF(SWM_D_EVENT, "enternotify: window is NULL; ignoring\n");
7421                 return;
7422         }
7423
7424         last_event_time = e->time;
7425
7426         focus_win(get_focus_magic(win));
7427
7428         xcb_flush(conn);
7429 }
7430
7431 #ifdef SWM_DEBUG
7432 void
7433 leavenotify(xcb_leave_notify_event_t *e)
7434 {
7435         DNPRINTF(SWM_D_FOCUS, "leavenotify: time: %u, win (x,y): 0x%x "
7436             "(%d,%d), mode: %s(%d), detail: %s(%d), root (x,y): 0x%x (%d,%d), "
7437             "child: 0x%x, same_screen_focus: %s, state: %d\n",
7438             e->time, e->event, e->event_x, e->event_y,
7439             get_notify_mode_label(e->mode), e->mode,
7440             get_notify_detail_label(e->detail), e->detail,
7441             e->root, e->root_x, e->root_y, e->child,
7442             YESNO(e->same_screen_focus), e->state);
7443 }
7444 #endif
7445
7446 /* lets us use one switch statement for arbitrary mode/detail combinations */
7447 #define MERGE_MEMBERS(a,b)      (((a & 0xffff) << 16) | (b & 0xffff))
7448
7449 void
7450 mapnotify(xcb_map_notify_event_t *e)
7451 {
7452         struct ws_win           *win;
7453
7454         DNPRINTF(SWM_D_EVENT, "mapnotify: window: 0x%x\n", e->window);
7455
7456         if ((win = find_window(e->window)) == NULL)
7457                 win = manage_window(e->window, 1);
7458
7459         win->mapped = 1;
7460         set_win_state(win, XCB_ICCCM_WM_STATE_NORMAL);
7461
7462         /* Focus on window if it is selected. */
7463         if (win->ws->focus == win)
7464                 focus_win(win);
7465
7466         xcb_flush(conn);
7467 }
7468
7469 void
7470 mappingnotify(xcb_mapping_notify_event_t *e)
7471 {
7472         xcb_refresh_keyboard_mapping(syms, e);
7473
7474         if (e->request == XCB_MAPPING_KEYBOARD)
7475                 grabkeys();
7476 }
7477
7478 void
7479 maprequest(xcb_map_request_event_t *e)
7480 {
7481         struct ws_win           *win;
7482         xcb_get_window_attributes_reply_t *war;
7483
7484         DNPRINTF(SWM_D_EVENT, "maprequest: win 0x%x\n",
7485             e->window);
7486
7487         war = xcb_get_window_attributes_reply(conn,
7488             xcb_get_window_attributes(conn, e->window),
7489             NULL);
7490         if (war == NULL) {
7491                 DNPRINTF(SWM_D_EVENT, "maprequest: window lost.\n");
7492                 goto out;
7493         }
7494
7495         if (war->override_redirect) {
7496                 DNPRINTF(SWM_D_EVENT, "maprequest: override_redirect; "
7497                     "skipping.\n");
7498                 goto out;
7499         }
7500
7501         win = manage_window(e->window,
7502             (war->map_state == XCB_MAP_STATE_VIEWABLE));
7503
7504         /* All windows need to be mapped if they are in the current workspace.*/
7505         if (win->ws->r)
7506                 stack();
7507
7508         /* The new window should get focus. */
7509         win->ws->focus = get_focus_magic(win);
7510
7511         /* Ignore EnterNotify to handle the mapnotify without interference. */
7512         if (focus_mode == SWM_FOCUS_DEFAULT)
7513                 event_drain(XCB_ENTER_NOTIFY);
7514 out:
7515         free(war);
7516         DNPRINTF(SWM_D_EVENT, "maprequest: done.\n");
7517 }
7518
7519 #ifdef SWM_DEBUG
7520 char *
7521 get_atom_name(xcb_atom_t atom)
7522 {
7523         char                            *name = NULL;
7524 #if 0
7525         /*
7526          * This should be disabled during most debugging since
7527          * xcb_get_* causes an xcb_flush.
7528          */
7529         size_t                          len;
7530         xcb_get_atom_name_reply_t       *r;
7531
7532         r = xcb_get_atom_name_reply(conn,
7533             xcb_get_atom_name(conn, atom),
7534             NULL);
7535         if (r) {
7536                 len = xcb_get_atom_name_name_length(r);
7537                 if (len > 0) {
7538                         name = malloc(len + 1);
7539                         if (name) {
7540                                 memcpy(name, xcb_get_atom_name_name(r), len);
7541                                 name[len] = '\0';
7542                         }
7543                 }
7544                 free(r);
7545         }
7546 #else
7547         (void)atom;
7548 #endif
7549         return (name);
7550 }
7551 #endif
7552
7553 void
7554 propertynotify(xcb_property_notify_event_t *e)
7555 {
7556         struct ws_win           *win;
7557         union arg a;
7558 #ifdef SWM_DEBUG
7559         char                    *name;
7560
7561         name = get_atom_name(e->atom);
7562         DNPRINTF(SWM_D_EVENT, "propertynotify: window: 0x%x, atom: %s(%u), "
7563             "time: %#x\n", e->window, name, e->atom, e->time);
7564         free(name);
7565 #endif
7566         win = find_window(e->window);
7567         if (win == NULL)
7568                 return;
7569
7570         last_event_time = e->time;
7571
7572         if (e->atom == a_swm_iconic) {
7573                 if (e->state == XCB_PROPERTY_DELETE) {
7574                         /* The window is no longer iconic, restack ws. */
7575                         stack();
7576
7577                         /* The window should get focus. */
7578                         win->ws->focus = get_focus_magic(win);
7579
7580                         /* Flush EnterNotify for mapnotify, if needed. */
7581                         focus_flush();
7582                         return;
7583                 } else if (e->state == XCB_PROPERTY_NEW_VALUE) {
7584                         win->ws->focus = NULL;
7585
7586                         unfocus_win(win);
7587                         unmap_window(win);
7588
7589                         if (win->ws->r) {
7590                                 focus_win(get_focus_prev(win));
7591                                 stack();
7592                                 focus_flush();
7593                         }
7594                 }
7595         } else if (e->atom == a_state && e->state == XCB_PROPERTY_NEW_VALUE) {
7596                 /* Focus on window if it is selected. */
7597                 if (win->ws->focus == win)
7598                         focus_win(win);
7599         }
7600
7601         switch (e->atom) {
7602         case XCB_ATOM_WM_CLASS:
7603         case XCB_ATOM_WM_NAME:
7604                 bar_update();
7605                 break;
7606         default:
7607                 break;
7608         }
7609
7610         xcb_flush(conn);
7611 }
7612
7613 void
7614 unmapnotify(xcb_unmap_notify_event_t *e)
7615 {
7616         struct ws_win           *win;
7617
7618         DNPRINTF(SWM_D_EVENT, "unmapnotify: window: 0x%x\n", e->window);
7619
7620         /* determine if we need to help unmanage this window */
7621         win = find_window(e->window);
7622         if (win == NULL)
7623                 return;
7624
7625         if (getstate(e->window) == XCB_ICCCM_WM_STATE_NORMAL) {
7626                 unmanage_window(win);
7627                 stack();
7628                 focus_flush();
7629         }
7630 }
7631
7632 #if 0
7633 void
7634 visibilitynotify(xcb_visibility_notify_event_t *e)
7635 {
7636         DNPRINTF(SWM_D_EVENT, "visibilitynotify: window: 0x%x\n",
7637             e->window);
7638 }
7639 #endif
7640
7641 void
7642 clientmessage(xcb_client_message_event_t *e)
7643 {
7644         struct ws_win *win;
7645         xcb_map_request_event_t mre;
7646 #ifdef SWM_DEBUG
7647         char                    *name;
7648
7649         name = get_atom_name(e->type);
7650         DNPRINTF(SWM_D_EVENT, "clientmessage: window: 0x%x, atom: %s(%u)\n",
7651             e->window, name, e->type);
7652         free(name);
7653 #endif
7654         win = find_window(e->window);
7655
7656         if (win == NULL) {
7657                 if (e->type == ewmh[_NET_ACTIVE_WINDOW].atom) {
7658                         DNPRINTF(SWM_D_EVENT, "clientmessage: request focus on "
7659                             "unmanaged window.\n");
7660                         mre.window = e->window;
7661                         maprequest(&mre);
7662                 }
7663                 return;
7664         }
7665
7666         if (e->type == ewmh[_NET_ACTIVE_WINDOW].atom) {
7667                 DNPRINTF(SWM_D_EVENT, "clientmessage: _NET_ACTIVE_WINDOW\n");
7668                 focus_win(win);
7669         }
7670         if (e->type == ewmh[_NET_CLOSE_WINDOW].atom) {
7671                 DNPRINTF(SWM_D_EVENT, "clientmessage: _NET_CLOSE_WINDOW\n");
7672                 if (win->can_delete)
7673                         client_msg(win, a_delete, 0);
7674                 else
7675                         xcb_kill_client(conn, win->id);
7676         }
7677         if (e->type == ewmh[_NET_MOVERESIZE_WINDOW].atom) {
7678                 DNPRINTF(SWM_D_EVENT,
7679                     "clientmessage: _NET_MOVERESIZE_WINDOW\n");
7680                 if (win->floating) {
7681                         if (e->data.data32[0] & (1<<8)) /* x */
7682                                 X(win) = e->data.data32[1];
7683                         if (e->data.data32[0] & (1<<9)) /* y */
7684                                 Y(win) = e->data.data32[2];
7685                         if (e->data.data32[0] & (1<<10)) /* width */
7686                                 WIDTH(win) = e->data.data32[3];
7687                         if (e->data.data32[0] & (1<<11)) /* height */
7688                                 HEIGHT(win) = e->data.data32[4];
7689
7690                         update_window(win);
7691                 }
7692                 else {
7693                         /* TODO: Change stack sizes */
7694                         /* notify no change was made. */
7695                         config_win(win, NULL);
7696                 }
7697         }
7698         if (e->type == ewmh[_NET_WM_STATE].atom) {
7699                 DNPRINTF(SWM_D_EVENT, "clientmessage: _NET_WM_STATE\n");
7700                 ewmh_update_win_state(win, e->data.data32[1], e->data.data32[0]);
7701                 if (e->data.data32[2])
7702                         ewmh_update_win_state(win, e->data.data32[2],
7703                             e->data.data32[0]);
7704
7705                 stack();
7706         }
7707
7708         xcb_flush(conn);
7709 }
7710
7711 void
7712 check_conn(void)
7713 {
7714         int      errcode = xcb_connection_has_error(conn);
7715 #ifdef XCB_CONN_ERROR
7716         char    *s;
7717         switch (errcode) {
7718         case XCB_CONN_ERROR:
7719                 s = "Socket error, pipe error or other stream error.";
7720                 break;
7721         case XCB_CONN_CLOSED_EXT_NOTSUPPORTED:
7722                 s = "Extension not supported.";
7723                 break;
7724         case XCB_CONN_CLOSED_MEM_INSUFFICIENT:
7725                 s = "Insufficient memory.";
7726                 break;
7727         case XCB_CONN_CLOSED_REQ_LEN_EXCEED:
7728                 s = "Request length was exceeded.";
7729                 break;
7730         case XCB_CONN_CLOSED_PARSE_ERR:
7731                 s = "Error parsing display string.";
7732                 break;
7733         default:
7734                 s = "Unknown error.";
7735         }
7736         if (errcode)
7737                 errx(errcode, "X CONNECTION ERROR: %s", s);
7738 #else
7739         if (errcode)
7740                 errx(errcode, "X CONNECTION ERROR");
7741 #endif
7742 }
7743
7744 int
7745 enable_wm(void)
7746 {
7747         int                     num_screens, i;
7748         const uint32_t          val = XCB_EVENT_MASK_SUBSTRUCTURE_REDIRECT;
7749         xcb_screen_t            *sc;
7750         xcb_void_cookie_t       wac;
7751         xcb_generic_error_t     *error;
7752
7753         /* this causes an error if some other window manager is running */
7754         num_screens = xcb_setup_roots_length(xcb_get_setup(conn));
7755         for (i = 0; i < num_screens; i++) {
7756                 if ((sc = get_screen(i)) == NULL)
7757                         errx(1, "ERROR: can't get screen %d.", i);
7758                 DNPRINTF(SWM_D_INIT, "enable_wm: screen %d, root: 0x%x\n",
7759                     i, sc->root);
7760                 wac = xcb_change_window_attributes_checked(conn, sc->root,
7761                     XCB_CW_EVENT_MASK, &val);
7762                 if ((error = xcb_request_check(conn, wac))) {
7763                         DNPRINTF(SWM_D_INIT, "enable_wm: error_code: %u\n",
7764                             error->error_code);
7765                         free(error);
7766                         return 1;
7767                 }
7768         }
7769
7770         return 0;
7771 }
7772
7773 void
7774 new_region(struct swm_screen *s, int x, int y, int w, int h)
7775 {
7776         struct swm_region       *r, *n;
7777         struct workspace        *ws = NULL;
7778         int                     i;
7779
7780         DNPRINTF(SWM_D_MISC, "new region: screen[%d]:%dx%d+%d+%d\n",
7781              s->idx, w, h, x, y);
7782
7783         /* remove any conflicting regions */
7784         n = TAILQ_FIRST(&s->rl);
7785         while (n) {
7786                 r = n;
7787                 n = TAILQ_NEXT(r, entry);
7788                 if (X(r) < (x + w) &&
7789                     (X(r) + WIDTH(r)) > x &&
7790                     Y(r) < (y + h) &&
7791                     (Y(r) + HEIGHT(r)) > y) {
7792                         if (r->ws->r != NULL)
7793                                 r->ws->old_r = r->ws->r;
7794                         r->ws->r = NULL;
7795                         bar_cleanup(r);
7796                         TAILQ_REMOVE(&s->rl, r, entry);
7797                         TAILQ_INSERT_TAIL(&s->orl, r, entry);
7798                 }
7799         }
7800
7801         /* search old regions for one to reuse */
7802
7803         /* size + location match */
7804         TAILQ_FOREACH(r, &s->orl, entry)
7805                 if (X(r) == x && Y(r) == y &&
7806                     HEIGHT(r) == h && WIDTH(r) == w)
7807                         break;
7808
7809         /* size match */
7810         TAILQ_FOREACH(r, &s->orl, entry)
7811                 if (HEIGHT(r) == h && WIDTH(r) == w)
7812                         break;
7813
7814         if (r != NULL) {
7815                 TAILQ_REMOVE(&s->orl, r, entry);
7816                 /* try to use old region's workspace */
7817                 if (r->ws->r == NULL)
7818                         ws = r->ws;
7819         } else
7820                 if ((r = calloc(1, sizeof(struct swm_region))) == NULL)
7821                         err(1, "new_region: calloc: failed to allocate memory "
7822                             "for screen");
7823
7824         /* if we don't have a workspace already, find one */
7825         if (ws == NULL) {
7826                 for (i = 0; i < workspace_limit; i++)
7827                         if (s->ws[i].r == NULL) {
7828                                 ws = &s->ws[i];
7829                                 break;
7830                         }
7831         }
7832
7833         if (ws == NULL)
7834                 errx(1, "new_region: no free workspaces");
7835
7836         X(r) = x;
7837         Y(r) = y;
7838         WIDTH(r) = w;
7839         HEIGHT(r) = h;
7840         r->s = s;
7841         r->ws = ws;
7842         r->ws_prior = NULL;
7843         ws->r = r;
7844         outputs++;
7845         TAILQ_INSERT_TAIL(&s->rl, r, entry);
7846 }
7847
7848 void
7849 scan_xrandr(int i)
7850 {
7851 #ifdef SWM_XRR_HAS_CRTC
7852         int                                             c;
7853         int                                             ncrtc = 0;
7854 #endif /* SWM_XRR_HAS_CRTC */
7855         struct swm_region                               *r;
7856         int                                             num_screens;
7857         xcb_randr_get_screen_resources_current_cookie_t src;
7858         xcb_randr_get_screen_resources_current_reply_t  *srr;
7859         xcb_randr_get_crtc_info_cookie_t                cic;
7860         xcb_randr_get_crtc_info_reply_t                 *cir = NULL;
7861         xcb_randr_crtc_t                                *crtc;
7862         xcb_screen_t                                    *screen;
7863
7864         if ((screen = get_screen(i)) == NULL)
7865                 errx(1, "ERROR: can't get screen %d.", i);
7866
7867         num_screens = xcb_setup_roots_length(xcb_get_setup(conn));
7868         if (i >= num_screens)
7869                 errx(1, "scan_xrandr: invalid screen");
7870
7871         /* remove any old regions */
7872         while ((r = TAILQ_FIRST(&screens[i].rl)) != NULL) {
7873                 r->ws->old_r = r->ws->r = NULL;
7874                 bar_cleanup(r);
7875                 TAILQ_REMOVE(&screens[i].rl, r, entry);
7876                 TAILQ_INSERT_TAIL(&screens[i].orl, r, entry);
7877         }
7878         outputs = 0;
7879
7880         /* map virtual screens onto physical screens */
7881 #ifdef SWM_XRR_HAS_CRTC
7882         if (xrandr_support) {
7883                 src = xcb_randr_get_screen_resources_current(conn,
7884                     screens[i].root);
7885                 srr = xcb_randr_get_screen_resources_current_reply(conn, src,
7886                     NULL);
7887                 if (srr == NULL) {
7888                         new_region(&screens[i], 0, 0,
7889                             screen->width_in_pixels,
7890                             screen->height_in_pixels);
7891                         return;
7892                 } else
7893                         ncrtc = srr->num_crtcs;
7894
7895                 crtc = xcb_randr_get_screen_resources_current_crtcs(srr);
7896                 for (c = 0; c < ncrtc; c++) {
7897                         cic = xcb_randr_get_crtc_info(conn, crtc[c],
7898                             XCB_CURRENT_TIME);
7899                         cir = xcb_randr_get_crtc_info_reply(conn, cic, NULL);
7900                         if (cir == NULL)
7901                                 continue;
7902                         if (cir->num_outputs == 0) {
7903                                 free(cir);
7904                                 continue;
7905                         }
7906
7907                         if (cir->mode == 0)
7908                                 new_region(&screens[i], 0, 0,
7909                                     screen->width_in_pixels,
7910                                     screen->height_in_pixels);
7911                         else
7912                                 new_region(&screens[i],
7913                                     cir->x, cir->y, cir->width, cir->height);
7914                         free(cir);
7915                 }
7916                 free(srr);
7917         } else
7918 #endif /* SWM_XRR_HAS_CRTC */
7919         {
7920                 new_region(&screens[i], 0, 0, screen->width_in_pixels,
7921                     screen->height_in_pixels);
7922         }
7923 }
7924
7925 void
7926 screenchange(xcb_randr_screen_change_notify_event_t *e)
7927 {
7928         struct swm_region               *r;
7929         int                             i, num_screens;
7930
7931         DNPRINTF(SWM_D_EVENT, "screenchange: root: 0x%x\n", e->root);
7932
7933         num_screens = xcb_setup_roots_length(xcb_get_setup(conn));
7934         /* silly event doesn't include the screen index */
7935         for (i = 0; i < num_screens; i++)
7936                 if (screens[i].root == e->root)
7937                         break;
7938         if (i >= num_screens)
7939                 errx(1, "screenchange: screen not found");
7940
7941         /* brute force for now, just re-enumerate the regions */
7942         scan_xrandr(i);
7943
7944 #ifdef SWM_DEBUG
7945         print_win_geom(e->root);
7946 #endif
7947         /* add bars to all regions */
7948         for (i = 0; i < num_screens; i++)
7949                 TAILQ_FOREACH(r, &screens[i].rl, entry)
7950                         bar_setup(r);
7951         stack();
7952 }
7953
7954 void
7955 grab_windows(void)
7956 {
7957         xcb_window_t            *wins   = NULL;
7958         int                     no;
7959         int                     i, j, num_screens;
7960         uint16_t                state, manage, mapped;
7961
7962         xcb_query_tree_cookie_t                 qtc;
7963         xcb_query_tree_reply_t                  *qtr;
7964         xcb_get_window_attributes_cookie_t      c;
7965         xcb_get_window_attributes_reply_t       *r;
7966         xcb_get_property_cookie_t               pc;
7967
7968         DNPRINTF(SWM_D_INIT, "grab_windows: begin\n");
7969         num_screens = xcb_setup_roots_length(xcb_get_setup(conn));
7970         for (i = 0; i < num_screens; i++) {
7971                 qtc = xcb_query_tree(conn, screens[i].root);
7972                 qtr = xcb_query_tree_reply(conn, qtc, NULL);
7973                 if (!qtr)
7974                         continue;
7975                 wins = xcb_query_tree_children(qtr);
7976                 no = xcb_query_tree_children_length(qtr);
7977                 /* attach windows to a region */
7978                 /* normal windows */
7979                 for (j = 0; j < no; j++) {
7980                         c = xcb_get_window_attributes(conn, wins[j]);
7981                         r = xcb_get_window_attributes_reply(conn, c, NULL);
7982                         if (!r)
7983                                 continue;
7984                         if (r->override_redirect) {
7985                                 free(r);
7986                                 continue;
7987                         }
7988
7989                         pc = xcb_icccm_get_wm_transient_for(conn, wins[j]);
7990                         if (xcb_icccm_get_wm_transient_for_reply(conn, pc,
7991                             &wins[j], NULL)) {
7992                                 free(r);
7993                                 continue;
7994                         }
7995
7996                         state = getstate(wins[j]);
7997                         manage = state == XCB_ICCCM_WM_STATE_ICONIC;
7998                         mapped = r->map_state != XCB_MAP_STATE_UNMAPPED;
7999                         if (mapped || manage)
8000                                 manage_window(wins[j], mapped);
8001                         free(r);
8002                 }
8003                 /* transient windows */
8004                 for (j = 0; j < no; j++) {
8005                         c = xcb_get_window_attributes(conn, wins[j]);
8006                         r = xcb_get_window_attributes_reply(conn, c, NULL);
8007                         if (!r)
8008                                 continue;
8009                         if (r->override_redirect) {
8010                                 free(r);
8011                                 continue;
8012                         }
8013                         free(r);
8014
8015                         state = getstate(wins[j]);
8016                         manage = state == XCB_ICCCM_WM_STATE_ICONIC;
8017                         mapped = r->map_state != XCB_MAP_STATE_UNMAPPED;
8018                         pc = xcb_icccm_get_wm_transient_for(conn, wins[j]);
8019                         if (xcb_icccm_get_wm_transient_for_reply(conn, pc,
8020                             &wins[j], NULL) && manage)
8021                                 manage_window(wins[j], mapped);
8022                 }
8023                 free(qtr);
8024         }
8025         DNPRINTF(SWM_D_INIT, "grab_windows: done.\n");
8026 }
8027
8028 void
8029 setup_screens(void)
8030 {
8031         int                     i, j, k, num_screens;
8032         struct workspace        *ws;
8033         uint32_t                gcv[1], wa[1];
8034         const xcb_query_extension_reply_t *qep;
8035         xcb_screen_t                            *screen;
8036         xcb_cursor_t                            cursor;
8037         xcb_font_t                              cursor_font;
8038         xcb_randr_query_version_cookie_t        c;
8039         xcb_randr_query_version_reply_t         *r;
8040
8041         num_screens = xcb_setup_roots_length(xcb_get_setup(conn));
8042         if ((screens = calloc(num_screens,
8043              sizeof(struct swm_screen))) == NULL)
8044                 err(1, "setup_screens: calloc: failed to allocate memory for "
8045                     "screens");
8046
8047         /* initial Xrandr setup */
8048         xrandr_support = 0;
8049         qep = xcb_get_extension_data(conn, &xcb_randr_id);
8050         if (qep->present) {
8051                 c = xcb_randr_query_version(conn, 1, 1);
8052                 r = xcb_randr_query_version_reply(conn, c, NULL);
8053                 if (r) {
8054                         if (r->major_version >= 1) {
8055                                 xrandr_support = 1;
8056                                 xrandr_eventbase = qep->first_event;
8057                         }
8058                         free(r);
8059                 }
8060         }
8061
8062         cursor_font = xcb_generate_id(conn);
8063         xcb_open_font(conn, cursor_font, strlen("cursor"), "cursor");
8064
8065         cursor = xcb_generate_id(conn);
8066         xcb_create_glyph_cursor(conn, cursor, cursor_font, cursor_font,
8067             XC_left_ptr, XC_left_ptr + 1, 0, 0, 0, 0xffff, 0xffff, 0xffff);
8068         wa[0] = cursor;
8069
8070         /* map physical screens */
8071         for (i = 0; i < num_screens; i++) {
8072                 DNPRINTF(SWM_D_WS, "setup_screens: init screen: %d\n", i);
8073                 screens[i].idx = i;
8074                 TAILQ_INIT(&screens[i].rl);
8075                 TAILQ_INIT(&screens[i].orl);
8076                 if ((screen = get_screen(i)) == NULL)
8077                         errx(1, "ERROR: can't get screen %d.", i);
8078                 screens[i].root = screen->root;
8079
8080                 /* set default colors */
8081                 setscreencolor("red", i + 1, SWM_S_COLOR_FOCUS);
8082                 setscreencolor("rgb:88/88/88", i + 1, SWM_S_COLOR_UNFOCUS);
8083                 setscreencolor("rgb:00/80/80", i + 1, SWM_S_COLOR_BAR_BORDER);
8084                 setscreencolor("black", i + 1, SWM_S_COLOR_BAR);
8085                 setscreencolor("rgb:a0/a0/a0", i + 1, SWM_S_COLOR_BAR_FONT);
8086
8087                 /* create graphics context on screen */
8088                 screens[i].bar_gc = xcb_generate_id(conn);
8089                 gcv[0] = 0;
8090                 xcb_create_gc(conn, screens[i].bar_gc, screens[i].root,
8091                     XCB_GC_GRAPHICS_EXPOSURES, gcv);
8092
8093                 /* set default cursor */
8094                 xcb_change_window_attributes(conn, screens[i].root,
8095                     XCB_CW_CURSOR, wa);
8096
8097                 /* init all workspaces */
8098                 /* XXX these should be dynamically allocated too */
8099                 for (j = 0; j < SWM_WS_MAX; j++) {
8100                         ws = &screens[i].ws[j];
8101                         ws->idx = j;
8102                         ws->name = NULL;
8103                         ws->focus = NULL;
8104                         ws->r = NULL;
8105                         ws->old_r = NULL;
8106                         TAILQ_INIT(&ws->winlist);
8107                         TAILQ_INIT(&ws->unmanagedlist);
8108
8109                         for (k = 0; layouts[k].l_stack != NULL; k++)
8110                                 if (layouts[k].l_config != NULL)
8111                                         layouts[k].l_config(ws,
8112                                             SWM_ARG_ID_STACKINIT);
8113                         ws->cur_layout = &layouts[0];
8114                         ws->cur_layout->l_string(ws);
8115                 }
8116
8117                 scan_xrandr(i);
8118
8119                 if (xrandr_support)
8120                         xcb_randr_select_input(conn, screens[i].root,
8121                             XCB_RANDR_NOTIFY_MASK_SCREEN_CHANGE);
8122         }
8123         xcb_free_cursor(conn, cursor);
8124         xcb_close_font(conn, cursor_font);
8125 }
8126
8127 void
8128 setup_globals(void)
8129 {
8130         if ((bar_fonts = strdup(SWM_BAR_FONTS)) == NULL)
8131                 err(1, "setup_globals: strdup: failed to allocate memory.");
8132
8133         if ((clock_format = strdup("%a %b %d %R %Z %Y")) == NULL)
8134                 err(1, "setup_globals: strdup: failed to allocate memory.");
8135
8136         if ((syms = xcb_key_symbols_alloc(conn)) == NULL)
8137                 errx(1, "unable to allocate key symbols");
8138
8139         a_state = get_atom_from_string("WM_STATE");
8140         a_prot = get_atom_from_string("WM_PROTOCOLS");
8141         a_delete = get_atom_from_string("WM_DELETE_WINDOW");
8142         a_takefocus = get_atom_from_string("WM_TAKE_FOCUS");
8143         a_wmname = get_atom_from_string("WM_NAME");
8144         a_netwmname = get_atom_from_string("_NET_WM_NAME");
8145         a_utf8_string = get_atom_from_string("UTF8_STRING");
8146         a_string = get_atom_from_string("STRING");
8147         a_swm_iconic = get_atom_from_string("_SWM_ICONIC");
8148         a_swm_ws = get_atom_from_string("_SWM_WS");
8149 }
8150
8151 void
8152 workaround(void)
8153 {
8154         int                     i, num_screens;
8155         xcb_atom_t              netwmcheck;
8156         xcb_window_t            root, win;
8157
8158         /* work around sun jdk bugs, code from wmname */
8159         netwmcheck = get_atom_from_string("_NET_SUPPORTING_WM_CHECK");
8160
8161         num_screens = xcb_setup_roots_length(xcb_get_setup(conn));
8162         for (i = 0; i < num_screens; i++) {
8163                 root = screens[i].root;
8164
8165                 win = xcb_generate_id(conn);
8166                 xcb_create_window(conn, XCB_COPY_FROM_PARENT, win, root,
8167                     0, 0, 1, 1, 0, XCB_WINDOW_CLASS_INPUT_OUTPUT,
8168                     XCB_COPY_FROM_PARENT, 0, NULL);
8169
8170                 xcb_change_property(conn, XCB_PROP_MODE_REPLACE, root,
8171                     netwmcheck, XCB_ATOM_WINDOW, 32, 1, &win);
8172                 xcb_change_property(conn, XCB_PROP_MODE_REPLACE, win,
8173                     netwmcheck, XCB_ATOM_WINDOW, 32, 1, &win);
8174                 xcb_change_property(conn, XCB_PROP_MODE_REPLACE, win,
8175                     a_netwmname, a_utf8_string, 8, strlen("LG3D"), "LG3D");
8176         }
8177 }
8178
8179 void
8180 shutdown_cleanup(void)
8181 {
8182         int i, num_screens;
8183
8184         /* disable alarm because the following code may not be interrupted */
8185         alarm(0);
8186         if (signal(SIGALRM, SIG_IGN) == SIG_ERR)
8187                 err(1, "can't disable alarm");
8188
8189         bar_extra_stop();
8190         bar_extra = 1;
8191         unmap_all();
8192
8193         teardown_ewmh();
8194
8195         num_screens = xcb_setup_roots_length(xcb_get_setup(conn));
8196         for (i = 0; i < num_screens; ++i) {
8197                 if (screens[i].bar_gc != 0)
8198                         xcb_free_gc(conn, screens[i].bar_gc);
8199                 if (!bar_font_legacy)
8200                         XftColorFree(display, DefaultVisual(display, i),
8201                             DefaultColormap(display, i), &bar_font_color);
8202         }
8203
8204         if (bar_font_legacy)
8205                 XFreeFontSet(display, bar_fs);
8206         else {
8207                 XftFontClose(display, bar_font);
8208         }
8209
8210         xcb_key_symbols_free(syms);
8211         xcb_flush(conn);
8212         xcb_disconnect(conn);
8213 }
8214
8215 void
8216 event_error(xcb_generic_error_t *e)
8217 {
8218         (void)e;
8219
8220         DNPRINTF(SWM_D_EVENT, "event_error: %s(%u) from %s(%u), sequence: %u, "
8221             "resource_id: %u, minor_code: %u\n",
8222             xcb_event_get_error_label(e->error_code), e->error_code,
8223             xcb_event_get_request_label(e->major_code), e->major_code,
8224             e->sequence, e->resource_id, e->minor_code);
8225 }
8226
8227 void
8228 event_handle(xcb_generic_event_t *evt)
8229 {
8230         uint8_t type = XCB_EVENT_RESPONSE_TYPE(evt);
8231
8232         DNPRINTF(SWM_D_EVENT, "XCB Event: %s(%d), seq %u\n",
8233             xcb_event_get_label(XCB_EVENT_RESPONSE_TYPE(evt)),
8234             XCB_EVENT_RESPONSE_TYPE(evt), evt->sequence);
8235
8236         switch (type) {
8237 #define EVENT(type, callback) case type: callback((void *)evt); return
8238         EVENT(0, event_error);
8239         EVENT(XCB_BUTTON_PRESS, buttonpress);
8240         /*EVENT(XCB_BUTTON_RELEASE, buttonpress);*/
8241         /*EVENT(XCB_CIRCULATE_NOTIFY, );*/
8242         /*EVENT(XCB_CIRCULATE_REQUEST, );*/
8243         EVENT(XCB_CLIENT_MESSAGE, clientmessage);
8244         /*EVENT(XCB_COLORMAP_NOTIFY, );*/
8245         EVENT(XCB_CONFIGURE_NOTIFY, configurenotify);
8246         EVENT(XCB_CONFIGURE_REQUEST, configurerequest);
8247         /*EVENT(XCB_CREATE_NOTIFY, );*/
8248         EVENT(XCB_DESTROY_NOTIFY, destroynotify);
8249         EVENT(XCB_ENTER_NOTIFY, enternotify);
8250         EVENT(XCB_EXPOSE, expose);
8251 #ifdef SWM_DEBUG
8252         EVENT(XCB_FOCUS_IN, focusin);
8253         EVENT(XCB_FOCUS_OUT, focusout);
8254 #endif
8255         /*EVENT(XCB_GRAPHICS_EXPOSURE, );*/
8256         /*EVENT(XCB_GRAVITY_NOTIFY, );*/
8257         EVENT(XCB_KEY_PRESS, keypress);
8258         /*EVENT(XCB_KEY_RELEASE, keypress);*/
8259         /*EVENT(XCB_KEYMAP_NOTIFY, );*/
8260 #ifdef SWM_DEBUG
8261         EVENT(XCB_LEAVE_NOTIFY, leavenotify);
8262 #endif
8263         EVENT(XCB_MAP_NOTIFY, mapnotify);
8264         EVENT(XCB_MAP_REQUEST, maprequest);
8265         EVENT(XCB_MAPPING_NOTIFY, mappingnotify);
8266         /*EVENT(XCB_MOTION_NOTIFY, );*/
8267         /*EVENT(XCB_NO_EXPOSURE, );*/
8268         EVENT(XCB_PROPERTY_NOTIFY, propertynotify);
8269         /*EVENT(XCB_REPARENT_NOTIFY, );*/
8270         /*EVENT(XCB_RESIZE_REQUEST, );*/
8271         /*EVENT(XCB_SELECTION_CLEAR, );*/
8272         /*EVENT(XCB_SELECTION_NOTIFY, );*/
8273         /*EVENT(XCB_SELECTION_REQUEST, );*/
8274         EVENT(XCB_UNMAP_NOTIFY, unmapnotify);
8275         /*EVENT(XCB_VISIBILITY_NOTIFY, visibilitynotify);*/
8276 #undef EVENT
8277         }
8278         if (type - xrandr_eventbase == XCB_RANDR_SCREEN_CHANGE_NOTIFY)
8279                 screenchange((void *)evt);
8280 }
8281
8282 int
8283 main(int argc, char *argv[])
8284 {
8285         struct swm_region       *r, *rr;
8286         struct ws_win           *winfocus = NULL;
8287         char                    conf[PATH_MAX], *cfile = NULL;
8288         struct stat             sb;
8289         int                     xfd, i, num_screens;
8290         struct sigaction        sact;
8291         xcb_generic_event_t     *evt;
8292         struct timeval          tv;
8293         fd_set                  rd;
8294
8295         /* suppress unused warning since var is needed */
8296         (void)argc;
8297
8298         time_started = time(NULL);
8299
8300         start_argv = argv;
8301         warnx("Welcome to spectrwm V%s Build: %s", SPECTRWM_VERSION, buildstr);
8302         if (!setlocale(LC_CTYPE, "") || !setlocale(LC_TIME, ""))
8303                 warnx("no locale support");
8304
8305         /* handle some signals */
8306         bzero(&sact, sizeof(sact));
8307         sigemptyset(&sact.sa_mask);
8308         sact.sa_flags = 0;
8309         sact.sa_handler = sighdlr;
8310         sigaction(SIGINT, &sact, NULL);
8311         sigaction(SIGQUIT, &sact, NULL);
8312         sigaction(SIGTERM, &sact, NULL);
8313         sigaction(SIGHUP, &sact, NULL);
8314
8315         sact.sa_handler = sighdlr;
8316         sact.sa_flags = SA_NOCLDSTOP;
8317         sigaction(SIGCHLD, &sact, NULL);
8318
8319         if (!(display = XOpenDisplay(0)))
8320                 errx(1, "can not open display");
8321
8322         conn = XGetXCBConnection(display);
8323         if (xcb_connection_has_error(conn))
8324                 errx(1, "can not get XCB connection");
8325
8326         XSetEventQueueOwner(display, XCBOwnsEventQueue);
8327
8328         xcb_prefetch_extension_data(conn, &xcb_randr_id);
8329         xfd = xcb_get_file_descriptor(conn);
8330
8331         /* look for local and global conf file */
8332         pwd = getpwuid(getuid());
8333         if (pwd == NULL)
8334                 errx(1, "invalid user: %d", getuid());
8335
8336         xcb_grab_server(conn);
8337         xcb_aux_sync(conn);
8338
8339         /* flush all events */
8340         while ((evt = xcb_poll_for_event(conn))) {
8341                 if (XCB_EVENT_RESPONSE_TYPE(evt) == 0)
8342                         event_handle(evt);
8343                 free(evt);
8344         }
8345
8346         if (enable_wm() != 0)
8347                 errx(1, "another window manager is currently running");
8348
8349         xcb_aux_sync(conn);
8350
8351         setup_globals();
8352         setup_screens();
8353         setup_keys();
8354         setup_quirks();
8355         setup_spawn();
8356
8357         /* load config */
8358         for (i = 0; ; i++) {
8359                 conf[0] = '\0';
8360                 switch (i) {
8361                 case 0:
8362                         /* ~ */
8363                         snprintf(conf, sizeof conf, "%s/.%s",
8364                             pwd->pw_dir, SWM_CONF_FILE);
8365                         break;
8366                 case 1:
8367                         /* global */
8368                         snprintf(conf, sizeof conf, "/etc/%s",
8369                             SWM_CONF_FILE);
8370                         break;
8371                 case 2:
8372                         /* ~ compat */
8373                         snprintf(conf, sizeof conf, "%s/.%s",
8374                             pwd->pw_dir, SWM_CONF_FILE_OLD);
8375                         break;
8376                 case 3:
8377                         /* global compat */
8378                         snprintf(conf, sizeof conf, "/etc/%s",
8379                             SWM_CONF_FILE_OLD);
8380                         break;
8381                 default:
8382                         goto noconfig;
8383                 }
8384
8385                 if (strlen(conf) && stat(conf, &sb) != -1)
8386                         if (S_ISREG(sb.st_mode)) {
8387                                 cfile = conf;
8388                                 break;
8389                         }
8390         }
8391 noconfig:
8392
8393         /* load conf (if any) */
8394         if (cfile)
8395                 conf_load(cfile, SWM_CONF_DEFAULT);
8396
8397         setup_ewmh();
8398         /* set some values to work around bad programs */
8399         workaround();
8400         /* grab existing windows (before we build the bars) */
8401         grab_windows();
8402
8403         if (getenv("SWM_STARTED") == NULL)
8404                 setenv("SWM_STARTED", "YES", 1);
8405
8406         /* setup all bars */
8407         num_screens = xcb_setup_roots_length(xcb_get_setup(conn));
8408         for (i = 0; i < num_screens; i++)
8409                 TAILQ_FOREACH(r, &screens[i].rl, entry) {
8410                         if (winfocus == NULL)
8411                                 winfocus = TAILQ_FIRST(&r->ws->winlist);
8412                         bar_setup(r);
8413                 }
8414
8415         grabkeys();
8416         stack();
8417
8418         xcb_ungrab_server(conn);
8419         xcb_flush(conn);
8420
8421         while (running) {
8422                 while ((evt = xcb_poll_for_event(conn))) {
8423                         if (running == 0)
8424                                 goto done;
8425                         event_handle(evt);
8426                         free(evt);
8427                 }
8428
8429                 /* if we are being restarted go focus on first window */
8430                 if (winfocus) {
8431                         rr = winfocus->ws->r;
8432                         if (rr == NULL) {
8433                                 /* not a visible window */
8434                                 winfocus = NULL;
8435                                 continue;
8436                         }
8437                         /* move pointer to first screen if multi screen */
8438                         if (num_screens > 1 || outputs > 1)
8439                                 xcb_warp_pointer(conn, XCB_WINDOW_NONE,
8440                                     rr->s[0].root, 0, 0, 0, 0, X(rr),
8441                                     Y(rr) + (bar_enabled ? bar_height : 0));
8442
8443                         focus_win(get_region_focus(rr));
8444                         focus_flush();
8445                         winfocus = NULL;
8446                         continue;
8447                 }
8448
8449                 FD_ZERO(&rd);
8450                 FD_SET(xfd, &rd);
8451                 tv.tv_sec = 1;
8452                 tv.tv_usec = 0;
8453                 if (select(xfd + 1, &rd, NULL, NULL, &tv) == -1)
8454                         if (errno != EINTR) {
8455                                 DNPRINTF(SWM_D_MISC, "select failed");
8456                         }
8457                 if (restart_wm == 1)
8458                         restart(NULL, NULL);
8459                 if (search_resp == 1)
8460                         search_do_resp();
8461                 if (running == 0)
8462                         goto done;
8463                 if (bar_alarm) {
8464                         bar_alarm = 0;
8465                         bar_update();
8466                 }
8467         }
8468 done:
8469         shutdown_cleanup();
8470
8471         return (0);
8472 }