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