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