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