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