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