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