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