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