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