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