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