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