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