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