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