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