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