JasonWoof Got questions, comments, patches, etc.? Contact Jason Woofenden
fix fullscreen on mplayer again and revert most of the xemacs quirk as it
[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         fprintf(stderr, "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         DNPRINTF(SWM_D_MISC, "config_win: win %lu x %d y %d w %d h %d\n",
1387             win->id, win->g.x, win->g.y, win->g.w, win->g.h);
1388
1389         if (win == NULL)
1390                 return;
1391
1392         if (ev == NULL) {
1393                 ce.type = ConfigureNotify;
1394                 ce.display = display;
1395                 ce.event = win->id;
1396                 ce.window = win->id;
1397                 ce.x = win->g.x;
1398                 ce.y = win->g.y;
1399                 ce.width = win->g.w;
1400                 ce.height = win->g.h;
1401                 ce.border_width = border_width;
1402                 ce.above = None;
1403                 ce.override_redirect = False;
1404         } else {
1405                 ce.type = ConfigureNotify;
1406                 ce.display = ev->display;
1407                 ce.event = ev->window;
1408                 ce.window = ev->window;
1409                 ce.x = ev->x;
1410                 ce.y = ev->y;
1411                 ce.width = ev->width;
1412                 ce.height = ev->height;
1413                 ce.border_width = ev->border_width;
1414                 ce.above = ev->above;
1415                 ce.override_redirect = False;
1416         }
1417
1418         XSendEvent(display, win->id, False, StructureNotifyMask, (XEvent *)&ce);
1419 }
1420
1421 int
1422 count_win(struct workspace *ws, int count_transient)
1423 {
1424         struct ws_win           *win;
1425         int                     count = 0;
1426
1427         TAILQ_FOREACH(win, &ws->winlist, entry) {
1428                 if (count_transient == 0 && win->floating)
1429                         continue;
1430                 if (count_transient == 0 && win->transient)
1431                         continue;
1432                 count++;
1433         }
1434         DNPRINTF(SWM_D_MISC, "count_win: %d\n", count);
1435
1436         return (count);
1437 }
1438
1439 void
1440 quit(struct swm_region *r, union arg *args)
1441 {
1442         DNPRINTF(SWM_D_MISC, "quit\n");
1443         running = 0;
1444 }
1445
1446 void
1447 unmap_window(struct ws_win *win)
1448 {
1449         if (win == NULL)
1450                 return;
1451
1452         /* don't unmap again */
1453         if (getstate(win->id) == IconicState)
1454                 return;
1455
1456         set_win_state(win, IconicState);
1457
1458         XUnmapWindow(display, win->id);
1459         XSetWindowBorder(display, win->id,
1460             win->s->c[SWM_S_COLOR_UNFOCUS].color);
1461 }
1462
1463 void
1464 unmap_all(void)
1465 {
1466         struct ws_win           *win;
1467         int                     i, j;
1468
1469         for (i = 0; i < ScreenCount(display); i++)
1470                 for (j = 0; j < SWM_WS_MAX; j++)
1471                         TAILQ_FOREACH(win, &screens[i].ws[j].winlist, entry)
1472                                 unmap_window(win);
1473 }
1474
1475 void
1476 fake_keypress(struct ws_win *win, int keysym, int modifiers)
1477 {
1478         XKeyEvent event;
1479
1480         if (win == NULL)
1481                 return;
1482
1483         event.display = display;        /* Ignored, but what the hell */
1484         event.window = win->id;
1485         event.root = win->s->root;
1486         event.subwindow = None;
1487         event.time = CurrentTime;
1488         event.x = win->g.x;
1489         event.y = win->g.y;
1490         event.x_root = 1;
1491         event.y_root = 1;
1492         event.same_screen = True;
1493         event.keycode = XKeysymToKeycode(display, keysym);
1494         event.state = modifiers;
1495
1496         event.type = KeyPress;
1497         XSendEvent(event.display, event.window, True,
1498             KeyPressMask, (XEvent *)&event);
1499
1500         event.type = KeyRelease;
1501         XSendEvent(event.display, event.window, True,
1502             KeyPressMask, (XEvent *)&event);
1503
1504 }
1505
1506 void
1507 restart(struct swm_region *r, union arg *args)
1508 {
1509         DNPRINTF(SWM_D_MISC, "restart: %s\n", start_argv[0]);
1510
1511         /* disable alarm because the following code may not be interrupted */
1512         alarm(0);
1513         if (signal(SIGALRM, SIG_IGN) == SIG_ERR)
1514                 errx(1, "can't disable alarm");
1515
1516         bar_extra_stop();
1517         bar_extra = 1;
1518         unmap_all();
1519         XCloseDisplay(display);
1520         execvp(start_argv[0], start_argv);
1521         fprintf(stderr, "execvp failed\n");
1522         perror(" failed");
1523         quit(NULL, NULL);
1524 }
1525
1526 struct swm_region *
1527 root_to_region(Window root)
1528 {
1529         struct swm_region       *r = NULL;
1530         Window                  rr, cr;
1531         int                     i, x, y, wx, wy;
1532         unsigned int            mask;
1533
1534         for (i = 0; i < ScreenCount(display); i++)
1535                 if (screens[i].root == root)
1536                         break;
1537
1538         if (XQueryPointer(display, screens[i].root,
1539             &rr, &cr, &x, &y, &wx, &wy, &mask) != False) {
1540                 /* choose a region based on pointer location */
1541                 TAILQ_FOREACH(r, &screens[i].rl, entry)
1542                         if (x >= X(r) && x <= X(r) + WIDTH(r) &&
1543                             y >= Y(r) && y <= Y(r) + HEIGHT(r))
1544                                 break;
1545         }
1546
1547         if (r == NULL)
1548                 r = TAILQ_FIRST(&screens[i].rl);
1549
1550         return (r);
1551 }
1552
1553 struct ws_win *
1554 find_unmanaged_window(Window id)
1555 {
1556         struct ws_win           *win;
1557         int                     i, j;
1558
1559         for (i = 0; i < ScreenCount(display); i++)
1560                 for (j = 0; j < SWM_WS_MAX; j++)
1561                         TAILQ_FOREACH(win, &screens[i].ws[j].unmanagedlist,
1562                             entry)
1563                                 if (id == win->id)
1564                                         return (win);
1565         return (NULL);
1566 }
1567
1568 struct ws_win *
1569 find_window(Window id)
1570 {
1571         struct ws_win           *win;
1572         Window                  wrr, wpr, *wcr = NULL;
1573         int                     i, j;
1574         unsigned int            nc;
1575
1576         for (i = 0; i < ScreenCount(display); i++)
1577                 for (j = 0; j < SWM_WS_MAX; j++)
1578                         TAILQ_FOREACH(win, &screens[i].ws[j].winlist, entry)
1579                                 if (id == win->id)
1580                                         return (win);
1581
1582         /* if we were looking for the parent return that window instead */
1583         if (XQueryTree(display, id, &wrr, &wpr, &wcr, &nc) == 0)
1584                 return (NULL);
1585         if (wcr)
1586                 XFree(wcr);
1587
1588         /* ignore not found and root */
1589         if (wpr == 0 || wrr == wpr)
1590                 return (NULL);
1591
1592         /* look for parent */
1593         for (i = 0; i < ScreenCount(display); i++)
1594                 for (j = 0; j < SWM_WS_MAX; j++)
1595                         TAILQ_FOREACH(win, &screens[i].ws[j].winlist, entry)
1596                                 if (wpr == win->id)
1597                                         return (win);
1598
1599         return (NULL);
1600 }
1601
1602 void
1603 spawn(struct swm_region *r, union arg *args)
1604 {
1605         int                     fd;
1606         char                    *ret = NULL;
1607
1608         DNPRINTF(SWM_D_MISC, "spawn: %s\n", args->argv[0]);
1609
1610         if (fork() == 0) {
1611                 if (display)
1612                         close(ConnectionNumber(display));
1613
1614                 setenv("LD_PRELOAD", SWM_LIB, 1);
1615
1616                 if (asprintf(&ret, "%d", r->ws->idx) == -1) {
1617                         perror("_SWM_WS");
1618                         _exit(1);
1619                 }
1620                 setenv("_SWM_WS", ret, 1);
1621                 free(ret);
1622                 ret = NULL;
1623
1624                 if (asprintf(&ret, "%d", getpid()) == -1) {
1625                         perror("_SWM_PID");
1626                         _exit(1);
1627                 }
1628                 setenv("_SWM_PID", ret, 1);
1629                 free(ret);
1630                 ret = NULL;
1631
1632                 if (setsid() == -1) {
1633                         perror("setsid");
1634                         _exit(1);
1635                 }
1636
1637                 /*
1638                  * close stdin and stdout to prevent interaction between apps
1639                  * and the baraction script
1640                  * leave stderr open to record errors
1641                 */
1642                 if ((fd = open(_PATH_DEVNULL, O_RDWR, 0)) == -1) {
1643                         perror("open");
1644                         _exit(1);
1645                 }
1646                 dup2(fd, STDIN_FILENO);
1647                 dup2(fd, STDOUT_FILENO);
1648                 if (fd > 2)
1649                         close(fd);
1650
1651                 execvp(args->argv[0], args->argv);
1652
1653                 perror("execvp");
1654                 _exit(1);
1655         }
1656 }
1657
1658 void
1659 spawnterm(struct swm_region *r, union arg *args)
1660 {
1661         DNPRINTF(SWM_D_MISC, "spawnterm\n");
1662
1663         if (term_width)
1664                 setenv("_SWM_XTERM_FONTADJ", "", 1);
1665         spawn(r, args);
1666 }
1667
1668 void
1669 kill_refs(struct ws_win *win)
1670 {
1671         int                     i, x;
1672         struct swm_region       *r;
1673         struct workspace        *ws;
1674
1675         if (win == NULL)
1676                 return;
1677
1678         for (i = 0; i < ScreenCount(display); i++)
1679                 TAILQ_FOREACH(r, &screens[i].rl, entry)
1680                         for (x = 0; x < SWM_WS_MAX; x++) {
1681                                 ws = &r->s->ws[x];
1682                                 if (win == ws->focus)
1683                                         ws->focus = NULL;
1684                                 if (win == ws->focus_prev)
1685                                         ws->focus_prev = NULL;
1686                         }
1687 }
1688
1689 int
1690 validate_win(struct ws_win *testwin)
1691 {
1692         struct ws_win           *win;
1693         struct workspace        *ws;
1694         struct swm_region       *r;
1695         int                     i, x, foundit = 0;
1696
1697         if (testwin == NULL)
1698                 return(0);
1699
1700         for (i = 0, foundit = 0; i < ScreenCount(display); i++)
1701                 TAILQ_FOREACH(r, &screens[i].rl, entry)
1702                         for (x = 0; x < SWM_WS_MAX; x++) {
1703                                 ws = &r->s->ws[x];
1704                                 TAILQ_FOREACH(win, &ws->winlist, entry)
1705                                         if (win == testwin)
1706                                                 return (0);
1707                         }
1708         return (1);
1709 }
1710
1711 int
1712 validate_ws(struct workspace *testws)
1713 {
1714         struct swm_region       *r;
1715         struct workspace        *ws;
1716         int                     foundit, i, x;
1717
1718         /* validate all ws */
1719         for (i = 0, foundit = 0; i < ScreenCount(display); i++)
1720                 TAILQ_FOREACH(r, &screens[i].rl, entry)
1721                         for (x = 0; x < SWM_WS_MAX; x++) {
1722                                 ws = &r->s->ws[x];
1723                                 if (ws == testws)
1724                                         return (0);
1725                         }
1726         return (1);
1727 }
1728
1729 void
1730 unfocus_win(struct ws_win *win)
1731 {
1732         XEvent                  cne;
1733         Window                  none = None;
1734
1735         DNPRINTF(SWM_D_FOCUS, "unfocus_win: id: %lu\n", WINID(win));
1736
1737         if (win == NULL)
1738                 return;
1739         if (win->ws == NULL)
1740                 return;
1741
1742         if (validate_ws(win->ws))
1743                 return; /* XXX this gets hit with thunderbird, needs fixing */
1744
1745         if (win->ws->r == NULL)
1746                 return;
1747
1748         if (validate_win(win)) {
1749                 kill_refs(win);
1750                 return;
1751         }
1752
1753         if (win->ws->focus == win) {
1754                 win->ws->focus = NULL;
1755                 win->ws->focus_prev = win;
1756         }
1757
1758         if (validate_win(win->ws->focus)) {
1759                 kill_refs(win->ws->focus);
1760                 win->ws->focus = NULL;
1761         }
1762         if (validate_win(win->ws->focus_prev)) {
1763                 kill_refs(win->ws->focus_prev);
1764                 win->ws->focus_prev = NULL;
1765         }
1766
1767         /* drain all previous unfocus events */
1768         while (XCheckTypedEvent(display, FocusOut, &cne) == True)
1769                 ;
1770
1771         grabbuttons(win, 0);
1772         XSetWindowBorder(display, win->id,
1773             win->ws->r->s->c[SWM_S_COLOR_UNFOCUS].color);
1774
1775         XChangeProperty(display, win->s->root,
1776             ewmh[_NET_ACTIVE_WINDOW].atom, XA_WINDOW, 32,
1777             PropModeReplace, (unsigned char *)&none,1);
1778 }
1779
1780 void
1781 unfocus_all(void)
1782 {
1783         struct ws_win           *win;
1784         int                     i, j;
1785
1786         DNPRINTF(SWM_D_FOCUS, "unfocus_all\n");
1787
1788         for (i = 0; i < ScreenCount(display); i++)
1789                 for (j = 0; j < SWM_WS_MAX; j++)
1790                         TAILQ_FOREACH(win, &screens[i].ws[j].winlist, entry)
1791                                 unfocus_win(win);
1792 }
1793
1794 void
1795 focus_win(struct ws_win *win)
1796 {
1797         XEvent                  cne;
1798         Window                  cur_focus;
1799         int                     rr;
1800         struct ws_win           *cfw = NULL;
1801
1802
1803         DNPRINTF(SWM_D_FOCUS, "focus_win: id: %lu\n", win ? win->id : 0);
1804
1805         if (win == NULL)
1806                 return;
1807         if (win->ws == NULL)
1808                 return;
1809
1810         if (validate_ws(win->ws))
1811                 return; /* XXX this gets hit with thunderbird, needs fixing */
1812
1813         if (validate_win(win)) {
1814                 kill_refs(win);
1815                 return;
1816         }
1817
1818         if (validate_win(win)) {
1819                 kill_refs(win);
1820                 return;
1821         }
1822
1823         XGetInputFocus(display, &cur_focus, &rr);
1824         if ((cfw = find_window(cur_focus)) != NULL)
1825                 unfocus_win(cfw);
1826
1827         win->ws->focus = win;
1828
1829         if (win->ws->r != NULL) {
1830                 /* drain all previous focus events */
1831                 while (XCheckTypedEvent(display, FocusIn, &cne) == True)
1832                         ;
1833
1834                 if (win->java == 0)
1835                         XSetInputFocus(display, win->id,
1836                             RevertToParent, CurrentTime);
1837                 grabbuttons(win, 1);
1838                 XSetWindowBorder(display, win->id,
1839                     win->ws->r->s->c[SWM_S_COLOR_FOCUS].color);
1840                 if (win->ws->cur_layout->flags & SWM_L_MAPONFOCUS)
1841                         XMapRaised(display, win->id);
1842
1843                 XChangeProperty(display, win->s->root,
1844                     ewmh[_NET_ACTIVE_WINDOW].atom, XA_WINDOW, 32,
1845                     PropModeReplace, (unsigned char *)&win->id,1);
1846         }
1847
1848         if (window_name_enabled)
1849                 bar_update();
1850 }
1851
1852 void
1853 switchws(struct swm_region *r, union arg *args)
1854 {
1855         int                     wsid = args->id, unmap_old = 0;
1856         struct swm_region       *this_r, *other_r;
1857         struct ws_win           *win;
1858         struct workspace        *new_ws, *old_ws;
1859         union arg               a;
1860
1861         if (!(r && r->s))
1862                 return;
1863
1864         this_r = r;
1865         old_ws = this_r->ws;
1866         new_ws = &this_r->s->ws[wsid];
1867
1868         DNPRINTF(SWM_D_WS, "switchws screen[%d]:%dx%d+%d+%d: "
1869             "%d -> %d\n", r->s->idx, WIDTH(r), HEIGHT(r), X(r), Y(r),
1870             old_ws->idx, wsid);
1871
1872         if (new_ws == NULL || old_ws == NULL)
1873                 return;
1874         if (new_ws == old_ws)
1875                 return;
1876
1877         other_r = new_ws->r;
1878         if (other_r == NULL) {
1879                 /* the other workspace is hidden, hide this one */
1880                 old_ws->r = NULL;
1881                 unmap_old = 1;
1882         } else {
1883                 /* the other ws is visible in another region, exchange them */
1884                 other_r->ws_prior = new_ws;
1885                 other_r->ws = old_ws;
1886                 old_ws->r = other_r;
1887         }
1888         this_r->ws_prior = old_ws;
1889         this_r->ws = new_ws;
1890         new_ws->r = this_r;
1891
1892         stack();
1893         a.id = SWM_ARG_ID_FOCUSCUR;
1894         focus(new_ws->r, &a);
1895         bar_update();
1896
1897         /* unmap old windows */
1898         if (unmap_old)
1899                 TAILQ_FOREACH(win, &old_ws->winlist, entry)
1900                         unmap_window(win);
1901 }
1902
1903 void
1904 cyclews(struct swm_region *r, union arg *args)
1905 {
1906         union                   arg a;
1907         struct swm_screen       *s = r->s;
1908
1909         DNPRINTF(SWM_D_WS, "cyclews id %d "
1910             "in screen[%d]:%dx%d+%d+%d ws %d\n", args->id,
1911             r->s->idx, WIDTH(r), HEIGHT(r), X(r), Y(r), r->ws->idx);
1912
1913         a.id = r->ws->idx;
1914         do {
1915                 switch (args->id) {
1916                 case SWM_ARG_ID_CYCLEWS_UP:
1917                         if (a.id < SWM_WS_MAX - 1)
1918                                 a.id++;
1919                         else
1920                                 a.id = 0;
1921                         break;
1922                 case SWM_ARG_ID_CYCLEWS_DOWN:
1923                         if (a.id > 0)
1924                                 a.id--;
1925                         else
1926                                 a.id = SWM_WS_MAX - 1;
1927                         break;
1928                 default:
1929                         return;
1930                 };
1931
1932                 if (cycle_empty == 0 && TAILQ_EMPTY(&s->ws[a.id].winlist))
1933                         continue;
1934                 if (cycle_visible == 0 && s->ws[a.id].r != NULL)
1935                         continue;
1936
1937                 switchws(r, &a);
1938         } while (a.id != r->ws->idx);
1939 }
1940
1941 void
1942 priorws(struct swm_region *r, union arg *args)
1943 {
1944         union arg               a;
1945
1946         DNPRINTF(SWM_D_WS, "priorws id %d "
1947             "in screen[%d]:%dx%d+%d+%d ws %d\n", args->id,
1948             r->s->idx, WIDTH(r), HEIGHT(r), X(r), Y(r), r->ws->idx);
1949
1950         if (r->ws_prior == NULL)
1951                 return;
1952
1953         a.id = r->ws_prior->idx;
1954         switchws(r, &a);
1955 }
1956
1957 void
1958 cyclescr(struct swm_region *r, union arg *args)
1959 {
1960         struct swm_region       *rr = NULL;
1961         union arg               a;
1962         int                     i, x, y;
1963
1964         /* do nothing if we don't have more than one screen */
1965         if (!(ScreenCount(display) > 1 || outputs > 1))
1966                 return;
1967
1968         i = r->s->idx;
1969         switch (args->id) {
1970         case SWM_ARG_ID_CYCLESC_UP:
1971                 rr = TAILQ_NEXT(r, entry);
1972                 if (rr == NULL)
1973                         rr = TAILQ_FIRST(&screens[i].rl);
1974                 break;
1975         case SWM_ARG_ID_CYCLESC_DOWN:
1976                 rr = TAILQ_PREV(r, swm_region_list, entry);
1977                 if (rr == NULL)
1978                         rr = TAILQ_LAST(&screens[i].rl, swm_region_list);
1979                 break;
1980         default:
1981                 return;
1982         };
1983         if (rr == NULL)
1984                 return;
1985
1986         /* move mouse to region */
1987         x = rr->g.x + 1;
1988         y = rr->g.y + 1 + (bar_enabled ? bar_height : 0);
1989         XWarpPointer(display, None, rr->s[i].root, 0, 0, 0, 0, x, y);
1990
1991         a.id = SWM_ARG_ID_FOCUSCUR;
1992         focus(rr, &a);
1993
1994         if (rr->ws->focus) {
1995                 /* move to focus window */
1996                 x = rr->ws->focus->g.x + 1;
1997                 y = rr->ws->focus->g.y + 1;
1998                 XWarpPointer(display, None, rr->s[i].root, 0, 0, 0, 0, x, y);
1999         }
2000 }
2001
2002 void
2003 swapwin(struct swm_region *r, union arg *args)
2004 {
2005         struct ws_win           *target, *source;
2006         struct ws_win           *cur_focus;
2007         struct ws_win_list      *wl;
2008
2009
2010         DNPRINTF(SWM_D_WS, "swapwin id %d "
2011             "in screen %d region %dx%d+%d+%d ws %d\n", args->id,
2012             r->s->idx, WIDTH(r), HEIGHT(r), X(r), Y(r), r->ws->idx);
2013
2014         cur_focus = r->ws->focus;
2015         if (cur_focus == NULL)
2016                 return;
2017
2018         source = cur_focus;
2019         wl = &source->ws->winlist;
2020
2021         switch (args->id) {
2022         case SWM_ARG_ID_SWAPPREV:
2023                 target = TAILQ_PREV(source, ws_win_list, entry);
2024                 TAILQ_REMOVE(wl, cur_focus, entry);
2025                 if (target == NULL)
2026                         TAILQ_INSERT_TAIL(wl, source, entry);
2027                 else
2028                         TAILQ_INSERT_BEFORE(target, source, entry);
2029                 break;
2030         case SWM_ARG_ID_SWAPNEXT:
2031                 target = TAILQ_NEXT(source, entry);
2032                 TAILQ_REMOVE(wl, source, entry);
2033                 if (target == NULL)
2034                         TAILQ_INSERT_HEAD(wl, source, entry);
2035                 else
2036                         TAILQ_INSERT_AFTER(wl, target, source, entry);
2037                 break;
2038         case SWM_ARG_ID_SWAPMAIN:
2039                 target = TAILQ_FIRST(wl);
2040                 if (target == source) {
2041                         if (source->ws->focus_prev != NULL &&
2042                             source->ws->focus_prev != target)
2043
2044                                 source = source->ws->focus_prev;
2045                         else
2046                                 return;
2047                 }
2048                 if (target == NULL || source == NULL)
2049                         return;
2050                 source->ws->focus_prev = target;
2051                 TAILQ_REMOVE(wl, target, entry);
2052                 TAILQ_INSERT_BEFORE(source, target, entry);
2053                 TAILQ_REMOVE(wl, source, entry);
2054                 TAILQ_INSERT_HEAD(wl, source, entry);
2055                 break;
2056         case SWM_ARG_ID_MOVELAST:
2057                 TAILQ_REMOVE(wl, source, entry);
2058                 TAILQ_INSERT_TAIL(wl, source, entry);
2059                 break;
2060         default:
2061                 DNPRINTF(SWM_D_MOVE, "invalid id: %d\n", args->id);
2062                 return;
2063         }
2064
2065         stack();
2066 }
2067
2068 void
2069 focus_prev(struct ws_win *win)
2070 {
2071         struct ws_win           *winfocus = NULL, *winlostfocus = NULL;
2072         struct ws_win           *cur_focus = NULL;
2073         struct ws_win_list      *wl = NULL;
2074         struct workspace        *ws = NULL;
2075
2076         DNPRINTF(SWM_D_FOCUS, "focus_prev: id %lu\n", WINID(win));
2077
2078         if (!(win && win->ws))
2079                 return;
2080
2081         ws = win->ws;
2082         wl = &ws->winlist;
2083         cur_focus = ws->focus;
2084         winlostfocus = cur_focus;
2085
2086         /* pickle, just focus on whatever */
2087         if (cur_focus == NULL) {
2088                 /* use prev_focus if valid */
2089                 if (ws->focus_prev && ws->focus_prev != cur_focus &&
2090                     find_window(WINID(ws->focus_prev)))
2091                         winfocus = ws->focus_prev;
2092                 if (winfocus == NULL)
2093                         winfocus = TAILQ_FIRST(wl);
2094                 goto done;
2095         }
2096
2097         /* if transient focus on parent */
2098         if (cur_focus->transient) {
2099                 winfocus = find_window(cur_focus->transient);
2100                 goto done;
2101         }
2102
2103         /* if in max_stack try harder */
2104         if (ws->cur_layout->flags & SWM_L_FOCUSPREV) {
2105                 if (cur_focus != ws->focus_prev)
2106                         winfocus = ws->focus_prev;
2107                 else if (cur_focus != ws->focus)
2108                         winfocus = ws->focus;
2109                 else
2110                         winfocus = TAILQ_PREV(win, ws_win_list, entry);
2111                 if (winfocus)
2112                         goto done;
2113         }
2114
2115         if (cur_focus == win)
2116                 winfocus = TAILQ_PREV(win, ws_win_list, entry);
2117         if (winfocus == NULL)
2118                 winfocus = TAILQ_LAST(wl, ws_win_list);
2119         if (winfocus == NULL || winfocus == win)
2120                 winfocus = TAILQ_NEXT(cur_focus, entry);
2121 done:
2122         if (winfocus == winlostfocus || winfocus == NULL)
2123                 return;
2124
2125         focus_magic(winfocus, SWM_F_GENERIC);
2126 }
2127
2128 void
2129 focus(struct swm_region *r, union arg *args)
2130 {
2131         struct ws_win           *winfocus = NULL, *winlostfocus = NULL;
2132         struct ws_win           *cur_focus = NULL;
2133         struct ws_win_list      *wl = NULL;
2134         struct workspace        *ws = NULL;
2135
2136         if (!(r && r->ws))
2137                 return;
2138
2139         DNPRINTF(SWM_D_FOCUS, "focus: id %d\n", args->id);
2140
2141         /* treat FOCUS_CUR special */
2142         if (args->id == SWM_ARG_ID_FOCUSCUR) {
2143                 if (r->ws->focus)
2144                         winfocus = r->ws->focus;
2145                 else if (r->ws->focus_prev)
2146                         winfocus = r->ws->focus_prev;
2147                 else
2148                         winfocus = TAILQ_FIRST(&r->ws->winlist);
2149
2150                 focus_magic(winfocus, SWM_F_GENERIC);
2151                 return;
2152         }
2153
2154         if ((cur_focus = r->ws->focus) == NULL)
2155                 return;
2156         ws = r->ws;
2157         wl = &ws->winlist;
2158
2159         winlostfocus = cur_focus;
2160
2161         switch (args->id) {
2162         case SWM_ARG_ID_FOCUSPREV:
2163                 winfocus = TAILQ_PREV(cur_focus, ws_win_list, entry);
2164                 if (winfocus == NULL)
2165                         winfocus = TAILQ_LAST(wl, ws_win_list);
2166                 break;
2167
2168         case SWM_ARG_ID_FOCUSNEXT:
2169                 winfocus = TAILQ_NEXT(cur_focus, entry);
2170                 if (winfocus == NULL)
2171                         winfocus = TAILQ_FIRST(wl);
2172                 break;
2173
2174         case SWM_ARG_ID_FOCUSMAIN:
2175                 winfocus = TAILQ_FIRST(wl);
2176                 if (winfocus == cur_focus)
2177                         winfocus = cur_focus->ws->focus_prev;
2178                 break;
2179
2180         default:
2181                 return;
2182         }
2183
2184         if (winfocus == winlostfocus || winfocus == NULL)
2185                 return;
2186
2187         focus_magic(winfocus, SWM_F_GENERIC);
2188 }
2189
2190 void
2191 cycle_layout(struct swm_region *r, union arg *args)
2192 {
2193         struct workspace        *ws = r->ws;
2194         struct ws_win           *winfocus;
2195         union arg               a;
2196
2197         DNPRINTF(SWM_D_EVENT, "cycle_layout: workspace: %d\n", ws->idx);
2198
2199         winfocus = ws->focus;
2200
2201         ws->cur_layout++;
2202         if (ws->cur_layout->l_stack == NULL)
2203                 ws->cur_layout = &layouts[0];
2204
2205         stack();
2206         a.id = SWM_ARG_ID_FOCUSCUR;
2207         focus(r, &a);
2208         bar_update();
2209 }
2210
2211 void
2212 stack_config(struct swm_region *r, union arg *args)
2213 {
2214         struct workspace        *ws = r->ws;
2215
2216         DNPRINTF(SWM_D_STACK, "stack_config for workspace %d (id %d\n",
2217             args->id, ws->idx);
2218
2219         if (ws->cur_layout->l_config != NULL)
2220                 ws->cur_layout->l_config(ws, args->id);
2221
2222         if (args->id != SWM_ARG_ID_STACKINIT);
2223                 stack();
2224 }
2225
2226 void
2227 stack(void) {
2228         struct swm_geometry     g;
2229         struct swm_region       *r;
2230         int                     i, j;
2231
2232         DNPRINTF(SWM_D_STACK, "stack\n");
2233
2234         for (i = 0; i < ScreenCount(display); i++) {
2235                 j = 0;
2236                 TAILQ_FOREACH(r, &screens[i].rl, entry) {
2237                         DNPRINTF(SWM_D_STACK, "stacking workspace %d "
2238                             "(screen %d, region %d)\n", r->ws->idx, i, j++);
2239
2240                         /* start with screen geometry, adjust for bar */
2241                         g = r->g;
2242                         g.w -= 2 * border_width;
2243                         g.h -= 2 * border_width;
2244                         if (bar_enabled) {
2245                                 if (!bar_at_bottom)
2246                                         g.y += bar_height;
2247                                 g.h -= bar_height;
2248                         }
2249                         r->ws->cur_layout->l_stack(r->ws, &g);
2250                         /* save r so we can track region changes */
2251                         r->ws->old_r = r;
2252                 }
2253         }
2254         if (font_adjusted)
2255                 font_adjusted--;
2256 }
2257
2258 void
2259 store_float_geom(struct ws_win *win, struct swm_region *r)
2260 {
2261         /* retain window geom and region geom */
2262         win->g_float.x = win->g.x;
2263         win->g_float.y = win->g.y;
2264         win->g_float.w = win->g.w;
2265         win->g_float.h = win->g.h;
2266         win->rg_float.x = r->g.x;
2267         win->rg_float.y = r->g.y;
2268         win->rg_float.w = r->g.w;
2269         win->rg_float.h = r->g.h;
2270         win->g_floatvalid = 1;
2271 }
2272
2273 void
2274 stack_floater(struct ws_win *win, struct swm_region *r)
2275 {
2276         unsigned int            mask;
2277         XWindowChanges          wc;
2278
2279         if (win == NULL)
2280                 return;
2281
2282         bzero(&wc, sizeof wc);
2283         mask = CWX | CWY | CWBorderWidth | CWWidth | CWHeight;
2284
2285         /*
2286          * to allow windows to change their size (e.g. mplayer fs) only retrieve
2287          * geom on ws switches or return from max mode
2288          */
2289
2290         if (win->floatmaxed || (r != r->ws->old_r && win->g_floatvalid
2291             && !(win->ewmh_flags & EWMH_F_FULLSCREEN))) {
2292                 /*
2293                  * use stored g and rg to set relative position and size
2294                  * as in old region or before max stack mode
2295                  */
2296                 win->g.x = win->g_float.x - win->rg_float.x + r->g.x;
2297                 win->g.y = win->g_float.y - win->rg_float.y + r->g.y;
2298                 win->g.w = win->g_float.w;
2299                 win->g.h = win->g_float.h;
2300                 win->g_floatvalid = 0;
2301         }
2302
2303         win->floatmaxed = 0;
2304
2305         if ((win->quirks & SWM_Q_FULLSCREEN) && (win->g.w >= WIDTH(r)) &&
2306             (win->g.h >= HEIGHT(r)))
2307                 wc.border_width = 0;
2308         else
2309                 wc.border_width = border_width;
2310         if (win->transient && (win->quirks & SWM_Q_TRANSSZ)) {
2311                 win->g.w = (double)WIDTH(r) * dialog_ratio;
2312                 win->g.h = (double)HEIGHT(r) * dialog_ratio;
2313         }
2314
2315         if (!win->manual) {
2316                 /*
2317                  * floaters and transients are auto-centred unless moved
2318                  * or resized
2319                  */
2320                 win->g.x = r->g.x + (WIDTH(r) - win->g.w) / 2 - border_width;
2321                 win->g.y = r->g.y + (HEIGHT(r) - win->g.h) / 2 - border_width;
2322         }
2323
2324         /* win can be outside r if new r smaller than old r */
2325         /* Ensure top left corner inside r (move probs otherwise) */
2326         if (win->g.x < r->g.x - border_width)
2327                 win->g.x = r->g.x - border_width;
2328         if (win->g.x > r->g.x + r->g.w - 1)
2329                 win->g.x = (win->g.w > r->g.w) ? r->g.x :
2330                     (r->g.x + r->g.w - win->g.w - 2 * border_width);
2331         if (win->g.y < r->g.y - border_width)
2332                 win->g.y = r->g.y - border_width;
2333         if (win->g.y > r->g.y + r->g.h - 1)
2334                 win->g.y = (win->g.h > r->g.h) ? r->g.y :
2335                     (r->g.y + r->g.h - win->g.h - 2 * border_width);
2336
2337         wc.x = win->g.x;
2338         wc.y = win->g.y;
2339         wc.width = win->g.w;
2340         wc.height = win->g.h;
2341
2342         /*
2343          * Retain floater and transient geometry for correct positioning
2344          * when ws changes region
2345          */
2346         if (!(win->ewmh_flags & EWMH_F_FULLSCREEN))
2347                 store_float_geom(win, r);
2348
2349         DNPRINTF(SWM_D_MISC, "stack_floater: win %lu x %d y %d w %d h %d\n",
2350             win->id, wc.x, wc.y, wc.width, wc.height);
2351
2352         XConfigureWindow(display, win->id, mask, &wc);
2353 }
2354
2355 /*
2356  * Send keystrokes to terminal to decrease/increase the font size as the
2357  * window size changes.
2358  */
2359 void
2360 adjust_font(struct ws_win *win)
2361 {
2362         if (!(win->quirks & SWM_Q_XTERM_FONTADJ) ||
2363             win->floating || win->transient)
2364                 return;
2365
2366         if (win->sh.width_inc && win->last_inc != win->sh.width_inc &&
2367             win->g.w / win->sh.width_inc < term_width &&
2368             win->font_steps < SWM_MAX_FONT_STEPS) {
2369                 win->font_size_boundary[win->font_steps] =
2370                     (win->sh.width_inc * term_width) + win->sh.base_width;
2371                 win->font_steps++;
2372                 font_adjusted++;
2373                 win->last_inc = win->sh.width_inc;
2374                 fake_keypress(win, XK_KP_Subtract, ShiftMask);
2375         } else if (win->font_steps && win->last_inc != win->sh.width_inc &&
2376             win->g.w > win->font_size_boundary[win->font_steps - 1]) {
2377                 win->font_steps--;
2378                 font_adjusted++;
2379                 win->last_inc = win->sh.width_inc;
2380                 fake_keypress(win, XK_KP_Add, ShiftMask);
2381         }
2382 }
2383
2384 #define SWAPXY(g)       do {                            \
2385         int tmp;                                        \
2386         tmp = (g)->y; (g)->y = (g)->x; (g)->x = tmp;    \
2387         tmp = (g)->h; (g)->h = (g)->w; (g)->w = tmp;    \
2388 } while (0)
2389 void
2390 stack_master(struct workspace *ws, struct swm_geometry *g, int rot, int flip)
2391 {
2392         XWindowChanges          wc;
2393         XWindowAttributes       wa;
2394         struct swm_geometry     win_g, r_g = *g;
2395         struct ws_win           *win, *fs_win = 0;
2396         int                     i, j, s, stacks;
2397         int                     w_inc = 1, h_inc, w_base = 1, h_base;
2398         int                     hrh, extra = 0, h_slice, last_h = 0;
2399         int                     split, colno, winno, mwin, msize, mscale;
2400         int                     remain, missing, v_slice, reconfigure;
2401         unsigned int            mask;
2402
2403         DNPRINTF(SWM_D_STACK, "stack_master: workspace: %d\n rot=%s flip=%s",
2404             ws->idx, rot ? "yes" : "no", flip ? "yes" : "no");
2405
2406         winno = count_win(ws, 0);
2407         if (winno == 0 && count_win(ws, 1) == 0)
2408                 return;
2409
2410         TAILQ_FOREACH(win, &ws->winlist, entry)
2411                 if (win->transient == 0 && win->floating == 0)
2412                         break;
2413
2414         if (win == NULL)
2415                 goto notiles;
2416
2417         if (rot) {
2418                 w_inc = win->sh.width_inc;
2419                 w_base = win->sh.base_width;
2420                 mwin = ws->l_state.horizontal_mwin;
2421                 mscale = ws->l_state.horizontal_msize;
2422                 stacks = ws->l_state.horizontal_stacks;
2423                 SWAPXY(&r_g);
2424         } else {
2425                 w_inc = win->sh.height_inc;
2426                 w_base = win->sh.base_height;
2427                 mwin = ws->l_state.vertical_mwin;
2428                 mscale = ws->l_state.vertical_msize;
2429                 stacks = ws->l_state.vertical_stacks;
2430         }
2431         win_g = r_g;
2432
2433         if (stacks > winno - mwin)
2434                 stacks = winno - mwin;
2435         if (stacks < 1)
2436                 stacks = 1;
2437
2438         h_slice = r_g.h / SWM_H_SLICE;
2439         if (mwin && winno > mwin) {
2440                 v_slice = r_g.w / SWM_V_SLICE;
2441
2442                 split = mwin;
2443                 colno = split;
2444                 win_g.w = v_slice * mscale;
2445
2446                 if (w_inc > 1 && w_inc < v_slice) {
2447                         /* adjust for window's requested size increment */
2448                         remain = (win_g.w - w_base) % w_inc;
2449                         missing = w_inc - remain;
2450                         win_g.w -= remain;
2451                         extra += remain;
2452                 }
2453
2454                 msize = win_g.w;
2455                 if (flip)
2456                         win_g.x += r_g.w - msize;
2457         } else {
2458                 msize = -2;
2459                 colno = split = winno / stacks;
2460                 win_g.w = ((r_g.w - (stacks * 2 * border_width) + 2 * border_width) / stacks);
2461         }
2462         hrh = r_g.h / colno;
2463         extra = r_g.h - (colno * hrh);
2464         win_g.h = hrh - 2 * border_width;
2465
2466         /*  stack all the tiled windows */
2467         i = j = 0, s = stacks;
2468         TAILQ_FOREACH(win, &ws->winlist, entry) {
2469                 if (win->transient != 0 || win->floating != 0)
2470                         continue;
2471
2472                 if (win->ewmh_flags & EWMH_F_FULLSCREEN) {
2473                         fs_win = win;
2474                         continue;
2475                 }
2476
2477                 if (split && i == split) {
2478                         colno = (winno - mwin) / stacks;
2479                         if (s <= (winno - mwin) % stacks)
2480                                 colno++;
2481                         split = split + colno;
2482                         hrh = (r_g.h / colno);
2483                         extra = r_g.h - (colno * hrh);
2484                         if (flip)
2485                                 win_g.x = r_g.x;
2486                         else
2487                                 win_g.x += win_g.w + 2 * border_width;
2488                         win_g.w = (r_g.w - msize - (stacks * 2 * border_width)) / stacks;
2489                         if (s == 1)
2490                                 win_g.w += (r_g.w - msize - (stacks * 2 * border_width)) %
2491                                     stacks;
2492                         s--;
2493                         j = 0;
2494                 }
2495                 win_g.h = hrh - 2 * border_width;
2496                 if (rot) {
2497                         h_inc = win->sh.width_inc;
2498                         h_base = win->sh.base_width;
2499                 } else {
2500                         h_inc = win->sh.height_inc;
2501                         h_base = win->sh.base_height;
2502                 }
2503                 if (j == colno - 1) {
2504                         win_g.h = hrh + extra;
2505                 } else if (h_inc > 1 && h_inc < h_slice) {
2506                         /* adjust for window's requested size increment */
2507                         remain = (win_g.h - h_base) % h_inc;
2508                         missing = h_inc - remain;
2509
2510                         if (missing <= extra || j == 0) {
2511                                 extra -= missing;
2512                                 win_g.h += missing;
2513                         } else {
2514                                 win_g.h -= remain;
2515                                 extra += remain;
2516                         }
2517                 }
2518
2519                 if (j == 0)
2520                         win_g.y = r_g.y;
2521                 else
2522                         win_g.y += last_h + 2 * border_width;
2523
2524                 bzero(&wc, sizeof wc);
2525                 if (disable_border && bar_enabled == 0 && winno == 1){
2526                         wc.border_width = 0;
2527                         win_g.w += 2 * border_width;
2528                         win_g.h += 2 * border_width;
2529                 } else
2530                         wc.border_width = border_width;
2531                 reconfigure = 0;
2532                 if (rot) {
2533                         if (win->g.x != win_g.y || win->g.y != win_g.x ||
2534                             win->g.w != win_g.h || win->g.h != win_g.w) {
2535                                 reconfigure = 1;
2536                                 win->g.x = wc.x = win_g.y;
2537                                 win->g.y = wc.y = win_g.x;
2538                                 win->g.w = wc.width = win_g.h;
2539                                 win->g.h = wc.height = win_g.w;
2540                         }
2541                 } else {
2542                         if (win->g.x != win_g.x || win->g.y != win_g.y ||
2543                             win->g.w != win_g.w || win->g.h != win_g.h) {
2544                                 reconfigure = 1;
2545                                 win->g.x = wc.x = win_g.x;
2546                                 win->g.y = wc.y = win_g.y;
2547                                 win->g.w = wc.width = win_g.w;
2548                                 win->g.h = wc.height = win_g.h;
2549                         }
2550                 }
2551                 if (reconfigure) {
2552                         adjust_font(win);
2553                         mask = CWX | CWY | CWWidth | CWHeight | CWBorderWidth;
2554                         XConfigureWindow(display, win->id, mask, &wc);
2555                 }
2556
2557                 if (XGetWindowAttributes(display, win->id, &wa))
2558                         if (wa.map_state == IsUnmapped)
2559                                 XMapRaised(display, win->id);
2560
2561                 last_h = win_g.h;
2562                 i++;
2563                 j++;
2564         }
2565
2566  notiles:
2567         /* now, stack all the floaters and transients */
2568         TAILQ_FOREACH(win, &ws->winlist, entry) {
2569                 if (win->transient == 0 && win->floating == 0)
2570                         continue;
2571
2572                 if (win->ewmh_flags & EWMH_F_FULLSCREEN) {
2573                         fs_win = win;
2574                         continue;
2575                 }
2576
2577                 stack_floater(win, ws->r);
2578                 XMapRaised(display, win->id);
2579         }
2580
2581         if (fs_win) {
2582                 stack_floater(fs_win, ws->r);
2583                 XMapRaised(display, fs_win->id);
2584         }
2585 }
2586
2587 void
2588 vertical_config(struct workspace *ws, int id)
2589 {
2590         DNPRINTF(SWM_D_STACK, "vertical_resize: workspace: %d\n", ws->idx);
2591
2592         switch (id) {
2593         case SWM_ARG_ID_STACKRESET:
2594         case SWM_ARG_ID_STACKINIT:
2595                 ws->l_state.vertical_msize = SWM_V_SLICE / 2;
2596                 ws->l_state.vertical_mwin = 1;
2597                 ws->l_state.vertical_stacks = 1;
2598                 break;
2599         case SWM_ARG_ID_MASTERSHRINK:
2600                 if (ws->l_state.vertical_msize > 1)
2601                         ws->l_state.vertical_msize--;
2602                 break;
2603         case SWM_ARG_ID_MASTERGROW:
2604                 if (ws->l_state.vertical_msize < SWM_V_SLICE - 1)
2605                         ws->l_state.vertical_msize++;
2606                 break;
2607         case SWM_ARG_ID_MASTERADD:
2608                 ws->l_state.vertical_mwin++;
2609                 break;
2610         case SWM_ARG_ID_MASTERDEL:
2611                 if (ws->l_state.vertical_mwin > 0)
2612                         ws->l_state.vertical_mwin--;
2613                 break;
2614         case SWM_ARG_ID_STACKINC:
2615                 ws->l_state.vertical_stacks++;
2616                 break;
2617         case SWM_ARG_ID_STACKDEC:
2618                 if (ws->l_state.vertical_stacks > 1)
2619                         ws->l_state.vertical_stacks--;
2620                 break;
2621         default:
2622                 return;
2623         }
2624 }
2625
2626 void
2627 vertical_stack(struct workspace *ws, struct swm_geometry *g)
2628 {
2629         DNPRINTF(SWM_D_STACK, "vertical_stack: workspace: %d\n", ws->idx);
2630
2631         stack_master(ws, g, 0, 0);
2632 }
2633
2634 void
2635 horizontal_config(struct workspace *ws, int id)
2636 {
2637         DNPRINTF(SWM_D_STACK, "horizontal_config: workspace: %d\n", ws->idx);
2638
2639         switch (id) {
2640         case SWM_ARG_ID_STACKRESET:
2641         case SWM_ARG_ID_STACKINIT:
2642                 ws->l_state.horizontal_mwin = 1;
2643                 ws->l_state.horizontal_msize = SWM_H_SLICE / 2;
2644                 ws->l_state.horizontal_stacks = 1;
2645                 break;
2646         case SWM_ARG_ID_MASTERSHRINK:
2647                 if (ws->l_state.horizontal_msize > 1)
2648                         ws->l_state.horizontal_msize--;
2649                 break;
2650         case SWM_ARG_ID_MASTERGROW:
2651                 if (ws->l_state.horizontal_msize < SWM_H_SLICE - 1)
2652                         ws->l_state.horizontal_msize++;
2653                 break;
2654         case SWM_ARG_ID_MASTERADD:
2655                 ws->l_state.horizontal_mwin++;
2656                 break;
2657         case SWM_ARG_ID_MASTERDEL:
2658                 if (ws->l_state.horizontal_mwin > 0)
2659                         ws->l_state.horizontal_mwin--;
2660                 break;
2661         case SWM_ARG_ID_STACKINC:
2662                 ws->l_state.horizontal_stacks++;
2663                 break;
2664         case SWM_ARG_ID_STACKDEC:
2665                 if (ws->l_state.horizontal_stacks > 1)
2666                         ws->l_state.horizontal_stacks--;
2667                 break;
2668         default:
2669                 return;
2670         }
2671 }
2672
2673 void
2674 horizontal_stack(struct workspace *ws, struct swm_geometry *g)
2675 {
2676         DNPRINTF(SWM_D_STACK, "horizontal_stack: workspace: %d\n", ws->idx);
2677
2678         stack_master(ws, g, 1, 0);
2679 }
2680
2681 /* fullscreen view */
2682 void
2683 max_stack(struct workspace *ws, struct swm_geometry *g)
2684 {
2685         XWindowChanges          wc;
2686         struct swm_geometry     gg = *g;
2687         struct ws_win           *win, *wintrans = NULL, *parent = NULL;
2688         unsigned int            mask;
2689         int                     winno;
2690
2691         DNPRINTF(SWM_D_STACK, "max_stack: workspace: %d\n", ws->idx);
2692
2693         if (ws == NULL)
2694                 return;
2695
2696         winno = count_win(ws, 0);
2697         if (winno == 0 && count_win(ws, 1) == 0)
2698                 return;
2699
2700         TAILQ_FOREACH(win, &ws->winlist, entry) {
2701                 if (win->transient) {
2702                         wintrans = win;
2703                         parent = find_window(win->transient);
2704                         continue;
2705                 }
2706
2707                 if (win->floating && win->floatmaxed == 0 ) {
2708                         /*
2709                          * retain geometry for retrieval on exit from
2710                          * max_stack mode
2711                          */
2712                         store_float_geom(win, ws->r);
2713                         win->floatmaxed = 1;
2714                 }
2715
2716                 /* only reconfigure if necessary */
2717                 if (win->g.x != gg.x || win->g.y != gg.y || win->g.w != gg.w ||
2718                     win->g.h != gg.h) {
2719                         bzero(&wc, sizeof wc);
2720                         win->g.x = wc.x = gg.x;
2721                         win->g.y = wc.y = gg.y;
2722                         if (bar_enabled){
2723                                 wc.border_width = border_width;
2724                                 win->g.w = wc.width = gg.w;
2725                                 win->g.h = wc.height = gg.h;
2726                         } else {
2727                                 wc.border_width = 0;
2728                                 win->g.w = wc.width = gg.w + 2 * border_width;
2729                                 win->g.h = wc.height = gg.h + 2 * border_width;
2730                         }
2731                         mask = CWX | CWY | CWWidth | CWHeight | CWBorderWidth;
2732                         XConfigureWindow(display, win->id, mask, &wc);
2733                 }
2734                 /* unmap only if we don't have multi screen */
2735                 if (win != ws->focus)
2736                         if (!(ScreenCount(display) > 1 || outputs > 1))
2737                                 unmap_window(win);
2738         }
2739
2740         /* put the last transient on top */
2741         if (wintrans) {
2742                 if (parent)
2743                         XMapRaised(display, parent->id);
2744                 stack_floater(wintrans, ws->r);
2745                 focus_magic(wintrans, SWM_F_TRANSIENT);
2746         }
2747 }
2748
2749 void
2750 send_to_ws(struct swm_region *r, union arg *args)
2751 {
2752         int                     wsid = args->id;
2753         struct ws_win           *win = win;
2754         struct workspace        *ws, *nws;
2755         Atom                    ws_idx_atom = 0;
2756         unsigned char           ws_idx_str[SWM_PROPLEN];
2757         union arg               a;
2758
2759         if (r && r->ws)
2760                 win = r->ws->focus;
2761         else
2762                 return;
2763         if (win == NULL)
2764                 return;
2765         if (win->ws->idx == wsid)
2766                 return;
2767
2768         DNPRINTF(SWM_D_MOVE, "send_to_ws: win: %lu\n", win->id);
2769
2770         ws = win->ws;
2771         nws = &win->s->ws[wsid];
2772
2773         a.id = SWM_ARG_ID_FOCUSPREV;
2774         focus(r, &a);
2775         unmap_window(win);
2776         TAILQ_REMOVE(&ws->winlist, win, entry);
2777         TAILQ_INSERT_TAIL(&nws->winlist, win, entry);
2778         win->ws = nws;
2779
2780         /* Try to update the window's workspace property */
2781         ws_idx_atom = XInternAtom(display, "_SWM_WS", False);
2782         if (ws_idx_atom &&
2783             snprintf(ws_idx_str, SWM_PROPLEN, "%d", nws->idx) < SWM_PROPLEN) {
2784                 DNPRINTF(SWM_D_PROP, "setting property _SWM_WS to %s\n",
2785                     ws_idx_str);
2786                 XChangeProperty(display, win->id, ws_idx_atom, XA_STRING, 8,
2787                     PropModeReplace, ws_idx_str, SWM_PROPLEN);
2788         }
2789
2790         stack();
2791 }
2792
2793 void
2794 wkill(struct swm_region *r, union arg *args)
2795 {
2796         DNPRINTF(SWM_D_MISC, "wkill %d\n", args->id);
2797
2798         if (r->ws->focus == NULL)
2799                 return;
2800
2801         if (args->id == SWM_ARG_ID_KILLWINDOW)
2802                 XKillClient(display, r->ws->focus->id);
2803         else
2804                 if (r->ws->focus->can_delete)
2805                         client_msg(r->ws->focus, adelete);
2806 }
2807
2808
2809 int
2810 floating_toggle_win(struct ws_win *win)
2811 {
2812         struct swm_region       *r;
2813
2814         if (win == NULL)
2815                 return 0;
2816
2817         if (!win->ws->r)
2818                 return 0;
2819
2820         r = win->ws->r;
2821
2822         /* reject floating toggles in max stack mode */
2823         if (win->ws->cur_layout == &layouts[SWM_MAX_STACK])
2824                 return 0;
2825
2826         if (win->floating) {
2827                 if (!win->floatmaxed) {
2828                         /* retain position for refloat */
2829                         store_float_geom(win, r);
2830                 }
2831                 win->floating = 0;
2832         } else {
2833                 if (win->g_floatvalid) {
2834                         /* refloat at last floating relative position */
2835                         win->g.x = win->g_float.x - win->rg_float.x + r->g.x;
2836                         win->g.y = win->g_float.y - win->rg_float.y + r->g.y;
2837                         win->g.w = win->g_float.w;
2838                         win->g.h = win->g_float.h;
2839                 }
2840                 win->floating = 1;
2841         }
2842
2843         ewmh_update_actions(win);
2844
2845         return 1;
2846 }
2847
2848 void
2849 floating_toggle(struct swm_region *r, union arg *args)
2850 {
2851         struct ws_win           *win = r->ws->focus;
2852         union arg               a;
2853
2854         if (win == NULL)
2855                 return;
2856
2857         ewmh_update_win_state(win, ewmh[_NET_WM_STATE_ABOVE].atom,
2858             _NET_WM_STATE_TOGGLE);
2859
2860         stack();
2861
2862         if (win == win->ws->focus) {
2863                 a.id = SWM_ARG_ID_FOCUSCUR;
2864                 focus(win->ws->r, &a);
2865         }
2866 }
2867
2868 void
2869 resize_window(struct ws_win *win, int center)
2870 {
2871         unsigned int            mask;
2872         XWindowChanges          wc;
2873         struct swm_region       *r;
2874
2875         r = root_to_region(win->wa.root);
2876         bzero(&wc, sizeof wc);
2877         mask = CWBorderWidth | CWWidth | CWHeight;
2878         wc.border_width = border_width;
2879         wc.width = win->g.w;
2880         wc.height = win->g.h;
2881         if (center == SWM_ARG_ID_CENTER) {
2882                 wc.x = (WIDTH(r) - win->g.w) / 2 - border_width;
2883                 wc.y = (HEIGHT(r) - win->g.h) / 2 - border_width;
2884                 mask |= CWX | CWY;
2885         }
2886
2887         DNPRINTF(SWM_D_STACK, "resize_window: win %lu x %d y %d w %d h %d\n",
2888             win->id, wc.x, wc.y, wc.width, wc.height);
2889
2890         XConfigureWindow(display, win->id, mask, &wc);
2891 }
2892
2893 void
2894 resize(struct ws_win *win, union arg *args)
2895 {
2896         XEvent                  ev;
2897         Time                    time = 0;
2898         struct swm_region       *r = win->ws->r;
2899         int                     relx, rely;
2900         union arg               a;
2901
2902
2903         DNPRINTF(SWM_D_MOUSE, "resize: win %lu floating %d trans %lu\n",
2904             win->id, win->floating, win->transient);
2905
2906         if (!(win->transient != 0 || win->floating != 0))
2907                 return;
2908
2909         /* reject resizes in max mode for floaters (transient ok) */
2910         if (win->floatmaxed)
2911                 return;
2912
2913         win->manual = 1;
2914         ewmh_update_win_state(win, ewmh[_SWM_WM_STATE_MANUAL].atom,
2915             _NET_WM_STATE_ADD);
2916         /* raise the window = move to last in window list */
2917         a.id = SWM_ARG_ID_MOVELAST;
2918         swapwin(r, &a);
2919         stack();
2920
2921         if (XGrabPointer(display, win->id, False, MOUSEMASK, GrabModeAsync,
2922             GrabModeAsync, None, None /* cursor */, CurrentTime) != GrabSuccess)
2923                 return;
2924
2925         /* place pointer at bottom left corner or nearest point inside r */
2926         if ( win->g.x + win->g.w < r->g.x + r->g.w - 1)
2927                 relx = win->g.w - 1;
2928         else
2929                 relx = r->g.x + r->g.w - win->g.x - 1;
2930
2931         if ( win->g.y + win->g.h < r->g.y + r->g.h - 1)
2932                 rely = win->g.h - 1;
2933         else
2934                 rely = r->g.y + r->g.h - win->g.y - 1;
2935
2936         XWarpPointer(display, None, win->id, 0, 0, 0, 0, relx, rely);
2937         do {
2938                 XMaskEvent(display, MOUSEMASK | ExposureMask |
2939                     SubstructureRedirectMask, &ev);
2940                 switch(ev.type) {
2941                 case ConfigureRequest:
2942                 case Expose:
2943                 case MapRequest:
2944                         handler[ev.type](&ev);
2945                         break;
2946                 case MotionNotify:
2947                         /* do not allow resize outside of region */
2948                         if (    ev.xmotion.x_root < r->g.x ||
2949                                 ev.xmotion.x_root > r->g.x + r->g.w - 1 ||
2950                                 ev.xmotion.y_root < r->g.y ||
2951                                 ev.xmotion.y_root > r->g.y + r->g.h - 1)
2952                                 continue;
2953
2954                         if (ev.xmotion.x <= 1)
2955                                 ev.xmotion.x = 1;
2956                         if (ev.xmotion.y <= 1)
2957                                 ev.xmotion.y = 1;
2958                         win->g.w = ev.xmotion.x + 1;
2959                         win->g.h = ev.xmotion.y + 1;
2960
2961                         /* not free, don't sync more than 120 times / second */
2962                         if ((ev.xmotion.time - time) > (1000 / 120) ) {
2963                                 time = ev.xmotion.time;
2964                                 XSync(display, False);
2965                                 resize_window(win, args->id);
2966                         }
2967                         break;
2968                 }
2969         } while (ev.type != ButtonRelease);
2970         if (time) {
2971                 XSync(display, False);
2972                 resize_window(win, args->id);
2973         }
2974         store_float_geom(win,r);
2975
2976         XWarpPointer(display, None, win->id, 0, 0, 0, 0, win->g.w - 1,
2977             win->g.h - 1);
2978         XUngrabPointer(display, CurrentTime);
2979
2980         /* drain events */
2981         while (XCheckMaskEvent(display, EnterWindowMask, &ev));
2982 }
2983
2984 void
2985 move_window(struct ws_win *win)
2986 {
2987         unsigned int            mask;
2988         XWindowChanges          wc;
2989         struct swm_region       *r;
2990
2991         r = root_to_region(win->wa.root);
2992         bzero(&wc, sizeof wc);
2993         mask = CWX | CWY;
2994         wc.x = win->g.x;
2995         wc.y = win->g.y;
2996
2997         DNPRINTF(SWM_D_STACK, "move_window: win %lu x %d y %d w %d h %d\n",
2998             win->id, wc.x, wc.y, wc.width, wc.height);
2999
3000         XConfigureWindow(display, win->id, mask, &wc);
3001 }
3002
3003 void
3004 move(struct ws_win *win, union arg *args)
3005 {
3006         XEvent                  ev;
3007         Time                    time = 0;
3008         struct swm_region       *r = win->ws->r;
3009         union arg               a;
3010
3011         DNPRINTF(SWM_D_MOUSE, "move: win %lu floating %d trans %lu\n",
3012             win->id, win->floating, win->transient);
3013
3014         /* in max_stack mode should only move transients */
3015         if (win->ws->cur_layout == &layouts[SWM_MAX_STACK] && !win->transient)
3016                 return;
3017
3018         win->manual = 1;
3019         if (win->floating == 0 && !win->transient) {
3020                 win->floating = 1;
3021                 ewmh_update_win_state(win, ewmh[_NET_WM_STATE_ABOVE].atom,
3022                     _NET_WM_STATE_ADD);
3023         }
3024         ewmh_update_win_state(win, ewmh[_SWM_WM_STATE_MANUAL].atom,
3025             _NET_WM_STATE_ADD);
3026
3027         /* raise the window = move to last in window list */
3028         a.id = SWM_ARG_ID_MOVELAST;
3029         swapwin(r, &a);
3030         stack();
3031
3032         if (XGrabPointer(display, win->id, False, MOUSEMASK, GrabModeAsync,
3033             GrabModeAsync, None, None /* cursor */, CurrentTime) != GrabSuccess)
3034                 return;
3035         XWarpPointer(display, None, win->id, 0, 0, 0, 0, 0, 0);
3036         do {
3037                 XMaskEvent(display, MOUSEMASK | ExposureMask |
3038                     SubstructureRedirectMask, &ev);
3039                 switch(ev.type) {
3040                 case ConfigureRequest:
3041                 case Expose:
3042                 case MapRequest:
3043                         handler[ev.type](&ev);
3044                         break;
3045                 case MotionNotify:
3046                         /* don't allow to move window origin out of region */
3047                         if (    ev.xmotion.x_root < r->g.x ||
3048                                 ev.xmotion.x_root > r->g.x + r->g.w - 1 ||
3049                                 ev.xmotion.y_root < r->g.y ||
3050                                 ev.xmotion.y_root > r->g.y + r->g.h - 1)
3051                                 continue;
3052
3053                         win->g.x = ev.xmotion.x_root - border_width;
3054                         win->g.y = ev.xmotion.y_root - border_width;
3055
3056                         /* not free, don't sync more than 120 times / second */
3057                         if ((ev.xmotion.time - time) > (1000 / 120) ) {
3058                                 time = ev.xmotion.time;
3059                                 XSync(display, False);
3060                                 move_window(win);
3061                         }
3062                         break;
3063                 }
3064         } while (ev.type != ButtonRelease);
3065         if (time) {
3066                 XSync(display, False);
3067                 move_window(win);
3068         }
3069         store_float_geom(win,r);
3070         XWarpPointer(display, None, win->id, 0, 0, 0, 0, 0, 0);
3071         XUngrabPointer(display, CurrentTime);
3072
3073         /* drain events */
3074         while (XCheckMaskEvent(display, EnterWindowMask, &ev));
3075 }
3076
3077 /* user/key callable function IDs */
3078 enum keyfuncid {
3079         kf_cycle_layout,
3080         kf_stack_reset,
3081         kf_master_shrink,
3082         kf_master_grow,
3083         kf_master_add,
3084         kf_master_del,
3085         kf_stack_inc,
3086         kf_stack_dec,
3087         kf_swap_main,
3088         kf_focus_next,
3089         kf_focus_prev,
3090         kf_swap_next,
3091         kf_swap_prev,
3092         kf_spawn_term,
3093         kf_spawn_menu,
3094         kf_quit,
3095         kf_restart,
3096         kf_focus_main,
3097         kf_ws_1,
3098         kf_ws_2,
3099         kf_ws_3,
3100         kf_ws_4,
3101         kf_ws_5,
3102         kf_ws_6,
3103         kf_ws_7,
3104         kf_ws_8,
3105         kf_ws_9,
3106         kf_ws_10,
3107         kf_ws_next,
3108         kf_ws_prev,
3109         kf_ws_prior,
3110         kf_screen_next,
3111         kf_screen_prev,
3112         kf_mvws_1,
3113         kf_mvws_2,
3114         kf_mvws_3,
3115         kf_mvws_4,
3116         kf_mvws_5,
3117         kf_mvws_6,
3118         kf_mvws_7,
3119         kf_mvws_8,
3120         kf_mvws_9,
3121         kf_mvws_10,
3122         kf_bar_toggle,
3123         kf_wind_kill,
3124         kf_wind_del,
3125         kf_screenshot_all,
3126         kf_screenshot_wind,
3127         kf_float_toggle,
3128         kf_version,
3129         kf_spawn_lock,
3130         kf_spawn_initscr,
3131         kf_spawn_custom,
3132         kf_dumpwins,
3133         kf_invalid
3134 };
3135
3136 /* key definitions */
3137 void
3138 dummykeyfunc(struct swm_region *r, union arg *args)
3139 {
3140 };
3141
3142 void
3143 legacyfunc(struct swm_region *r, union arg *args)
3144 {
3145 };
3146
3147 struct keyfunc {
3148         char                    name[SWM_FUNCNAME_LEN];
3149         void                    (*func)(struct swm_region *r, union arg *);
3150         union arg               args;
3151 } keyfuncs[kf_invalid + 1] = {
3152         /* name                 function        argument */
3153         { "cycle_layout",       cycle_layout,   {0} },
3154         { "stack_reset",        stack_config,   {.id = SWM_ARG_ID_STACKRESET} },
3155         { "master_shrink",      stack_config,   {.id = SWM_ARG_ID_MASTERSHRINK} },
3156         { "master_grow",        stack_config,   {.id = SWM_ARG_ID_MASTERGROW} },
3157         { "master_add",         stack_config,   {.id = SWM_ARG_ID_MASTERADD} },
3158         { "master_del",         stack_config,   {.id = SWM_ARG_ID_MASTERDEL} },
3159         { "stack_inc",          stack_config,   {.id = SWM_ARG_ID_STACKINC} },
3160         { "stack_dec",          stack_config,   {.id = SWM_ARG_ID_STACKDEC} },
3161         { "swap_main",          swapwin,        {.id = SWM_ARG_ID_SWAPMAIN} },
3162         { "focus_next",         focus,          {.id = SWM_ARG_ID_FOCUSNEXT} },
3163         { "focus_prev",         focus,          {.id = SWM_ARG_ID_FOCUSPREV} },
3164         { "swap_next",          swapwin,        {.id = SWM_ARG_ID_SWAPNEXT} },
3165         { "swap_prev",          swapwin,        {.id = SWM_ARG_ID_SWAPPREV} },
3166         { "spawn_term",         spawnterm,      {.argv = spawn_term} },
3167         { "spawn_menu",         legacyfunc,     {0} },
3168         { "quit",               quit,           {0} },
3169         { "restart",            restart,        {0} },
3170         { "focus_main",         focus,          {.id = SWM_ARG_ID_FOCUSMAIN} },
3171         { "ws_1",               switchws,       {.id = 0} },
3172         { "ws_2",               switchws,       {.id = 1} },
3173         { "ws_3",               switchws,       {.id = 2} },
3174         { "ws_4",               switchws,       {.id = 3} },
3175         { "ws_5",               switchws,       {.id = 4} },
3176         { "ws_6",               switchws,       {.id = 5} },
3177         { "ws_7",               switchws,       {.id = 6} },
3178         { "ws_8",               switchws,       {.id = 7} },
3179         { "ws_9",               switchws,       {.id = 8} },
3180         { "ws_10",              switchws,       {.id = 9} },
3181         { "ws_next",            cyclews,        {.id = SWM_ARG_ID_CYCLEWS_UP} },
3182         { "ws_prev",            cyclews,        {.id = SWM_ARG_ID_CYCLEWS_DOWN} },
3183         { "ws_prior",           priorws,        {0} },
3184         { "screen_next",        cyclescr,       {.id = SWM_ARG_ID_CYCLESC_UP} },
3185         { "screen_prev",        cyclescr,       {.id = SWM_ARG_ID_CYCLESC_DOWN} },
3186         { "mvws_1",             send_to_ws,     {.id = 0} },
3187         { "mvws_2",             send_to_ws,     {.id = 1} },
3188         { "mvws_3",             send_to_ws,     {.id = 2} },
3189         { "mvws_4",             send_to_ws,     {.id = 3} },
3190         { "mvws_5",             send_to_ws,     {.id = 4} },
3191         { "mvws_6",             send_to_ws,     {.id = 5} },
3192         { "mvws_7",             send_to_ws,     {.id = 6} },
3193         { "mvws_8",             send_to_ws,     {.id = 7} },
3194         { "mvws_9",             send_to_ws,     {.id = 8} },
3195         { "mvws_10",            send_to_ws,     {.id = 9} },
3196         { "bar_toggle",         bar_toggle,     {0} },
3197         { "wind_kill",          wkill,          {.id = SWM_ARG_ID_KILLWINDOW} },
3198         { "wind_del",           wkill,          {.id = SWM_ARG_ID_DELETEWINDOW} },
3199         { "screenshot_all",     legacyfunc,     {0} },
3200         { "screenshot_wind",    legacyfunc,     {0} },
3201         { "float_toggle",       floating_toggle,{0} },
3202         { "version",            version,        {0} },
3203         { "spawn_lock",         legacyfunc,     {0} },
3204         { "spawn_initscr",      legacyfunc,     {0} },
3205         { "spawn_custom",       dummykeyfunc,   {0} },
3206         { "dumpwins",           dumpwins,       {0} },
3207         { "invalid key func",   NULL,           {0} },
3208 };
3209 struct key {
3210         unsigned int            mod;
3211         KeySym                  keysym;
3212         enum keyfuncid          funcid;
3213         char                    *spawn_name;
3214 };
3215 int                             keys_size = 0, keys_length = 0;
3216 struct key                      *keys = NULL;
3217
3218 /* mouse */
3219 enum { client_click, root_click };
3220 struct button {
3221         unsigned int            action;
3222         unsigned int            mask;
3223         unsigned int            button;
3224         void                    (*func)(struct ws_win *, union arg *);
3225         union arg               args;
3226 } buttons[] = {
3227           /* action     key             mouse button    func    args */
3228         { client_click, MODKEY,         Button3,        resize, {.id = SWM_ARG_ID_DONTCENTER} },
3229         { client_click, MODKEY | ShiftMask, Button3,    resize, {.id = SWM_ARG_ID_CENTER} },
3230         { client_click, MODKEY,         Button1,        move,   {0} },
3231 };
3232
3233 void
3234 update_modkey(unsigned int mod)
3235 {
3236         int                     i;
3237
3238         mod_key = mod;
3239         for (i = 0; i < keys_length; i++)
3240                 if (keys[i].mod & ShiftMask)
3241                         keys[i].mod = mod | ShiftMask;
3242                 else
3243                         keys[i].mod = mod;
3244
3245         for (i = 0; i < LENGTH(buttons); i++)
3246                 if (buttons[i].mask & ShiftMask)
3247                         buttons[i].mask = mod | ShiftMask;
3248                 else
3249                         buttons[i].mask = mod;
3250 }
3251
3252 /* spawn */
3253 struct spawn_prog {
3254         char                    *name;
3255         int                     argc;
3256         char                    **argv;
3257 };
3258
3259 int                             spawns_size = 0, spawns_length = 0;
3260 struct spawn_prog               *spawns = NULL;
3261
3262 void
3263 spawn_custom(struct swm_region *r, union arg *args, char *spawn_name)
3264 {
3265         union arg               a;
3266         struct spawn_prog       *prog = NULL;
3267         int                     i;
3268         char                    *ap, **real_args;
3269
3270         DNPRINTF(SWM_D_SPAWN, "spawn_custom %s\n", spawn_name);
3271
3272         /* find program */
3273         for (i = 0; i < spawns_length; i++) {
3274                 if (!strcasecmp(spawn_name, spawns[i].name))
3275                         prog = &spawns[i];
3276         }
3277         if (prog == NULL) {
3278                 fprintf(stderr, "spawn_custom: program %s not found\n",
3279                     spawn_name);
3280                 return;
3281         }
3282
3283         /* make room for expanded args */
3284         if ((real_args = calloc(prog->argc + 1, sizeof(char *))) == NULL)
3285                 err(1, "spawn_custom: calloc real_args");
3286
3287         /* expand spawn_args into real_args */
3288         for (i = 0; i < prog->argc; i++) {
3289                 ap = prog->argv[i];
3290                 DNPRINTF(SWM_D_SPAWN, "spawn_custom: raw arg = %s\n", ap);
3291                 if (!strcasecmp(ap, "$bar_border")) {
3292                         if ((real_args[i] =
3293                             strdup(r->s->c[SWM_S_COLOR_BAR_BORDER].name))
3294                             == NULL)
3295                                 err(1,  "spawn_custom border color");
3296                 } else if (!strcasecmp(ap, "$bar_color")) {
3297                         if ((real_args[i] =
3298                             strdup(r->s->c[SWM_S_COLOR_BAR].name))
3299                             == NULL)
3300                                 err(1, "spawn_custom bar color");
3301                 } else if (!strcasecmp(ap, "$bar_font")) {
3302                         if ((real_args[i] = strdup(bar_fonts[bar_fidx]))
3303                             == NULL)
3304                                 err(1, "spawn_custom bar fonts");
3305                 } else if (!strcasecmp(ap, "$bar_font_color")) {
3306                         if ((real_args[i] =
3307                             strdup(r->s->c[SWM_S_COLOR_BAR_FONT].name))
3308                             == NULL)
3309                                 err(1, "spawn_custom color font");
3310                 } else if (!strcasecmp(ap, "$color_focus")) {
3311                         if ((real_args[i] =
3312                             strdup(r->s->c[SWM_S_COLOR_FOCUS].name))
3313                             == NULL)
3314                                 err(1, "spawn_custom color focus");
3315                 } else if (!strcasecmp(ap, "$color_unfocus")) {
3316                         if ((real_args[i] =
3317                             strdup(r->s->c[SWM_S_COLOR_UNFOCUS].name))
3318                             == NULL)
3319                                 err(1, "spawn_custom color unfocus");
3320                 } else {
3321                         /* no match --> copy as is */
3322                         if ((real_args[i] = strdup(ap)) == NULL)
3323                                 err(1, "spawn_custom strdup(ap)");
3324                 }
3325                 DNPRINTF(SWM_D_SPAWN, "spawn_custom: cooked arg = %s\n",
3326                     real_args[i]);
3327         }
3328
3329 #ifdef SWM_DEBUG
3330         if ((swm_debug & SWM_D_SPAWN) != 0) {
3331                 fprintf(stderr, "spawn_custom: result = ");
3332                 for (i = 0; i < prog->argc; i++)
3333                         fprintf(stderr, "\"%s\" ", real_args[i]);
3334                 fprintf(stderr, "\n");
3335         }
3336 #endif
3337
3338         a.argv = real_args;
3339         spawn(r, &a);
3340         for (i = 0; i < prog->argc; i++)
3341                 free(real_args[i]);
3342         free(real_args);
3343 }
3344
3345 void
3346 setspawn(struct spawn_prog *prog)
3347 {
3348         int                     i, j;
3349
3350         if (prog == NULL || prog->name == NULL)
3351                 return;
3352
3353         /* find existing */
3354         for (i = 0; i < spawns_length; i++) {
3355                 if (!strcmp(spawns[i].name, prog->name)) {
3356                         /* found */
3357                         if (prog->argv == NULL) {
3358                                 /* delete */
3359                                 DNPRINTF(SWM_D_SPAWN,
3360                                     "setspawn: delete #%d %s\n",
3361                                     i, spawns[i].name);
3362                                 free(spawns[i].name);
3363                                 for (j = 0; j < spawns[i].argc; j++)
3364                                         free(spawns[i].argv[j]);
3365                                 free(spawns[i].argv);
3366                                 j = spawns_length - 1;
3367                                 if (i < j)
3368                                         spawns[i] = spawns[j];
3369                                 spawns_length--;
3370                                 free(prog->name);
3371                         } else {
3372                                 /* replace */
3373                                 DNPRINTF(SWM_D_SPAWN,
3374                                     "setspawn: replace #%d %s\n",
3375                                     i, spawns[i].name);
3376                                 free(spawns[i].name);
3377                                 for (j = 0; j < spawns[i].argc; j++)
3378                                         free(spawns[i].argv[j]);
3379                                 free(spawns[i].argv);
3380                                 spawns[i] = *prog;
3381                         }
3382                         /* found case handled */
3383                         free(prog);
3384                         return;
3385                 }
3386         }
3387
3388         if (prog->argv == NULL) {
3389                 fprintf(stderr,
3390                     "error: setspawn: cannot find program %s", prog->name);
3391                 free(prog);
3392                 return;
3393         }
3394
3395         /* not found: add */
3396         if (spawns_size == 0 || spawns == NULL) {
3397                 spawns_size = 4;
3398                 DNPRINTF(SWM_D_SPAWN, "setspawn: init list %d\n", spawns_size);
3399                 spawns = malloc((size_t)spawns_size *
3400                     sizeof(struct spawn_prog));
3401                 if (spawns == NULL) {
3402                         fprintf(stderr, "setspawn: malloc failed\n");
3403                         perror(" failed");
3404                         quit(NULL, NULL);
3405                 }
3406         } else if (spawns_length == spawns_size) {
3407                 spawns_size *= 2;
3408                 DNPRINTF(SWM_D_SPAWN, "setspawn: grow list %d\n", spawns_size);
3409                 spawns = realloc(spawns, (size_t)spawns_size *
3410                     sizeof(struct spawn_prog));
3411                 if (spawns == NULL) {
3412                         fprintf(stderr, "setspawn: realloc failed\n");
3413                         perror(" failed");
3414                         quit(NULL, NULL);
3415                 }
3416         }
3417
3418         if (spawns_length < spawns_size) {
3419                 DNPRINTF(SWM_D_SPAWN, "setspawn: add #%d %s\n",
3420                     spawns_length, prog->name);
3421                 i = spawns_length++;
3422                 spawns[i] = *prog;
3423         } else {
3424                 fprintf(stderr, "spawns array problem?\n");
3425                 if (spawns == NULL) {
3426                         fprintf(stderr, "spawns array is NULL!\n");
3427                         quit(NULL, NULL);
3428                 }
3429         }
3430         free(prog);
3431 }
3432
3433 int
3434 setconfspawn(char *selector, char *value, int flags)
3435 {
3436         struct spawn_prog       *prog;
3437         char                    *vp, *cp, *word;
3438
3439         DNPRINTF(SWM_D_SPAWN, "setconfspawn: [%s] [%s]\n", selector, value);
3440         if ((prog = calloc(1, sizeof *prog)) == NULL)
3441                 err(1, "setconfspawn: calloc prog");
3442         prog->name = strdup(selector);
3443         if (prog->name == NULL)
3444                 err(1, "setconfspawn prog->name");
3445         if ((cp = vp = strdup(value)) == NULL)
3446                 err(1, "setconfspawn: strdup(value) ");
3447         while ((word = strsep(&cp, " \t")) != NULL) {
3448                 DNPRINTF(SWM_D_SPAWN, "setconfspawn: arg [%s]\n", word);
3449                 if (cp)
3450                         cp += (long)strspn(cp, " \t");
3451                 if (strlen(word) > 0) {
3452                         prog->argc++;
3453                         prog->argv = realloc(prog->argv,
3454                             prog->argc * sizeof(char *));
3455                         if ((prog->argv[prog->argc - 1] = strdup(word)) == NULL)
3456                                 err(1, "setconfspawn: strdup");
3457                 }
3458         }
3459         free(vp);
3460
3461         setspawn(prog);
3462
3463         DNPRINTF(SWM_D_SPAWN, "setconfspawn: done\n");
3464         return (0);
3465 }
3466
3467 void
3468 setup_spawn(void)
3469 {
3470         setconfspawn("term",            "xterm",                0);
3471         setconfspawn("screenshot_all",  "screenshot.sh full",   0);
3472         setconfspawn("screenshot_wind", "screenshot.sh window", 0);
3473         setconfspawn("lock",            "xlock",                0);
3474         setconfspawn("initscr",         "initscreen.sh",        0);
3475         setconfspawn("menu",            "dmenu_run"
3476                                         " -fn $bar_font"
3477                                         " -nb $bar_color"
3478                                         " -nf $bar_font_color"
3479                                         " -sb $bar_border"
3480                                         " -sf $bar_color",      0);
3481 }
3482
3483 /* key bindings */
3484 #define SWM_MODNAME_SIZE        32
3485 #define SWM_KEY_WS              "\n+ \t"
3486 int
3487 parsekeys(char *keystr, unsigned int currmod, unsigned int *mod, KeySym *ks)
3488 {
3489         char                    *cp, *name;
3490         KeySym                  uks;
3491         DNPRINTF(SWM_D_KEY, "parsekeys: enter [%s]\n", keystr);
3492         if (mod == NULL || ks == NULL) {
3493                 DNPRINTF(SWM_D_KEY, "parsekeys: no mod or key vars\n");
3494                 return (1);
3495         }
3496         if (keystr == NULL || strlen(keystr) == 0) {
3497                 DNPRINTF(SWM_D_KEY, "parsekeys: no keystr\n");
3498                 return (1);
3499         }
3500         cp = keystr;
3501         *ks = NoSymbol;
3502         *mod = 0;
3503         while ((name = strsep(&cp, SWM_KEY_WS)) != NULL) {
3504                 DNPRINTF(SWM_D_KEY, "parsekeys: key [%s]\n", name);
3505                 if (cp)
3506                         cp += (long)strspn(cp, SWM_KEY_WS);
3507                 if (strncasecmp(name, "MOD", SWM_MODNAME_SIZE) == 0)
3508                         *mod |= currmod;
3509                 else if (!strncasecmp(name, "Mod1", SWM_MODNAME_SIZE))
3510                         *mod |= Mod1Mask;
3511                 else if (!strncasecmp(name, "Mod2", SWM_MODNAME_SIZE))
3512                         *mod += Mod2Mask;
3513                 else if (!strncmp(name, "Mod3", SWM_MODNAME_SIZE))
3514                         *mod |= Mod3Mask;
3515                 else if (!strncmp(name, "Mod4", SWM_MODNAME_SIZE))
3516                         *mod |= Mod4Mask;
3517                 else if (strncasecmp(name, "SHIFT", SWM_MODNAME_SIZE) == 0)
3518                         *mod |= ShiftMask;
3519                 else if (strncasecmp(name, "CONTROL", SWM_MODNAME_SIZE) == 0)
3520                         *mod |= ControlMask;
3521                 else {
3522                         *ks = XStringToKeysym(name);
3523                         XConvertCase(*ks, ks, &uks);
3524                         if (ks == NoSymbol) {
3525                                 DNPRINTF(SWM_D_KEY,
3526                                     "parsekeys: invalid key %s\n",
3527                                     name);
3528                                 return (1);
3529                         }
3530                 }
3531         }
3532         DNPRINTF(SWM_D_KEY, "parsekeys: leave ok\n");
3533         return (0);
3534 }
3535
3536 char *
3537 strdupsafe(char *str)
3538 {
3539         if (str == NULL)
3540                 return (NULL);
3541         else
3542                 return (strdup(str));
3543 }
3544
3545 void
3546 setkeybinding(unsigned int mod, KeySym ks, enum keyfuncid kfid, char *spawn_name)
3547 {
3548         int                     i, j;
3549         DNPRINTF(SWM_D_KEY, "setkeybinding: enter %s [%s]\n",
3550             keyfuncs[kfid].name, spawn_name);
3551         /* find existing */
3552         for (i = 0; i < keys_length; i++) {
3553                 if (keys[i].mod == mod && keys[i].keysym == ks) {
3554                         if (kfid == kf_invalid) {
3555                                 /* found: delete */
3556                                 DNPRINTF(SWM_D_KEY,
3557                                     "setkeybinding: delete #%d %s\n",
3558                                     i, keyfuncs[keys[i].funcid].name);
3559                                 free(keys[i].spawn_name);
3560                                 j = keys_length - 1;
3561                                 if (i < j)
3562                                         keys[i] = keys[j];
3563                                 keys_length--;
3564                                 DNPRINTF(SWM_D_KEY, "setkeybinding: leave\n");
3565                                 return;
3566                         } else {
3567                                 /* found: replace */
3568                                 DNPRINTF(SWM_D_KEY,
3569                                     "setkeybinding: replace #%d %s %s\n",
3570                                     i, keyfuncs[keys[i].funcid].name,
3571                                     spawn_name);
3572                                 free(keys[i].spawn_name);
3573                                 keys[i].mod = mod;
3574                                 keys[i].keysym = ks;
3575                                 keys[i].funcid = kfid;
3576                                 keys[i].spawn_name = strdupsafe(spawn_name);
3577                                 DNPRINTF(SWM_D_KEY, "setkeybinding: leave\n");
3578                                 return;
3579                         }
3580                 }
3581         }
3582         if (kfid == kf_invalid) {
3583                 fprintf(stderr,
3584                     "error: setkeybinding: cannot find mod/key combination");
3585                 DNPRINTF(SWM_D_KEY, "setkeybinding: leave\n");
3586                 return;
3587         }
3588         /* not found: add */
3589         if (keys_size == 0 || keys == NULL) {
3590                 keys_size = 4;
3591                 DNPRINTF(SWM_D_KEY, "setkeybinding: init list %d\n", keys_size);
3592                 keys = malloc((size_t)keys_size * sizeof(struct key));
3593                 if (!keys) {
3594                         fprintf(stderr, "malloc failed\n");
3595                         perror(" failed");
3596                         quit(NULL, NULL);
3597                 }
3598         } else if (keys_length == keys_size) {
3599                 keys_size *= 2;
3600                 DNPRINTF(SWM_D_KEY, "setkeybinding: grow list %d\n", keys_size);
3601                 keys = realloc(keys, (size_t)keys_size * sizeof(struct key));
3602                 if (!keys) {
3603                         fprintf(stderr, "realloc failed\n");
3604                         perror(" failed");
3605                         quit(NULL, NULL);
3606                 }
3607         }
3608         if (keys_length < keys_size) {
3609                 j = keys_length++;
3610                 DNPRINTF(SWM_D_KEY, "setkeybinding: add #%d %s %s\n",
3611                     j, keyfuncs[kfid].name, spawn_name);
3612                 keys[j].mod = mod;
3613                 keys[j].keysym = ks;
3614                 keys[j].funcid = kfid;
3615                 keys[j].spawn_name = strdupsafe(spawn_name);
3616         } else {
3617                 fprintf(stderr, "keys array problem?\n");
3618                 if (!keys) {
3619                         fprintf(stderr, "keys array problem\n");
3620                         quit(NULL, NULL);
3621                 }
3622         }
3623         DNPRINTF(SWM_D_KEY, "setkeybinding: leave\n");
3624 }
3625
3626 int
3627 setconfbinding(char *selector, char *value, int flags)
3628 {
3629         enum keyfuncid          kfid;
3630         unsigned int            mod;
3631         KeySym                  ks;
3632         int                     i;
3633         DNPRINTF(SWM_D_KEY, "setconfbinding: enter\n");
3634         if (selector == NULL) {
3635                 DNPRINTF(SWM_D_KEY, "setconfbinding: unbind %s\n", value);
3636                 if (parsekeys(value, mod_key, &mod, &ks) == 0) {
3637                         kfid = kf_invalid;
3638                         setkeybinding(mod, ks, kfid, NULL);
3639                         return (0);
3640                 } else
3641                         return (1);
3642         }
3643         /* search by key function name */
3644         for (kfid = 0; kfid < kf_invalid; (kfid)++) {
3645                 if (strncasecmp(selector, keyfuncs[kfid].name,
3646                     SWM_FUNCNAME_LEN) == 0) {
3647                         DNPRINTF(SWM_D_KEY, "setconfbinding: %s: match\n",
3648                             selector);
3649                         if (parsekeys(value, mod_key, &mod, &ks) == 0) {
3650                                 setkeybinding(mod, ks, kfid, NULL);
3651                                 return (0);
3652                         } else
3653                                 return (1);
3654                 }
3655         }
3656         /* search by custom spawn name */
3657         for (i = 0; i < spawns_length; i++) {
3658                 if (strcasecmp(selector, spawns[i].name) == 0) {
3659                         DNPRINTF(SWM_D_KEY, "setconfbinding: %s: match\n",
3660                             selector);
3661                         if (parsekeys(value, mod_key, &mod, &ks) == 0) {
3662                                 setkeybinding(mod, ks, kf_spawn_custom,
3663                                     spawns[i].name);
3664                                 return (0);
3665                         } else
3666                                 return (1);
3667                 }
3668         }
3669         DNPRINTF(SWM_D_KEY, "setconfbinding: no match\n");
3670         return (1);
3671 }
3672
3673 void
3674 setup_keys(void)
3675 {
3676         setkeybinding(MODKEY,           XK_space,       kf_cycle_layout,NULL);
3677         setkeybinding(MODKEY|ShiftMask, XK_space,       kf_stack_reset, NULL);
3678         setkeybinding(MODKEY,           XK_h,           kf_master_shrink,NULL);
3679         setkeybinding(MODKEY,           XK_l,           kf_master_grow, NULL);
3680         setkeybinding(MODKEY,           XK_comma,       kf_master_add,  NULL);
3681         setkeybinding(MODKEY,           XK_period,      kf_master_del,  NULL);
3682         setkeybinding(MODKEY|ShiftMask, XK_comma,       kf_stack_inc,   NULL);
3683         setkeybinding(MODKEY|ShiftMask, XK_period,      kf_stack_dec,   NULL);
3684         setkeybinding(MODKEY,           XK_Return,      kf_swap_main,   NULL);
3685         setkeybinding(MODKEY,           XK_j,           kf_focus_next,  NULL);
3686         setkeybinding(MODKEY,           XK_k,           kf_focus_prev,  NULL);
3687         setkeybinding(MODKEY|ShiftMask, XK_j,           kf_swap_next,   NULL);
3688         setkeybinding(MODKEY|ShiftMask, XK_k,           kf_swap_prev,   NULL);
3689         setkeybinding(MODKEY|ShiftMask, XK_Return,      kf_spawn_term,  NULL);
3690         setkeybinding(MODKEY,           XK_p,           kf_spawn_custom,        "menu");
3691         setkeybinding(MODKEY|ShiftMask, XK_q,           kf_quit,        NULL);
3692         setkeybinding(MODKEY,           XK_q,           kf_restart,     NULL);
3693         setkeybinding(MODKEY,           XK_m,           kf_focus_main,  NULL);
3694         setkeybinding(MODKEY,           XK_1,           kf_ws_1,        NULL);
3695         setkeybinding(MODKEY,           XK_2,           kf_ws_2,        NULL);
3696         setkeybinding(MODKEY,           XK_3,           kf_ws_3,        NULL);
3697         setkeybinding(MODKEY,           XK_4,           kf_ws_4,        NULL);
3698         setkeybinding(MODKEY,           XK_5,           kf_ws_5,        NULL);
3699         setkeybinding(MODKEY,           XK_6,           kf_ws_6,        NULL);
3700         setkeybinding(MODKEY,           XK_7,           kf_ws_7,        NULL);
3701         setkeybinding(MODKEY,           XK_8,           kf_ws_8,        NULL);
3702         setkeybinding(MODKEY,           XK_9,           kf_ws_9,        NULL);
3703         setkeybinding(MODKEY,           XK_0,           kf_ws_10,       NULL);
3704         setkeybinding(MODKEY,           XK_Right,       kf_ws_next,     NULL);
3705         setkeybinding(MODKEY,           XK_Left,        kf_ws_prev,     NULL);
3706         setkeybinding(MODKEY,           XK_a,           kf_ws_prior,    NULL);
3707         setkeybinding(MODKEY|ShiftMask, XK_Right,       kf_screen_next, NULL);
3708         setkeybinding(MODKEY|ShiftMask, XK_Left,        kf_screen_prev, NULL);
3709         setkeybinding(MODKEY|ShiftMask, XK_1,           kf_mvws_1,      NULL);
3710         setkeybinding(MODKEY|ShiftMask, XK_2,           kf_mvws_2,      NULL);
3711         setkeybinding(MODKEY|ShiftMask, XK_3,           kf_mvws_3,      NULL);
3712         setkeybinding(MODKEY|ShiftMask, XK_4,           kf_mvws_4,      NULL);
3713         setkeybinding(MODKEY|ShiftMask, XK_5,           kf_mvws_5,      NULL);
3714         setkeybinding(MODKEY|ShiftMask, XK_6,           kf_mvws_6,      NULL);
3715         setkeybinding(MODKEY|ShiftMask, XK_7,           kf_mvws_7,      NULL);
3716         setkeybinding(MODKEY|ShiftMask, XK_8,           kf_mvws_8,      NULL);
3717         setkeybinding(MODKEY|ShiftMask, XK_9,           kf_mvws_9,      NULL);
3718         setkeybinding(MODKEY|ShiftMask, XK_0,           kf_mvws_10,     NULL);
3719         setkeybinding(MODKEY,           XK_b,           kf_bar_toggle,  NULL);
3720         setkeybinding(MODKEY,           XK_Tab,         kf_focus_next,  NULL);
3721         setkeybinding(MODKEY|ShiftMask, XK_Tab,         kf_focus_prev,  NULL);
3722         setkeybinding(MODKEY|ShiftMask, XK_x,           kf_wind_kill,   NULL);
3723         setkeybinding(MODKEY,           XK_x,           kf_wind_del,    NULL);
3724         setkeybinding(MODKEY,           XK_s,           kf_spawn_custom,        "screenshot_all");
3725         setkeybinding(MODKEY|ShiftMask, XK_s,           kf_spawn_custom,        "screenshot_wind");
3726         setkeybinding(MODKEY,           XK_t,           kf_float_toggle,NULL);
3727         setkeybinding(MODKEY|ShiftMask, XK_v,           kf_version,     NULL);
3728         setkeybinding(MODKEY|ShiftMask, XK_Delete,      kf_spawn_custom,        "lock");
3729         setkeybinding(MODKEY|ShiftMask, XK_i,           kf_spawn_custom,        "initscr");
3730 #ifdef SWM_DEBUG
3731         setkeybinding(MODKEY|ShiftMask, XK_d,           kf_dumpwins,    NULL);
3732 #endif
3733 }
3734
3735 void
3736 updatenumlockmask(void)
3737 {
3738         unsigned int            i, j;
3739         XModifierKeymap         *modmap;
3740
3741         DNPRINTF(SWM_D_MISC, "updatenumlockmask\n");
3742         numlockmask = 0;
3743         modmap = XGetModifierMapping(display);
3744         for (i = 0; i < 8; i++)
3745                 for (j = 0; j < modmap->max_keypermod; j++)
3746                         if (modmap->modifiermap[i * modmap->max_keypermod + j]
3747                           == XKeysymToKeycode(display, XK_Num_Lock))
3748                                 numlockmask = (1 << i);
3749
3750         XFreeModifiermap(modmap);
3751 }
3752
3753 void
3754 grabkeys(void)
3755 {
3756         unsigned int            i, j, k;
3757         KeyCode                 code;
3758         unsigned int            modifiers[] =
3759             { 0, LockMask, numlockmask, numlockmask | LockMask };
3760
3761         DNPRINTF(SWM_D_MISC, "grabkeys\n");
3762         updatenumlockmask();
3763
3764         for (k = 0; k < ScreenCount(display); k++) {
3765                 if (TAILQ_EMPTY(&screens[k].rl))
3766                         continue;
3767                 XUngrabKey(display, AnyKey, AnyModifier, screens[k].root);
3768                 for (i = 0; i < keys_length; i++) {
3769                         if ((code = XKeysymToKeycode(display, keys[i].keysym)))
3770                                 for (j = 0; j < LENGTH(modifiers); j++)
3771                                         XGrabKey(display, code,
3772                                             keys[i].mod | modifiers[j],
3773                                             screens[k].root, True,
3774                                             GrabModeAsync, GrabModeAsync);
3775                 }
3776         }
3777 }
3778
3779 void
3780 grabbuttons(struct ws_win *win, int focused)
3781 {
3782         unsigned int            i, j;
3783         unsigned int            modifiers[] =
3784             { 0, LockMask, numlockmask, numlockmask|LockMask };
3785
3786         updatenumlockmask();
3787         XUngrabButton(display, AnyButton, AnyModifier, win->id);
3788         if (focused) {
3789                 for (i = 0; i < LENGTH(buttons); i++)
3790                         if (buttons[i].action == client_click)
3791                                 for (j = 0; j < LENGTH(modifiers); j++)
3792                                         XGrabButton(display, buttons[i].button,
3793                                             buttons[i].mask | modifiers[j],
3794                                             win->id, False, BUTTONMASK,
3795                                             GrabModeAsync, GrabModeSync, None,
3796                                             None);
3797         } else
3798                 XGrabButton(display, AnyButton, AnyModifier, win->id, False,
3799                     BUTTONMASK, GrabModeAsync, GrabModeSync, None, None);
3800 }
3801
3802 const char *quirkname[] = {
3803         "NONE",         /* config string for "no value" */
3804         "FLOAT",
3805         "TRANSSZ",
3806         "ANYWHERE",
3807         "XTERM_FONTADJ",
3808         "FULLSCREEN",
3809 };
3810
3811 /* SWM_Q_WS: retain '|' for back compat for now (2009-08-11) */
3812 #define SWM_Q_WS                "\n|+ \t"
3813 int
3814 parsequirks(char *qstr, unsigned long *quirk)
3815 {
3816         char                    *cp, *name;
3817         int                     i;
3818
3819         if (quirk == NULL)
3820                 return (1);
3821
3822         cp = qstr;
3823         *quirk = 0;
3824         while ((name = strsep(&cp, SWM_Q_WS)) != NULL) {
3825                 if (cp)
3826                         cp += (long)strspn(cp, SWM_Q_WS);
3827                 for (i = 0; i < LENGTH(quirkname); i++) {
3828                         if (!strncasecmp(name, quirkname[i], SWM_QUIRK_LEN)) {
3829                                 DNPRINTF(SWM_D_QUIRK, "parsequirks: %s\n", name);
3830                                 if (i == 0) {
3831                                         *quirk = 0;
3832                                         return (0);
3833                                 }
3834                                 *quirk |= 1 << (i-1);
3835                                 break;
3836                         }
3837                 }
3838                 if (i >= LENGTH(quirkname)) {
3839                         DNPRINTF(SWM_D_QUIRK,
3840                             "parsequirks: invalid quirk [%s]\n", name);
3841                         return (1);
3842                 }
3843         }
3844         return (0);
3845 }
3846
3847 void
3848 setquirk(const char *class, const char *name, const int quirk)
3849 {
3850         int                     i, j;
3851
3852         /* find existing */
3853         for (i = 0; i < quirks_length; i++) {
3854                 if (!strcmp(quirks[i].class, class) &&
3855                     !strcmp(quirks[i].name, name)) {
3856                         if (!quirk) {
3857                                 /* found: delete */
3858                                 DNPRINTF(SWM_D_QUIRK,
3859                                     "setquirk: delete #%d %s:%s\n",
3860                                     i, quirks[i].class, quirks[i].name);
3861                                 free(quirks[i].class);
3862                                 free(quirks[i].name);
3863                                 j = quirks_length - 1;
3864                                 if (i < j)
3865                                         quirks[i] = quirks[j];
3866                                 quirks_length--;
3867                                 return;
3868                         } else {
3869                                 /* found: replace */
3870                                 DNPRINTF(SWM_D_QUIRK,
3871                                     "setquirk: replace #%d %s:%s\n",
3872                                     i, quirks[i].class, quirks[i].name);
3873                                 free(quirks[i].class);
3874                                 free(quirks[i].name);
3875                                 quirks[i].class = strdup(class);
3876                                 quirks[i].name = strdup(name);
3877                                 quirks[i].quirk = quirk;
3878                                 return;
3879                         }
3880                 }
3881         }
3882         if (!quirk) {
3883                 fprintf(stderr,
3884                     "error: setquirk: cannot find class/name combination");
3885                 return;
3886         }
3887         /* not found: add */
3888         if (quirks_size == 0 || quirks == NULL) {
3889                 quirks_size = 4;
3890                 DNPRINTF(SWM_D_QUIRK, "setquirk: init list %d\n", quirks_size);
3891                 quirks = malloc((size_t)quirks_size * sizeof(struct quirk));
3892                 if (!quirks) {
3893                         fprintf(stderr, "setquirk: malloc failed\n");
3894                         perror(" failed");
3895                         quit(NULL, NULL);
3896                 }
3897         } else if (quirks_length == quirks_size) {
3898                 quirks_size *= 2;
3899                 DNPRINTF(SWM_D_QUIRK, "setquirk: grow list %d\n", quirks_size);
3900                 quirks = realloc(quirks, (size_t)quirks_size * sizeof(struct quirk));
3901                 if (!quirks) {
3902                         fprintf(stderr, "setquirk: realloc failed\n");
3903                         perror(" failed");
3904                         quit(NULL, NULL);
3905                 }
3906         }
3907         if (quirks_length < quirks_size) {
3908                 DNPRINTF(SWM_D_QUIRK, "setquirk: add %d\n", quirks_length);
3909                 j = quirks_length++;
3910                 quirks[j].class = strdup(class);
3911                 quirks[j].name = strdup(name);
3912                 quirks[j].quirk = quirk;
3913         } else {
3914                 fprintf(stderr, "quirks array problem?\n");
3915                 if (!quirks) {
3916                         fprintf(stderr, "quirks array problem!\n");
3917                         quit(NULL, NULL);
3918                 }
3919         }
3920 }
3921
3922 int
3923 setconfquirk(char *selector, char *value, int flags)
3924 {
3925         char                    *cp, *class, *name;
3926         int                     retval;
3927         unsigned long           quirks;
3928         if (selector == NULL)
3929                 return (0);
3930         if ((cp = strchr(selector, ':')) == NULL)
3931                 return (0);
3932         *cp = '\0';
3933         class = selector;
3934         name = cp + 1;
3935         if ((retval = parsequirks(value, &quirks)) == 0)
3936                 setquirk(class, name, quirks);
3937         return (retval);
3938 }
3939
3940 void
3941 setup_quirks(void)
3942 {
3943         setquirk("MPlayer",             "xv",           SWM_Q_FLOAT | SWM_Q_FULLSCREEN);
3944         setquirk("OpenOffice.org 3.2",  "VCLSalFrame",  SWM_Q_FLOAT);
3945         setquirk("Firefox-bin",         "firefox-bin",  SWM_Q_TRANSSZ);
3946         setquirk("Firefox",             "Dialog",       SWM_Q_FLOAT);
3947         setquirk("Gimp",                "gimp",         SWM_Q_FLOAT | SWM_Q_ANYWHERE);
3948         setquirk("XTerm",               "xterm",        SWM_Q_XTERM_FONTADJ);
3949         setquirk("xine",                "Xine Window",  SWM_Q_FLOAT | SWM_Q_ANYWHERE);
3950         setquirk("Xitk",                "Xitk Combo",   SWM_Q_FLOAT | SWM_Q_ANYWHERE);
3951         setquirk("xine",                "xine Panel",   SWM_Q_FLOAT | SWM_Q_ANYWHERE);
3952         setquirk("Xitk",                "Xine Window",  SWM_Q_FLOAT | SWM_Q_ANYWHERE);
3953         setquirk("xine",                "xine Video Fullscreen Window", SWM_Q_FULLSCREEN | SWM_Q_FLOAT);
3954         setquirk("pcb",                 "pcb",          SWM_Q_FLOAT);
3955 }
3956
3957 /* conf file stuff */
3958 #define SWM_CONF_FILE   "scrotwm.conf"
3959
3960 enum    { SWM_S_BAR_DELAY, SWM_S_BAR_ENABLED, SWM_S_BAR_BORDER_WIDTH, SWM_S_STACK_ENABLED,
3961           SWM_S_CLOCK_ENABLED, SWM_S_CLOCK_FORMAT, SWM_S_CYCLE_EMPTY,
3962           SWM_S_CYCLE_VISIBLE, SWM_S_SS_ENABLED, SWM_S_TERM_WIDTH,
3963           SWM_S_TITLE_CLASS_ENABLED, SWM_S_TITLE_NAME_ENABLED, SWM_S_WINDOW_NAME_ENABLED,
3964           SWM_S_FOCUS_MODE, SWM_S_DISABLE_BORDER, SWM_S_BORDER_WIDTH, SWM_S_BAR_FONT,
3965           SWM_S_BAR_ACTION, SWM_S_SPAWN_TERM, SWM_S_SS_APP, SWM_S_DIALOG_RATIO,
3966           SWM_S_BAR_AT_BOTTOM
3967         };
3968
3969 int
3970 setconfvalue(char *selector, char *value, int flags)
3971 {
3972         switch (flags) {
3973         case SWM_S_BAR_DELAY:
3974                 bar_delay = atoi(value);
3975                 break;
3976         case SWM_S_BAR_ENABLED:
3977                 bar_enabled = atoi(value);
3978                 break;
3979         case SWM_S_BAR_BORDER_WIDTH:
3980                 bar_border_width = atoi(value);
3981                 break;
3982         case SWM_S_BAR_AT_BOTTOM:
3983                 bar_at_bottom = atoi(value);
3984                 break;
3985         case SWM_S_STACK_ENABLED:
3986                 stack_enabled = atoi(value);
3987                 break;
3988         case SWM_S_CLOCK_ENABLED:
3989                 clock_enabled = atoi(value);
3990                 break;
3991         case SWM_S_CLOCK_FORMAT:
3992 #ifndef SWM_DENY_CLOCK_FORMAT
3993                 free(clock_format);
3994                 if ((clock_format = strdup(value)) == NULL)
3995                         err(1, "setconfvalue: clock_format");
3996 #endif
3997                 break;
3998         case SWM_S_CYCLE_EMPTY:
3999                 cycle_empty = atoi(value);
4000                 break;
4001         case SWM_S_CYCLE_VISIBLE:
4002                 cycle_visible = atoi(value);
4003                 break;
4004         case SWM_S_SS_ENABLED:
4005                 ss_enabled = atoi(value);
4006                 break;
4007         case SWM_S_TERM_WIDTH:
4008                 term_width = atoi(value);
4009                 break;
4010         case SWM_S_TITLE_CLASS_ENABLED:
4011                 title_class_enabled = atoi(value);
4012                 break;
4013         case SWM_S_WINDOW_NAME_ENABLED:
4014                 window_name_enabled = atoi(value);
4015                 break;
4016         case SWM_S_TITLE_NAME_ENABLED:
4017                 title_name_enabled = atoi(value);
4018                 break;
4019         case SWM_S_FOCUS_MODE:
4020                 if (!strcmp(value, "default"))
4021                         focus_mode = SWM_FOCUS_DEFAULT;
4022                 else if (!strcmp(value, "follow_cursor"))
4023                         focus_mode = SWM_FOCUS_FOLLOW;
4024                 else if (!strcmp(value, "synergy"))
4025                         focus_mode = SWM_FOCUS_SYNERGY;
4026                 else
4027                         err(1, "focus_mode");
4028                 break;
4029         case SWM_S_DISABLE_BORDER:
4030                 disable_border = atoi(value);
4031                 break;
4032         case SWM_S_BORDER_WIDTH:
4033                 border_width = atoi(value);
4034                 break;
4035         case SWM_S_BAR_FONT:
4036                 free(bar_fonts[0]);
4037                 if ((bar_fonts[0] = strdup(value)) == NULL)
4038                         err(1, "setconfvalue: bar_font");
4039                 break;
4040         case SWM_S_BAR_ACTION:
4041                 free(bar_argv[0]);
4042                 if ((bar_argv[0] = strdup(value)) == NULL)
4043                         err(1, "setconfvalue: bar_action");
4044                 break;
4045         case SWM_S_SPAWN_TERM:
4046                 free(spawn_term[0]);
4047                 if ((spawn_term[0] = strdup(value)) == NULL)
4048                         err(1, "setconfvalue: spawn_term");
4049                 break;
4050         case SWM_S_SS_APP:
4051                 break;
4052         case SWM_S_DIALOG_RATIO:
4053                 dialog_ratio = atof(value);
4054                 if (dialog_ratio > 1.0 || dialog_ratio <= .3)
4055                         dialog_ratio = .6;
4056                 break;
4057         default:
4058                 return (1);
4059         }
4060         return (0);
4061 }
4062
4063 int
4064 setconfmodkey(char *selector, char *value, int flags)
4065 {
4066         if (!strncasecmp(value, "Mod1", strlen("Mod1")))
4067                 update_modkey(Mod1Mask);
4068         else if (!strncasecmp(value, "Mod2", strlen("Mod2")))
4069                 update_modkey(Mod2Mask);
4070         else if (!strncasecmp(value, "Mod3", strlen("Mod3")))
4071                 update_modkey(Mod3Mask);
4072         else if (!strncasecmp(value, "Mod4", strlen("Mod4")))
4073                 update_modkey(Mod4Mask);
4074         else
4075                 return (1);
4076         return (0);
4077 }
4078
4079 int
4080 setconfcolor(char *selector, char *value, int flags)
4081 {
4082         setscreencolor(value, ((selector == NULL)?-1:atoi(selector)), flags);
4083         return (0);
4084 }
4085
4086 int
4087 setconfregion(char *selector, char *value, int flags)
4088 {
4089         custom_region(value);
4090         return (0);
4091 }
4092
4093 /* config options */
4094 struct config_option {
4095         char                    *optname;
4096         int (*func)(char*, char*, int);
4097         int funcflags;
4098 };
4099 struct config_option configopt[] = {
4100         { "bar_enabled",                setconfvalue,   SWM_S_BAR_ENABLED },
4101         { "bar_at_bottom",              setconfvalue,   SWM_S_BAR_AT_BOTTOM },
4102         { "bar_border",                 setconfcolor,   SWM_S_COLOR_BAR_BORDER },
4103         { "bar_border_width",                   setconfvalue,   SWM_S_BAR_BORDER_WIDTH },
4104         { "bar_color",                  setconfcolor,   SWM_S_COLOR_BAR },
4105         { "bar_font_color",             setconfcolor,   SWM_S_COLOR_BAR_FONT },
4106         { "bar_font",                   setconfvalue,   SWM_S_BAR_FONT },
4107         { "bar_action",                 setconfvalue,   SWM_S_BAR_ACTION },
4108         { "bar_delay",                  setconfvalue,   SWM_S_BAR_DELAY },
4109         { "bind",                       setconfbinding, 0 },
4110         { "stack_enabled",              setconfvalue,   SWM_S_STACK_ENABLED },
4111         { "clock_enabled",              setconfvalue,   SWM_S_CLOCK_ENABLED },
4112         { "clock_format",               setconfvalue,   SWM_S_CLOCK_FORMAT },
4113         { "color_focus",                setconfcolor,   SWM_S_COLOR_FOCUS },
4114         { "color_unfocus",              setconfcolor,   SWM_S_COLOR_UNFOCUS },
4115         { "cycle_empty",                setconfvalue,   SWM_S_CYCLE_EMPTY },
4116         { "cycle_visible",              setconfvalue,   SWM_S_CYCLE_VISIBLE },
4117         { "dialog_ratio",               setconfvalue,   SWM_S_DIALOG_RATIO },
4118         { "modkey",                     setconfmodkey,  0 },
4119         { "program",                    setconfspawn,   0 },
4120         { "quirk",                      setconfquirk,   0 },
4121         { "region",                     setconfregion,  0 },
4122         { "spawn_term",                 setconfvalue,   SWM_S_SPAWN_TERM },
4123         { "screenshot_enabled",         setconfvalue,   SWM_S_SS_ENABLED },
4124         { "screenshot_app",             setconfvalue,   SWM_S_SS_APP },
4125         { "window_name_enabled",        setconfvalue,   SWM_S_WINDOW_NAME_ENABLED },
4126         { "term_width",                 setconfvalue,   SWM_S_TERM_WIDTH },
4127         { "title_class_enabled",        setconfvalue,   SWM_S_TITLE_CLASS_ENABLED },
4128         { "title_name_enabled",         setconfvalue,   SWM_S_TITLE_NAME_ENABLED },
4129         { "focus_mode",                 setconfvalue,   SWM_S_FOCUS_MODE },
4130         { "disable_border",             setconfvalue,   SWM_S_DISABLE_BORDER },
4131         { "border_width",               setconfvalue,   SWM_S_BORDER_WIDTH },
4132 };
4133
4134
4135 int
4136 conf_load(char *filename)
4137 {
4138         FILE                    *config;
4139         char                    *line, *cp, *optsub, *optval;
4140         size_t                  linelen, lineno = 0;
4141         int                     wordlen, i, optind;
4142         struct config_option    *opt;
4143
4144         DNPRINTF(SWM_D_CONF, "conf_load begin\n");
4145
4146         if (filename == NULL) {
4147                 fprintf(stderr, "conf_load: no filename\n");
4148                 return (1);
4149         }
4150         if ((config = fopen(filename, "r")) == NULL) {
4151                 warn("conf_load: fopen");
4152                 return (1);
4153         }
4154
4155         while (!feof(config)) {
4156                 if ((line = fparseln(config, &linelen, &lineno, NULL, 0))
4157                     == NULL) {
4158                         if (ferror(config))
4159                                 err(1, "%s", filename);
4160                         else
4161                                 continue;
4162                 }
4163                 cp = line;
4164                 cp += strspn(cp, " \t\n"); /* eat whitespace */
4165                 if (cp[0] == '\0') {
4166                         /* empty line */
4167                         free(line);
4168                         continue;
4169                 }
4170                 /* get config option */
4171                 wordlen = strcspn(cp, "=[ \t\n");
4172                 if (wordlen == 0) {
4173                         warnx("%s: line %zd: no option found",
4174                             filename, lineno);
4175                         return (1);
4176                 }
4177                 optind = -1;
4178                 for (i = 0; i < LENGTH(configopt); i++) {
4179                         opt = &configopt[i];
4180                         if (!strncasecmp(cp, opt->optname, wordlen) &&
4181                             strlen(opt->optname) == wordlen) {
4182                                 optind = i;
4183                                 break;
4184                         }
4185                 }
4186                 if (optind == -1) {
4187                         warnx("%s: line %zd: unknown option %.*s",
4188                             filename, lineno, wordlen, cp);
4189                         return (1);
4190                 }
4191                 cp += wordlen;
4192                 cp += strspn(cp, " \t\n"); /* eat whitespace */
4193                 /* get [selector] if any */
4194                 optsub = NULL;
4195                 if (*cp == '[') {
4196                         cp++;
4197                         wordlen = strcspn(cp, "]");
4198                         if (*cp != ']') {
4199                                 if (wordlen == 0) {
4200                                         warnx("%s: line %zd: syntax error",
4201                                             filename, lineno);
4202                                         return (1);
4203                                 }
4204                                 asprintf(&optsub, "%.*s", wordlen, cp);
4205                         }
4206                         cp += wordlen;
4207                         cp += strspn(cp, "] \t\n"); /* eat trailing */
4208                 }
4209                 cp += strspn(cp, "= \t\n"); /* eat trailing */
4210                 /* get RHS value */
4211                 optval = strdup(cp);
4212                 /* call function to deal with it all */
4213                 if (configopt[optind].func(optsub, optval,
4214                     configopt[optind].funcflags) != 0) {
4215                         fprintf(stderr, "%s line %zd: %s\n",
4216                             filename, lineno, line);
4217                         errx(1, "%s: line %zd: invalid data for %s",
4218                             filename, lineno, configopt[optind].optname);
4219                 }
4220                 free(optval);
4221                 free(optsub);
4222                 free(line);
4223         }
4224
4225         fclose(config);
4226         DNPRINTF(SWM_D_CONF, "conf_load end\n");
4227
4228         return (0);
4229 }
4230
4231 void
4232 set_child_transient(struct ws_win *win)
4233 {
4234         struct ws_win           *parent;
4235
4236         parent = find_window(win->transient);
4237         if (parent)
4238                 parent->child_trans = win;
4239 }
4240
4241 struct ws_win *
4242 manage_window(Window id)
4243 {
4244         Window                  trans = 0;
4245         struct workspace        *ws;
4246         struct ws_win           *win, *ww;
4247         int                     format, i, ws_idx, n, border_me = 0;
4248         unsigned long           nitems, bytes;
4249         Atom                    ws_idx_atom = 0, type;
4250         Atom                    *prot = NULL, *pp;
4251         unsigned char           ws_idx_str[SWM_PROPLEN], *prop = NULL;
4252         struct swm_region       *r;
4253         long                    mask;
4254         const char              *errstr;
4255         XWindowChanges          wc;
4256
4257         if ((win = find_window(id)) != NULL)
4258                 return (win);   /* already being managed */
4259
4260         /* see if we are on the unmanaged list */
4261         if ((win = find_unmanaged_window(id)) != NULL) {
4262                 DNPRINTF(SWM_D_MISC, "manage previously unmanaged window "
4263                     "%lu\n", win->id);
4264                 TAILQ_REMOVE(&win->ws->unmanagedlist, win, entry);
4265                 TAILQ_INSERT_TAIL(&win->ws->winlist, win, entry);
4266                 if (win->transient)
4267                         set_child_transient(win);
4268                 ewmh_update_actions(win);
4269                 return (win);
4270         }
4271
4272         if ((win = calloc(1, sizeof(struct ws_win))) == NULL)
4273                 errx(1, "calloc: failed to allocate memory for new window");
4274
4275         /* Get all the window data in one shot */
4276         ws_idx_atom = XInternAtom(display, "_SWM_WS", False);
4277         if (ws_idx_atom)
4278                 XGetWindowProperty(display, id, ws_idx_atom, 0, SWM_PROPLEN,
4279                     False, XA_STRING, &type, &format, &nitems, &bytes, &prop);
4280         XGetWindowAttributes(display, id, &win->wa);
4281         XGetWMNormalHints(display, id, &win->sh, &mask);
4282         XGetTransientForHint(display, id, &trans);
4283         if (trans) {
4284                 win->transient = trans;
4285                 set_child_transient(win);
4286                 DNPRINTF(SWM_D_MISC, "manage_window: win %lu transient %lu\n",
4287                     win->id, win->transient);
4288         }
4289
4290         /* get supported protocols */
4291         if (XGetWMProtocols(display, id, &prot, &n)) {
4292                 for (i = 0, pp = prot; i < n; i++, pp++) {
4293                         if (*pp == takefocus)
4294                                 win->take_focus = 1;
4295                         if (*pp == adelete)
4296                                 win->can_delete = 1;
4297                 }
4298                 if (prot)
4299                         XFree(prot);
4300         }
4301
4302         /*
4303          * Figure out where to put the window. If it was previously assigned to
4304          * a workspace (either by spawn() or manually moving), and isn't
4305          * transient, * put it in the same workspace
4306          */
4307         r = root_to_region(win->wa.root);
4308         if (prop && win->transient == 0) {
4309                 DNPRINTF(SWM_D_PROP, "got property _SWM_WS=%s\n", prop);
4310                 ws_idx = strtonum(prop, 0, 9, &errstr);
4311                 if (errstr) {
4312                         DNPRINTF(SWM_D_EVENT, "window idx is %s: %s",
4313                             errstr, prop);
4314                 }
4315                 ws = &r->s->ws[ws_idx];
4316         } else {
4317                 ws = r->ws;
4318                 /* this should launch transients in the same ws as parent */
4319                 if (id && trans)
4320                         if ((ww = find_window(trans)) != NULL)
4321                                 if (ws->r) {
4322                                         ws = ww->ws;
4323                                         if (ww->ws->r)
4324                                                 r = ww->ws->r;
4325                                         else
4326                                                 fprintf(stderr,
4327                                                     "fix this bug mcbride\n");
4328                                         border_me = 1;
4329                                 }
4330         }
4331
4332         /* set up the window layout */
4333         win->id = id;
4334         win->ws = ws;
4335         win->s = r->s;  /* this never changes */
4336         TAILQ_INSERT_TAIL(&ws->winlist, win, entry);
4337
4338         win->g.w = win->wa.width;
4339         win->g.h = win->wa.height;
4340         win->g.x = win->wa.x;
4341         win->g.y = win->wa.y;
4342         win->g_floatvalid = 0;
4343         win->floatmaxed = 0;
4344         win->ewmh_flags = 0;
4345
4346         /* Set window properties so we can remember this after reincarnation */
4347         if (ws_idx_atom && prop == NULL &&
4348             snprintf(ws_idx_str, SWM_PROPLEN, "%d", ws->idx) < SWM_PROPLEN) {
4349                 DNPRINTF(SWM_D_PROP, "setting property _SWM_WS to %s\n",
4350                     ws_idx_str);
4351                 XChangeProperty(display, win->id, ws_idx_atom, XA_STRING, 8,
4352                     PropModeReplace, ws_idx_str, SWM_PROPLEN);
4353         }
4354         if (prop)
4355                 XFree(prop);
4356
4357         ewmh_autoquirk(win);
4358
4359         if (XGetClassHint(display, win->id, &win->ch)) {
4360                 DNPRINTF(SWM_D_CLASS, "class: %s name: %s\n",
4361                     win->ch.res_class, win->ch.res_name);
4362
4363                 /* java is retarded so treat it special */
4364                 if (strstr(win->ch.res_name, "sun-awt")) {
4365                         win->java = 1;
4366                         border_me = 1;
4367                 }
4368
4369                 for (i = 0; i < quirks_length; i++){
4370                         if (!strcmp(win->ch.res_class, quirks[i].class) &&
4371                             !strcmp(win->ch.res_name, quirks[i].name)) {
4372                                 DNPRINTF(SWM_D_CLASS, "found: %s name: %s\n",
4373                                     win->ch.res_class, win->ch.res_name);
4374                                 if (quirks[i].quirk & SWM_Q_FLOAT) {
4375                                         win->floating = 1;
4376                                         border_me = 1;
4377                                 }
4378                                 win->quirks = quirks[i].quirk;
4379                         }
4380                 }
4381         }
4382
4383         /* alter window position if quirky */
4384         if (win->quirks & SWM_Q_ANYWHERE) {
4385                 win->manual = 1; /* don't center the quirky windows */
4386                 bzero(&wc, sizeof wc);
4387                 mask = 0;
4388                 if (bar_enabled && win->g.y < bar_height) {
4389                         win->g.y = wc.y = bar_height;
4390                         mask |= CWY;
4391                 }
4392                 if (win->g.w + win->g.x > WIDTH(r)) {
4393                         win->g.x = wc.x = WIDTH(r) - win->g.w - 2;
4394                         mask |= CWX;
4395                 }
4396                 border_me = 1;
4397         }
4398
4399         /* Reset font sizes (the bruteforce way; no default keybinding). */
4400         if (win->quirks & SWM_Q_XTERM_FONTADJ) {
4401                 for (i = 0; i < SWM_MAX_FONT_STEPS; i++)
4402                         fake_keypress(win, XK_KP_Subtract, ShiftMask);
4403                 for (i = 0; i < SWM_MAX_FONT_STEPS; i++)
4404                         fake_keypress(win, XK_KP_Add, ShiftMask);
4405         }
4406
4407         ewmh_get_win_state(win);
4408         ewmh_update_actions(win);
4409         ewmh_update_win_state(win, None, _NET_WM_STATE_REMOVE);
4410
4411         /* border me */
4412         if (border_me) {
4413                 bzero(&wc, sizeof wc);
4414                 wc.border_width = border_width;
4415                 mask = CWBorderWidth;
4416                 XConfigureWindow(display, win->id, mask, &wc);
4417         }
4418
4419         XSelectInput(display, id, EnterWindowMask | FocusChangeMask |
4420             PropertyChangeMask | StructureNotifyMask);
4421
4422         set_win_state(win, NormalState);
4423
4424         /* floaters need to be mapped if they are in the current workspace */
4425         if ((win->floating || win->transient) && (ws->idx == r->ws->idx))
4426                 XMapRaised(display, win->id);
4427
4428         return (win);
4429 }
4430
4431 void
4432 free_window(struct ws_win *win)
4433 {
4434         DNPRINTF(SWM_D_MISC, "free_window:  %lu\n", win->id);
4435
4436         if (win == NULL)
4437                 return;
4438
4439         /* needed for restart wm */
4440         set_win_state(win, WithdrawnState);
4441
4442         TAILQ_REMOVE(&win->ws->unmanagedlist, win, entry);
4443
4444         if (win->ch.res_class)
4445                 XFree(win->ch.res_class);
4446         if (win->ch.res_name)
4447                 XFree(win->ch.res_name);
4448
4449         kill_refs(win);
4450
4451         /* paint memory */
4452         memset(win, 0xff, sizeof *win); /* XXX kill later */
4453
4454         free(win);
4455 }
4456
4457 void
4458 unmanage_window(struct ws_win *win)
4459 {
4460         struct ws_win           *parent;
4461
4462         if (win == NULL)
4463                 return;
4464
4465         DNPRINTF(SWM_D_MISC, "unmanage_window:  %lu\n", win->id);
4466
4467         if (win->transient) {
4468                 parent = find_window(win->transient);
4469                 if (parent)
4470                         parent->child_trans = NULL;
4471         }
4472
4473         /* focus on root just in case */
4474         XSetInputFocus(display, PointerRoot, PointerRoot, CurrentTime);
4475
4476         if (!win->floating)
4477                 focus_prev(win);
4478
4479         TAILQ_REMOVE(&win->ws->winlist, win, entry);
4480         TAILQ_INSERT_TAIL(&win->ws->unmanagedlist, win, entry);
4481
4482         kill_refs(win);
4483 }
4484
4485 void
4486 focus_magic(struct ws_win *win, int do_trans)
4487 {
4488         DNPRINTF(SWM_D_FOCUS, "focus_magic: %lu %d\n", WINID(win), do_trans);
4489
4490         if (win == NULL)
4491                 return;
4492
4493         if (do_trans == SWM_F_TRANSIENT && win->child_trans) {
4494                 /* win = parent & has a transient so focus on that */
4495                 if (win->java) {
4496                         focus_win(win->child_trans);
4497                         if (win->child_trans->take_focus)
4498                                 client_msg(win, takefocus);
4499                 } else {
4500                         /* make sure transient hasn't dissapeared */
4501                         if (validate_win(win->child_trans) == 0) {
4502                                 focus_win(win->child_trans);
4503                                 if (win->child_trans->take_focus)
4504                                         client_msg(win->child_trans, takefocus);
4505                         } else {
4506                                 win->child_trans = NULL;
4507                                 focus_win(win);
4508                                 if (win->take_focus)
4509                                         client_msg(win, takefocus);
4510                         }
4511                 }
4512         } else {
4513                 /* regular focus */
4514                 focus_win(win);
4515                 if (win->take_focus)
4516                         client_msg(win, takefocus);
4517         }
4518 }
4519
4520 void
4521 expose(XEvent *e)
4522 {
4523         DNPRINTF(SWM_D_EVENT, "expose: window: %lu\n", e->xexpose.window);
4524 }
4525
4526 void
4527 keypress(XEvent *e)
4528 {
4529         unsigned int            i;
4530         KeySym                  keysym;
4531         XKeyEvent               *ev = &e->xkey;
4532
4533         DNPRINTF(SWM_D_EVENT, "keypress: window: %lu\n", ev->window);
4534
4535         keysym = XKeycodeToKeysym(display, (KeyCode)ev->keycode, 0);
4536         for (i = 0; i < keys_length; i++)
4537                 if (keysym == keys[i].keysym
4538                    && CLEANMASK(keys[i].mod) == CLEANMASK(ev->state)
4539                    && keyfuncs[keys[i].funcid].func) {
4540                         if (keys[i].funcid == kf_spawn_custom)
4541                                 spawn_custom(
4542                                     root_to_region(ev->root),
4543                                     &(keyfuncs[keys[i].funcid].args),
4544                                     keys[i].spawn_name
4545                                     );
4546                         else
4547                                 keyfuncs[keys[i].funcid].func(
4548                                     root_to_region(ev->root),
4549                                     &(keyfuncs[keys[i].funcid].args)
4550                                     );
4551                 }
4552 }
4553
4554 void
4555 buttonpress(XEvent *e)
4556 {
4557         struct ws_win           *win;
4558         int                     i, action;
4559         XButtonPressedEvent     *ev = &e->xbutton;
4560
4561         DNPRINTF(SWM_D_EVENT, "buttonpress: window: %lu\n", ev->window);
4562
4563         action = root_click;
4564         if ((win = find_window(ev->window)) == NULL)
4565                 return;
4566
4567         focus_magic(win, SWM_F_TRANSIENT);
4568         action = client_click;
4569
4570         for (i = 0; i < LENGTH(buttons); i++)
4571                 if (action == buttons[i].action && buttons[i].func &&
4572                     buttons[i].button == ev->button &&
4573                     CLEANMASK(buttons[i].mask) == CLEANMASK(ev->state))
4574                         buttons[i].func(win, &buttons[i].args);
4575 }
4576
4577 void
4578 configurerequest(XEvent *e)
4579 {
4580         XConfigureRequestEvent  *ev = &e->xconfigurerequest;
4581         struct ws_win           *win;
4582         int                     new = 0;
4583         XWindowChanges          wc;
4584
4585         if ((win = find_window(ev->window)) == NULL)
4586                 if ((win = find_unmanaged_window(ev->window)) == NULL)
4587                         new = 1;
4588
4589         if (new) {
4590                 DNPRINTF(SWM_D_EVENT, "configurerequest: new window: %lu\n",
4591                     ev->window);
4592                 bzero(&wc, sizeof wc);
4593                 wc.x = ev->x;
4594                 wc.y = ev->y;
4595                 wc.width = ev->width;
4596                 wc.height = ev->height;
4597                 wc.border_width = ev->border_width;
4598                 wc.sibling = ev->above;
4599                 wc.stack_mode = ev->detail;
4600                 XConfigureWindow(display, ev->window, ev->value_mask, &wc);
4601         } else {
4602                 DNPRINTF(SWM_D_EVENT, "configurerequest: change window: %lu\n",
4603                     ev->window);
4604 #if 0
4605                 if (win->floating) {
4606                         if (ev->value_mask & CWX)
4607                                 win->g.x = ev->x;
4608                         if (ev->value_mask & CWY)
4609                                 win->g.y = ev->y;
4610                         if (ev->value_mask & CWWidth)
4611                                 win->g.w = ev->width;
4612                         if (ev->value_mask & CWHeight)
4613                                 win->g.h = ev->height;
4614                 }
4615 #endif
4616                 config_win(win, ev);
4617         }
4618 }
4619
4620 void
4621 configurenotify(XEvent *e)
4622 {
4623         struct ws_win           *win;
4624         long                    mask;
4625
4626         DNPRINTF(SWM_D_EVENT, "configurenotify: window: %lu\n",
4627             e->xconfigure.window);
4628
4629         win = find_window(e->xconfigure.window);
4630         if (win) {
4631                 XGetWMNormalHints(display, win->id, &win->sh, &mask);
4632                 adjust_font(win);
4633                 if (font_adjusted)
4634                         stack();
4635         }
4636 }
4637
4638 void
4639 destroynotify(XEvent *e)
4640 {
4641         struct ws_win           *win;
4642         XDestroyWindowEvent     *ev = &e->xdestroywindow;
4643
4644         DNPRINTF(SWM_D_EVENT, "destroynotify: window %lu\n", ev->window);
4645
4646         if ((win = find_window(ev->window)) == NULL) {
4647                 if ((win = find_unmanaged_window(ev->window)) == NULL)
4648                         return;
4649                 free_window(win);
4650                 return;
4651         }
4652
4653         /* make sure we focus on something */
4654         win->floating = 0;
4655
4656         unmanage_window(win);
4657         stack();
4658         free_window(win);
4659 }
4660
4661 void
4662 enternotify(XEvent *e)
4663 {
4664         XCrossingEvent          *ev = &e->xcrossing;
4665         XEvent                  cne;
4666         struct ws_win           *win;
4667 #if 0
4668         struct ws_win           *w;
4669         Window                  focus_return;
4670         int                     revert_to_return;
4671 #endif
4672         DNPRINTF(SWM_D_FOCUS, "enternotify: window: %lu mode %d detail %d root "
4673             "%lu subwindow %lu same_screen %d focus %d state %d\n",
4674             ev->window, ev->mode, ev->detail, ev->root, ev->subwindow,
4675             ev->same_screen, ev->focus, ev->state);
4676
4677         switch (focus_mode) {
4678         case SWM_FOCUS_DEFAULT:
4679                 if (QLength(display)) {
4680                         DNPRINTF(SWM_D_EVENT, "ignore enternotify %d\n",
4681                             QLength(display));
4682                         return;
4683                 }
4684                 break;
4685         case SWM_FOCUS_FOLLOW:
4686                 break;
4687         case SWM_FOCUS_SYNERGY:
4688 #if 0
4689         /*
4690          * all these checks need to be in this order because the
4691          * XCheckTypedWindowEvent relies on weeding out the previous events
4692          *
4693          * making this code an option would enable a follow mouse for focus
4694          * feature
4695          */
4696
4697         /*
4698          * state is set when we are switching workspaces and focus is set when
4699          * the window or a subwindow already has focus (occurs during restart).
4700          *
4701          * Only honor the focus flag if last_focus_event is not FocusOut,
4702          * this allows scrotwm to continue to control focus when another
4703          * program is also playing with it.
4704          */
4705         if (ev->state || (ev->focus && last_focus_event != FocusOut)) {
4706                 DNPRINTF(SWM_D_EVENT, "ignoring enternotify: focus\n");
4707                 return;
4708         }
4709
4710         /*
4711          * happens when a window is created or destroyed and the border
4712          * crosses the mouse pointer and when switching ws
4713          *
4714          * we need the subwindow test to see if we came from root in order
4715          * to give focus to floaters
4716          */
4717         if (ev->mode == NotifyNormal && ev->detail == NotifyVirtual &&
4718             ev->subwindow == 0) {
4719                 DNPRINTF(SWM_D_EVENT, "ignoring enternotify: NotifyVirtual\n");
4720                 return;
4721         }
4722
4723         /* this window already has focus */
4724         if (ev->mode == NotifyNormal && ev->detail == NotifyInferior) {
4725                 DNPRINTF(SWM_D_EVENT, "ignoring enternotify: win has focus\n");
4726                 return;
4727         }
4728
4729         /* this window is being deleted or moved to another ws */
4730         if (XCheckTypedWindowEvent(display, ev->window, ConfigureNotify,
4731             &cne) == True) {
4732                 DNPRINTF(SWM_D_EVENT, "ignoring enternotify: configurenotify\n");
4733                 XPutBackEvent(display, &cne);
4734                 return;
4735         }
4736
4737         if ((win = find_window(ev->window)) == NULL) {
4738                 DNPRINTF(SWM_D_EVENT, "ignoring enternotify: win == NULL\n");
4739                 return;
4740         }
4741
4742         /*
4743          * In fullstack kill all enters unless they come from a different ws
4744          * (i.e. another region) or focus has been grabbed externally.
4745          */
4746         if (win->ws->cur_layout->flags & SWM_L_FOCUSPREV &&
4747             last_focus_event != FocusOut) {
4748                 XGetInputFocus(display, &focus_return, &revert_to_return);
4749                 if ((w = find_window(focus_return)) == NULL ||
4750                     w->ws == win->ws) {
4751                         DNPRINTF(SWM_D_EVENT, "ignoring event: fullstack\n");
4752                         return;
4753                 }
4754         }
4755 #endif
4756                 break;
4757         }
4758
4759         if ((win = find_window(ev->window)) == NULL) {
4760                 DNPRINTF(SWM_D_EVENT, "ignoring enternotify: win == NULL\n");
4761                 return;
4762         }
4763
4764         /*
4765          * if we have more enternotifies let them handle it in due time
4766          */
4767         if (XCheckTypedEvent(display, EnterNotify, &cne) == True) {
4768                 DNPRINTF(SWM_D_EVENT,
4769                     "ignoring enternotify: got more enternotify\n");
4770                 XPutBackEvent(display, &cne);
4771                 return;
4772         }
4773
4774         focus_magic(win, SWM_F_TRANSIENT);
4775 }
4776
4777 /* lets us use one switch statement for arbitrary mode/detail combinations */
4778 #define MERGE_MEMBERS(a,b)      (((a & 0xffff) << 16) | (b & 0xffff))
4779
4780 void
4781 focusevent(XEvent *e)
4782 {
4783 #if 0
4784         struct ws_win           *win;
4785         u_int32_t               mode_detail;
4786         XFocusChangeEvent       *ev = &e->xfocus;
4787
4788         DNPRINTF(SWM_D_EVENT, "focusevent: %s window: %lu mode %d detail %d\n",
4789             ev->type == FocusIn ? "entering" : "leaving",
4790             ev->window, ev->mode, ev->detail);
4791
4792         if (last_focus_event == ev->type) {
4793                 DNPRINTF(SWM_D_FOCUS, "ignoring focusevent: bad ordering\n");
4794                 return;
4795         }
4796
4797         last_focus_event = ev->type;
4798         mode_detail = MERGE_MEMBERS(ev->mode, ev->detail);
4799
4800         switch (mode_detail) {
4801         /* synergy client focus operations */
4802         case MERGE_MEMBERS(NotifyNormal, NotifyNonlinear):
4803         case MERGE_MEMBERS(NotifyNormal, NotifyNonlinearVirtual):
4804
4805         /* synergy server focus operations */
4806         case MERGE_MEMBERS(NotifyWhileGrabbed, NotifyNonlinear):
4807
4808         /* Entering applications like rdesktop that mangle the pointer */
4809         case MERGE_MEMBERS(NotifyNormal, NotifyPointer):
4810
4811                 if ((win = find_window(e->xfocus.window)) != NULL && win->ws->r)
4812                         XSetWindowBorder(display, win->id,
4813                             win->ws->r->s->c[ev->type == FocusIn ?
4814                             SWM_S_COLOR_FOCUS : SWM_S_COLOR_UNFOCUS].color);
4815                 break;
4816         default:
4817                 fprintf(stderr, "ignoring focusevent\n");
4818                 DNPRINTF(SWM_D_FOCUS, "ignoring focusevent\n");
4819                 break;
4820         }
4821 #endif
4822 }
4823
4824 void
4825 mapnotify(XEvent *e)
4826 {
4827         struct ws_win           *win;
4828         XMapEvent               *ev = &e->xmap;
4829
4830         DNPRINTF(SWM_D_EVENT, "mapnotify: window: %lu\n", ev->window);
4831
4832         win = manage_window(ev->window);
4833         if (win)
4834                 set_win_state(win, NormalState);
4835 }
4836
4837 void
4838 mappingnotify(XEvent *e)
4839 {
4840         XMappingEvent           *ev = &e->xmapping;
4841
4842         XRefreshKeyboardMapping(ev);
4843         if (ev->request == MappingKeyboard)
4844                 grabkeys();
4845 }
4846
4847 void
4848 maprequest(XEvent *e)
4849 {
4850         struct ws_win           *win;
4851         struct swm_region       *r;
4852         XWindowAttributes       wa;
4853         XMapRequestEvent        *ev = &e->xmaprequest;
4854
4855         DNPRINTF(SWM_D_EVENT, "maprequest: window: %lu\n",
4856             e->xmaprequest.window);
4857
4858         if (!XGetWindowAttributes(display, ev->window, &wa))
4859                 return;
4860         if (wa.override_redirect)
4861                 return;
4862
4863         win = manage_window(e->xmaprequest.window);
4864         if (win == NULL)
4865                 return; /* can't happen */
4866
4867         stack();
4868
4869         /* make new win focused */
4870         r = root_to_region(win->wa.root);
4871         if (win->ws == r->ws)
4872                 focus_magic(win, SWM_F_GENERIC);
4873 }
4874
4875 void
4876 propertynotify(XEvent *e)
4877 {
4878         struct ws_win           *win;
4879         XPropertyEvent          *ev = &e->xproperty;
4880
4881         DNPRINTF(SWM_D_EVENT, "propertynotify: window: %lu\n",
4882             ev->window);
4883
4884         if (ev->state == PropertyDelete)
4885                 return; /* ignore */
4886         win = find_window(ev->window);
4887         if (win == NULL)
4888                 return;
4889
4890         switch (ev->atom) {
4891         case XA_WM_NORMAL_HINTS:
4892 #if 0
4893                 long            mask;
4894                 XGetWMNormalHints(display, win->id, &win->sh, &mask);
4895                 fprintf(stderr, "normal hints: flag 0x%x\n", win->sh.flags);
4896                 if (win->sh.flags & PMinSize) {
4897                         win->g.w = win->sh.min_width;
4898                         win->g.h = win->sh.min_height;
4899                         fprintf(stderr, "min %d %d\n", win->g.w, win->g.h);
4900                 }
4901                 XMoveResizeWindow(display, win->id,
4902                     win->g.x, win->g.y, win->g.w, win->g.h);
4903 #endif
4904                 if (window_name_enabled)
4905                         bar_update();
4906                 break;
4907         default:
4908                 break;
4909         }
4910 }
4911
4912 void
4913 unmapnotify(XEvent *e)
4914 {
4915         struct ws_win           *win;
4916
4917         DNPRINTF(SWM_D_EVENT, "unmapnotify: window: %lu\n", e->xunmap.window);
4918
4919         /* determine if we need to help unmanage this window */
4920         win = find_window(e->xunmap.window);
4921         if (win == NULL)
4922                 return;
4923
4924         if (getstate(e->xunmap.window) == NormalState) {
4925                 unmanage_window(win);
4926                 stack();
4927         }
4928 }
4929
4930 void
4931 visibilitynotify(XEvent *e)
4932 {
4933         int                     i;
4934         struct swm_region       *r;
4935
4936         DNPRINTF(SWM_D_EVENT, "visibilitynotify: window: %lu\n",
4937             e->xvisibility.window);
4938         if (e->xvisibility.state == VisibilityUnobscured)
4939                 for (i = 0; i < ScreenCount(display); i++)
4940                         TAILQ_FOREACH(r, &screens[i].rl, entry)
4941                                 if (e->xvisibility.window == r->bar_window)
4942                                         bar_update();
4943 }
4944
4945 void
4946 clientmessage(XEvent *e)
4947 {
4948         XClientMessageEvent *ev;
4949         struct ws_win *win;
4950
4951         ev = &e->xclient;
4952
4953         win = find_window(ev->window);
4954         if (win == NULL)
4955                 return;
4956
4957         DNPRINTF(SWM_D_EVENT, "clientmessage: window: 0x%lx type: %ld \n",
4958             ev->window, ev->message_type);
4959
4960         if (ev->message_type == ewmh[_NET_ACTIVE_WINDOW].atom) {
4961                 DNPRINTF(SWM_D_EVENT, "clientmessage: _NET_ACTIVE_WINDOW \n");
4962                 focus_win(win);
4963         }
4964         if (ev->message_type == ewmh[_NET_CLOSE_WINDOW].atom) {
4965                 DNPRINTF(SWM_D_EVENT, "clientmessage: _NET_CLOSE_WINDOW \n");
4966                 if (win->can_delete)
4967                         client_msg(win, adelete);
4968                 else
4969                         XKillClient(display, win->id);
4970         }
4971         if (ev->message_type == ewmh[_NET_MOVERESIZE_WINDOW].atom) {
4972                 DNPRINTF(SWM_D_EVENT, "clientmessage: _NET_MOVERESIZE_WINDOW \n");
4973                 if (win->floating) {
4974                         if (ev->data.l[0] & (1<<8)) /* x */
4975                                 win->g.x = ev->data.l[1];
4976                         if (ev->data.l[0] & (1<<9)) /* y */
4977                                 win->g.y = ev->data.l[2];
4978                         if (ev->data.l[0] & (1<<10)) /* width */
4979                                 win->g.w = ev->data.l[3];
4980                         if (ev->data.l[0] & (1<<11)) /* height */
4981                                 win->g.h = ev->data.l[4];
4982                 }
4983                 else {
4984                         /* TODO: Change stack sizes */
4985                 }
4986                 config_win(win, NULL);
4987         }
4988         if (ev->message_type == ewmh[_NET_WM_STATE].atom) {
4989                 DNPRINTF(SWM_D_EVENT, "clientmessage: _NET_WM_STATE \n");
4990                 ewmh_update_win_state(win, ev->data.l[1], ev->data.l[0]);
4991                 if (ev->data.l[2])
4992                         ewmh_update_win_state(win, ev->data.l[2], ev->data.l[0]);
4993
4994                 stack();
4995         }
4996 }
4997
4998 int
4999 xerror_start(Display *d, XErrorEvent *ee)
5000 {
5001         other_wm = 1;
5002         return (-1);
5003 }
5004
5005 int
5006 xerror(Display *d, XErrorEvent *ee)
5007 {
5008         /* fprintf(stderr, "error: %p %p\n", display, ee); */
5009         return (-1);
5010 }
5011
5012 int
5013 active_wm(void)
5014 {
5015         other_wm = 0;
5016         xerrorxlib = XSetErrorHandler(xerror_start);
5017
5018         /* this causes an error if some other window manager is running */
5019         XSelectInput(display, DefaultRootWindow(display),
5020             SubstructureRedirectMask);
5021         XSync(display, False);
5022         if (other_wm)
5023                 return (1);
5024
5025         XSetErrorHandler(xerror);
5026         XSync(display, False);
5027         return (0);
5028 }
5029
5030 void
5031 new_region(struct swm_screen *s, int x, int y, int w, int h)
5032 {
5033         struct swm_region       *r, *n;
5034         struct workspace        *ws = NULL;
5035         int                     i;
5036
5037         DNPRINTF(SWM_D_MISC, "new region: screen[%d]:%dx%d+%d+%d\n",
5038              s->idx, w, h, x, y);
5039
5040         /* remove any conflicting regions */
5041         n = TAILQ_FIRST(&s->rl);
5042         while (n) {
5043                 r = n;
5044                 n = TAILQ_NEXT(r, entry);
5045                 if (X(r) < (x + w) &&
5046                     (X(r) + WIDTH(r)) > x &&
5047                     Y(r) < (y + h) &&
5048                     (Y(r) + HEIGHT(r)) > y) {
5049                         if (r->ws->r != NULL)
5050                                 r->ws->old_r = r->ws->r;
5051                         r->ws->r = NULL;
5052                         XDestroyWindow(display, r->bar_window);
5053                         TAILQ_REMOVE(&s->rl, r, entry);
5054                         TAILQ_INSERT_TAIL(&s->orl, r, entry);
5055                 }
5056         }
5057
5058         /* search old regions for one to reuse */
5059
5060         /* size + location match */
5061         TAILQ_FOREACH(r, &s->orl, entry)
5062                 if (X(r) == x && Y(r) == y &&
5063                     HEIGHT(r) == h && WIDTH(r) == w)
5064                         break;
5065
5066         /* size match */
5067         TAILQ_FOREACH(r, &s->orl, entry)
5068                 if (HEIGHT(r) == h && WIDTH(r) == w)
5069                         break;
5070
5071         if (r != NULL) {
5072                 TAILQ_REMOVE(&s->orl, r, entry);
5073                 /* try to use old region's workspace */
5074                 if (r->ws->r == NULL)
5075                         ws = r->ws;
5076         } else
5077                 if ((r = calloc(1, sizeof(struct swm_region))) == NULL)
5078                         errx(1, "calloc: failed to allocate memory for screen");
5079
5080         /* if we don't have a workspace already, find one */
5081         if (ws == NULL) {
5082                 for (i = 0; i < SWM_WS_MAX; i++)
5083                         if (s->ws[i].r == NULL) {
5084                                 ws = &s->ws[i];
5085                                 break;
5086                         }
5087         }
5088
5089         if (ws == NULL)
5090                 errx(1, "no free workspaces\n");
5091
5092         X(r) = x;
5093         Y(r) = y;
5094         WIDTH(r) = w;
5095         HEIGHT(r) = h;
5096         r->s = s;
5097         r->ws = ws;
5098         r->ws_prior = NULL;
5099         ws->r = r;
5100         outputs++;
5101         TAILQ_INSERT_TAIL(&s->rl, r, entry);
5102 }
5103
5104 void
5105 scan_xrandr(int i)
5106 {
5107 #ifdef SWM_XRR_HAS_CRTC
5108         XRRCrtcInfo             *ci;
5109         XRRScreenResources      *sr;
5110         int                     c;
5111         int                     ncrtc = 0;
5112 #endif /* SWM_XRR_HAS_CRTC */
5113         struct swm_region       *r;
5114
5115
5116         if (i >= ScreenCount(display))
5117                 errx(1, "invalid screen");
5118
5119         /* remove any old regions */
5120         while ((r = TAILQ_FIRST(&screens[i].rl)) != NULL) {
5121                 r->ws->old_r = r->ws->r = NULL;
5122                 XDestroyWindow(display, r->bar_window);
5123                 TAILQ_REMOVE(&screens[i].rl, r, entry);
5124                 TAILQ_INSERT_TAIL(&screens[i].orl, r, entry);
5125         }
5126         outputs = 0;
5127
5128         /* map virtual screens onto physical screens */
5129 #ifdef SWM_XRR_HAS_CRTC
5130         if (xrandr_support) {
5131                 sr = XRRGetScreenResources(display, screens[i].root);
5132                 if (sr == NULL)
5133                         new_region(&screens[i], 0, 0,
5134                             DisplayWidth(display, i),
5135                             DisplayHeight(display, i));
5136                 else
5137                         ncrtc = sr->ncrtc;
5138
5139                 for (c = 0, ci = NULL; c < ncrtc; c++) {
5140                         ci = XRRGetCrtcInfo(display, sr, sr->crtcs[c]);
5141                         if (ci->noutput == 0)
5142                                 continue;
5143
5144                         if (ci != NULL && ci->mode == None)
5145                                 new_region(&screens[i], 0, 0,
5146                                     DisplayWidth(display, i),
5147                                     DisplayHeight(display, i));
5148                         else
5149                                 new_region(&screens[i],
5150                                     ci->x, ci->y, ci->width, ci->height);
5151                 }
5152                 if (ci)
5153                         XRRFreeCrtcInfo(ci);
5154                 XRRFreeScreenResources(sr);
5155         } else
5156 #endif /* SWM_XRR_HAS_CRTC */
5157         {
5158                 new_region(&screens[i], 0, 0, DisplayWidth(display, i),
5159                     DisplayHeight(display, i));
5160         }
5161 }
5162
5163 void
5164 screenchange(XEvent *e) {
5165         XRRScreenChangeNotifyEvent      *xe = (XRRScreenChangeNotifyEvent *)e;
5166         struct swm_region               *r;
5167         int                             i;
5168
5169         DNPRINTF(SWM_D_EVENT, "screenchange: %lu\n", xe->root);
5170
5171         if (!XRRUpdateConfiguration(e))
5172                 return;
5173
5174         /* silly event doesn't include the screen index */
5175         for (i = 0; i < ScreenCount(display); i++)
5176                 if (screens[i].root == xe->root)
5177                         break;
5178         if (i >= ScreenCount(display))
5179                 errx(1, "screenchange: screen not found\n");
5180
5181         /* brute force for now, just re-enumerate the regions */
5182         scan_xrandr(i);
5183
5184         /* add bars to all regions */
5185         for (i = 0; i < ScreenCount(display); i++)
5186                 TAILQ_FOREACH(r, &screens[i].rl, entry)
5187                         bar_setup(r);
5188         stack();
5189 }
5190
5191 void
5192 grab_windows(void)
5193 {
5194         Window                  d1, d2, *wins = NULL;
5195         XWindowAttributes       wa;
5196         unsigned int            no;
5197         int                     i, j;
5198         long                    state, manage;
5199
5200         for (i = 0; i < ScreenCount(display); i++) {
5201                 if (!XQueryTree(display, screens[i].root, &d1, &d2, &wins, &no))
5202                         continue;
5203
5204                 /* attach windows to a region */
5205                 /* normal windows */
5206                 for (j = 0; j < no; j++) {
5207                         if (!XGetWindowAttributes(display, wins[j], &wa) ||
5208                             wa.override_redirect ||
5209                             XGetTransientForHint(display, wins[j], &d1))
5210                                 continue;
5211
5212                         state = getstate(wins[j]);
5213                         manage = state == IconicState;
5214                         if (wa.map_state == IsViewable || manage)
5215                                 manage_window(wins[j]);
5216                 }
5217                 /* transient windows */
5218                 for (j = 0; j < no; j++) {
5219                         if (!XGetWindowAttributes(display, wins[j], &wa) ||
5220                             wa.override_redirect)
5221                                 continue;
5222
5223                         state = getstate(wins[j]);
5224                         manage = state == IconicState;
5225                         if (XGetTransientForHint(display, wins[j], &d1) &&
5226                             manage)
5227                                 manage_window(wins[j]);
5228                 }
5229                 if (wins) {
5230                         XFree(wins);
5231                         wins = NULL;
5232                 }
5233         }
5234 }
5235
5236 void
5237 setup_screens(void)
5238 {
5239         int                     i, j, k;
5240         int                     errorbase, major, minor;
5241         struct workspace        *ws;
5242         int                     ws_idx_atom;
5243
5244         if ((screens = calloc(ScreenCount(display),
5245              sizeof(struct swm_screen))) == NULL)
5246                 errx(1, "calloc: screens");
5247
5248         ws_idx_atom = XInternAtom(display, "_SWM_WS", False);
5249
5250         /* initial Xrandr setup */
5251         xrandr_support = XRRQueryExtension(display,
5252             &xrandr_eventbase, &errorbase);
5253         if (xrandr_support)
5254                 if (XRRQueryVersion(display, &major, &minor) && major < 1)
5255                         xrandr_support = 0;
5256
5257         /* map physical screens */
5258         for (i = 0; i < ScreenCount(display); i++) {
5259                 DNPRINTF(SWM_D_WS, "setup_screens: init screen %d\n", i);
5260                 screens[i].idx = i;
5261                 TAILQ_INIT(&screens[i].rl);
5262                 TAILQ_INIT(&screens[i].orl);
5263                 screens[i].root = RootWindow(display, i);
5264
5265                 /* set default colors */
5266                 setscreencolor("red", i + 1, SWM_S_COLOR_FOCUS);
5267                 setscreencolor("rgb:88/88/88", i + 1, SWM_S_COLOR_UNFOCUS);
5268                 setscreencolor("rgb:00/80/80", i + 1, SWM_S_COLOR_BAR_BORDER);
5269                 setscreencolor("black", i + 1, SWM_S_COLOR_BAR);
5270                 setscreencolor("rgb:a0/a0/a0", i + 1, SWM_S_COLOR_BAR_FONT);
5271
5272                 /* set default cursor */
5273                 XDefineCursor(display, screens[i].root,
5274                     XCreateFontCursor(display, XC_left_ptr));
5275
5276                 /* init all workspaces */
5277                 /* XXX these should be dynamically allocated too */
5278                 for (j = 0; j < SWM_WS_MAX; j++) {
5279                         ws = &screens[i].ws[j];
5280                         ws->idx = j;
5281                         ws->focus = NULL;
5282                         ws->r = NULL;
5283                         ws->old_r = NULL;
5284                         TAILQ_INIT(&ws->winlist);
5285                         TAILQ_INIT(&ws->unmanagedlist);
5286
5287                         for (k = 0; layouts[k].l_stack != NULL; k++)
5288                                 if (layouts[k].l_config != NULL)
5289                                         layouts[k].l_config(ws,
5290                                             SWM_ARG_ID_STACKINIT);
5291                         ws->cur_layout = &layouts[0];
5292                 }
5293
5294                 scan_xrandr(i);
5295
5296                 if (xrandr_support)
5297                         XRRSelectInput(display, screens[i].root,
5298                             RRScreenChangeNotifyMask);
5299         }
5300 }
5301
5302 void
5303 setup_globals(void)
5304 {
5305         if ((bar_fonts[0] = strdup("-*-terminus-medium-*-*-*-*-*-*-*-*-*-*-*"))
5306             == NULL)
5307                 err(1, "setup_globals: strdup");
5308         if ((bar_fonts[1] = strdup("-*-times-medium-r-*-*-*-*-*-*-*-*-*-*"))
5309             == NULL)
5310                 err(1, "setup_globals: strdup");
5311         if ((bar_fonts[2] = strdup("-misc-fixed-medium-r-*-*-*-*-*-*-*-*-*-*"))
5312             == NULL)
5313                 err(1, "setup_globals: strdup");
5314         if ((spawn_term[0] = strdup("xterm")) == NULL)
5315                 err(1, "setup_globals: strdup");
5316         if ((clock_format = strdup("%a %b %d %R %Z %Y")) == NULL)
5317                 errx(1, "strdup");
5318 }
5319
5320 void
5321 workaround(void)
5322 {
5323         int                     i;
5324         Atom                    netwmcheck, netwmname, utf8_string;
5325         Window                  root, win;
5326
5327         /* work around sun jdk bugs, code from wmname */
5328         netwmcheck = XInternAtom(display, "_NET_SUPPORTING_WM_CHECK", False);
5329         netwmname = XInternAtom(display, "_NET_WM_NAME", False);
5330         utf8_string = XInternAtom(display, "UTF8_STRING", False);
5331         for (i = 0; i < ScreenCount(display); i++) {
5332                 root = screens[i].root;
5333                 win = XCreateSimpleWindow(display,root, 0, 0, 1, 1, 0,
5334                     screens[i].c[SWM_S_COLOR_UNFOCUS].color,
5335                     screens[i].c[SWM_S_COLOR_UNFOCUS].color);
5336
5337                 XChangeProperty(display, root, netwmcheck, XA_WINDOW, 32,
5338                     PropModeReplace, (unsigned char *)&win,1);
5339                 XChangeProperty(display, win, netwmcheck, XA_WINDOW, 32,
5340                     PropModeReplace, (unsigned char *)&win,1);
5341                 XChangeProperty(display, win, netwmname, utf8_string, 8,
5342                     PropModeReplace, (unsigned char*)"LG3D", strlen("LG3D"));
5343         }
5344 }
5345
5346 int
5347 main(int argc, char *argv[])
5348 {
5349         struct passwd           *pwd;
5350         struct swm_region       *r, *rr;
5351         struct ws_win           *winfocus = NULL;
5352         struct timeval          tv;
5353         union arg               a;
5354         char                    conf[PATH_MAX], *cfile = NULL;
5355         struct stat             sb;
5356         XEvent                  e;
5357         int                     xfd, i;
5358         fd_set                  rd;
5359         struct sigaction        sact;
5360
5361         start_argv = argv;
5362         fprintf(stderr, "Welcome to scrotwm V%s cvs tag: %s\n",
5363             SWM_VERSION, cvstag);
5364         if (!setlocale(LC_CTYPE, "") || !XSupportsLocale())
5365                 warnx("no locale support");
5366
5367         if (!(display = XOpenDisplay(0)))
5368                 errx(1, "can not open display");
5369
5370         if (active_wm())
5371                 errx(1, "other wm running");
5372
5373         /* handle some signals */
5374         bzero(&sact, sizeof(sact));
5375         sigemptyset(&sact.sa_mask);
5376         sact.sa_flags = 0;
5377         sact.sa_handler = sighdlr;
5378         sigaction(SIGINT, &sact, NULL);
5379         sigaction(SIGQUIT, &sact, NULL);
5380         sigaction(SIGTERM, &sact, NULL);
5381         sigaction(SIGHUP, &sact, NULL);
5382
5383         sact.sa_handler = sighdlr;
5384         sact.sa_flags = SA_NOCLDSTOP;
5385         sigaction(SIGCHLD, &sact, NULL);
5386
5387         astate = XInternAtom(display, "WM_STATE", False);
5388         aprot = XInternAtom(display, "WM_PROTOCOLS", False);
5389         adelete = XInternAtom(display, "WM_DELETE_WINDOW", False);
5390         takefocus = XInternAtom(display, "WM_TAKE_FOCUS", False);
5391
5392         /* look for local and global conf file */
5393         pwd = getpwuid(getuid());
5394         if (pwd == NULL)
5395                 errx(1, "invalid user %d", getuid());
5396
5397         setup_screens();
5398         setup_globals();
5399         setup_keys();
5400         setup_quirks();
5401         setup_spawn();
5402
5403         /* load config */
5404         snprintf(conf, sizeof conf, "%s/.%s", pwd->pw_dir, SWM_CONF_FILE);
5405         if (stat(conf, &sb) != -1) {
5406                 if (S_ISREG(sb.st_mode))
5407                         cfile = conf;
5408         } else {
5409                 /* try global conf file */
5410                 snprintf(conf, sizeof conf, "/etc/%s", SWM_CONF_FILE);
5411                 if (!stat(conf, &sb))
5412                         if (S_ISREG(sb.st_mode))
5413                                 cfile = conf;
5414         }
5415         if (cfile)
5416                 conf_load(cfile);
5417
5418         setup_ewmh();
5419         /* set some values to work around bad programs */
5420         workaround();
5421
5422         /* grab existing windows (before we build the bars) */
5423         grab_windows();
5424
5425         /* setup all bars */
5426         for (i = 0; i < ScreenCount(display); i++)
5427                 TAILQ_FOREACH(r, &screens[i].rl, entry) {
5428                         if (winfocus == NULL)
5429                                 winfocus = TAILQ_FIRST(&r->ws->winlist);
5430                         bar_setup(r);
5431                 }
5432
5433         unfocus_all();
5434
5435         grabkeys();
5436         stack();
5437
5438         xfd = ConnectionNumber(display);
5439         while (running) {
5440                 while (XPending(display)) {
5441                         XNextEvent(display, &e);
5442                         if (running == 0)
5443                                 goto done;
5444                         if (e.type < LASTEvent) {
5445                                 dumpevent(&e);
5446                                 if (handler[e.type])
5447                                         handler[e.type](&e);
5448                                 else
5449                                         DNPRINTF(SWM_D_EVENT,
5450                                             "win: %lu unknown event: %d\n",
5451                                             e.xany.window, e.type);
5452                         } else {
5453                                 switch (e.type - xrandr_eventbase) {
5454                                 case RRScreenChangeNotify:
5455                                         screenchange(&e);
5456                                         break;
5457                                 default:
5458                                         DNPRINTF(SWM_D_EVENT,
5459                                             "win: %lu unknown xrandr event: "
5460                                             "%d\n", e.xany.window, e.type);
5461                                         break;
5462                                 }
5463                         }
5464                 }
5465
5466                 /* if we are being restarted go focus on first window */
5467                 if (winfocus) {
5468                         rr = winfocus->ws->r;
5469                         if (rr == NULL) {
5470                                 /* not a visible window */
5471                                 winfocus = NULL;
5472                                 continue;
5473                         }
5474                         /* move pointer to first screen if multi screen */
5475                         if (ScreenCount(display) > 1 || outputs > 1)
5476                                 XWarpPointer(display, None, rr->s[0].root,
5477                                     0, 0, 0, 0, rr->g.x,
5478                                     rr->g.y + (bar_enabled ? bar_height : 0));
5479
5480                         a.id = SWM_ARG_ID_FOCUSCUR;
5481                         focus(rr, &a);
5482                         winfocus = NULL;
5483                         continue;
5484                 }
5485
5486                 FD_ZERO(&rd);
5487                 FD_SET(xfd, &rd);
5488                 tv.tv_sec = 1;
5489                 tv.tv_usec = 0;
5490                 if (select(xfd + 1, &rd, NULL, NULL, &tv) == -1)
5491                         if (errno != EINTR)
5492                                 DNPRINTF(SWM_D_MISC, "select failed");
5493                 if (restart_wm == 1)
5494                         restart(NULL, NULL);
5495                 if (running == 0)
5496                         goto done;
5497                 if (bar_alarm) {
5498                         bar_alarm = 0;
5499                         bar_update();
5500                 }
5501         }
5502 done:
5503         teardown_ewmh();
5504         bar_extra_stop();
5505         XFreeGC(display, bar_gc);
5506         XCloseDisplay(display);
5507
5508         return (0);
5509 }