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