JasonWoof Got questions, comments, patches, etc.? Contact Jason Woofenden
Add xcb_flush to wkill().
[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         xcb_flush(conn);
4040 }
4041
4042
4043 int
4044 floating_toggle_win(struct ws_win *win)
4045 {
4046         struct swm_region       *r;
4047
4048         if (win == NULL)
4049                 return (0);
4050
4051         if (!win->ws->r)
4052                 return (0);
4053
4054         r = win->ws->r;
4055
4056         /* reject floating toggles in max stack mode */
4057         if (win->ws->cur_layout == &layouts[SWM_MAX_STACK])
4058                 return (0);
4059
4060         if (win->floating) {
4061                 if (!win->floatmaxed) {
4062                         /* retain position for refloat */
4063                         store_float_geom(win, r);
4064                 }
4065                 win->floating = 0;
4066         } else {
4067                 if (win->g_floatvalid) {
4068                         /* refloat at last floating relative position */
4069                         X(win) = win->g_float.x + X(r);
4070                         Y(win) = win->g_float.y + Y(r);
4071                         WIDTH(win) = win->g_float.w;
4072                         HEIGHT(win) = win->g_float.h;
4073                 }
4074                 win->floating = 1;
4075         }
4076
4077         ewmh_update_actions(win);
4078
4079         return (1);
4080 }
4081
4082 void
4083 floating_toggle(struct swm_region *r, union arg *args)
4084 {
4085         struct ws_win           *win = r->ws->focus;
4086         union arg               a;
4087
4088         if (win == NULL)
4089                 return;
4090
4091         ewmh_update_win_state(win, ewmh[_NET_WM_STATE_ABOVE].atom,
4092             _NET_WM_STATE_TOGGLE);
4093
4094         stack();
4095
4096         if (win == win->ws->focus) {
4097                 a.id = SWM_ARG_ID_FOCUSCUR;
4098                 focus(win->ws->r, &a);
4099         }
4100 }
4101
4102 void
4103 constrain_window(struct ws_win *win, struct swm_region *r, int resizable)
4104 {
4105         if (MAX_X(win) + BORDER(win) > MAX_X(r)) {
4106                 if (resizable)
4107                         WIDTH(win) = MAX_X(r) - X(win) - BORDER(win);
4108                 else
4109                         X(win) = MAX_X(r)- WIDTH(win) - BORDER(win);
4110         }
4111
4112         if (X(win) + BORDER(win) < X(r)) {
4113                 if (resizable)
4114                         WIDTH(win) -= X(r) - X(win) - BORDER(win);
4115
4116                 X(win) = X(r) - BORDER(win);
4117         }
4118
4119         if (MAX_Y(win) + BORDER(win) > MAX_Y(r)) {
4120                 if (resizable)
4121                         HEIGHT(win) = MAX_Y(r) - Y(win) - BORDER(win);
4122                 else
4123                         Y(win) = MAX_Y(r) - HEIGHT(win) - BORDER(win);
4124         }
4125
4126         if (Y(win) + BORDER(win) < Y(r)) {
4127                 if (resizable)
4128                         HEIGHT(win) -= Y(r) - Y(win) - BORDER(win);
4129
4130                 Y(win) = Y(r) - BORDER(win);
4131         }
4132
4133         if (resizable) {
4134                 if (WIDTH(win) < 1)
4135                         WIDTH(win) = 1;
4136                 if (HEIGHT(win) < 1)
4137                         HEIGHT(win) = 1;
4138         }
4139 }
4140
4141 void
4142 update_window(struct ws_win *win)
4143 {
4144         uint16_t        mask;
4145         uint32_t        wc[5];
4146
4147         mask = XCB_CONFIG_WINDOW_X | XCB_CONFIG_WINDOW_Y |
4148                 XCB_CONFIG_WINDOW_WIDTH | XCB_CONFIG_WINDOW_HEIGHT |
4149                 XCB_CONFIG_WINDOW_BORDER_WIDTH;
4150         wc[0] = X(win);
4151         wc[1] = Y(win);
4152         wc[2] = WIDTH(win);
4153         wc[3] = HEIGHT(win);
4154         wc[4] = BORDER(win);
4155
4156         DNPRINTF(SWM_D_EVENT, "update_window: window: 0x%x, (x,y) w x h: "
4157             "(%d,%d) %d x %d, bordered: %s\n", win->id, wc[0], wc[1], wc[2],
4158             wc[3], YESNO(win->bordered));
4159
4160         xcb_configure_window(conn, win->id, mask, wc);
4161 }
4162
4163 #define SWM_RESIZE_STEPS        (50)
4164
4165 void
4166 resize(struct ws_win *win, union arg *args)
4167 {
4168         xcb_timestamp_t         timestamp = 0;
4169         struct swm_region       *r = NULL;
4170         int                     resize_step = 0;
4171         struct swm_geometry     g;
4172         int                     top = 0, left = 0, resizing;
4173         int                     dx, dy;
4174         unsigned int            shape; /* cursor style */
4175         xcb_cursor_t            cursor;
4176         xcb_font_t              cursor_font;
4177         xcb_grab_pointer_cookie_t       gpc;
4178         xcb_grab_pointer_reply_t        *gpr;
4179         xcb_query_pointer_reply_t       *xpr;
4180         xcb_generic_event_t             *evt;
4181         xcb_motion_notify_event_t       *mne;
4182
4183         if (win == NULL)
4184                 return;
4185         r = win->ws->r;
4186
4187         if (win->ewmh_flags & EWMH_F_FULLSCREEN)
4188                 return;
4189
4190         DNPRINTF(SWM_D_EVENT, "resize: window: 0x%x, floating: %s, "
4191             "transient: 0x%x\n", win->id, YESNO(win->floating),
4192             win->transient);
4193
4194         if (!(win->transient != 0 || win->floating != 0))
4195                 return;
4196
4197         /* reject resizes in max mode for floaters (transient ok) */
4198         if (win->floatmaxed)
4199                 return;
4200
4201         win->manual = 1;
4202         ewmh_update_win_state(win, ewmh[_SWM_WM_STATE_MANUAL].atom,
4203             _NET_WM_STATE_ADD);
4204
4205         stack();
4206
4207         switch (args->id) {
4208         case SWM_ARG_ID_WIDTHSHRINK:
4209                 WIDTH(win) -= SWM_RESIZE_STEPS;
4210                 resize_step = 1;
4211                 break;
4212         case SWM_ARG_ID_WIDTHGROW:
4213                 WIDTH(win) += SWM_RESIZE_STEPS;
4214                 resize_step = 1;
4215                 break;
4216         case SWM_ARG_ID_HEIGHTSHRINK:
4217                 HEIGHT(win) -= SWM_RESIZE_STEPS;
4218                 resize_step = 1;
4219                 break;
4220         case SWM_ARG_ID_HEIGHTGROW:
4221                 HEIGHT(win) += SWM_RESIZE_STEPS;
4222                 resize_step = 1;
4223                 break;
4224         default:
4225                 break;
4226         }
4227         if (resize_step) {
4228                 constrain_window(win, r, 1);
4229                 update_window(win);
4230                 store_float_geom(win,r);
4231                 return;
4232         }
4233
4234         /* get cursor offset from window root */
4235         xpr = xcb_query_pointer_reply(conn, xcb_query_pointer(conn, win->id),
4236             NULL);
4237         if (!xpr)
4238                 return;
4239
4240         g = win->g;
4241
4242         if (xpr->win_x < WIDTH(win) / 2)
4243                 left = 1;
4244
4245         if (xpr->win_y < HEIGHT(win) / 2)
4246                 top = 1;
4247
4248         if (args->id == SWM_ARG_ID_CENTER)
4249                 shape = XC_sizing;
4250         else if (top)
4251                 shape = (left) ? XC_top_left_corner : XC_top_right_corner;
4252         else
4253                 shape = (left) ? XC_bottom_left_corner : XC_bottom_right_corner;
4254
4255         cursor_font = xcb_generate_id(conn);
4256         xcb_open_font(conn, cursor_font, strlen("cursor"), "cursor");
4257
4258         cursor = xcb_generate_id(conn);
4259         xcb_create_glyph_cursor(conn, cursor, cursor_font, cursor_font,
4260             shape, shape + 1, 0, 0, 0, 0xffff, 0xffff, 0xffff);
4261
4262         gpc = xcb_grab_pointer(conn, False, win->id, MOUSEMASK,
4263             XCB_GRAB_MODE_ASYNC, XCB_GRAB_MODE_ASYNC, XCB_WINDOW_NONE, cursor,
4264             XCB_CURRENT_TIME),
4265         gpr = xcb_grab_pointer_reply(conn, gpc, NULL);
4266         if (!gpr) {
4267                 xcb_free_cursor(conn, cursor);
4268                 xcb_close_font(conn, cursor_font);
4269                 free(xpr);
4270                 return;
4271         }
4272
4273         xcb_flush(conn);
4274         resizing = 1;
4275         while ((evt = xcb_wait_for_event(conn)) && resizing) {
4276                 /*
4277                 XMaskEvent(display, MOUSEMASK | ExposureMask |
4278                     SubstructureRedirectMask, &ev);
4279                 */
4280                 switch (XCB_EVENT_RESPONSE_TYPE(evt)) {
4281                 case XCB_BUTTON_RELEASE:
4282                         DNPRINTF(SWM_D_EVENT, "resize: BUTTON_RELEASE\n");
4283                         resizing = 0;
4284                         break;
4285                 case XCB_MOTION_NOTIFY:
4286                         mne = (xcb_motion_notify_event_t *)evt;
4287                         /* cursor offset/delta from start of the operation */
4288                         dx = mne->root_x - xpr->root_x;
4289                         dy = mne->root_y - xpr->root_y;
4290
4291                         /* vertical */
4292                         if (top)
4293                                 dy = -dy;
4294
4295                         if (args->id == SWM_ARG_ID_CENTER) {
4296                                 if (g.h / 2 + dy < 1)
4297                                         dy = 1 - g.h / 2;
4298
4299                                 Y(win) = g.y - dy;
4300                                 HEIGHT(win) = g.h + 2 * dy;
4301                         } else {
4302                                 if (g.h + dy < 1)
4303                                         dy = 1 - g.h;
4304
4305                                 if (top)
4306                                         Y(win) = g.y - dy;
4307
4308                                 HEIGHT(win) = g.h + dy;
4309                         }
4310
4311                         /* horizontal */
4312                         if (left)
4313                                 dx = -dx;
4314
4315                         if (args->id == SWM_ARG_ID_CENTER) {
4316                                 if (g.w / 2 + dx < 1)
4317                                         dx = 1 - g.w / 2;
4318
4319                                 X(win) = g.x - dx;
4320                                 WIDTH(win) = g.w + 2 * dx;
4321                         } else {
4322                                 if (g.w + dx < 1)
4323                                         dx = 1 - g.w;
4324
4325                                 if (left)
4326                                         X(win) = g.x - dx;
4327
4328                                 WIDTH(win) = g.w + dx;
4329                         }
4330
4331                         constrain_window(win, r, 1);
4332
4333                         /* not free, don't sync more than 120 times / second */
4334                         if ((mne->time - timestamp) > (1000 / 120) ) {
4335                                 timestamp = mne->time;
4336                                 do_sync();
4337                                 update_window(win);
4338                         }
4339                         break;
4340                 default:
4341                         event_handle(evt);
4342                         break;
4343                 }
4344                 free(evt);
4345         }
4346         if (timestamp) {
4347                 do_sync();
4348                 update_window(win);
4349         }
4350         store_float_geom(win,r);
4351
4352         xcb_ungrab_pointer(conn, XCB_CURRENT_TIME);
4353         xcb_free_cursor(conn, cursor);
4354         xcb_close_font(conn, cursor_font);
4355         free(gpr);
4356         free(xpr);
4357         DNPRINTF(SWM_D_EVENT, "resize: done\n");
4358 }
4359
4360 void
4361 resize_step(struct swm_region *r, union arg *args)
4362 {
4363         struct ws_win           *win = NULL;
4364
4365         if (r && r->ws && r->ws->focus)
4366                 win = r->ws->focus;
4367         else
4368                 return;
4369
4370         resize(win, args);
4371 }
4372
4373 #define SWM_MOVE_STEPS  (50)
4374
4375 void
4376 move(struct ws_win *win, union arg *args)
4377 {
4378         xcb_timestamp_t         timestamp = 0;
4379         int                     move_step = 0, moving;
4380         struct swm_region       *r = NULL;
4381         xcb_font_t                      cursor_font;
4382         xcb_cursor_t                    cursor;
4383         xcb_grab_pointer_cookie_t       gpc;
4384         xcb_grab_pointer_reply_t        *gpr;
4385         xcb_query_pointer_reply_t       *qpr;
4386         xcb_generic_event_t             *evt;
4387         xcb_motion_notify_event_t       *mne;
4388
4389         if (win == NULL)
4390                 return;
4391         r = win->ws->r;
4392
4393         if (win->ewmh_flags & EWMH_F_FULLSCREEN)
4394                 return;
4395
4396         DNPRINTF(SWM_D_EVENT, "move: window: 0x%x, floating: %s, transient: "
4397             "0x%x\n", win->id, YESNO(win->floating), win->transient);
4398
4399         /* in max_stack mode should only move transients */
4400         if (win->ws->cur_layout == &layouts[SWM_MAX_STACK] && !win->transient)
4401                 return;
4402
4403         win->manual = 1;
4404         if (win->floating == 0 && !win->transient) {
4405                 store_float_geom(win, r);
4406                 ewmh_update_win_state(win, ewmh[_NET_WM_STATE_ABOVE].atom,
4407                     _NET_WM_STATE_ADD);
4408         }
4409         ewmh_update_win_state(win, ewmh[_SWM_WM_STATE_MANUAL].atom,
4410             _NET_WM_STATE_ADD);
4411
4412         stack();
4413
4414         move_step = 0;
4415         switch (args->id) {
4416         case SWM_ARG_ID_MOVELEFT:
4417                 X(win) -= (SWM_MOVE_STEPS - border_width);
4418                 move_step = 1;
4419                 break;
4420         case SWM_ARG_ID_MOVERIGHT:
4421                 X(win) += (SWM_MOVE_STEPS - border_width);
4422                 move_step = 1;
4423                 break;
4424         case SWM_ARG_ID_MOVEUP:
4425                 Y(win) -= (SWM_MOVE_STEPS - border_width);
4426                 move_step = 1;
4427                 break;
4428         case SWM_ARG_ID_MOVEDOWN:
4429                 Y(win) += (SWM_MOVE_STEPS - border_width);
4430                 move_step = 1;
4431                 break;
4432         default:
4433                 break;
4434         }
4435         if (move_step) {
4436                 constrain_window(win, r, 0);
4437                 update_window(win);
4438                 store_float_geom(win, r);
4439                 return;
4440         }
4441
4442         cursor_font = xcb_generate_id(conn);
4443         xcb_open_font(conn, cursor_font, strlen("cursor"), "cursor");
4444
4445         cursor = xcb_generate_id(conn);
4446         xcb_create_glyph_cursor(conn, cursor, cursor_font, cursor_font,
4447                 XC_fleur, XC_fleur + 1, 0, 0, 0, 0xffff, 0xffff, 0xffff);
4448
4449         gpc = xcb_grab_pointer(conn, False, win->id, MOUSEMASK,
4450             XCB_GRAB_MODE_ASYNC, XCB_GRAB_MODE_ASYNC,
4451             XCB_WINDOW_NONE, cursor, XCB_CURRENT_TIME);
4452         gpr = xcb_grab_pointer_reply(conn, gpc, NULL);
4453         if (!gpr) {
4454                 xcb_free_cursor(conn, cursor);
4455                 xcb_close_font(conn, cursor_font);
4456                 return;
4457         }
4458
4459         /* get cursor offset from window root */
4460         qpr = xcb_query_pointer_reply(conn, xcb_query_pointer(conn, win->id),
4461                 NULL);
4462         if (!qpr) {
4463                 xcb_ungrab_pointer(conn, XCB_CURRENT_TIME);
4464                 xcb_free_cursor(conn, cursor);
4465                 xcb_close_font(conn, cursor_font);
4466                 return;
4467         }
4468
4469         xcb_flush(conn);
4470         moving = 1;
4471         while ((evt = xcb_wait_for_event(conn)) && moving) {
4472                 switch (XCB_EVENT_RESPONSE_TYPE(evt)) {
4473                 case XCB_BUTTON_RELEASE:
4474                         DNPRINTF(SWM_D_EVENT, "move: BUTTON_RELEASE\n");
4475                         moving = 0;
4476                         break;
4477                 case XCB_MOTION_NOTIFY:
4478                         mne = (xcb_motion_notify_event_t *)evt;
4479                         X(win) = mne->root_x - qpr->win_x - border_width;
4480                         Y(win) = mne->root_y - qpr->win_y - border_width;
4481
4482                         constrain_window(win, r, 0);
4483
4484                         /* not free, don't sync more than 120 times / second */
4485                         if ((mne->time - timestamp) > (1000 / 120) ) {
4486                                 timestamp = mne->time;
4487                                 do_sync();
4488                                 update_window(win);
4489                         }
4490                         break;
4491                 default:
4492                         event_handle(evt);
4493                         break;
4494                 }
4495                 free(evt);
4496         }
4497         if (timestamp) {
4498                 do_sync();
4499                 update_window(win);
4500         }
4501         store_float_geom(win, r);
4502         free(qpr);
4503         xcb_free_cursor(conn, cursor);
4504         xcb_close_font(conn, cursor_font);
4505         xcb_ungrab_pointer(conn, XCB_CURRENT_TIME);
4506         DNPRINTF(SWM_D_EVENT, "move: done\n");
4507 }
4508
4509 void
4510 move_step(struct swm_region *r, union arg *args)
4511 {
4512         struct ws_win           *win = NULL;
4513
4514         if (r && r->ws && r->ws->focus)
4515                 win = r->ws->focus;
4516         else
4517                 return;
4518
4519         if (!(win->transient != 0 || win->floating != 0))
4520                 return;
4521
4522         move(win, args);
4523 }
4524
4525
4526 /* user/key callable function IDs */
4527 enum keyfuncid {
4528         kf_cycle_layout,
4529         kf_flip_layout,
4530         kf_stack_reset,
4531         kf_master_shrink,
4532         kf_master_grow,
4533         kf_master_add,
4534         kf_master_del,
4535         kf_stack_inc,
4536         kf_stack_dec,
4537         kf_swap_main,
4538         kf_focus_next,
4539         kf_focus_prev,
4540         kf_swap_next,
4541         kf_swap_prev,
4542         kf_quit,
4543         kf_restart,
4544         kf_focus_main,
4545         kf_ws_1,
4546         kf_ws_2,
4547         kf_ws_3,
4548         kf_ws_4,
4549         kf_ws_5,
4550         kf_ws_6,
4551         kf_ws_7,
4552         kf_ws_8,
4553         kf_ws_9,
4554         kf_ws_10,
4555         kf_ws_11,
4556         kf_ws_12,
4557         kf_ws_13,
4558         kf_ws_14,
4559         kf_ws_15,
4560         kf_ws_16,
4561         kf_ws_17,
4562         kf_ws_18,
4563         kf_ws_19,
4564         kf_ws_20,
4565         kf_ws_21,
4566         kf_ws_22,
4567         kf_ws_next,
4568         kf_ws_prev,
4569         kf_ws_next_all,
4570         kf_ws_prev_all,
4571         kf_ws_prior,
4572         kf_screen_next,
4573         kf_screen_prev,
4574         kf_mvws_1,
4575         kf_mvws_2,
4576         kf_mvws_3,
4577         kf_mvws_4,
4578         kf_mvws_5,
4579         kf_mvws_6,
4580         kf_mvws_7,
4581         kf_mvws_8,
4582         kf_mvws_9,
4583         kf_mvws_10,
4584         kf_mvws_11,
4585         kf_mvws_12,
4586         kf_mvws_13,
4587         kf_mvws_14,
4588         kf_mvws_15,
4589         kf_mvws_16,
4590         kf_mvws_17,
4591         kf_mvws_18,
4592         kf_mvws_19,
4593         kf_mvws_20,
4594         kf_mvws_21,
4595         kf_mvws_22,
4596         kf_bar_toggle,
4597         kf_wind_kill,
4598         kf_wind_del,
4599         kf_float_toggle,
4600         kf_version,
4601         kf_spawn_custom,
4602         kf_iconify,
4603         kf_uniconify,
4604         kf_raise_toggle,
4605         kf_button2,
4606         kf_width_shrink,
4607         kf_width_grow,
4608         kf_height_shrink,
4609         kf_height_grow,
4610         kf_move_left,
4611         kf_move_right,
4612         kf_move_up,
4613         kf_move_down,
4614         kf_name_workspace,
4615         kf_search_workspace,
4616         kf_search_win,
4617         kf_dumpwins, /* MUST BE LAST */
4618         kf_invalid
4619 };
4620
4621 /* key definitions */
4622 void
4623 dummykeyfunc(struct swm_region *r, union arg *args)
4624 {
4625 };
4626
4627 struct keyfunc {
4628         char                    name[SWM_FUNCNAME_LEN];
4629         void                    (*func)(struct swm_region *r, union arg *);
4630         union arg               args;
4631 } keyfuncs[kf_invalid + 1] = {
4632         /* name                 function        argument */
4633         { "cycle_layout",       cycle_layout,   {0} },
4634         { "flip_layout",        stack_config,   {.id = SWM_ARG_ID_FLIPLAYOUT} },
4635         { "stack_reset",        stack_config,   {.id = SWM_ARG_ID_STACKRESET} },
4636         { "master_shrink",      stack_config,   {.id = SWM_ARG_ID_MASTERSHRINK} },
4637         { "master_grow",        stack_config,   {.id = SWM_ARG_ID_MASTERGROW} },
4638         { "master_add",         stack_config,   {.id = SWM_ARG_ID_MASTERADD} },
4639         { "master_del",         stack_config,   {.id = SWM_ARG_ID_MASTERDEL} },
4640         { "stack_inc",          stack_config,   {.id = SWM_ARG_ID_STACKINC} },
4641         { "stack_dec",          stack_config,   {.id = SWM_ARG_ID_STACKDEC} },
4642         { "swap_main",          swapwin,        {.id = SWM_ARG_ID_SWAPMAIN} },
4643         { "focus_next",         focus,          {.id = SWM_ARG_ID_FOCUSNEXT} },
4644         { "focus_prev",         focus,          {.id = SWM_ARG_ID_FOCUSPREV} },
4645         { "swap_next",          swapwin,        {.id = SWM_ARG_ID_SWAPNEXT} },
4646         { "swap_prev",          swapwin,        {.id = SWM_ARG_ID_SWAPPREV} },
4647         { "quit",               quit,           {0} },
4648         { "restart",            restart,        {0} },
4649         { "focus_main",         focus,          {.id = SWM_ARG_ID_FOCUSMAIN} },
4650         { "ws_1",               switchws,       {.id = 0} },
4651         { "ws_2",               switchws,       {.id = 1} },
4652         { "ws_3",               switchws,       {.id = 2} },
4653         { "ws_4",               switchws,       {.id = 3} },
4654         { "ws_5",               switchws,       {.id = 4} },
4655         { "ws_6",               switchws,       {.id = 5} },
4656         { "ws_7",               switchws,       {.id = 6} },
4657         { "ws_8",               switchws,       {.id = 7} },
4658         { "ws_9",               switchws,       {.id = 8} },
4659         { "ws_10",              switchws,       {.id = 9} },
4660         { "ws_11",              switchws,       {.id = 10} },
4661         { "ws_12",              switchws,       {.id = 11} },
4662         { "ws_13",              switchws,       {.id = 12} },
4663         { "ws_14",              switchws,       {.id = 13} },
4664         { "ws_15",              switchws,       {.id = 14} },
4665         { "ws_16",              switchws,       {.id = 15} },
4666         { "ws_17",              switchws,       {.id = 16} },
4667         { "ws_18",              switchws,       {.id = 17} },
4668         { "ws_19",              switchws,       {.id = 18} },
4669         { "ws_20",              switchws,       {.id = 19} },
4670         { "ws_21",              switchws,       {.id = 20} },
4671         { "ws_22",              switchws,       {.id = 21} },
4672         { "ws_next",            cyclews,        {.id = SWM_ARG_ID_CYCLEWS_UP} },
4673         { "ws_prev",            cyclews,        {.id = SWM_ARG_ID_CYCLEWS_DOWN} },
4674         { "ws_next_all",        cyclews,        {.id = SWM_ARG_ID_CYCLEWS_UP_ALL} },
4675         { "ws_prev_all",        cyclews,        {.id = SWM_ARG_ID_CYCLEWS_DOWN_ALL} },
4676         { "ws_prior",           priorws,        {0} },
4677         { "screen_next",        cyclescr,       {.id = SWM_ARG_ID_CYCLESC_UP} },
4678         { "screen_prev",        cyclescr,       {.id = SWM_ARG_ID_CYCLESC_DOWN} },
4679         { "mvws_1",             send_to_ws,     {.id = 0} },
4680         { "mvws_2",             send_to_ws,     {.id = 1} },
4681         { "mvws_3",             send_to_ws,     {.id = 2} },
4682         { "mvws_4",             send_to_ws,     {.id = 3} },
4683         { "mvws_5",             send_to_ws,     {.id = 4} },
4684         { "mvws_6",             send_to_ws,     {.id = 5} },
4685         { "mvws_7",             send_to_ws,     {.id = 6} },
4686         { "mvws_8",             send_to_ws,     {.id = 7} },
4687         { "mvws_9",             send_to_ws,     {.id = 8} },
4688         { "mvws_10",            send_to_ws,     {.id = 9} },
4689         { "mvws_11",            send_to_ws,     {.id = 10} },
4690         { "mvws_12",            send_to_ws,     {.id = 11} },
4691         { "mvws_13",            send_to_ws,     {.id = 12} },
4692         { "mvws_14",            send_to_ws,     {.id = 13} },
4693         { "mvws_15",            send_to_ws,     {.id = 14} },
4694         { "mvws_16",            send_to_ws,     {.id = 15} },
4695         { "mvws_17",            send_to_ws,     {.id = 16} },
4696         { "mvws_18",            send_to_ws,     {.id = 17} },
4697         { "mvws_19",            send_to_ws,     {.id = 18} },
4698         { "mvws_20",            send_to_ws,     {.id = 19} },
4699         { "mvws_21",            send_to_ws,     {.id = 20} },
4700         { "mvws_22",            send_to_ws,     {.id = 21} },
4701         { "bar_toggle",         bar_toggle,     {0} },
4702         { "wind_kill",          wkill,          {.id = SWM_ARG_ID_KILLWINDOW} },
4703         { "wind_del",           wkill,          {.id = SWM_ARG_ID_DELETEWINDOW} },
4704         { "float_toggle",       floating_toggle,{0} },
4705         { "version",            version,        {0} },
4706         { "spawn_custom",       dummykeyfunc,   {0} },
4707         { "iconify",            iconify,        {0} },
4708         { "uniconify",          uniconify,      {0} },
4709         { "raise_toggle",       raise_toggle,   {0} },
4710         { "button2",            pressbutton,    {2} },
4711         { "width_shrink",       resize_step,    {.id = SWM_ARG_ID_WIDTHSHRINK} },
4712         { "width_grow",         resize_step,    {.id = SWM_ARG_ID_WIDTHGROW} },
4713         { "height_shrink",      resize_step,    {.id = SWM_ARG_ID_HEIGHTSHRINK} },
4714         { "height_grow",        resize_step,    {.id = SWM_ARG_ID_HEIGHTGROW} },
4715         { "move_left",          move_step,      {.id = SWM_ARG_ID_MOVELEFT} },
4716         { "move_right",         move_step,      {.id = SWM_ARG_ID_MOVERIGHT} },
4717         { "move_up",            move_step,      {.id = SWM_ARG_ID_MOVEUP} },
4718         { "move_down",          move_step,      {.id = SWM_ARG_ID_MOVEDOWN} },
4719         { "name_workspace",     name_workspace, {0} },
4720         { "search_workspace",   search_workspace,       {0} },
4721         { "search_win",         search_win,     {0} },
4722         { "dumpwins",           dumpwins,       {0} }, /* MUST BE LAST */
4723         { "invalid key func",   NULL,           {0} },
4724 };
4725 struct key {
4726         RB_ENTRY(key)           entry;
4727         unsigned int            mod;
4728         KeySym                  keysym;
4729         enum keyfuncid          funcid;
4730         char                    *spawn_name;
4731 };
4732 RB_HEAD(key_tree, key);
4733
4734 int
4735 key_cmp(struct key *kp1, struct key *kp2)
4736 {
4737         if (kp1->keysym < kp2->keysym)
4738                 return (-1);
4739         if (kp1->keysym > kp2->keysym)
4740                 return (1);
4741
4742         if (kp1->mod < kp2->mod)
4743                 return (-1);
4744         if (kp1->mod > kp2->mod)
4745                 return (1);
4746
4747         return (0);
4748 }
4749
4750 RB_GENERATE(key_tree, key, entry, key_cmp);
4751 struct key_tree                 keys;
4752
4753 /* mouse */
4754 enum { client_click, root_click };
4755 struct button {
4756         unsigned int            action;
4757         unsigned int            mask;
4758         unsigned int            button;
4759         void                    (*func)(struct ws_win *, union arg *);
4760         union arg               args;
4761 } buttons[] = {
4762           /* action     key             mouse button    func    args */
4763         { client_click, MODKEY,         Button3,        resize, {.id = SWM_ARG_ID_DONTCENTER} },
4764         { client_click, MODKEY | ShiftMask, Button3,    resize, {.id = SWM_ARG_ID_CENTER} },
4765         { client_click, MODKEY,         Button1,        move,   {0} },
4766 };
4767
4768 void
4769 update_modkey(unsigned int mod)
4770 {
4771         int                     i;
4772         struct key              *kp;
4773
4774         mod_key = mod;
4775         RB_FOREACH(kp, key_tree, &keys)
4776                 if (kp->mod & ShiftMask)
4777                         kp->mod = mod | ShiftMask;
4778                 else
4779                         kp->mod = mod;
4780
4781         for (i = 0; i < LENGTH(buttons); i++)
4782                 if (buttons[i].mask & ShiftMask)
4783                         buttons[i].mask = mod | ShiftMask;
4784                 else
4785                         buttons[i].mask = mod;
4786 }
4787
4788 /* spawn */
4789 struct spawn_prog {
4790         TAILQ_ENTRY(spawn_prog) entry;
4791         char                    *name;
4792         int                     argc;
4793         char                    **argv;
4794 };
4795 TAILQ_HEAD(spawn_list, spawn_prog);
4796 struct spawn_list               spawns = TAILQ_HEAD_INITIALIZER(spawns);
4797
4798 int
4799 spawn_expand(struct swm_region *r, union arg *args, char *spawn_name,
4800     char ***ret_args)
4801 {
4802         struct spawn_prog       *prog = NULL;
4803         int                     i;
4804         char                    *ap, **real_args;
4805
4806         DNPRINTF(SWM_D_SPAWN, "spawn_expand: %s\n", spawn_name);
4807
4808         /* find program */
4809         TAILQ_FOREACH(prog, &spawns, entry) {
4810                 if (!strcasecmp(spawn_name, prog->name))
4811                         break;
4812         }
4813         if (prog == NULL) {
4814                 warnx("spawn_custom: program %s not found", spawn_name);
4815                 return (-1);
4816         }
4817
4818         /* make room for expanded args */
4819         if ((real_args = calloc(prog->argc + 1, sizeof(char *))) == NULL)
4820                 err(1, "spawn_custom: calloc real_args");
4821
4822         /* expand spawn_args into real_args */
4823         for (i = 0; i < prog->argc; i++) {
4824                 ap = prog->argv[i];
4825                 DNPRINTF(SWM_D_SPAWN, "spawn_custom: raw arg: %s\n", ap);
4826                 if (!strcasecmp(ap, "$bar_border")) {
4827                         if ((real_args[i] =
4828                             strdup(r->s->c[SWM_S_COLOR_BAR_BORDER].name))
4829                             == NULL)
4830                                 err(1,  "spawn_custom border color");
4831                 } else if (!strcasecmp(ap, "$bar_color")) {
4832                         if ((real_args[i] =
4833                             strdup(r->s->c[SWM_S_COLOR_BAR].name))
4834                             == NULL)
4835                                 err(1, "spawn_custom bar color");
4836                 } else if (!strcasecmp(ap, "$bar_font")) {
4837                         if ((real_args[i] = strdup(bar_fonts))
4838                             == NULL)
4839                                 err(1, "spawn_custom bar fonts");
4840                 } else if (!strcasecmp(ap, "$bar_font_color")) {
4841                         if ((real_args[i] =
4842                             strdup(r->s->c[SWM_S_COLOR_BAR_FONT].name))
4843                             == NULL)
4844                                 err(1, "spawn_custom color font");
4845                 } else if (!strcasecmp(ap, "$color_focus")) {
4846                         if ((real_args[i] =
4847                             strdup(r->s->c[SWM_S_COLOR_FOCUS].name))
4848                             == NULL)
4849                                 err(1, "spawn_custom color focus");
4850                 } else if (!strcasecmp(ap, "$color_unfocus")) {
4851                         if ((real_args[i] =
4852                             strdup(r->s->c[SWM_S_COLOR_UNFOCUS].name))
4853                             == NULL)
4854                                 err(1, "spawn_custom color unfocus");
4855                 } else {
4856                         /* no match --> copy as is */
4857                         if ((real_args[i] = strdup(ap)) == NULL)
4858                                 err(1, "spawn_custom strdup(ap)");
4859                 }
4860                 DNPRINTF(SWM_D_SPAWN, "spawn_custom: cooked arg: %s\n",
4861                     real_args[i]);
4862         }
4863
4864 #ifdef SWM_DEBUG
4865         DNPRINTF(SWM_D_SPAWN, "spawn_custom: result: ");
4866         for (i = 0; i < prog->argc; i++)
4867                 DNPRINTF(SWM_D_SPAWN, "\"%s\" ", real_args[i]);
4868         DNPRINTF(SWM_D_SPAWN, "\n");
4869 #endif
4870         *ret_args = real_args;
4871         return (prog->argc);
4872 }
4873
4874 void
4875 spawn_custom(struct swm_region *r, union arg *args, char *spawn_name)
4876 {
4877         union arg               a;
4878         char                    **real_args;
4879         int                     spawn_argc, i;
4880
4881         if ((spawn_argc = spawn_expand(r, args, spawn_name, &real_args)) < 0)
4882                 return;
4883         a.argv = real_args;
4884         if (fork() == 0)
4885                 spawn(r->ws->idx, &a, 1);
4886
4887         for (i = 0; i < spawn_argc; i++)
4888                 free(real_args[i]);
4889         free(real_args);
4890 }
4891
4892 void
4893 spawn_select(struct swm_region *r, union arg *args, char *spawn_name, int *pid)
4894 {
4895         union arg               a;
4896         char                    **real_args;
4897         int                     i, spawn_argc;
4898
4899         if ((spawn_argc = spawn_expand(r, args, spawn_name, &real_args)) < 0)
4900                 return;
4901         a.argv = real_args;
4902
4903         if (pipe(select_list_pipe) == -1)
4904                 err(1, "pipe error");
4905         if (pipe(select_resp_pipe) == -1)
4906                 err(1, "pipe error");
4907
4908         if (signal(SIGPIPE, SIG_IGN) == SIG_ERR)
4909                 err(1, "could not disable SIGPIPE");
4910         switch (*pid = fork()) {
4911         case -1:
4912                 err(1, "cannot fork");
4913                 break;
4914         case 0: /* child */
4915                 if (dup2(select_list_pipe[0], 0) == -1)
4916                         err(1, "dup2");
4917                 if (dup2(select_resp_pipe[1], 1) == -1)
4918                         err(1, "dup2");
4919                 close(select_list_pipe[1]);
4920                 close(select_resp_pipe[0]);
4921                 spawn(r->ws->idx, &a, 0);
4922                 break;
4923         default: /* parent */
4924                 close(select_list_pipe[0]);
4925                 close(select_resp_pipe[1]);
4926                 break;
4927         }
4928
4929         for (i = 0; i < spawn_argc; i++)
4930                 free(real_args[i]);
4931         free(real_args);
4932 }
4933
4934 void
4935 spawn_insert(char *name, char *args)
4936 {
4937         char                    *arg, *cp, *ptr;
4938         struct spawn_prog       *sp;
4939
4940         DNPRINTF(SWM_D_SPAWN, "spawn_insert: %s\n", name);
4941
4942         if ((sp = calloc(1, sizeof *sp)) == NULL)
4943                 err(1, "spawn_insert: malloc");
4944         if ((sp->name = strdup(name)) == NULL)
4945                 err(1, "spawn_insert: strdup");
4946
4947         /* convert the arguments to an argument list */
4948         if ((ptr = cp = strdup(args)) == NULL)
4949                 err(1, "spawn_insert: strdup");
4950         while ((arg = strsep(&ptr, " \t")) != NULL) {
4951                 /* empty field; skip it */
4952                 if (*arg == '\0')
4953                         continue;
4954
4955                 sp->argc++;
4956                 if ((sp->argv = realloc(sp->argv, sp->argc *
4957                     sizeof *sp->argv)) == NULL)
4958                         err(1, "spawn_insert: realloc");
4959                 if ((sp->argv[sp->argc - 1] = strdup(arg)) == NULL)
4960                         err(1, "spawn_insert: strdup");
4961         }
4962         free(cp);
4963
4964         TAILQ_INSERT_TAIL(&spawns, sp, entry);
4965         DNPRINTF(SWM_D_SPAWN, "spawn_insert: leave\n");
4966 }
4967
4968 void
4969 spawn_remove(struct spawn_prog *sp)
4970 {
4971         int                     i;
4972
4973         DNPRINTF(SWM_D_SPAWN, "spawn_remove: %s\n", sp->name);
4974
4975         TAILQ_REMOVE(&spawns, sp, entry);
4976         for (i = 0; i < sp->argc; i++)
4977                 free(sp->argv[i]);
4978         free(sp->argv);
4979         free(sp->name);
4980         free(sp);
4981
4982         DNPRINTF(SWM_D_SPAWN, "spawn_remove: leave\n");
4983 }
4984
4985 void
4986 spawn_replace(struct spawn_prog *sp, char *name, char *args)
4987 {
4988         DNPRINTF(SWM_D_SPAWN, "spawn_replace: %s [%s]\n", sp->name, name);
4989
4990         spawn_remove(sp);
4991         spawn_insert(name, args);
4992
4993         DNPRINTF(SWM_D_SPAWN, "spawn_replace: leave\n");
4994 }
4995
4996 void
4997 setspawn(char *name, char *args)
4998 {
4999         struct spawn_prog       *sp;
5000
5001         DNPRINTF(SWM_D_SPAWN, "setspawn: %s\n", name);
5002
5003         if (name == NULL)
5004                 return;
5005
5006         TAILQ_FOREACH(sp, &spawns, entry) {
5007                 if (!strcmp(sp->name, name)) {
5008                         if (*args == '\0')
5009                                 spawn_remove(sp);
5010                         else
5011                                 spawn_replace(sp, name, args);
5012                         DNPRINTF(SWM_D_SPAWN, "setspawn: leave\n");
5013                         return;
5014                 }
5015         }
5016         if (*args == '\0') {
5017                 warnx("error: setspawn: cannot find program: %s", name);
5018                 return;
5019         }
5020
5021         spawn_insert(name, args);
5022         DNPRINTF(SWM_D_SPAWN, "setspawn: leave\n");
5023 }
5024
5025 int
5026 setconfspawn(char *selector, char *value, int flags)
5027 {
5028         DNPRINTF(SWM_D_SPAWN, "setconfspawn: [%s] [%s]\n", selector, value);
5029
5030         setspawn(selector, value);
5031
5032         DNPRINTF(SWM_D_SPAWN, "setconfspawn: done\n");
5033         return (0);
5034 }
5035
5036 void
5037 setup_spawn(void)
5038 {
5039         setconfspawn("term",            "xterm",                0);
5040         setconfspawn("spawn_term",      "xterm",                0);
5041         setconfspawn("screenshot_all",  "screenshot.sh full",   0);
5042         setconfspawn("screenshot_wind", "screenshot.sh window", 0);
5043         setconfspawn("lock",            "xlock",                0);
5044         setconfspawn("initscr",         "initscreen.sh",        0);
5045         setconfspawn("menu",            "dmenu_run"
5046                                         " -fn $bar_font"
5047                                         " -nb $bar_color"
5048                                         " -nf $bar_font_color"
5049                                         " -sb $bar_border"
5050                                         " -sf $bar_color",      0);
5051         setconfspawn("search",          "dmenu"
5052                                         " -i"
5053                                         " -fn $bar_font"
5054                                         " -nb $bar_color"
5055                                         " -nf $bar_font_color"
5056                                         " -sb $bar_border"
5057                                         " -sf $bar_color",      0);
5058         setconfspawn("name_workspace",  "dmenu"
5059                                         " -p Workspace"
5060                                         " -fn $bar_font"
5061                                         " -nb $bar_color"
5062                                         " -nf $bar_font_color"
5063                                         " -sb $bar_border"
5064                                         " -sf $bar_color",      0);
5065 }
5066
5067 /* key bindings */
5068 #define SWM_MODNAME_SIZE        32
5069 #define SWM_KEY_WS              "\n+ \t"
5070 int
5071 parsekeys(char *keystr, unsigned int currmod, unsigned int *mod, KeySym *ks)
5072 {
5073         char                    *cp, *name;
5074         KeySym                  uks;
5075         DNPRINTF(SWM_D_KEY, "parsekeys: enter [%s]\n", keystr);
5076         if (mod == NULL || ks == NULL) {
5077                 DNPRINTF(SWM_D_KEY, "parsekeys: no mod or key vars\n");
5078                 return (1);
5079         }
5080         if (keystr == NULL || strlen(keystr) == 0) {
5081                 DNPRINTF(SWM_D_KEY, "parsekeys: no keystr\n");
5082                 return (1);
5083         }
5084         cp = keystr;
5085         *ks = NoSymbol;
5086         *mod = 0;
5087         while ((name = strsep(&cp, SWM_KEY_WS)) != NULL) {
5088                 DNPRINTF(SWM_D_KEY, "parsekeys: key [%s]\n", name);
5089                 if (cp)
5090                         cp += (long)strspn(cp, SWM_KEY_WS);
5091                 if (strncasecmp(name, "MOD", SWM_MODNAME_SIZE) == 0)
5092                         *mod |= currmod;
5093                 else if (!strncasecmp(name, "Mod1", SWM_MODNAME_SIZE))
5094                         *mod |= Mod1Mask;
5095                 else if (!strncasecmp(name, "Mod2", SWM_MODNAME_SIZE))
5096                         *mod += Mod2Mask;
5097                 else if (!strncmp(name, "Mod3", SWM_MODNAME_SIZE))
5098                         *mod |= Mod3Mask;
5099                 else if (!strncmp(name, "Mod4", SWM_MODNAME_SIZE))
5100                         *mod |= Mod4Mask;
5101                 else if (strncasecmp(name, "SHIFT", SWM_MODNAME_SIZE) == 0)
5102                         *mod |= ShiftMask;
5103                 else if (strncasecmp(name, "CONTROL", SWM_MODNAME_SIZE) == 0)
5104                         *mod |= ControlMask;
5105                 else {
5106                         *ks = XStringToKeysym(name);
5107                         XConvertCase(*ks, ks, &uks);
5108                         if (ks == NoSymbol) {
5109                                 DNPRINTF(SWM_D_KEY,
5110                                     "parsekeys: invalid key %s\n",
5111                                     name);
5112                                 return (1);
5113                         }
5114                 }
5115         }
5116         DNPRINTF(SWM_D_KEY, "parsekeys: leave ok\n");
5117         return (0);
5118 }
5119
5120 char *
5121 strdupsafe(char *str)
5122 {
5123         if (str == NULL)
5124                 return (NULL);
5125         else
5126                 return (strdup(str));
5127 }
5128
5129 void
5130 key_insert(unsigned int mod, KeySym ks, enum keyfuncid kfid, char *spawn_name)
5131 {
5132         struct key              *kp;
5133
5134         DNPRINTF(SWM_D_KEY, "key_insert: enter %s [%s]\n",
5135             keyfuncs[kfid].name, spawn_name);
5136
5137         if ((kp = malloc(sizeof *kp)) == NULL)
5138                 err(1, "key_insert: malloc");
5139
5140         kp->mod = mod;
5141         kp->keysym = ks;
5142         kp->funcid = kfid;
5143         kp->spawn_name = strdupsafe(spawn_name);
5144         RB_INSERT(key_tree, &keys, kp);
5145
5146         DNPRINTF(SWM_D_KEY, "key_insert: leave\n");
5147 }
5148
5149 struct key *
5150 key_lookup(unsigned int mod, KeySym ks)
5151 {
5152         struct key              kp;
5153
5154         kp.keysym = ks;
5155         kp.mod = mod;
5156
5157         return (RB_FIND(key_tree, &keys, &kp));
5158 }
5159
5160 void
5161 key_remove(struct key *kp)
5162 {
5163         DNPRINTF(SWM_D_KEY, "key_remove: %s\n", keyfuncs[kp->funcid].name);
5164
5165         RB_REMOVE(key_tree, &keys, kp);
5166         free(kp->spawn_name);
5167         free(kp);
5168
5169         DNPRINTF(SWM_D_KEY, "key_remove: leave\n");
5170 }
5171
5172 void
5173 key_replace(struct key *kp, unsigned int mod, KeySym ks, enum keyfuncid kfid,
5174     char *spawn_name)
5175 {
5176         DNPRINTF(SWM_D_KEY, "key_replace: %s [%s]\n", keyfuncs[kp->funcid].name,
5177             spawn_name);
5178
5179         key_remove(kp);
5180         key_insert(mod, ks, kfid, spawn_name);
5181
5182         DNPRINTF(SWM_D_KEY, "key_replace: leave\n");
5183 }
5184
5185 void
5186 setkeybinding(unsigned int mod, KeySym ks, enum keyfuncid kfid,
5187     char *spawn_name)
5188 {
5189         struct key              *kp;
5190
5191         DNPRINTF(SWM_D_KEY, "setkeybinding: enter %s [%s]\n",
5192             keyfuncs[kfid].name, spawn_name);
5193
5194         if ((kp = key_lookup(mod, ks)) != NULL) {
5195                 if (kfid == kf_invalid)
5196                         key_remove(kp);
5197                 else
5198                         key_replace(kp, mod, ks, kfid, spawn_name);
5199                 DNPRINTF(SWM_D_KEY, "setkeybinding: leave\n");
5200                 return;
5201         }
5202         if (kfid == kf_invalid) {
5203                 warnx("error: setkeybinding: cannot find mod/key combination");
5204                 DNPRINTF(SWM_D_KEY, "setkeybinding: leave\n");
5205                 return;
5206         }
5207
5208         key_insert(mod, ks, kfid, spawn_name);
5209         DNPRINTF(SWM_D_KEY, "setkeybinding: leave\n");
5210 }
5211
5212 int
5213 setconfbinding(char *selector, char *value, int flags)
5214 {
5215         enum keyfuncid          kfid;
5216         unsigned int            mod;
5217         KeySym                  ks;
5218         struct spawn_prog       *sp;
5219         DNPRINTF(SWM_D_KEY, "setconfbinding: enter\n");
5220         if (selector == NULL) {
5221                 DNPRINTF(SWM_D_KEY, "setconfbinding: unbind %s\n", value);
5222                 if (parsekeys(value, mod_key, &mod, &ks) == 0) {
5223                         kfid = kf_invalid;
5224                         setkeybinding(mod, ks, kfid, NULL);
5225                         return (0);
5226                 } else
5227                         return (1);
5228         }
5229         /* search by key function name */
5230         for (kfid = 0; kfid < kf_invalid; (kfid)++) {
5231                 if (strncasecmp(selector, keyfuncs[kfid].name,
5232                     SWM_FUNCNAME_LEN) == 0) {
5233                         DNPRINTF(SWM_D_KEY, "setconfbinding: %s: match\n",
5234                             selector);
5235                         if (parsekeys(value, mod_key, &mod, &ks) == 0) {
5236                                 setkeybinding(mod, ks, kfid, NULL);
5237                                 return (0);
5238                         } else
5239                                 return (1);
5240                 }
5241         }
5242         /* search by custom spawn name */
5243         TAILQ_FOREACH(sp, &spawns, entry) {
5244                 if (strcasecmp(selector, sp->name) == 0) {
5245                         DNPRINTF(SWM_D_KEY, "setconfbinding: %s: match\n",
5246                             selector);
5247                         if (parsekeys(value, mod_key, &mod, &ks) == 0) {
5248                                 setkeybinding(mod, ks, kf_spawn_custom,
5249                                     sp->name);
5250                                 return (0);
5251                         } else
5252                                 return (1);
5253                 }
5254         }
5255         DNPRINTF(SWM_D_KEY, "setconfbinding: no match\n");
5256         return (1);
5257 }
5258
5259 void
5260 setup_keys(void)
5261 {
5262         setkeybinding(MODKEY,           XK_space,       kf_cycle_layout,NULL);
5263         setkeybinding(MODKEY|ShiftMask, XK_backslash,   kf_flip_layout, NULL);
5264         setkeybinding(MODKEY|ShiftMask, XK_space,       kf_stack_reset, NULL);
5265         setkeybinding(MODKEY,           XK_h,           kf_master_shrink,NULL);
5266         setkeybinding(MODKEY,           XK_l,           kf_master_grow, NULL);
5267         setkeybinding(MODKEY,           XK_comma,       kf_master_add,  NULL);
5268         setkeybinding(MODKEY,           XK_period,      kf_master_del,  NULL);
5269         setkeybinding(MODKEY|ShiftMask, XK_comma,       kf_stack_inc,   NULL);
5270         setkeybinding(MODKEY|ShiftMask, XK_period,      kf_stack_dec,   NULL);
5271         setkeybinding(MODKEY,           XK_Return,      kf_swap_main,   NULL);
5272         setkeybinding(MODKEY,           XK_j,           kf_focus_next,  NULL);
5273         setkeybinding(MODKEY,           XK_k,           kf_focus_prev,  NULL);
5274         setkeybinding(MODKEY|ShiftMask, XK_j,           kf_swap_next,   NULL);
5275         setkeybinding(MODKEY|ShiftMask, XK_k,           kf_swap_prev,   NULL);
5276         setkeybinding(MODKEY|ShiftMask, XK_Return,      kf_spawn_custom,"term");
5277         setkeybinding(MODKEY,           XK_p,           kf_spawn_custom,"menu");
5278         setkeybinding(MODKEY|ShiftMask, XK_q,           kf_quit,        NULL);
5279         setkeybinding(MODKEY,           XK_q,           kf_restart,     NULL);
5280         setkeybinding(MODKEY,           XK_m,           kf_focus_main,  NULL);
5281         setkeybinding(MODKEY,           XK_1,           kf_ws_1,        NULL);
5282         setkeybinding(MODKEY,           XK_2,           kf_ws_2,        NULL);
5283         setkeybinding(MODKEY,           XK_3,           kf_ws_3,        NULL);
5284         setkeybinding(MODKEY,           XK_4,           kf_ws_4,        NULL);
5285         setkeybinding(MODKEY,           XK_5,           kf_ws_5,        NULL);
5286         setkeybinding(MODKEY,           XK_6,           kf_ws_6,        NULL);
5287         setkeybinding(MODKEY,           XK_7,           kf_ws_7,        NULL);
5288         setkeybinding(MODKEY,           XK_8,           kf_ws_8,        NULL);
5289         setkeybinding(MODKEY,           XK_9,           kf_ws_9,        NULL);
5290         setkeybinding(MODKEY,           XK_0,           kf_ws_10,       NULL);
5291         setkeybinding(MODKEY,           XK_F1,          kf_ws_11,       NULL);
5292         setkeybinding(MODKEY,           XK_F2,          kf_ws_12,       NULL);
5293         setkeybinding(MODKEY,           XK_F3,          kf_ws_13,       NULL);
5294         setkeybinding(MODKEY,           XK_F4,          kf_ws_14,       NULL);
5295         setkeybinding(MODKEY,           XK_F5,          kf_ws_15,       NULL);
5296         setkeybinding(MODKEY,           XK_F6,          kf_ws_16,       NULL);
5297         setkeybinding(MODKEY,           XK_F7,          kf_ws_17,       NULL);
5298         setkeybinding(MODKEY,           XK_F8,          kf_ws_18,       NULL);
5299         setkeybinding(MODKEY,           XK_F9,          kf_ws_19,       NULL);
5300         setkeybinding(MODKEY,           XK_F10,         kf_ws_20,       NULL);
5301         setkeybinding(MODKEY,           XK_F11,         kf_ws_21,       NULL);
5302         setkeybinding(MODKEY,           XK_F12,         kf_ws_22,       NULL);
5303         setkeybinding(MODKEY,           XK_Right,       kf_ws_next,     NULL);
5304         setkeybinding(MODKEY,           XK_Left,        kf_ws_prev,     NULL);
5305         setkeybinding(MODKEY,           XK_Up,          kf_ws_next_all, NULL);
5306         setkeybinding(MODKEY,           XK_Down,        kf_ws_prev_all, NULL);
5307         setkeybinding(MODKEY,           XK_a,           kf_ws_prior,    NULL);
5308         setkeybinding(MODKEY|ShiftMask, XK_Right,       kf_screen_next, NULL);
5309         setkeybinding(MODKEY|ShiftMask, XK_Left,        kf_screen_prev, NULL);
5310         setkeybinding(MODKEY|ShiftMask, XK_1,           kf_mvws_1,      NULL);
5311         setkeybinding(MODKEY|ShiftMask, XK_2,           kf_mvws_2,      NULL);
5312         setkeybinding(MODKEY|ShiftMask, XK_3,           kf_mvws_3,      NULL);
5313         setkeybinding(MODKEY|ShiftMask, XK_4,           kf_mvws_4,      NULL);
5314         setkeybinding(MODKEY|ShiftMask, XK_5,           kf_mvws_5,      NULL);
5315         setkeybinding(MODKEY|ShiftMask, XK_6,           kf_mvws_6,      NULL);
5316         setkeybinding(MODKEY|ShiftMask, XK_7,           kf_mvws_7,      NULL);
5317         setkeybinding(MODKEY|ShiftMask, XK_8,           kf_mvws_8,      NULL);
5318         setkeybinding(MODKEY|ShiftMask, XK_9,           kf_mvws_9,      NULL);
5319         setkeybinding(MODKEY|ShiftMask, XK_0,           kf_mvws_10,     NULL);
5320         setkeybinding(MODKEY|ShiftMask, XK_F1,          kf_mvws_11,     NULL);
5321         setkeybinding(MODKEY|ShiftMask, XK_F2,          kf_mvws_12,     NULL);
5322         setkeybinding(MODKEY|ShiftMask, XK_F3,          kf_mvws_13,     NULL);
5323         setkeybinding(MODKEY|ShiftMask, XK_F4,          kf_mvws_14,     NULL);
5324         setkeybinding(MODKEY|ShiftMask, XK_F5,          kf_mvws_15,     NULL);
5325         setkeybinding(MODKEY|ShiftMask, XK_F6,          kf_mvws_16,     NULL);
5326         setkeybinding(MODKEY|ShiftMask, XK_F7,          kf_mvws_17,     NULL);
5327         setkeybinding(MODKEY|ShiftMask, XK_F8,          kf_mvws_18,     NULL);
5328         setkeybinding(MODKEY|ShiftMask, XK_F9,          kf_mvws_19,     NULL);
5329         setkeybinding(MODKEY|ShiftMask, XK_F10,         kf_mvws_20,     NULL);
5330         setkeybinding(MODKEY|ShiftMask, XK_F11,         kf_mvws_21,     NULL);
5331         setkeybinding(MODKEY|ShiftMask, XK_F12,         kf_mvws_22,     NULL);
5332         setkeybinding(MODKEY,           XK_b,           kf_bar_toggle,  NULL);
5333         setkeybinding(MODKEY,           XK_Tab,         kf_focus_next,  NULL);
5334         setkeybinding(MODKEY|ShiftMask, XK_Tab,         kf_focus_prev,  NULL);
5335         setkeybinding(MODKEY|ShiftMask, XK_x,           kf_wind_kill,   NULL);
5336         setkeybinding(MODKEY,           XK_x,           kf_wind_del,    NULL);
5337         setkeybinding(MODKEY,           XK_s,           kf_spawn_custom,"screenshot_all");
5338         setkeybinding(MODKEY|ShiftMask, XK_s,           kf_spawn_custom,"screenshot_wind");
5339         setkeybinding(MODKEY,           XK_t,           kf_float_toggle,NULL);
5340         setkeybinding(MODKEY|ShiftMask, XK_v,           kf_version,     NULL);
5341         setkeybinding(MODKEY|ShiftMask, XK_Delete,      kf_spawn_custom,"lock");
5342         setkeybinding(MODKEY|ShiftMask, XK_i,           kf_spawn_custom,"initscr");
5343         setkeybinding(MODKEY,           XK_w,           kf_iconify,     NULL);
5344         setkeybinding(MODKEY|ShiftMask, XK_w,           kf_uniconify,   NULL);
5345         setkeybinding(MODKEY|ShiftMask, XK_r,           kf_raise_toggle,NULL);
5346         setkeybinding(MODKEY,           XK_v,           kf_button2,     NULL);
5347         setkeybinding(MODKEY,           XK_equal,       kf_width_grow,  NULL);
5348         setkeybinding(MODKEY,           XK_minus,       kf_width_shrink,NULL);
5349         setkeybinding(MODKEY|ShiftMask, XK_equal,       kf_height_grow, NULL);
5350         setkeybinding(MODKEY|ShiftMask, XK_minus,       kf_height_shrink,NULL);
5351         setkeybinding(MODKEY,           XK_bracketleft, kf_move_left,   NULL);
5352         setkeybinding(MODKEY,           XK_bracketright,kf_move_right,  NULL);
5353         setkeybinding(MODKEY|ShiftMask, XK_bracketleft, kf_move_up,     NULL);
5354         setkeybinding(MODKEY|ShiftMask, XK_bracketright,kf_move_down,   NULL);
5355         setkeybinding(MODKEY|ShiftMask, XK_slash,       kf_name_workspace,NULL);
5356         setkeybinding(MODKEY,           XK_slash,       kf_search_workspace,NULL);
5357         setkeybinding(MODKEY,           XK_f,           kf_search_win,  NULL);
5358 #ifdef SWM_DEBUG
5359         setkeybinding(MODKEY|ShiftMask, XK_d,           kf_dumpwins,    NULL);
5360 #endif
5361 }
5362
5363 void
5364 clear_keys(void)
5365 {
5366         struct key              *kp;
5367
5368         while (RB_EMPTY(&keys) == 0) {
5369                 kp = RB_ROOT(&keys);
5370                 key_remove(kp);
5371         }
5372 }
5373
5374 int
5375 setkeymapping(char *selector, char *value, int flags)
5376 {
5377         char                    keymapping_file[PATH_MAX];
5378         DNPRINTF(SWM_D_KEY, "setkeymapping: enter\n");
5379         if (value[0] == '~')
5380                 snprintf(keymapping_file, sizeof keymapping_file, "%s/%s",
5381                     pwd->pw_dir, &value[1]);
5382         else
5383                 strlcpy(keymapping_file, value, sizeof keymapping_file);
5384         clear_keys();
5385         /* load new key bindings; if it fails, revert to default bindings */
5386         if (conf_load(keymapping_file, SWM_CONF_KEYMAPPING)) {
5387                 clear_keys();
5388                 setup_keys();
5389         }
5390         DNPRINTF(SWM_D_KEY, "setkeymapping: leave\n");
5391         return (0);
5392 }
5393
5394 void
5395 updatenumlockmask(void)
5396 {
5397         unsigned int                            i, j;
5398         xcb_get_modifier_mapping_reply_t        *modmap_r;
5399         xcb_keycode_t                           *modmap, kc;
5400
5401         DNPRINTF(SWM_D_MISC, "updatenumlockmask\n");
5402         numlockmask = 0;
5403
5404         modmap_r = xcb_get_modifier_mapping_reply(conn,
5405             xcb_get_modifier_mapping(conn),
5406             NULL);
5407         if (modmap_r) {
5408                 modmap = xcb_get_modifier_mapping_keycodes(modmap_r);
5409                 for (i = 0; i < 8; i++) {
5410                         for (j = 0; j < modmap_r->keycodes_per_modifier; j++) {
5411                                 kc = modmap[i * modmap_r->keycodes_per_modifier
5412                                     + j];
5413
5414                                 if (kc == *((xcb_keycode_t *)xcb_key_symbols_get_keycode(syms,
5415                                     XK_Num_Lock)))
5416                                         numlockmask = (1 << i);
5417                         }
5418                 }
5419                 free(modmap_r);
5420         }
5421 }
5422
5423 void
5424 grabkeys(void)
5425 {
5426         int                     num_screens;
5427         unsigned int            j, k;
5428         xcb_keycode_t           *code;
5429         unsigned int            modifiers[] =
5430             { 0, LockMask, numlockmask, numlockmask | LockMask };
5431         struct key              *kp;
5432
5433         DNPRINTF(SWM_D_MISC, "grabkeys\n");
5434         updatenumlockmask();
5435
5436         num_screens = xcb_setup_roots_length(xcb_get_setup(conn));
5437         for (k = 0; k < num_screens; k++) {
5438                 if (TAILQ_EMPTY(&screens[k].rl))
5439                         continue;
5440                 xcb_ungrab_key(conn, XCB_GRAB_ANY, screens[k].root,
5441                         XCB_MOD_MASK_ANY);
5442                 RB_FOREACH(kp, key_tree, &keys) {
5443                         if ((code = xcb_key_symbols_get_keycode(syms,
5444                                         kp->keysym)))
5445                                 for (j = 0; j < LENGTH(modifiers); j++)
5446                                         xcb_grab_key(conn, True,
5447                                             screens[k].root,
5448                                             kp->mod | modifiers[j],
5449                                             *code, XCB_GRAB_MODE_ASYNC,
5450                                             XCB_GRAB_MODE_ASYNC);
5451                 }
5452         }
5453 }
5454
5455 void
5456 grabbuttons(struct ws_win *win, int focused)
5457 {
5458         unsigned int            i, j;
5459         unsigned int            modifiers[] =
5460             { 0, LockMask, numlockmask, numlockmask|LockMask };
5461
5462         updatenumlockmask();
5463         xcb_ungrab_button(conn, XCB_BUTTON_INDEX_ANY, win->id,
5464             XCB_BUTTON_MASK_ANY);
5465         if (focused) {
5466                 for (i = 0; i < LENGTH(buttons); i++)
5467                         if (buttons[i].action == client_click)
5468                                 for (j = 0; j < LENGTH(modifiers); j++)
5469                                         xcb_grab_button(conn, False, win->id,
5470                                             BUTTONMASK,
5471                                             XCB_GRAB_MODE_ASYNC,
5472                                             XCB_GRAB_MODE_SYNC,
5473                                             XCB_WINDOW_NONE,
5474                                             XCB_CURSOR_NONE,
5475                                             buttons[i].button,
5476                                             buttons[i].mask);
5477         } else
5478                 xcb_grab_button(conn, False, win->id, BUTTONMASK,
5479                     XCB_GRAB_MODE_ASYNC, XCB_GRAB_MODE_SYNC, XCB_WINDOW_NONE,
5480                     XCB_CURSOR_NONE, XCB_BUTTON_INDEX_ANY, XCB_BUTTON_MASK_ANY);
5481 }
5482
5483 const char *quirkname[] = {
5484         "NONE",         /* config string for "no value" */
5485         "FLOAT",
5486         "TRANSSZ",
5487         "ANYWHERE",
5488         "XTERM_FONTADJ",
5489         "FULLSCREEN",
5490         "FOCUSPREV",
5491 };
5492
5493 /* SWM_Q_WS: retain '|' for back compat for now (2009-08-11) */
5494 #define SWM_Q_WS                "\n|+ \t"
5495 int
5496 parsequirks(char *qstr, unsigned long *quirk)
5497 {
5498         char                    *cp, *name;
5499         int                     i;
5500
5501         if (quirk == NULL)
5502                 return (1);
5503
5504         cp = qstr;
5505         *quirk = 0;
5506         while ((name = strsep(&cp, SWM_Q_WS)) != NULL) {
5507                 if (cp)
5508                         cp += (long)strspn(cp, SWM_Q_WS);
5509                 for (i = 0; i < LENGTH(quirkname); i++) {
5510                         if (!strncasecmp(name, quirkname[i], SWM_QUIRK_LEN)) {
5511                                 DNPRINTF(SWM_D_QUIRK,
5512                                     "parsequirks: %s\n", name);
5513                                 if (i == 0) {
5514                                         *quirk = 0;
5515                                         return (0);
5516                                 }
5517                                 *quirk |= 1 << (i-1);
5518                                 break;
5519                         }
5520                 }
5521                 if (i >= LENGTH(quirkname)) {
5522                         DNPRINTF(SWM_D_QUIRK,
5523                             "parsequirks: invalid quirk [%s]\n", name);
5524                         return (1);
5525                 }
5526         }
5527         return (0);
5528 }
5529
5530 void
5531 quirk_insert(const char *class, const char *name, unsigned long quirk)
5532 {
5533         struct quirk            *qp;
5534
5535         DNPRINTF(SWM_D_QUIRK, "quirk_insert: %s:%s [%lu]\n", class, name,
5536             quirk);
5537
5538         if ((qp = malloc(sizeof *qp)) == NULL)
5539                 err(1, "quirk_insert: malloc");
5540         if ((qp->class = strdup(class)) == NULL)
5541                 err(1, "quirk_insert: strdup");
5542         if ((qp->name = strdup(name)) == NULL)
5543                 err(1, "quirk_insert: strdup");
5544
5545         qp->quirk = quirk;
5546         TAILQ_INSERT_TAIL(&quirks, qp, entry);
5547
5548         DNPRINTF(SWM_D_QUIRK, "quirk_insert: leave\n");
5549 }
5550
5551 void
5552 quirk_remove(struct quirk *qp)
5553 {
5554         DNPRINTF(SWM_D_QUIRK, "quirk_remove: %s:%s [%lu]\n", qp->class,
5555             qp->name, qp->quirk);
5556
5557         TAILQ_REMOVE(&quirks, qp, entry);
5558         free(qp->class);
5559         free(qp->name);
5560         free(qp);
5561
5562         DNPRINTF(SWM_D_QUIRK, "quirk_remove: leave\n");
5563 }
5564
5565 void
5566 quirk_replace(struct quirk *qp, const char *class, const char *name,
5567     unsigned long quirk)
5568 {
5569         DNPRINTF(SWM_D_QUIRK, "quirk_replace: %s:%s [%lu]\n", qp->class,
5570             qp->name, qp->quirk);
5571
5572         quirk_remove(qp);
5573         quirk_insert(class, name, quirk);
5574
5575         DNPRINTF(SWM_D_QUIRK, "quirk_replace: leave\n");
5576 }
5577
5578 void
5579 setquirk(const char *class, const char *name, unsigned long quirk)
5580 {
5581         struct quirk            *qp;
5582
5583         DNPRINTF(SWM_D_QUIRK, "setquirk: enter %s:%s [%lu]\n", class, name,
5584            quirk);
5585
5586         TAILQ_FOREACH(qp, &quirks, entry) {
5587                 if (!strcmp(qp->class, class) && !strcmp(qp->name, name)) {
5588                         if (!quirk)
5589                                 quirk_remove(qp);
5590                         else
5591                                 quirk_replace(qp, class, name, quirk);
5592                         DNPRINTF(SWM_D_QUIRK, "setquirk: leave\n");
5593                         return;
5594                 }
5595         }
5596         if (!quirk) {
5597                 warnx("error: setquirk: cannot find class/name combination");
5598                 return;
5599         }
5600
5601         quirk_insert(class, name, quirk);
5602         DNPRINTF(SWM_D_QUIRK, "setquirk: leave\n");
5603 }
5604
5605 int
5606 setconfquirk(char *selector, char *value, int flags)
5607 {
5608         char                    *cp, *class, *name;
5609         int                     retval;
5610         unsigned long           quirks;
5611         if (selector == NULL)
5612                 return (0);
5613         if ((cp = strchr(selector, ':')) == NULL)
5614                 return (0);
5615         *cp = '\0';
5616         class = selector;
5617         name = cp + 1;
5618         if ((retval = parsequirks(value, &quirks)) == 0)
5619                 setquirk(class, name, quirks);
5620         return (retval);
5621 }
5622
5623 void
5624 setup_quirks(void)
5625 {
5626         setquirk("MPlayer",             "xv",           SWM_Q_FLOAT | SWM_Q_FULLSCREEN | SWM_Q_FOCUSPREV);
5627         setquirk("OpenOffice.org 3.2",  "VCLSalFrame",  SWM_Q_FLOAT);
5628         setquirk("Firefox-bin",         "firefox-bin",  SWM_Q_TRANSSZ);
5629         setquirk("Firefox",             "Dialog",       SWM_Q_FLOAT);
5630         setquirk("Gimp",                "gimp",         SWM_Q_FLOAT | SWM_Q_ANYWHERE);
5631         setquirk("XTerm",               "xterm",        SWM_Q_XTERM_FONTADJ);
5632         setquirk("xine",                "Xine Window",  SWM_Q_FLOAT | SWM_Q_ANYWHERE);
5633         setquirk("Xitk",                "Xitk Combo",   SWM_Q_FLOAT | SWM_Q_ANYWHERE);
5634         setquirk("xine",                "xine Panel",   SWM_Q_FLOAT | SWM_Q_ANYWHERE);
5635         setquirk("Xitk",                "Xine Window",  SWM_Q_FLOAT | SWM_Q_ANYWHERE);
5636         setquirk("xine",                "xine Video Fullscreen Window", SWM_Q_FULLSCREEN | SWM_Q_FLOAT);
5637         setquirk("pcb",                 "pcb",          SWM_Q_FLOAT);
5638         setquirk("SDL_App",             "SDL_App",      SWM_Q_FLOAT | SWM_Q_FULLSCREEN);
5639 }
5640
5641 /* conf file stuff */
5642 #define SWM_CONF_FILE           "spectrwm.conf"
5643 #define SWM_CONF_FILE_OLD       "scrotwm.conf"
5644
5645 enum {
5646         SWM_S_BAR_ACTION,
5647         SWM_S_BAR_AT_BOTTOM,
5648         SWM_S_BAR_BORDER_WIDTH,
5649         SWM_S_BAR_DELAY,
5650         SWM_S_BAR_ENABLED,
5651         SWM_S_BAR_FONT,
5652         SWM_S_BAR_FORMAT,
5653         SWM_S_BAR_JUSTIFY,
5654         SWM_S_BORDER_WIDTH,
5655         SWM_S_CLOCK_ENABLED,
5656         SWM_S_CLOCK_FORMAT,
5657         SWM_S_CYCLE_EMPTY,
5658         SWM_S_CYCLE_VISIBLE,
5659         SWM_S_DIALOG_RATIO,
5660         SWM_S_DISABLE_BORDER,
5661         SWM_S_FOCUS_CLOSE,
5662         SWM_S_FOCUS_CLOSE_WRAP,
5663         SWM_S_FOCUS_DEFAULT,
5664         SWM_S_FOCUS_MODE,
5665         SWM_S_SPAWN_ORDER,
5666         SWM_S_SPAWN_TERM,
5667         SWM_S_SS_APP,
5668         SWM_S_SS_ENABLED,
5669         SWM_S_STACK_ENABLED,
5670         SWM_S_TERM_WIDTH,
5671         SWM_S_TITLE_CLASS_ENABLED,
5672         SWM_S_TITLE_NAME_ENABLED,
5673         SWM_S_URGENT_ENABLED,
5674         SWM_S_VERBOSE_LAYOUT,
5675         SWM_S_WINDOW_NAME_ENABLED,
5676         SWM_S_WORKSPACE_LIMIT
5677 };
5678
5679 int
5680 setconfvalue(char *selector, char *value, int flags)
5681 {
5682         int     i;
5683         char    *b;
5684
5685         switch (flags) {
5686         case SWM_S_BAR_ACTION:
5687                 free(bar_argv[0]);
5688                 if ((bar_argv[0] = strdup(value)) == NULL)
5689                         err(1, "setconfvalue: bar_action");
5690                 break;
5691         case SWM_S_BAR_AT_BOTTOM:
5692                 bar_at_bottom = atoi(value);
5693                 break;
5694         case SWM_S_BAR_BORDER_WIDTH:
5695                 bar_border_width = atoi(value);
5696                 if (bar_border_width < 0)
5697                         bar_border_width = 0;
5698                 break;
5699         case SWM_S_BAR_DELAY:
5700                 bar_delay = atoi(value);
5701                 break;
5702         case SWM_S_BAR_ENABLED:
5703                 bar_enabled = atoi(value);
5704                 break;
5705         case SWM_S_BAR_FONT:
5706                 b = bar_fonts;
5707                 if (asprintf(&bar_fonts, "%s,%s", value, bar_fonts) == -1)
5708                         err(1, "setconfvalue: asprintf: failed to allocate "
5709                                 "memory for bar_fonts.");
5710
5711                 free(b);
5712                 break;
5713         case SWM_S_BAR_FORMAT:
5714                 free(bar_format);
5715                 if ((bar_format = strdup(value)) == NULL)
5716                         err(1, "setconfvalue: bar_format");
5717                 break;
5718         case SWM_S_BAR_JUSTIFY:
5719                 if (!strcmp(value, "left"))
5720                         bar_justify = SWM_BAR_JUSTIFY_LEFT;
5721                 else if (!strcmp(value, "center"))
5722                         bar_justify = SWM_BAR_JUSTIFY_CENTER;
5723                 else if (!strcmp(value, "right"))
5724                         bar_justify = SWM_BAR_JUSTIFY_RIGHT;
5725                 else
5726                         errx(1, "invalid bar_justify");
5727                 break;
5728         case SWM_S_BORDER_WIDTH:
5729                 border_width = atoi(value);
5730                 if (border_width < 0)
5731                         border_width = 0;
5732                 break;
5733         case SWM_S_CLOCK_ENABLED:
5734                 clock_enabled = atoi(value);
5735                 break;
5736         case SWM_S_CLOCK_FORMAT:
5737 #ifndef SWM_DENY_CLOCK_FORMAT
5738                 free(clock_format);
5739                 if ((clock_format = strdup(value)) == NULL)
5740                         err(1, "setconfvalue: clock_format");
5741 #endif
5742                 break;
5743         case SWM_S_CYCLE_EMPTY:
5744                 cycle_empty = atoi(value);
5745                 break;
5746         case SWM_S_CYCLE_VISIBLE:
5747                 cycle_visible = atoi(value);
5748                 break;
5749         case SWM_S_DIALOG_RATIO:
5750                 dialog_ratio = atof(value);
5751                 if (dialog_ratio > 1.0 || dialog_ratio <= .3)
5752                         dialog_ratio = .6;
5753                 break;
5754         case SWM_S_DISABLE_BORDER:
5755                 disable_border = atoi(value);
5756                 break;
5757         case SWM_S_FOCUS_CLOSE:
5758                 if (!strcmp(value, "first"))
5759                         focus_close = SWM_STACK_BOTTOM;
5760                 else if (!strcmp(value, "last"))
5761                         focus_close = SWM_STACK_TOP;
5762                 else if (!strcmp(value, "next"))
5763                         focus_close = SWM_STACK_ABOVE;
5764                 else if (!strcmp(value, "previous"))
5765                         focus_close = SWM_STACK_BELOW;
5766                 else
5767                         errx(1, "focus_close");
5768                 break;
5769         case SWM_S_FOCUS_CLOSE_WRAP:
5770                 focus_close_wrap = atoi(value);
5771                 break;
5772         case SWM_S_FOCUS_DEFAULT:
5773                 if (!strcmp(value, "last"))
5774                         focus_default = SWM_STACK_TOP;
5775                 else if (!strcmp(value, "first"))
5776                         focus_default = SWM_STACK_BOTTOM;
5777                 else
5778                         errx(1, "focus_default");
5779                 break;
5780         case SWM_S_FOCUS_MODE:
5781                 if (!strcmp(value, "default"))
5782                         focus_mode = SWM_FOCUS_DEFAULT;
5783                 else if (!strcmp(value, "follow_cursor"))
5784                         focus_mode = SWM_FOCUS_FOLLOW;
5785                 else if (!strcmp(value, "synergy"))
5786                         focus_mode = SWM_FOCUS_SYNERGY;
5787                 else
5788                         errx(1, "focus_mode");
5789                 break;
5790         case SWM_S_SPAWN_ORDER:
5791                 if (!strcmp(value, "first"))
5792                         spawn_position = SWM_STACK_BOTTOM;
5793                 else if (!strcmp(value, "last"))
5794                         spawn_position = SWM_STACK_TOP;
5795                 else if (!strcmp(value, "next"))
5796                         spawn_position = SWM_STACK_ABOVE;
5797                 else if (!strcmp(value, "previous"))
5798                         spawn_position = SWM_STACK_BELOW;
5799                 else
5800                         errx(1, "spawn_position");
5801                 break;
5802         case SWM_S_SPAWN_TERM:
5803                 setconfspawn("term", value, 0);
5804                 setconfspawn("spawn_term", value, 0);
5805                 break;
5806         case SWM_S_SS_APP:
5807                 break;
5808         case SWM_S_SS_ENABLED:
5809                 ss_enabled = atoi(value);
5810                 break;
5811         case SWM_S_STACK_ENABLED:
5812                 stack_enabled = atoi(value);
5813                 break;
5814         case SWM_S_TERM_WIDTH:
5815                 term_width = atoi(value);
5816                 if (term_width < 0)
5817                         term_width = 0;
5818                 break;
5819         case SWM_S_TITLE_CLASS_ENABLED:
5820                 title_class_enabled = atoi(value);
5821                 break;
5822         case SWM_S_TITLE_NAME_ENABLED:
5823                 title_name_enabled = atoi(value);
5824                 break;
5825         case SWM_S_URGENT_ENABLED:
5826                 urgent_enabled = atoi(value);
5827                 break;
5828         case SWM_S_VERBOSE_LAYOUT:
5829                 verbose_layout = atoi(value);
5830                 for (i = 0; layouts[i].l_stack != NULL; i++) {
5831                         if (verbose_layout)
5832                                 layouts[i].l_string = fancy_stacker;
5833                         else
5834                                 layouts[i].l_string = plain_stacker;
5835                 }
5836                 break;
5837         case SWM_S_WINDOW_NAME_ENABLED:
5838                 window_name_enabled = atoi(value);
5839                 break;
5840         case SWM_S_WORKSPACE_LIMIT:
5841                 workspace_limit = atoi(value);
5842                 if (workspace_limit > SWM_WS_MAX)
5843                         workspace_limit = SWM_WS_MAX;
5844                 else if (workspace_limit < 1)
5845                         workspace_limit = 1;
5846                 break;
5847         default:
5848                 return (1);
5849         }
5850         return (0);
5851 }
5852
5853 int
5854 setconfmodkey(char *selector, char *value, int flags)
5855 {
5856         if (!strncasecmp(value, "Mod1", strlen("Mod1")))
5857                 update_modkey(Mod1Mask);
5858         else if (!strncasecmp(value, "Mod2", strlen("Mod2")))
5859                 update_modkey(Mod2Mask);
5860         else if (!strncasecmp(value, "Mod3", strlen("Mod3")))
5861                 update_modkey(Mod3Mask);
5862         else if (!strncasecmp(value, "Mod4", strlen("Mod4")))
5863                 update_modkey(Mod4Mask);
5864         else
5865                 return (1);
5866         return (0);
5867 }
5868
5869 int
5870 setconfcolor(char *selector, char *value, int flags)
5871 {
5872         setscreencolor(value, ((selector == NULL)?-1:atoi(selector)), flags);
5873         return (0);
5874 }
5875
5876 int
5877 setconfregion(char *selector, char *value, int flags)
5878 {
5879         custom_region(value);
5880         return (0);
5881 }
5882
5883 int
5884 setautorun(char *selector, char *value, int flags)
5885 {
5886         int                     ws_id;
5887         char                    s[1024];
5888         char                    *ap, *sp = s;
5889         union arg               a;
5890         int                     argc = 0;
5891         long                    pid;
5892         struct pid_e            *p;
5893
5894         if (getenv("SWM_STARTED"))
5895                 return (0);
5896
5897         bzero(s, sizeof s);
5898         if (sscanf(value, "ws[%d]:%1023c", &ws_id, s) != 2)
5899                 errx(1, "invalid autorun entry, should be 'ws[<idx>]:command'");
5900         ws_id--;
5901         if (ws_id < 0 || ws_id >= workspace_limit)
5902                 errx(1, "autorun: invalid workspace %d", ws_id + 1);
5903
5904         /*
5905          * This is a little intricate
5906          *
5907          * If the pid already exists we simply reuse it because it means it was
5908          * used before AND not claimed by manage_window.  We get away with
5909          * altering it in the parent after INSERT because this can not be a race
5910          */
5911         a.argv = NULL;
5912         while ((ap = strsep(&sp, " \t")) != NULL) {
5913                 if (*ap == '\0')
5914                         continue;
5915                 DNPRINTF(SWM_D_SPAWN, "setautorun: arg [%s]\n", ap);
5916                 argc++;
5917                 if ((a.argv = realloc(a.argv, argc * sizeof(char *))) == NULL)
5918                         err(1, "setautorun: realloc");
5919                 a.argv[argc - 1] = ap;
5920         }
5921
5922         if ((a.argv = realloc(a.argv, (argc + 1) * sizeof(char *))) == NULL)
5923                 err(1, "setautorun: realloc");
5924         a.argv[argc] = NULL;
5925
5926         if ((pid = fork()) == 0) {
5927                 spawn(ws_id, &a, 1);
5928                 /* NOTREACHED */
5929                 _exit(1);
5930         }
5931         free(a.argv);
5932
5933         /* parent */
5934         p = find_pid(pid);
5935         if (p == NULL) {
5936                 p = calloc(1, sizeof *p);
5937                 if (p == NULL)
5938                         return (1);
5939                 TAILQ_INSERT_TAIL(&pidlist, p, entry);
5940         }
5941
5942         p->pid = pid;
5943         p->ws = ws_id;
5944
5945         return (0);
5946 }
5947
5948 int
5949 setlayout(char *selector, char *value, int flags)
5950 {
5951         int                     ws_id, i, x, mg, ma, si, raise, f = 0;
5952         int                     st = SWM_V_STACK, num_screens;
5953         char                    s[1024];
5954         struct workspace        *ws;
5955
5956         if (getenv("SWM_STARTED"))
5957                 return (0);
5958
5959         bzero(s, sizeof s);
5960         if (sscanf(value, "ws[%d]:%d:%d:%d:%d:%1023c",
5961             &ws_id, &mg, &ma, &si, &raise, s) != 6)
5962                 errx(1, "invalid layout entry, should be 'ws[<idx>]:"
5963                     "<master_grow>:<master_add>:<stack_inc>:<always_raise>:"
5964                     "<type>'");
5965         ws_id--;
5966         if (ws_id < 0 || ws_id >= workspace_limit)
5967                 errx(1, "layout: invalid workspace %d", ws_id + 1);
5968
5969         if (!strcasecmp(s, "vertical"))
5970                 st = SWM_V_STACK;
5971         else if (!strcasecmp(s, "vertical_flip")) {
5972                 st = SWM_V_STACK;
5973                 f = 1;
5974         } else if (!strcasecmp(s, "horizontal"))
5975                 st = SWM_H_STACK;
5976         else if (!strcasecmp(s, "horizontal_flip")) {
5977                 st = SWM_H_STACK;
5978                 f = 1;
5979         } else if (!strcasecmp(s, "fullscreen"))
5980                 st = SWM_MAX_STACK;
5981         else
5982                 errx(1, "invalid layout entry, should be 'ws[<idx>]:"
5983                     "<master_grow>:<master_add>:<stack_inc>:<always_raise>:"
5984                     "<type>'");
5985
5986         num_screens = xcb_setup_roots_length(xcb_get_setup(conn));
5987         for (i = 0; i < num_screens; i++) {
5988                 ws = (struct workspace *)&screens[i].ws;
5989                 ws[ws_id].cur_layout = &layouts[st];
5990
5991                 ws[ws_id].always_raise = raise;
5992                 if (st == SWM_MAX_STACK)
5993                         continue;
5994
5995                 /* master grow */
5996                 for (x = 0; x < abs(mg); x++) {
5997                         ws[ws_id].cur_layout->l_config(&ws[ws_id],
5998                             mg >= 0 ?  SWM_ARG_ID_MASTERGROW :
5999                             SWM_ARG_ID_MASTERSHRINK);
6000                         stack();
6001                 }
6002                 /* master add */
6003                 for (x = 0; x < abs(ma); x++) {
6004                         ws[ws_id].cur_layout->l_config(&ws[ws_id],
6005                             ma >= 0 ?  SWM_ARG_ID_MASTERADD :
6006                             SWM_ARG_ID_MASTERDEL);
6007                         stack();
6008                 }
6009                 /* stack inc */
6010                 for (x = 0; x < abs(si); x++) {
6011                         ws[ws_id].cur_layout->l_config(&ws[ws_id],
6012                             si >= 0 ?  SWM_ARG_ID_STACKINC :
6013                             SWM_ARG_ID_STACKDEC);
6014                         stack();
6015                 }
6016                 /* Apply flip */
6017                 if (f) {
6018                         ws[ws_id].cur_layout->l_config(&ws[ws_id],
6019                             SWM_ARG_ID_FLIPLAYOUT);
6020                         stack();
6021                 }
6022         }
6023
6024         return (0);
6025 }
6026
6027 /* config options */
6028 struct config_option {
6029         char                    *optname;
6030         int                     (*func)(char*, char*, int);
6031         int                     funcflags;
6032 };
6033 struct config_option configopt[] = {
6034         { "bar_enabled",                setconfvalue,   SWM_S_BAR_ENABLED },
6035         { "bar_at_bottom",              setconfvalue,   SWM_S_BAR_AT_BOTTOM },
6036         { "bar_border",                 setconfcolor,   SWM_S_COLOR_BAR_BORDER },
6037         { "bar_border_width",           setconfvalue,   SWM_S_BAR_BORDER_WIDTH },
6038         { "bar_color",                  setconfcolor,   SWM_S_COLOR_BAR },
6039         { "bar_font_color",             setconfcolor,   SWM_S_COLOR_BAR_FONT },
6040         { "bar_font",                   setconfvalue,   SWM_S_BAR_FONT },
6041         { "bar_action",                 setconfvalue,   SWM_S_BAR_ACTION },
6042         { "bar_delay",                  setconfvalue,   SWM_S_BAR_DELAY },
6043         { "bar_justify",                setconfvalue,   SWM_S_BAR_JUSTIFY },
6044         { "bar_format",                 setconfvalue,   SWM_S_BAR_FORMAT },
6045         { "keyboard_mapping",           setkeymapping,  0 },
6046         { "bind",                       setconfbinding, 0 },
6047         { "stack_enabled",              setconfvalue,   SWM_S_STACK_ENABLED },
6048         { "clock_enabled",              setconfvalue,   SWM_S_CLOCK_ENABLED },
6049         { "clock_format",               setconfvalue,   SWM_S_CLOCK_FORMAT },
6050         { "color_focus",                setconfcolor,   SWM_S_COLOR_FOCUS },
6051         { "color_unfocus",              setconfcolor,   SWM_S_COLOR_UNFOCUS },
6052         { "cycle_empty",                setconfvalue,   SWM_S_CYCLE_EMPTY },
6053         { "cycle_visible",              setconfvalue,   SWM_S_CYCLE_VISIBLE },
6054         { "workspace_limit",            setconfvalue,   SWM_S_WORKSPACE_LIMIT },
6055         { "dialog_ratio",               setconfvalue,   SWM_S_DIALOG_RATIO },
6056         { "verbose_layout",             setconfvalue,   SWM_S_VERBOSE_LAYOUT },
6057         { "modkey",                     setconfmodkey,  0 },
6058         { "program",                    setconfspawn,   0 },
6059         { "quirk",                      setconfquirk,   0 },
6060         { "region",                     setconfregion,  0 },
6061         { "spawn_term",                 setconfvalue,   SWM_S_SPAWN_TERM },
6062         { "screenshot_enabled",         setconfvalue,   SWM_S_SS_ENABLED },
6063         { "screenshot_app",             setconfvalue,   SWM_S_SS_APP },
6064         { "window_name_enabled",        setconfvalue,   SWM_S_WINDOW_NAME_ENABLED },
6065         { "urgent_enabled",             setconfvalue,   SWM_S_URGENT_ENABLED },
6066         { "term_width",                 setconfvalue,   SWM_S_TERM_WIDTH },
6067         { "title_class_enabled",        setconfvalue,   SWM_S_TITLE_CLASS_ENABLED },
6068         { "title_name_enabled",         setconfvalue,   SWM_S_TITLE_NAME_ENABLED },
6069         { "focus_mode",                 setconfvalue,   SWM_S_FOCUS_MODE },
6070         { "focus_close",                setconfvalue,   SWM_S_FOCUS_CLOSE },
6071         { "focus_close_wrap",           setconfvalue,   SWM_S_FOCUS_CLOSE_WRAP },
6072         { "focus_default",              setconfvalue,   SWM_S_FOCUS_DEFAULT },
6073         { "spawn_position",             setconfvalue,   SWM_S_SPAWN_ORDER },
6074         { "disable_border",             setconfvalue,   SWM_S_DISABLE_BORDER },
6075         { "border_width",               setconfvalue,   SWM_S_BORDER_WIDTH },
6076         { "autorun",                    setautorun,     0 },
6077         { "layout",                     setlayout,      0 },
6078 };
6079
6080
6081 int
6082 conf_load(char *filename, int keymapping)
6083 {
6084         FILE                    *config;
6085         char                    *line, *cp, *optsub, *optval;
6086         size_t                  linelen, lineno = 0;
6087         int                     wordlen, i, optind;
6088         struct config_option    *opt;
6089
6090         DNPRINTF(SWM_D_CONF, "conf_load: begin\n");
6091
6092         if (filename == NULL) {
6093                 warnx("conf_load: no filename");
6094                 return (1);
6095         }
6096         if ((config = fopen(filename, "r")) == NULL) {
6097                 warn("conf_load: fopen: %s", filename);
6098                 return (1);
6099         }
6100
6101         while (!feof(config)) {
6102                 if ((line = fparseln(config, &linelen, &lineno, NULL, 0))
6103                     == NULL) {
6104                         if (ferror(config))
6105                                 err(1, "%s", filename);
6106                         else
6107                                 continue;
6108                 }
6109                 cp = line;
6110                 cp += strspn(cp, " \t\n"); /* eat whitespace */
6111                 if (cp[0] == '\0') {
6112                         /* empty line */
6113                         free(line);
6114                         continue;
6115                 }
6116                 /* get config option */
6117                 wordlen = strcspn(cp, "=[ \t\n");
6118                 if (wordlen == 0) {
6119                         warnx("%s: line %zd: no option found",
6120                             filename, lineno);
6121                         goto out;
6122                 }
6123                 optind = -1;
6124                 for (i = 0; i < LENGTH(configopt); i++) {
6125                         opt = &configopt[i];
6126                         if (!strncasecmp(cp, opt->optname, wordlen) &&
6127                             strlen(opt->optname) == wordlen) {
6128                                 optind = i;
6129                                 break;
6130                         }
6131                 }
6132                 if (optind == -1) {
6133                         warnx("%s: line %zd: unknown option %.*s",
6134                             filename, lineno, wordlen, cp);
6135                         goto out;
6136                 }
6137                 if (keymapping && strcmp(opt->optname, "bind")) {
6138                         warnx("%s: line %zd: invalid option %.*s",
6139                             filename, lineno, wordlen, cp);
6140                         goto out;
6141                 }
6142                 cp += wordlen;
6143                 cp += strspn(cp, " \t\n"); /* eat whitespace */
6144                 /* get [selector] if any */
6145                 optsub = NULL;
6146                 if (*cp == '[') {
6147                         cp++;
6148                         wordlen = strcspn(cp, "]");
6149                         if (*cp != ']') {
6150                                 if (wordlen == 0) {
6151                                         warnx("%s: line %zd: syntax error",
6152                                             filename, lineno);
6153                                         goto out;
6154                                 }
6155
6156                                 if (asprintf(&optsub, "%.*s", wordlen, cp) ==
6157                                     -1) {
6158                                         warnx("%s: line %zd: unable to allocate"
6159                                             "memory for selector", filename,
6160                                             lineno);
6161                                         goto out;
6162                                 }
6163                         }
6164                         cp += wordlen;
6165                         cp += strspn(cp, "] \t\n"); /* eat trailing */
6166                 }
6167                 cp += strspn(cp, "= \t\n"); /* eat trailing */
6168                 /* get RHS value */
6169                 optval = strdup(cp);
6170                 /* call function to deal with it all */
6171                 if (configopt[optind].func(optsub, optval,
6172                     configopt[optind].funcflags) != 0)
6173                         errx(1, "%s: line %zd: invalid data for %s",
6174                             filename, lineno, configopt[optind].optname);
6175                 free(optval);
6176                 free(optsub);
6177                 free(line);
6178         }
6179
6180         fclose(config);
6181         DNPRINTF(SWM_D_CONF, "conf_load: end\n");
6182
6183         return (0);
6184
6185 out:
6186         free(line);
6187         fclose(config);
6188         DNPRINTF(SWM_D_CONF, "conf_load: end with error.\n");
6189
6190         return (1);
6191 }
6192
6193 void
6194 set_child_transient(struct ws_win *win, xcb_window_t *trans)
6195 {
6196         struct ws_win           *parent, *w;
6197         struct swm_region       *r;
6198         struct workspace        *ws;
6199         xcb_icccm_wm_hints_t    wmh;
6200
6201         parent = find_window(win->transient);
6202         if (parent)
6203                 parent->child_trans = win;
6204         else {
6205                 DNPRINTF(SWM_D_MISC, "set_child_transient: parent doesn't exist"
6206                     " for 0x%x trans 0x%x\n", win->id, win->transient);
6207
6208                 r = root_to_region(win->wa->root);
6209                 ws = r->ws;
6210                 /* parent doen't exist in our window list */
6211                 TAILQ_FOREACH(w, &ws->winlist, entry) {
6212                         if (xcb_icccm_get_wm_hints_reply(conn,
6213                             xcb_icccm_get_wm_hints(conn, w->id),
6214                             &wmh, NULL) != 1) {
6215                                 warnx("can't get hints for 0x%x", w->id);
6216                                 continue;
6217                         }
6218
6219                         if (win->hints.window_group != wmh.window_group)
6220                                 continue;
6221
6222                         w->child_trans = win;
6223                         win->transient = w->id;
6224                         *trans = w->id;
6225                         DNPRINTF(SWM_D_MISC, "set_child_transient: adjusting "
6226                             "transient to 0x%x\n", win->transient);
6227                         break;
6228                 }
6229         }
6230 }
6231
6232 long
6233 window_get_pid(xcb_window_t win)
6234 {
6235         long                            ret = 0;
6236         const char                      *errstr;
6237         xcb_atom_t                      apid;
6238         xcb_get_property_cookie_t       pc;
6239         xcb_get_property_reply_t        *pr;
6240
6241         apid = get_atom_from_string("_NET_WM_PID");
6242         if (apid == XCB_ATOM_NONE)
6243                 goto tryharder;
6244
6245         pc = xcb_get_property(conn, False, win, apid, XCB_ATOM_CARDINAL, 0, 1);
6246         pr = xcb_get_property_reply(conn, pc, NULL);
6247         if (!pr)
6248                 goto tryharder;
6249         if (pr->type != XCB_ATOM_CARDINAL)
6250                 goto tryharder;
6251
6252         ret = *(long *)xcb_get_property_value(pr);
6253         free(pr);
6254
6255         return (ret);
6256
6257 tryharder:
6258         apid = get_atom_from_string("_SWM_PID");
6259         pc = xcb_get_property(conn, False, win, apid, XCB_ATOM_STRING,
6260             0, SWM_PROPLEN);
6261         pr = xcb_get_property_reply(conn, pc, NULL);
6262         if (!pr)
6263                 return (0);
6264         if (pr->type != XCB_ATOM_STRING)
6265                 free(pr);
6266                 return (0);
6267         ret = strtonum(xcb_get_property_value(pr), 0, UINT_MAX, &errstr);
6268         free(pr);
6269
6270         return (ret);
6271 }
6272
6273 struct ws_win *
6274 manage_window(xcb_window_t id)
6275 {
6276         xcb_window_t            trans = XCB_WINDOW_NONE;
6277         struct workspace        *ws;
6278         struct ws_win           *win, *ww;
6279         int                     i, ws_idx, border_me = 0;
6280         xcb_atom_t              ws_idx_atom = XCB_ATOM_NONE;
6281         char                    ws_idx_str[SWM_PROPLEN], *prop = NULL;
6282         size_t                  proplen;
6283         struct swm_region       *r;
6284         const char              *errstr;
6285         struct pid_e            *p;
6286         struct quirk            *qp;
6287         uint32_t                event_mask;
6288         xcb_atom_t              prot;
6289         xcb_get_property_reply_t        *gpr;
6290         xcb_icccm_get_wm_protocols_reply_t      wpr;
6291
6292         if ((win = find_window(id)) != NULL)
6293                 return (win);   /* already being managed */
6294
6295         /* see if we are on the unmanaged list */
6296         if ((win = find_unmanaged_window(id)) != NULL) {
6297                 DNPRINTF(SWM_D_MISC, "manage_window: previously unmanaged "
6298                     "window: 0x%x\n", win->id);
6299                 TAILQ_REMOVE(&win->ws->unmanagedlist, win, entry);
6300                 if (win->transient)
6301                         set_child_transient(win, &trans);
6302
6303                 if (trans && (ww = find_window(trans)))
6304                         TAILQ_INSERT_AFTER(&win->ws->winlist, ww, win, entry);
6305                 else if ((ww = win->ws->focus) &&
6306                     spawn_position == SWM_STACK_ABOVE)
6307                         TAILQ_INSERT_AFTER(&win->ws->winlist, win->ws->focus,
6308                             win, entry);
6309                 else if (ww && spawn_position == SWM_STACK_BELOW)
6310                         TAILQ_INSERT_BEFORE(win->ws->focus, win, entry);
6311                 else switch (spawn_position) {
6312                 default:
6313                 case SWM_STACK_TOP:
6314                 case SWM_STACK_ABOVE:
6315                         TAILQ_INSERT_TAIL(&win->ws->winlist, win, entry);
6316                         break;
6317                 case SWM_STACK_BOTTOM:
6318                 case SWM_STACK_BELOW:
6319                         TAILQ_INSERT_HEAD(&win->ws->winlist, win, entry);
6320                 }
6321
6322                 ewmh_update_actions(win);
6323                 return (win);
6324         }
6325
6326         if ((win = calloc(1, sizeof(struct ws_win))) == NULL)
6327                 err(1, "manage_window: calloc: failed to allocate memory for "
6328                     "new window");
6329
6330         win->id = id;
6331         win->bordered = 0;
6332
6333         /* see if we need to override the workspace */
6334         p = find_pid(window_get_pid(id));
6335
6336         /* Get all the window data in one shot */
6337         ws_idx_atom = get_atom_from_string("_SWM_WS");
6338         if (ws_idx_atom) {
6339                 gpr = xcb_get_property_reply(conn,
6340                         xcb_get_property(conn, False, id, ws_idx_atom,
6341                             XCB_ATOM_STRING, 0, SWM_PROPLEN),
6342                         NULL);
6343                 if (gpr) {
6344                         proplen = xcb_get_property_value_length(gpr);
6345                         if (proplen > 0) {
6346                                 prop = malloc(proplen + 1);
6347                                 if (prop) {
6348                                         memcpy(prop,
6349                                             xcb_get_property_value(gpr),
6350                                             proplen);
6351                                         prop[proplen] = '\0';
6352                                 }
6353                         }
6354                         free(gpr);
6355                 }
6356         }
6357         win->wa = xcb_get_geometry_reply(conn,
6358             xcb_get_geometry(conn, id),
6359             NULL);
6360         xcb_icccm_get_wm_normal_hints_reply(conn,
6361             xcb_icccm_get_wm_normal_hints(conn, id),
6362             &win->sh, NULL);
6363         xcb_icccm_get_wm_hints_reply(conn,
6364             xcb_icccm_get_wm_hints(conn, id),
6365             &win->hints, NULL);
6366         xcb_icccm_get_wm_transient_for_reply(conn,
6367             xcb_icccm_get_wm_transient_for(conn, id),
6368             &trans, NULL);
6369         if (trans) {
6370                 win->transient = trans;
6371                 set_child_transient(win, &trans);
6372                 DNPRINTF(SWM_D_MISC, "manage_window: window: 0x%x, "
6373                     "transient: 0x%x\n", win->id, win->transient);
6374         }
6375
6376         prot = get_atom_from_string("WM_PROTOCOLS");
6377
6378         /* get supported protocols */
6379         if (xcb_icccm_get_wm_protocols_reply(conn,
6380             xcb_icccm_get_wm_protocols(conn, id, prot),
6381             &wpr, NULL)) {
6382                 for (i = 0; i < wpr.atoms_len; i++) {
6383                         if (wpr.atoms[i] == takefocus)
6384                                 win->take_focus = 1;
6385                         if (wpr.atoms[i] == adelete)
6386                                 win->can_delete = 1;
6387                 }
6388                 xcb_icccm_get_wm_protocols_reply_wipe(&wpr);
6389         }
6390
6391         win->iconic = get_iconic(win);
6392
6393         /*
6394          * Figure out where to put the window. If it was previously assigned to
6395          * a workspace (either by spawn() or manually moving), and isn't
6396          * transient, * put it in the same workspace
6397          */
6398         r = root_to_region(win->wa->root);
6399         if (p) {
6400                 ws = &r->s->ws[p->ws];
6401                 TAILQ_REMOVE(&pidlist, p, entry);
6402                 free(p);
6403                 p = NULL;
6404         } else if (prop && win->transient == 0) {
6405                 DNPRINTF(SWM_D_PROP, "manage_window: get _SWM_WS: %s\n", prop);
6406                 ws_idx = strtonum(prop, 0, workspace_limit - 1,
6407                     &errstr);
6408                 if (errstr) {
6409                         DNPRINTF(SWM_D_EVENT, "manage_window: window: #%s: %s",
6410                             errstr, prop);
6411                 }
6412                 ws = &r->s->ws[ws_idx];
6413         } else {
6414                 ws = r->ws;
6415                 /* this should launch transients in the same ws as parent */
6416                 if (id && trans)
6417                         if ((ww = find_window(trans)) != NULL)
6418                                 if (ws->r) {
6419                                         ws = ww->ws;
6420                                         if (ww->ws->r)
6421                                                 r = ww->ws->r;
6422                                         else
6423                                                 warnx("manage_window: fix this "
6424                                                     "bug mcbride");
6425                                         border_me = 1;
6426                                 }
6427         }
6428
6429         /* set up the window layout */
6430         win->id = id;
6431         win->ws = ws;
6432         win->s = r->s;  /* this never changes */
6433         if (trans && (ww = find_window(trans)))
6434                 TAILQ_INSERT_AFTER(&ws->winlist, ww, win, entry);
6435         else if (win->ws->focus && spawn_position == SWM_STACK_ABOVE)
6436                 TAILQ_INSERT_AFTER(&win->ws->winlist, win->ws->focus, win,
6437                     entry);
6438         else if (win->ws->focus && spawn_position == SWM_STACK_BELOW)
6439                 TAILQ_INSERT_BEFORE(win->ws->focus, win, entry);
6440         else switch (spawn_position) {
6441         default:
6442         case SWM_STACK_TOP:
6443         case SWM_STACK_ABOVE:
6444                 TAILQ_INSERT_TAIL(&win->ws->winlist, win, entry);
6445                 break;
6446         case SWM_STACK_BOTTOM:
6447         case SWM_STACK_BELOW:
6448                 TAILQ_INSERT_HEAD(&win->ws->winlist, win, entry);
6449         }
6450
6451         /* ignore window border if there is one. */
6452         WIDTH(win) = win->wa->width;
6453         HEIGHT(win) = win->wa->height;
6454         X(win) = win->wa->x + win->wa->border_width;
6455         Y(win) = win->wa->y + win->wa->border_width;
6456         win->bordered = 0;
6457         win->g_floatvalid = 0;
6458         win->floatmaxed = 0;
6459         win->ewmh_flags = 0;
6460
6461         DNPRINTF(SWM_D_MISC, "manage_window: window: 0x%x, (x,y) w x h: "
6462             "(%d,%d) %d x %d, ws: %d\n", win->id, X(win), Y(win), WIDTH(win),
6463             HEIGHT(win), ws->idx);
6464
6465         constrain_window(win, r, 0);
6466
6467         /* Set window properties so we can remember this after reincarnation */
6468         if (ws_idx_atom && prop == NULL &&
6469             snprintf(ws_idx_str, SWM_PROPLEN, "%d", ws->idx) <
6470                 SWM_PROPLEN) {
6471                 DNPRINTF(SWM_D_PROP, "manage_window: set _SWM_WS: %s\n",
6472                     ws_idx_str);
6473                 xcb_change_property(conn, XCB_PROP_MODE_REPLACE, win->id,
6474                     ws_idx_atom, XCB_ATOM_STRING, 8, strlen(ws_idx_str),
6475                     ws_idx_str);
6476         }
6477         if (prop)
6478                 free(prop);
6479
6480         ewmh_autoquirk(win);
6481
6482         if (xcb_icccm_get_wm_class_reply(conn,
6483             xcb_icccm_get_wm_class(conn, win->id),
6484             &win->ch, NULL)) {
6485                 DNPRINTF(SWM_D_CLASS, "manage_window: class: %s, name: %s\n",
6486                     win->ch.class_name, win->ch.instance_name);
6487
6488                 /* java is retarded so treat it special */
6489                 if (strstr(win->ch.instance_name, "sun-awt")) {
6490                         win->java = 1;
6491                         border_me = 1;
6492                 }
6493
6494                 TAILQ_FOREACH(qp, &quirks, entry) {
6495                         if (!strcmp(win->ch.class_name, qp->class) &&
6496                             !strcmp(win->ch.instance_name, qp->name)) {
6497                                 DNPRINTF(SWM_D_CLASS, "manage_window: found: "
6498                                     "class: %s, name: %s\n", win->ch.class_name,
6499                                     win->ch.instance_name);
6500                                 if (qp->quirk & SWM_Q_FLOAT) {
6501                                         win->floating = 1;
6502                                         border_me = 1;
6503                                 }
6504                                 win->quirks = qp->quirk;
6505                         }
6506                 }
6507         }
6508
6509         /* alter window position if quirky */
6510         if (win->quirks & SWM_Q_ANYWHERE) {
6511                 win->manual = 1; /* don't center the quirky windows */
6512                 if (bar_enabled && Y(win) < bar_height)
6513                         Y(win) = bar_height;
6514                 if (WIDTH(win) + X(win) > WIDTH(r))
6515                         X(win) = WIDTH(r) - WIDTH(win) - 2;
6516                 border_me = 1;
6517         }
6518
6519         /* Reset font sizes (the bruteforce way; no default keybinding). */
6520         if (win->quirks & SWM_Q_XTERM_FONTADJ) {
6521                 for (i = 0; i < SWM_MAX_FONT_STEPS; i++)
6522                         fake_keypress(win, XK_KP_Subtract, ShiftMask);
6523                 for (i = 0; i < SWM_MAX_FONT_STEPS; i++)
6524                         fake_keypress(win, XK_KP_Add, ShiftMask);
6525         }
6526
6527         ewmh_get_win_state(win);
6528         ewmh_update_actions(win);
6529         ewmh_update_win_state(win, None, _NET_WM_STATE_REMOVE);
6530
6531         /* border me */
6532         if (border_me) {
6533                 win->bordered = 1;
6534                 X(win) -= border_width;
6535                 Y(win) -= border_width;
6536                 update_window(win);
6537         }
6538
6539         event_mask = XCB_EVENT_MASK_ENTER_WINDOW | XCB_EVENT_MASK_FOCUS_CHANGE |
6540             XCB_EVENT_MASK_PROPERTY_CHANGE | XCB_EVENT_MASK_STRUCTURE_NOTIFY;
6541
6542         xcb_change_window_attributes(conn, id, XCB_CW_EVENT_MASK, &event_mask);
6543
6544         /* floaters need to be mapped if they are in the current workspace */
6545         if ((win->floating || win->transient) && (ws->idx == r->ws->idx))
6546                 map_window_raised(win->id);
6547
6548         return (win);
6549 }
6550
6551 void
6552 free_window(struct ws_win *win)
6553 {
6554         DNPRINTF(SWM_D_MISC, "free_window: window: 0x%x\n", win->id);
6555
6556         if (win == NULL)
6557                 return;
6558
6559         TAILQ_REMOVE(&win->ws->unmanagedlist, win, entry);
6560
6561         if (win->wa)
6562                 free(win->wa);
6563
6564         xcb_icccm_get_wm_class_reply_wipe(&win->ch);
6565
6566         kill_refs(win);
6567
6568         /* paint memory */
6569         memset(win, 0xff, sizeof *win); /* XXX kill later */
6570
6571         free(win);
6572         DNPRINTF(SWM_D_MISC, "free_window: done\n");
6573 }
6574
6575 void
6576 unmanage_window(struct ws_win *win)
6577 {
6578         struct ws_win           *parent;
6579         xcb_screen_t            *screen;
6580
6581         if (win == NULL)
6582                 return;
6583
6584         DNPRINTF(SWM_D_MISC, "unmanage_window: window: 0x%x\n", win->id);
6585
6586         if (win->transient) {
6587                 parent = find_window(win->transient);
6588                 if (parent)
6589                         parent->child_trans = NULL;
6590         }
6591
6592         /* focus on root just in case */
6593         screen = xcb_setup_roots_iterator(xcb_get_setup(conn)).data;
6594         xcb_set_input_focus(conn, XCB_INPUT_FOCUS_POINTER_ROOT,
6595             screen->root, XCB_CURRENT_TIME);
6596
6597         focus_prev(win);
6598
6599         TAILQ_REMOVE(&win->ws->winlist, win, entry);
6600         TAILQ_INSERT_TAIL(&win->ws->unmanagedlist, win, entry);
6601 }
6602
6603 void
6604 focus_magic(struct ws_win *win)
6605 {
6606         DNPRINTF(SWM_D_FOCUS, "focus_magic: window: 0x%x\n", WINID(win));
6607
6608         if (win == NULL) {
6609                 /* if there are no windows clear the status-bar */
6610                 bar_update();
6611                 return;
6612         }
6613
6614         if (win->child_trans) {
6615                 /* win = parent & has a transient so focus on that */
6616                 if (win->java) {
6617                         focus_win(win->child_trans);
6618                         if (win->child_trans->take_focus)
6619                                 client_msg(win, takefocus);
6620                 } else {
6621                         /* make sure transient hasn't disappeared */
6622                         if (validate_win(win->child_trans) == 0) {
6623                                 focus_win(win->child_trans);
6624                                 if (win->child_trans->take_focus)
6625                                         client_msg(win->child_trans, takefocus);
6626                         } else {
6627                                 win->child_trans = NULL;
6628                                 focus_win(win);
6629                                 if (win->take_focus)
6630                                         client_msg(win, takefocus);
6631                         }
6632                 }
6633         } else {
6634                 /* regular focus */
6635                 focus_win(win);
6636                 if (win->take_focus)
6637                         client_msg(win, takefocus);
6638         }
6639 }
6640
6641 void
6642 expose(xcb_expose_event_t *e)
6643 {
6644         int                     i, num_screens;
6645         struct swm_region       *r;
6646
6647         DNPRINTF(SWM_D_EVENT, "expose: window: 0x%x\n", e->window);
6648
6649         num_screens = xcb_setup_roots_length(xcb_get_setup(conn));
6650         for (i = 0; i < num_screens; i++)
6651                 TAILQ_FOREACH(r, &screens[i].rl, entry)
6652                         if (e->window == WINID(r->bar))
6653                                 bar_update();
6654
6655         xcb_flush(conn);
6656 }
6657
6658 void
6659 keypress(xcb_key_press_event_t *e)
6660 {
6661         KeySym                  keysym;
6662         struct key              *kp;
6663         struct swm_region       *r;
6664
6665         keysym = XkbKeycodeToKeysym(display, (KeyCode)e->detail, 0, 0);
6666
6667         DNPRINTF(SWM_D_EVENT, "keypress: %u\n", e->detail);
6668
6669         if ((kp = key_lookup(CLEANMASK(e->state), keysym)) == NULL)
6670                 return;
6671         if (keyfuncs[kp->funcid].func == NULL)
6672                 return;
6673
6674         r = root_to_region(e->root);
6675         if (kp->funcid == kf_spawn_custom)
6676                 spawn_custom(r, &(keyfuncs[kp->funcid].args), kp->spawn_name);
6677         else
6678                 keyfuncs[kp->funcid].func(r, &(keyfuncs[kp->funcid].args));
6679 }
6680
6681 void
6682 buttonpress(xcb_button_press_event_t *e)
6683 {
6684         struct ws_win           *win;
6685         int                     i, action;
6686
6687         DNPRINTF(SWM_D_EVENT, "buttonpress: window 0x%x, detail: %u\n",
6688             e->event, e->detail);
6689
6690         if ((win = find_window(e->event)) == NULL)
6691                 return;
6692
6693         focus_magic(win);
6694         action = client_click;
6695
6696         for (i = 0; i < LENGTH(buttons); i++)
6697                 if (action == buttons[i].action && buttons[i].func &&
6698                     buttons[i].button == e->detail &&
6699                     CLEANMASK(buttons[i].mask) == CLEANMASK(e->state))
6700                         buttons[i].func(win, &buttons[i].args);
6701 }
6702
6703 void
6704 configurerequest(xcb_configure_request_event_t *e)
6705 {
6706         struct ws_win           *win;
6707         int                     new = 0, i = 0;
6708         uint16_t                mask = 0;
6709         uint32_t                wc[7] = {0};
6710
6711         if ((win = find_window(e->window)) == NULL)
6712                 if ((win = find_unmanaged_window(e->window)) == NULL)
6713                         new = 1;
6714
6715         if (new) {
6716                 if (e->value_mask & XCB_CONFIG_WINDOW_X) {
6717                         mask |= XCB_CONFIG_WINDOW_X;
6718                         wc[i++] = e->x;
6719                 }
6720                 if (e->value_mask & XCB_CONFIG_WINDOW_Y) {
6721                         mask |= XCB_CONFIG_WINDOW_Y;
6722                         wc[i++] = e->y;
6723                 }
6724                 if (e->value_mask & XCB_CONFIG_WINDOW_WIDTH) {
6725                         mask |= XCB_CONFIG_WINDOW_WIDTH;
6726                         wc[i++] = e->width;
6727                 }
6728                 if (e->value_mask & XCB_CONFIG_WINDOW_HEIGHT) {
6729                         mask |= XCB_CONFIG_WINDOW_HEIGHT;
6730                         wc[i++] = e->height;
6731                 }
6732                 if (e->value_mask & XCB_CONFIG_WINDOW_BORDER_WIDTH) {
6733                         mask |= XCB_CONFIG_WINDOW_BORDER_WIDTH;
6734                         wc[i++] = e->border_width;
6735                 }
6736                 if (e->value_mask & XCB_CONFIG_WINDOW_SIBLING) {
6737                         mask |= XCB_CONFIG_WINDOW_SIBLING;
6738                         wc[i++] = e->sibling;
6739                 }
6740                 if (e->value_mask & XCB_CONFIG_WINDOW_STACK_MODE) {
6741                         mask |= XCB_CONFIG_WINDOW_STACK_MODE;
6742                         wc[i++] = e->stack_mode;
6743                 }
6744
6745                 DNPRINTF(SWM_D_EVENT, "configurerequest: new window: 0x%x, "
6746                     "new: %s, (x,y) w x h: (%d,%d) %d x %d\n", e->window,
6747                     YESNO(new), wc[0], wc[1], wc[2], wc[3]);
6748
6749                 xcb_configure_window(conn, e->window, mask, wc);
6750         } else if ((!win->manual || win->quirks & SWM_Q_ANYWHERE) &&
6751             !(win->ewmh_flags & EWMH_F_FULLSCREEN)) {
6752                 win->g_float.x = e->x - X(win->ws->r);
6753                 win->g_float.y = e->y - Y(win->ws->r);
6754                 win->g_float.w = e->width;
6755                 win->g_float.h = e->height;
6756                 win->g_floatvalid = 1;
6757
6758                 if (win->floating) {
6759                         win->g = win->g_float;
6760                         win->g.x += X(win->ws->r);
6761                         win->g.y += Y(win->ws->r);
6762                         update_window(win);
6763                 } else {
6764                         config_win(win, e);
6765                 }
6766         } else {
6767                 config_win(win, e);
6768         }
6769 }
6770
6771 void
6772 configurenotify(xcb_configure_notify_event_t *e)
6773 {
6774         struct ws_win           *win;
6775
6776         DNPRINTF(SWM_D_EVENT, "configurenotify: window: 0x%x\n",
6777             e->window);
6778
6779         win = find_window(e->window);
6780         if (win) {
6781                 xcb_icccm_get_wm_normal_hints_reply(conn,
6782                     xcb_icccm_get_wm_normal_hints(conn, win->id),
6783                     &win->sh, NULL);
6784                 adjust_font(win);
6785                 if (font_adjusted)
6786                         stack();
6787         }
6788 }
6789
6790 void
6791 destroynotify(xcb_destroy_notify_event_t *e)
6792 {
6793         struct ws_win           *win;
6794
6795         DNPRINTF(SWM_D_EVENT, "destroynotify: window: 0x%x\n", e->window);
6796
6797         if ((win = find_window(e->window)) == NULL) {
6798                 if ((win = find_unmanaged_window(e->window)) == NULL)
6799                         return;
6800                 free_window(win);
6801                 return;
6802         }
6803
6804         /* make sure we focus on something */
6805         win->floating = 0;
6806
6807         unmanage_window(win);
6808         stack();
6809         free_window(win);
6810 }
6811
6812 void
6813 enternotify(xcb_enter_notify_event_t *e)
6814 {
6815         struct ws_win           *win;
6816 #if 0
6817         struct ws_win           *w;
6818         Window                  focus_return;
6819         int                     revert_to_return;
6820 #endif
6821         DNPRINTF(SWM_D_FOCUS, "enternotify: window: 0x%x, mode: %d, detail: "
6822             "%d, root: 0x%x, subwindow: 0x%x, same_screen_focus: %s, "
6823             "state: %d\n", e->event, e->mode, e->detail, e->root,
6824             e->child, YESNO(e->same_screen_focus), e->state);
6825
6826         if (e->mode != XCB_NOTIFY_MODE_NORMAL) {
6827                 DNPRINTF(SWM_D_EVENT, "skip enternotify: generated by "
6828                     "cursor grab.\n");
6829                 return;
6830         }
6831
6832         switch (focus_mode) {
6833         case SWM_FOCUS_DEFAULT:
6834                 break;
6835         case SWM_FOCUS_FOLLOW:
6836                 break;
6837         case SWM_FOCUS_SYNERGY:
6838 #if 0
6839         /*
6840          * all these checks need to be in this order because the
6841          * XCheckTypedWindowEvent relies on weeding out the previous events
6842          *
6843          * making this code an option would enable a follow mouse for focus
6844          * feature
6845          */
6846
6847         /*
6848          * state is set when we are switching workspaces and focus is set when
6849          * the window or a subwindow already has focus (occurs during restart).
6850          *
6851          * Only honor the focus flag if last_focus_event is not FocusOut,
6852          * this allows spectrwm to continue to control focus when another
6853          * program is also playing with it.
6854          */
6855         if (ev->state || (ev->focus && last_focus_event != FocusOut)) {
6856                 DNPRINTF(SWM_D_EVENT, "ignoring enternotify: focus\n");
6857                 return;
6858         }
6859
6860         /*
6861          * happens when a window is created or destroyed and the border
6862          * crosses the mouse pointer and when switching ws
6863          *
6864          * we need the subwindow test to see if we came from root in order
6865          * to give focus to floaters
6866          */
6867         if (ev->mode == NotifyNormal && ev->detail == NotifyVirtual &&
6868             ev->subwindow == 0) {
6869                 DNPRINTF(SWM_D_EVENT, "ignoring enternotify: NotifyVirtual\n");
6870                 return;
6871         }
6872
6873         /* this window already has focus */
6874         if (ev->mode == NotifyNormal && ev->detail == NotifyInferior) {
6875                 DNPRINTF(SWM_D_EVENT, "ignoring enternotify: win has focus\n");
6876                 return;
6877         }
6878
6879         /* this window is being deleted or moved to another ws */
6880         if (XCheckTypedWindowEvent(display, ev->window, ConfigureNotify,
6881             &cne) == True) {
6882                 DNPRINTF(SWM_D_EVENT, "ignoring enternotify: configurenotify\n");
6883                 XPutBackEvent(display, &cne);
6884                 return;
6885         }
6886
6887         if ((win = find_window(ev->window)) == NULL) {
6888                 DNPRINTF(SWM_D_EVENT, "ignoring enternotify: win == NULL\n");
6889                 return;
6890         }
6891
6892         /*
6893          * In fullstack kill all enters unless they come from a different ws
6894          * (i.e. another region) or focus has been grabbed externally.
6895          */
6896         if (win->ws->cur_layout->flags & SWM_L_FOCUSPREV &&
6897             last_focus_event != FocusOut) {
6898                 XGetInputFocus(display, &focus_return, &revert_to_return);
6899                 if ((w = find_window(focus_return)) == NULL ||
6900                     w->ws == win->ws) {
6901                         DNPRINTF(SWM_D_EVENT, "ignoring event: fullstack\n");
6902                         return;
6903                 }
6904         }
6905 #endif
6906                 break;
6907         }
6908
6909         if ((win = find_window(e->event)) == NULL) {
6910                 DNPRINTF(SWM_D_EVENT, "skip enternotify: window is NULL\n");
6911                 return;
6912         }
6913
6914         focus_magic(win);
6915 }
6916
6917 /* lets us use one switch statement for arbitrary mode/detail combinations */
6918 #define MERGE_MEMBERS(a,b)      (((a & 0xffff) << 16) | (b & 0xffff))
6919
6920 void
6921 mapnotify(xcb_map_notify_event_t *e)
6922 {
6923         struct ws_win           *win;
6924
6925         DNPRINTF(SWM_D_EVENT, "mapnotify: window: 0x%x\n", e->window);
6926
6927         win = manage_window(e->window);
6928         if (win)
6929                 set_win_state(win, XCB_ICCCM_WM_STATE_NORMAL);
6930
6931         /*
6932          * focus_win can only set input focus on a mapped window.
6933          * make sure the window really has focus since it is just being mapped.
6934          */
6935         if (win->ws->focus == win)
6936                 focus_win(win);
6937 }
6938
6939 void
6940 mappingnotify(xcb_mapping_notify_event_t *e)
6941 {
6942         xcb_refresh_keyboard_mapping(syms, e);
6943
6944         if (e->request == XCB_MAPPING_KEYBOARD)
6945                 grabkeys();
6946 }
6947
6948 void
6949 maprequest(xcb_map_request_event_t *e)
6950 {
6951         struct ws_win           *win;
6952         struct swm_region       *r;
6953         xcb_get_window_attributes_reply_t *war;
6954
6955         DNPRINTF(SWM_D_EVENT, "maprequest: window: 0x%x\n",
6956             e->window);
6957
6958         war = xcb_get_window_attributes_reply(conn,
6959             xcb_get_window_attributes(conn, e->window),
6960             NULL);
6961         if (!war)
6962                 return;
6963         if (war->override_redirect) {
6964                 free(war);
6965                 return;
6966         }
6967         free(war);
6968
6969         win = manage_window(e->window);
6970         if (win == NULL) {
6971                 return; /* can't happen */
6972         }
6973
6974         stack();
6975
6976         /* make new win focused */
6977         r = root_to_region(win->wa->root);
6978         if (win->ws == r->ws)
6979                 focus_magic(win);
6980 }
6981
6982 void
6983 propertynotify(xcb_property_notify_event_t *e)
6984 {
6985         struct ws_win           *win;
6986 #ifdef SWM_DEBUG
6987         char                            *name;
6988         size_t                          len;
6989         xcb_get_atom_name_reply_t       *r;
6990
6991         r = xcb_get_atom_name_reply(conn,
6992             xcb_get_atom_name(conn, e->atom),
6993             NULL);
6994         if (r) {
6995                 len = xcb_get_atom_name_name_length(r);
6996                 if (len > 0) {
6997                         name = malloc(len + 1);
6998                         if (name) {
6999                                 memcpy(name, xcb_get_atom_name_name(r), len);
7000                                 name[len] = '\0';
7001
7002                                 DNPRINTF(SWM_D_EVENT,
7003                                     "propertynotify: window: 0x%x, atom: %s\n",
7004                                     e->window, name);
7005                                 free(name);
7006                         }
7007                 }
7008                 free(r);
7009         }
7010 #endif
7011
7012         win = find_window(e->window);
7013         if (win == NULL)
7014                 return;
7015
7016         if (e->state == XCB_PROPERTY_DELETE && e->atom == a_swm_iconic) {
7017                 update_iconic(win, 0);
7018                 map_window_raised(win->id);
7019                 stack();
7020                 focus_win(win);
7021                 return;
7022         }
7023
7024         switch (e->atom) {
7025 #if 0
7026         case XCB_ATOM_WM_NORMAL_HINTS:
7027                 xcb_icccm_get_wm_normal_hints(conn,
7028                         xcb_iccom_get_wm_normal_hints(conn, win->id),
7029                         &win->sh, NULL);
7030                 warnx("normal hints: flag 0x%x", win->sh.flags);
7031                 if (win->sh.flags & XCB_SIZE_HINT_P_MIN_SIZE) {
7032                         WIDTH(win) = win->sh.min_width;
7033                         HEIGHT(win) = win->sh.min_height;
7034                         warnx("min %d %d", WIDTH(win), HEIGHT(win));
7035                 }
7036                 XMoveResizeWindow(display, win->id,
7037                     X(win), Y(win), WIDTH(win), HEIGHT(win));
7038 #endif
7039         case XCB_ATOM_WM_CLASS:
7040         case XCB_ATOM_WM_NAME:
7041                 bar_update();
7042                 break;
7043         default:
7044                 break;
7045         }
7046 }
7047
7048 void
7049 unmapnotify(xcb_unmap_notify_event_t *e)
7050 {
7051         struct ws_win           *win;
7052
7053         DNPRINTF(SWM_D_EVENT, "unmapnotify: window: 0x%x\n", e->window);
7054
7055         /* determine if we need to help unmanage this window */
7056         win = find_window(e->window);
7057         if (win == NULL)
7058                 return;
7059
7060         if (getstate(e->window) == XCB_ICCCM_WM_STATE_NORMAL) {
7061                 unmanage_window(win);
7062                 stack();
7063
7064                 /* resend unmap because we ated it */
7065                 xcb_unmap_window(conn, e->window);
7066         }
7067 }
7068
7069 /*void
7070 visibilitynotify(xcb_visibility_notify_event_t *e)
7071 {
7072         DNPRINTF(SWM_D_EVENT, "visibilitynotify: window: 0x%x\n",
7073             e->window);
7074 }*/
7075
7076 void
7077 clientmessage(xcb_client_message_event_t *e)
7078 {
7079         struct ws_win *win;
7080
7081         win = find_window(e->window);
7082         if (win == NULL)
7083                 return;
7084         }
7085
7086         DNPRINTF(SWM_D_EVENT, "clientmessage: window: 0x%x, type: %u\n",
7087             e->window, e->type);
7088
7089         if (e->type == ewmh[_NET_ACTIVE_WINDOW].atom) {
7090                 DNPRINTF(SWM_D_EVENT, "clientmessage: _NET_ACTIVE_WINDOW\n");
7091                 focus_win(win);
7092         }
7093         if (e->type == ewmh[_NET_CLOSE_WINDOW].atom) {
7094                 DNPRINTF(SWM_D_EVENT, "clientmessage: _NET_CLOSE_WINDOW\n");
7095                 if (win->can_delete)
7096                         client_msg(win, adelete);
7097                 else
7098                         xcb_kill_client(conn, win->id);
7099         }
7100         if (e->type == ewmh[_NET_MOVERESIZE_WINDOW].atom) {
7101                 DNPRINTF(SWM_D_EVENT,
7102                     "clientmessage: _NET_MOVERESIZE_WINDOW\n");
7103                 if (win->floating) {
7104                         if (e->data.data32[0] & (1<<8)) /* x */
7105                                 X(win) = e->data.data32[1];
7106                         if (e->data.data32[0] & (1<<9)) /* y */
7107                                 Y(win) = e->data.data32[2];
7108                         if (e->data.data32[0] & (1<<10)) /* width */
7109                                 WIDTH(win) = e->data.data32[3];
7110                         if (e->data.data32[0] & (1<<11)) /* height */
7111                                 HEIGHT(win) = e->data.data32[4];
7112
7113                         update_window(win);
7114                 }
7115                 else {
7116                         /* TODO: Change stack sizes */
7117                         /* notify no change was made. */
7118                         config_win(win, NULL);
7119                 }
7120         }
7121         if (e->type == ewmh[_NET_WM_STATE].atom) {
7122                 DNPRINTF(SWM_D_EVENT, "clientmessage: _NET_WM_STATE\n");
7123                 ewmh_update_win_state(win, e->data.data32[1], e->data.data32[0]);
7124                 if (e->data.data32[2])
7125                         ewmh_update_win_state(win, e->data.data32[2],
7126                             e->data.data32[0]);
7127
7128                 stack();
7129         }
7130 }
7131
7132 int
7133 xerror_start(Display *d, XErrorEvent *ee)
7134 {
7135         other_wm = 1;
7136         return (-1);
7137 }
7138
7139 int
7140 xerror(Display *d, XErrorEvent *ee)
7141 {
7142         /* warnx("error: %p %p", display, ee); */
7143         return (-1);
7144 }
7145
7146 int
7147 active_wm(void)
7148 {
7149         other_wm = 0;
7150         xerrorxlib = XSetErrorHandler(xerror_start);
7151
7152         /* this causes an error if some other window manager is running */
7153         XSelectInput(display, DefaultRootWindow(display),
7154             SubstructureRedirectMask);
7155         do_sync();
7156         if (other_wm)
7157                 return (1);
7158
7159         XSetErrorHandler(xerror);
7160         do_sync();
7161         return (0);
7162 }
7163
7164 void
7165 new_region(struct swm_screen *s, int x, int y, int w, int h)
7166 {
7167         struct swm_region       *r, *n;
7168         struct workspace        *ws = NULL;
7169         int                     i;
7170
7171         DNPRINTF(SWM_D_MISC, "new region: screen[%d]:%dx%d+%d+%d\n",
7172              s->idx, w, h, x, y);
7173
7174         /* remove any conflicting regions */
7175         n = TAILQ_FIRST(&s->rl);
7176         while (n) {
7177                 r = n;
7178                 n = TAILQ_NEXT(r, entry);
7179                 if (X(r) < (x + w) &&
7180                     (X(r) + WIDTH(r)) > x &&
7181                     Y(r) < (y + h) &&
7182                     (Y(r) + HEIGHT(r)) > y) {
7183                         if (r->ws->r != NULL)
7184                                 r->ws->old_r = r->ws->r;
7185                         r->ws->r = NULL;
7186                         bar_cleanup(r);
7187                         TAILQ_REMOVE(&s->rl, r, entry);
7188                         TAILQ_INSERT_TAIL(&s->orl, r, entry);
7189                 }
7190         }
7191
7192         /* search old regions for one to reuse */
7193
7194         /* size + location match */
7195         TAILQ_FOREACH(r, &s->orl, entry)
7196                 if (X(r) == x && Y(r) == y &&
7197                     HEIGHT(r) == h && WIDTH(r) == w)
7198                         break;
7199
7200         /* size match */
7201         TAILQ_FOREACH(r, &s->orl, entry)
7202                 if (HEIGHT(r) == h && WIDTH(r) == w)
7203                         break;
7204
7205         if (r != NULL) {
7206                 TAILQ_REMOVE(&s->orl, r, entry);
7207                 /* try to use old region's workspace */
7208                 if (r->ws->r == NULL)
7209                         ws = r->ws;
7210         } else
7211                 if ((r = calloc(1, sizeof(struct swm_region))) == NULL)
7212                         err(1, "new_region: calloc: failed to allocate memory "
7213                             "for screen");
7214
7215         /* if we don't have a workspace already, find one */
7216         if (ws == NULL) {
7217                 for (i = 0; i < workspace_limit; i++)
7218                         if (s->ws[i].r == NULL) {
7219                                 ws = &s->ws[i];
7220                                 break;
7221                         }
7222         }
7223
7224         if (ws == NULL)
7225                 errx(1, "new_region: no free workspaces");
7226
7227         X(r) = x;
7228         Y(r) = y;
7229         WIDTH(r) = w;
7230         HEIGHT(r) = h;
7231         r->s = s;
7232         r->ws = ws;
7233         r->ws_prior = NULL;
7234         ws->r = r;
7235         outputs++;
7236         TAILQ_INSERT_TAIL(&s->rl, r, entry);
7237 }
7238
7239 void
7240 scan_xrandr(int i)
7241 {
7242 #ifdef SWM_XRR_HAS_CRTC
7243         int                                             c;
7244         int                                             ncrtc = 0;
7245 #endif /* SWM_XRR_HAS_CRTC */
7246         struct swm_region                               *r;
7247         int                                             num_screens;
7248         xcb_randr_get_screen_resources_current_cookie_t src;
7249         xcb_randr_get_screen_resources_current_reply_t  *srr;
7250         xcb_randr_get_crtc_info_cookie_t                cic;
7251         xcb_randr_get_crtc_info_reply_t                 *cir = NULL;
7252         xcb_randr_crtc_t                                *crtc;
7253         xcb_screen_t                                    *screen = get_screen(i);
7254
7255         num_screens = xcb_setup_roots_length(xcb_get_setup(conn));
7256         if (i >= num_screens)
7257                 errx(1, "scan_xrandr: invalid screen");
7258
7259         /* remove any old regions */
7260         while ((r = TAILQ_FIRST(&screens[i].rl)) != NULL) {
7261                 r->ws->old_r = r->ws->r = NULL;
7262                 bar_cleanup(r);
7263                 TAILQ_REMOVE(&screens[i].rl, r, entry);
7264                 TAILQ_INSERT_TAIL(&screens[i].orl, r, entry);
7265         }
7266         outputs = 0;
7267
7268         /* map virtual screens onto physical screens */
7269 #ifdef SWM_XRR_HAS_CRTC
7270         if (xrandr_support) {
7271                 src = xcb_randr_get_screen_resources_current(conn,
7272                     screens[i].root);
7273                 srr = xcb_randr_get_screen_resources_current_reply(conn, src,
7274                     NULL);
7275                 if (srr == NULL) {
7276                         new_region(&screens[i], 0, 0,
7277                             screen->width_in_pixels,
7278                             screen->height_in_pixels);
7279                         return;
7280                 } else
7281                         ncrtc = srr->num_crtcs;
7282                 for (c = 0; c < ncrtc; c++) {
7283                         crtc = xcb_randr_get_screen_resources_current_crtcs(srr);
7284                         cic = xcb_randr_get_crtc_info(conn, crtc[c],
7285                             XCB_CURRENT_TIME);
7286                         cir = xcb_randr_get_crtc_info_reply(conn, cic, NULL);
7287                         if (cir == NULL)
7288                                 continue;
7289                         if (cir->num_outputs == 0) {
7290                                 free(cir);
7291                                 continue;
7292                         }
7293
7294                         if (cir->mode == 0)
7295                                 new_region(&screens[i], 0, 0,
7296                                     screen->width_in_pixels,
7297                                     screen->height_in_pixels);
7298                         else
7299                                 new_region(&screens[i],
7300                                     cir->x, cir->y, cir->width, cir->height);
7301                         free(cir);
7302                 }
7303                 free(srr);
7304         } else
7305 #endif /* SWM_XRR_HAS_CRTC */
7306         {
7307                 new_region(&screens[i], 0, 0, screen->width_in_pixels,
7308                     screen->height_in_pixels);
7309         }
7310 }
7311
7312 void
7313 screenchange(xcb_randr_screen_change_notify_event_t *e)
7314 {
7315         struct swm_region               *r;
7316         int                             i, num_screens;
7317
7318         DNPRINTF(SWM_D_EVENT, "screenchange: root: 0x%x\n", e->root);
7319
7320         if (e->rotation & (XCB_RANDR_ROTATION_ROTATE_90
7321             | XCB_RANDR_ROTATION_ROTATE_270))
7322                 xcb_randr_set_screen_size(conn, e->root, e->height,
7323                     e->width, e->mheight, e->mwidth);
7324         else
7325                 xcb_randr_set_screen_size(conn, e->root, e->width,
7326                     e->height, e->mwidth, e->mheight);
7327
7328         num_screens = xcb_setup_roots_length(xcb_get_setup(conn));
7329         /* silly event doesn't include the screen index */
7330         for (i = 0; i < num_screens; i++)
7331                 if (screens[i].root == e->root)
7332                         break;
7333         if (i >= num_screens)
7334                 errx(1, "screenchange: screen not found");
7335
7336         /* brute force for now, just re-enumerate the regions */
7337         scan_xrandr(i);
7338
7339         /* add bars to all regions */
7340         for (i = 0; i < num_screens; i++)
7341                 TAILQ_FOREACH(r, &screens[i].rl, entry)
7342                         bar_setup(r);
7343         stack();
7344 }
7345
7346 void
7347 grab_windows(void)
7348 {
7349         xcb_window_t            *wins   = NULL;
7350         int                     no;
7351         int                     i, j, num_screens;
7352         uint16_t                state, manage;
7353
7354         xcb_query_tree_cookie_t                 qtc;
7355         xcb_query_tree_reply_t                  *qtr;
7356         xcb_get_window_attributes_cookie_t      c;
7357         xcb_get_window_attributes_reply_t       *r;
7358         xcb_get_property_cookie_t               pc;
7359
7360         num_screens = xcb_setup_roots_length(xcb_get_setup(conn));
7361         for (i = 0; i < num_screens; i++) {
7362                 qtc = xcb_query_tree(conn, screens[i].root);
7363                 qtr = xcb_query_tree_reply(conn, qtc, NULL);
7364                 if (!qtr)
7365                         continue;
7366                 wins = xcb_query_tree_children(qtr);
7367                 no = xcb_query_tree_children_length(qtr);
7368                 /* attach windows to a region */
7369                 /* normal windows */
7370                 for (j = 0; j < no; j++) {
7371                         c = xcb_get_window_attributes(conn, wins[j]);
7372                         r = xcb_get_window_attributes_reply(conn, c, NULL);
7373                         if (!r)
7374                                 continue;
7375                         if (r->override_redirect) {
7376                                 free(r);
7377                                 continue;
7378                         }
7379
7380                         pc = xcb_icccm_get_wm_transient_for(conn, wins[j]);
7381                         if (xcb_icccm_get_wm_transient_for_reply(conn, pc,
7382                             &wins[j], NULL)) {
7383                                 free(r);
7384                                 continue;
7385                         }
7386
7387                         state = getstate(wins[j]);
7388                         manage = state == XCB_ICCCM_WM_STATE_ICONIC;
7389                         if (r->map_state == XCB_MAP_STATE_VIEWABLE || manage)
7390                                 manage_window(wins[j]);
7391                         free(r);
7392                 }
7393                 /* transient windows */
7394                 for (j = 0; j < no; j++) {
7395                         c = xcb_get_window_attributes(conn, wins[j]);
7396                         r = xcb_get_window_attributes_reply(conn, c, NULL);
7397                         if (!r)
7398                                 continue;
7399                         if (r->override_redirect) {
7400                                 free(r);
7401                                 continue;
7402                         }
7403                         free(r);
7404
7405                         state = getstate(wins[j]);
7406                         manage = state == XCB_ICCCM_WM_STATE_ICONIC;
7407                         pc = xcb_icccm_get_wm_transient_for(conn, wins[j]);
7408                         if (xcb_icccm_get_wm_transient_for_reply(conn, pc,
7409                             &wins[j], NULL) && manage)
7410                                 manage_window(wins[j]);
7411                 }
7412                 free(qtr);
7413         }
7414 }
7415
7416 void
7417 setup_screens(void)
7418 {
7419         int                     i, j, k, num_screens;
7420         struct workspace        *ws;
7421         uint32_t                gcv[1], wa[1];
7422         const xcb_query_extension_reply_t *qep;
7423         xcb_cursor_t                            cursor;
7424         xcb_font_t                              cursor_font;
7425         xcb_randr_query_version_cookie_t        c;
7426         xcb_randr_query_version_reply_t         *r;
7427
7428         num_screens = xcb_setup_roots_length(xcb_get_setup(conn));
7429         if ((screens = calloc(num_screens,
7430              sizeof(struct swm_screen))) == NULL)
7431                 err(1, "setup_screens: calloc: failed to allocate memory for "
7432                     "screens");
7433
7434         /* initial Xrandr setup */
7435         xrandr_support = False;
7436         c = xcb_randr_query_version(conn, True, True);
7437         r = xcb_randr_query_version_reply(conn, c, NULL);
7438         if (r) {
7439                 if (r->major_version >= 1)
7440                         xrandr_support = True;
7441                 free(r);
7442         }
7443         qep = xcb_get_extension_data(conn, &xcb_randr_id);
7444         xrandr_eventbase = qep->first_event;
7445
7446         cursor_font = xcb_generate_id(conn);
7447         xcb_open_font(conn, cursor_font, strlen("cursor"), "cursor");
7448
7449         cursor = xcb_generate_id(conn);
7450         xcb_create_glyph_cursor(conn, cursor, cursor_font, cursor_font,
7451                 XC_left_ptr, XC_left_ptr + 1, 0, 0, 0, 0xffff, 0xffff, 0xffff);
7452         wa[0] = cursor;
7453
7454         /* map physical screens */
7455         for (i = 0; i < num_screens; i++) {
7456                 DNPRINTF(SWM_D_WS, "setup_screens: init screen: %d\n", i);
7457                 screens[i].idx = i;
7458                 TAILQ_INIT(&screens[i].rl);
7459                 TAILQ_INIT(&screens[i].orl);
7460                 screens[i].root = RootWindow(display, i);
7461
7462                 /* set default colors */
7463                 setscreencolor("red", i + 1, SWM_S_COLOR_FOCUS);
7464                 setscreencolor("rgb:88/88/88", i + 1, SWM_S_COLOR_UNFOCUS);
7465                 setscreencolor("rgb:00/80/80", i + 1, SWM_S_COLOR_BAR_BORDER);
7466                 setscreencolor("black", i + 1, SWM_S_COLOR_BAR);
7467                 setscreencolor("rgb:a0/a0/a0", i + 1, SWM_S_COLOR_BAR_FONT);
7468
7469                 /* create graphics context on screen */
7470                 screens[i].bar_gc = xcb_generate_id(conn);
7471                 gcv[0] = 0;
7472                 xcb_create_gc(conn, screens[i].bar_gc, screens[i].root,
7473                     XCB_GC_GRAPHICS_EXPOSURES, gcv);
7474
7475                 /* set default cursor */
7476                 xcb_change_window_attributes(conn, screens[i].root,
7477                     XCB_CW_CURSOR, wa);
7478
7479                 /* init all workspaces */
7480                 /* XXX these should be dynamically allocated too */
7481                 for (j = 0; j < SWM_WS_MAX; j++) {
7482                         ws = &screens[i].ws[j];
7483                         ws->idx = j;
7484                         ws->name = NULL;
7485                         ws->focus = NULL;
7486                         ws->r = NULL;
7487                         ws->old_r = NULL;
7488                         TAILQ_INIT(&ws->winlist);
7489                         TAILQ_INIT(&ws->unmanagedlist);
7490
7491                         for (k = 0; layouts[k].l_stack != NULL; k++)
7492                                 if (layouts[k].l_config != NULL)
7493                                         layouts[k].l_config(ws,
7494                                             SWM_ARG_ID_STACKINIT);
7495                         ws->cur_layout = &layouts[0];
7496                         ws->cur_layout->l_string(ws);
7497                 }
7498
7499                 scan_xrandr(i);
7500
7501                 if (xrandr_support)
7502                         xcb_randr_select_input(conn, screens[i].root,
7503                             XCB_RANDR_NOTIFY_MASK_SCREEN_CHANGE);
7504         }
7505         xcb_free_cursor(conn, cursor);
7506         xcb_close_font(conn, cursor_font);
7507 }
7508
7509 void
7510 setup_globals(void)
7511 {
7512         if ((bar_fonts = strdup(SWM_BAR_FONTS)) == NULL)
7513                 err(1, "setup_globals: strdup: failed to allocate memory.");
7514
7515         if ((clock_format = strdup("%a %b %d %R %Z %Y")) == NULL)
7516                 err(1, "setup_globals: strdup: failed to allocate memory.");
7517 }
7518
7519 void
7520 workaround(void)
7521 {
7522         int                     i, num_screens;
7523         xcb_atom_t              netwmcheck, netwmname, utf8_string;
7524         xcb_window_t            root, win;
7525         uint32_t                wa[2];
7526
7527         /* work around sun jdk bugs, code from wmname */
7528         netwmcheck = get_atom_from_string("_NET_SUPPORTING_WM_CHECK");
7529         netwmname = get_atom_from_string("_NET_WM_NAME");
7530         utf8_string = get_atom_from_string("UTF8_STRING");
7531
7532         num_screens = xcb_setup_roots_length(xcb_get_setup(conn));
7533         for (i = 0; i < num_screens; i++) {
7534                 root = screens[i].root;
7535
7536                 win = xcb_generate_id(conn);
7537                 wa[0] = screens[i].c[SWM_S_COLOR_UNFOCUS].color;
7538                 wa[1] = screens[i].c[SWM_S_COLOR_UNFOCUS].color;
7539                 xcb_create_window(conn, XCB_COPY_FROM_PARENT, win, 0, 0, 0, 1,
7540                     1, 0, XCB_WINDOW_CLASS_INPUT_OUTPUT, XCB_COPY_FROM_PARENT,
7541                     XCB_CW_BACK_PIXEL | XCB_CW_BORDER_PIXEL, wa);
7542
7543                 xcb_change_property(conn, XCB_PROP_MODE_REPLACE, root,
7544                     netwmcheck, XCB_ATOM_WINDOW, 32, 1, &win);
7545                 xcb_change_property(conn, XCB_PROP_MODE_REPLACE, win,
7546                     netwmcheck, XCB_ATOM_WINDOW, 32, 1, &win);
7547                 xcb_change_property(conn, XCB_PROP_MODE_REPLACE, win,
7548                     netwmname, utf8_string, 8, strlen("LG3D"), "LG3D");
7549         }
7550 }
7551
7552 void
7553 event_error(xcb_generic_error_t *e)
7554 {
7555         DNPRINTF(SWM_D_EVENT, "event_error: %s(%u) from %s(%u), sequence: %u, "
7556             "resource_id: %u, minor_code: %u\n",
7557             xcb_event_get_error_label(e->error_code), e->error_code,
7558             xcb_event_get_request_label(e->major_code), e->major_code,
7559             e->sequence, e->resource_id, e->minor_code);
7560 }
7561
7562 void
7563 event_handle(xcb_generic_event_t *evt)
7564 {
7565         uint8_t type = XCB_EVENT_RESPONSE_TYPE(evt);
7566
7567         DNPRINTF(SWM_D_EVENT, "XCB Event: %s(%d)\n",
7568             xcb_event_get_label(XCB_EVENT_RESPONSE_TYPE(evt)),
7569             XCB_EVENT_RESPONSE_TYPE(evt));
7570
7571         switch (type) {
7572 #define EVENT(type, callback) case type: callback((void *)evt); return
7573         EVENT(0, event_error);
7574         EVENT(XCB_BUTTON_PRESS, buttonpress);
7575         /*EVENT(XCB_BUTTON_RELEASE, buttonpress);*/
7576         /*EVENT(XCB_CIRCULATE_NOTIFY, );*/
7577         /*EVENT(XCB_CIRCULATE_REQUEST, );*/
7578         EVENT(XCB_CLIENT_MESSAGE, clientmessage);
7579         /*EVENT(XCB_COLORMAP_NOTIFY, );*/
7580         EVENT(XCB_CONFIGURE_NOTIFY, configurenotify);
7581         EVENT(XCB_CONFIGURE_REQUEST, configurerequest);
7582         /*EVENT(XCB_CREATE_NOTIFY, );*/
7583         EVENT(XCB_DESTROY_NOTIFY, destroynotify);
7584         EVENT(XCB_ENTER_NOTIFY, enternotify);
7585         EVENT(XCB_EXPOSE, expose);
7586         /*EVENT(XCB_FOCUS_IN, );*/
7587         /*EVENT(XCB_FOCUS_OUT, );*/
7588         /*EVENT(XCB_GRAPHICS_EXPOSURE, );*/
7589         /*EVENT(XCB_GRAVITY_NOTIFY, );*/
7590         EVENT(XCB_KEY_PRESS, keypress);
7591         /*EVENT(XCB_KEY_RELEASE, keypress);*/
7592         /*EVENT(XCB_KEYMAP_NOTIFY, );*/
7593         /*EVENT(XCB_LEAVE_NOTIFY, );*/
7594         EVENT(XCB_MAP_NOTIFY, mapnotify);
7595         EVENT(XCB_MAP_REQUEST, maprequest);
7596         EVENT(XCB_MAPPING_NOTIFY, mappingnotify);
7597         /*EVENT(XCB_MOTION_NOTIFY, );*/
7598         /*EVENT(XCB_NO_EXPOSURE, );*/
7599         EVENT(XCB_PROPERTY_NOTIFY, propertynotify);
7600         /*EVENT(XCB_REPARENT_NOTIFY, );*/
7601         /*EVENT(XCB_RESIZE_REQUEST, );*/
7602         /*EVENT(XCB_SELECTION_CLEAR, );*/
7603         /*EVENT(XCB_SELECTION_NOTIFY, );*/
7604         /*EVENT(XCB_SELECTION_REQUEST, );*/
7605         EVENT(XCB_UNMAP_NOTIFY, unmapnotify);
7606         /*EVENT(XCB_VISIBILITY_NOTIFY, visibilitynotify);*/
7607 #undef EVENT
7608         }
7609         if (type - xrandr_eventbase == XCB_RANDR_SCREEN_CHANGE_NOTIFY)
7610                 screenchange((void *)evt);
7611 }
7612
7613 int
7614 main(int argc, char *argv[])
7615 {
7616         struct swm_region       *r, *rr;
7617         struct ws_win           *winfocus = NULL;
7618         union arg               a;
7619         char                    conf[PATH_MAX], *cfile = NULL;
7620         struct stat             sb;
7621         int                     xfd, i, num_screens;
7622         struct sigaction        sact;
7623         xcb_generic_event_t     *evt;
7624 #if 0
7625         struct timeval          tv;
7626         fd_set                  rd;
7627 #endif
7628
7629         time_started = time(NULL);
7630
7631         start_argv = argv;
7632         warnx("Welcome to spectrwm V%s Build: %s", SPECTRWM_VERSION, buildstr);
7633         if (!setlocale(LC_CTYPE, "") || !setlocale(LC_TIME, "") ||
7634             !XSupportsLocale())
7635                 warnx("no locale support");
7636
7637         if (!X_HAVE_UTF8_STRING)
7638                 warnx("no UTF-8 support");
7639
7640         if (!(display = XOpenDisplay(0)))
7641                 errx(1, "can not open display");
7642
7643         /* handle some signals */
7644         bzero(&sact, sizeof(sact));
7645         sigemptyset(&sact.sa_mask);
7646         sact.sa_flags = 0;
7647         sact.sa_handler = sighdlr;
7648         sigaction(SIGINT, &sact, NULL);
7649         sigaction(SIGQUIT, &sact, NULL);
7650         sigaction(SIGTERM, &sact, NULL);
7651         sigaction(SIGHUP, &sact, NULL);
7652
7653         sact.sa_handler = sighdlr;
7654         sact.sa_flags = SA_NOCLDSTOP;
7655         sigaction(SIGCHLD, &sact, NULL);
7656
7657         conn = XGetXCBConnection(display);
7658         if (xcb_connection_has_error(conn))
7659                 errx(1, "can not get XCB connection");
7660
7661         xfd = xcb_get_file_descriptor(conn);
7662         syms = xcb_key_symbols_alloc(conn);
7663         if (!syms)
7664                 errx(1, "unable to allocate key symbols");
7665
7666         astate = get_atom_from_string("WM_STATE");
7667         aprot = get_atom_from_string("WM_PROTOCOLS");
7668         adelete = get_atom_from_string("WM_DELETE_WINDOW");
7669         takefocus = get_atom_from_string("WM_TAKE_FOCUS");
7670         a_wmname = get_atom_from_string("WM_NAME");
7671         a_netwmname = get_atom_from_string("_NET_WM_NAME");
7672         a_utf8_string = get_atom_from_string("UTF8_STRING");
7673         a_string = get_atom_from_string("STRING");
7674         a_swm_iconic = get_atom_from_string("_SWM_ICONIC");
7675
7676         /* look for local and global conf file */
7677         pwd = getpwuid(getuid());
7678         if (pwd == NULL)
7679                 errx(1, "invalid user: %d", getuid());
7680
7681         xcb_grab_server(conn);
7682         xcb_aux_sync(conn);
7683
7684         /* flush all events */
7685         while ((evt = xcb_poll_for_event(conn))) {
7686                 if (XCB_EVENT_RESPONSE_TYPE(evt) == 0)
7687                         event_handle(evt);
7688                 free(evt);
7689         }
7690
7691         if (active_wm())
7692                 errx(1, "other wm running");
7693
7694         xcb_aux_sync(conn);
7695
7696         setup_globals();
7697         setup_screens();
7698         setup_keys();
7699         setup_quirks();
7700         setup_spawn();
7701
7702         /* load config */
7703         for (i = 0; ; i++) {
7704                 conf[0] = '\0';
7705                 switch (i) {
7706                 case 0:
7707                         /* ~ */
7708                         snprintf(conf, sizeof conf, "%s/.%s",
7709                             pwd->pw_dir, SWM_CONF_FILE);
7710                         break;
7711                 case 1:
7712                         /* global */
7713                         snprintf(conf, sizeof conf, "/etc/%s",
7714                             SWM_CONF_FILE);
7715                         break;
7716                 case 2:
7717                         /* ~ compat */
7718                         snprintf(conf, sizeof conf, "%s/.%s",
7719                             pwd->pw_dir, SWM_CONF_FILE_OLD);
7720                         break;
7721                 case 3:
7722                         /* global compat */
7723                         snprintf(conf, sizeof conf, "/etc/%s",
7724                             SWM_CONF_FILE_OLD);
7725                         break;
7726                 default:
7727                         goto noconfig;
7728                 }
7729
7730                 if (strlen(conf) && stat(conf, &sb) != -1)
7731                         if (S_ISREG(sb.st_mode)) {
7732                                 cfile = conf;
7733                                 break;
7734                         }
7735         }
7736 noconfig:
7737
7738         /* load conf (if any) */
7739         if (cfile)
7740                 conf_load(cfile, SWM_CONF_DEFAULT);
7741
7742         setup_ewmh();
7743         /* set some values to work around bad programs */
7744         workaround();
7745         /* grab existing windows (before we build the bars) */
7746         grab_windows();
7747
7748         if (getenv("SWM_STARTED") == NULL)
7749                 setenv("SWM_STARTED", "YES", 1);
7750
7751         /* setup all bars */
7752         num_screens = xcb_setup_roots_length(xcb_get_setup(conn));
7753         for (i = 0; i < num_screens; i++)
7754                 TAILQ_FOREACH(r, &screens[i].rl, entry) {
7755                         if (winfocus == NULL)
7756                                 winfocus = TAILQ_FIRST(&r->ws->winlist);
7757                         bar_setup(r);
7758                 }
7759
7760         //unfocus_all();
7761
7762         grabkeys();
7763         stack();
7764
7765         xcb_ungrab_server(conn);
7766         xcb_flush(conn);
7767
7768         while (running) {
7769                 while ((evt = xcb_poll_for_event(conn))) {
7770                         if (running == 0)
7771                                 goto done;
7772                         event_handle(evt);
7773                         free(evt);
7774                 }
7775
7776                 /* if we are being restarted go focus on first window */
7777                 if (winfocus) {
7778                         rr = winfocus->ws->r;
7779                         if (rr == NULL) {
7780                                 /* not a visible window */
7781                                 winfocus = NULL;
7782                                 continue;
7783                         }
7784                         /* move pointer to first screen if multi screen */
7785                         if (num_screens > 1 || outputs > 1)
7786                                 xcb_warp_pointer(conn, XCB_WINDOW_NONE,
7787                                     rr->s[0].root, 0, 0, 0, 0, X(rr),
7788                                     Y(rr) + (bar_enabled ? bar_height : 0));
7789
7790                         a.id = SWM_ARG_ID_FOCUSCUR;
7791                         focus(rr, &a);
7792                         winfocus = NULL;
7793                         continue;
7794                 }
7795
7796 #if 0
7797                 FD_ZERO(&rd);
7798                 FD_SET(xfd, &rd);
7799                 tv.tv_sec = 1;
7800                 tv.tv_usec = 0;
7801                 if (select(xfd + 1, &rd, NULL, NULL, &tv) == -1)
7802                         if (errno != EINTR)
7803                                 DNPRINTF(SWM_D_MISC, "select failed");
7804 #endif
7805                 if (restart_wm == 1)
7806                         restart(NULL, NULL);
7807                 if (search_resp == 1)
7808                         search_do_resp();
7809                 if (running == 0)
7810                         goto done;
7811                 if (bar_alarm) {
7812                         bar_alarm = 0;
7813                         bar_update();
7814                 }
7815         }
7816 done:
7817         teardown_ewmh();
7818         bar_extra_stop();
7819
7820         for (i = 0; i < num_screens; ++i)
7821                 if (screens[i].bar_gc != 0)
7822                         xcb_free_gc(conn, screens[i].bar_gc);
7823         XFreeFontSet(display, bar_fs);
7824
7825         xcb_key_symbols_free(syms);
7826         xcb_disconnect(conn);
7827
7828         return (0);
7829 }