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