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