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