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