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