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