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