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