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