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