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