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