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