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