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