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