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