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