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