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