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