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