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