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