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