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