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