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