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