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