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