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