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