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