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