JasonWoof Got questions, comments, patches, etc.? Contact Jason Woofenden
6ae2fc03ec670e5f678544293009156f66d325da
[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                         XSetWindowBorder(display, cfw->id,
1918                             cfw->ws->r->s->c[SWM_S_COLOR_UNFOCUS].color);
1919         }
1920
1921         win->ws->focus = win;
1922
1923         if (win->ws->r != NULL) {
1924                 /* drain all previous focus events */
1925                 while (XCheckTypedEvent(display, FocusIn, &cne) == True)
1926                         ;
1927
1928                 if (win->java == 0)
1929                         XSetInputFocus(display, win->id,
1930                             RevertToParent, CurrentTime);
1931                 XMapRaised(display, win->id);
1932                 grabbuttons(win, 1);
1933                 XSetWindowBorder(display, win->id,
1934                     win->ws->r->s->c[SWM_S_COLOR_FOCUS].color);
1935                 if (win->ws->cur_layout->flags & SWM_L_MAPONFOCUS)
1936                         XMapRaised(display, win->id);
1937
1938                 XChangeProperty(display, win->s->root,
1939                     ewmh[_NET_ACTIVE_WINDOW].atom, XA_WINDOW, 32,
1940                     PropModeReplace, (unsigned char *)&win->id,1);
1941         }
1942
1943         if (window_name_enabled)
1944                 bar_update();
1945 }
1946
1947 void
1948 switchws(struct swm_region *r, union arg *args)
1949 {
1950         int                     wsid = args->id, unmap_old = 0;
1951         struct swm_region       *this_r, *other_r;
1952         struct ws_win           *win;
1953         struct workspace        *new_ws, *old_ws;
1954         union arg               a;
1955
1956         if (!(r && r->s))
1957                 return;
1958
1959         this_r = r;
1960         old_ws = this_r->ws;
1961         new_ws = &this_r->s->ws[wsid];
1962
1963         DNPRINTF(SWM_D_WS, "switchws screen[%d]:%dx%d+%d+%d: "
1964             "%d -> %d\n", r->s->idx, WIDTH(r), HEIGHT(r), X(r), Y(r),
1965             old_ws->idx, wsid);
1966
1967         if (new_ws == NULL || old_ws == NULL)
1968                 return;
1969         if (new_ws == old_ws)
1970                 return;
1971
1972         other_r = new_ws->r;
1973         if (other_r == NULL) {
1974                 /* the other workspace is hidden, hide this one */
1975                 old_ws->r = NULL;
1976                 unmap_old = 1;
1977         } else {
1978                 /* the other ws is visible in another region, exchange them */
1979                 other_r->ws_prior = new_ws;
1980                 other_r->ws = old_ws;
1981                 old_ws->r = other_r;
1982         }
1983         this_r->ws_prior = old_ws;
1984         this_r->ws = new_ws;
1985         new_ws->r = this_r;
1986
1987         /* this is needed so that we can click on a window after a restart */
1988         unfocus_all();
1989
1990         stack();
1991         a.id = SWM_ARG_ID_FOCUSCUR;
1992         focus(new_ws->r, &a);
1993
1994         bar_update();
1995
1996         /* unmap old windows */
1997         if (unmap_old)
1998                 TAILQ_FOREACH(win, &old_ws->winlist, entry)
1999                         unmap_window(win);
2000
2001         if (focus_mode == SWM_FOCUS_DEFAULT)
2002                 drain_enter_notify();
2003 }
2004
2005 void
2006 cyclews(struct swm_region *r, union arg *args)
2007 {
2008         union                   arg a;
2009         struct swm_screen       *s = r->s;
2010
2011         DNPRINTF(SWM_D_WS, "cyclews id %d "
2012             "in screen[%d]:%dx%d+%d+%d ws %d\n", args->id,
2013             r->s->idx, WIDTH(r), HEIGHT(r), X(r), Y(r), r->ws->idx);
2014
2015         a.id = r->ws->idx;
2016         do {
2017                 switch (args->id) {
2018                 case SWM_ARG_ID_CYCLEWS_UP:
2019                         if (a.id < SWM_WS_MAX - 1)
2020                                 a.id++;
2021                         else
2022                                 a.id = 0;
2023                         break;
2024                 case SWM_ARG_ID_CYCLEWS_DOWN:
2025                         if (a.id > 0)
2026                                 a.id--;
2027                         else
2028                                 a.id = SWM_WS_MAX - 1;
2029                         break;
2030                 default:
2031                         return;
2032                 };
2033
2034                 if (cycle_empty == 0 && TAILQ_EMPTY(&s->ws[a.id].winlist))
2035                         continue;
2036                 if (cycle_visible == 0 && s->ws[a.id].r != NULL)
2037                         continue;
2038
2039                 switchws(r, &a);
2040         } while (a.id != r->ws->idx);
2041 }
2042
2043 void
2044 priorws(struct swm_region *r, union arg *args)
2045 {
2046         union arg               a;
2047
2048         DNPRINTF(SWM_D_WS, "priorws id %d "
2049             "in screen[%d]:%dx%d+%d+%d ws %d\n", args->id,
2050             r->s->idx, WIDTH(r), HEIGHT(r), X(r), Y(r), r->ws->idx);
2051
2052         if (r->ws_prior == NULL)
2053                 return;
2054
2055         a.id = r->ws_prior->idx;
2056         switchws(r, &a);
2057 }
2058
2059 void
2060 cyclescr(struct swm_region *r, union arg *args)
2061 {
2062         struct swm_region       *rr = NULL;
2063         union arg               a;
2064         int                     i, x, y;
2065
2066         /* do nothing if we don't have more than one screen */
2067         if (!(ScreenCount(display) > 1 || outputs > 1))
2068                 return;
2069
2070         i = r->s->idx;
2071         switch (args->id) {
2072         case SWM_ARG_ID_CYCLESC_UP:
2073                 rr = TAILQ_NEXT(r, entry);
2074                 if (rr == NULL)
2075                         rr = TAILQ_FIRST(&screens[i].rl);
2076                 break;
2077         case SWM_ARG_ID_CYCLESC_DOWN:
2078                 rr = TAILQ_PREV(r, swm_region_list, entry);
2079                 if (rr == NULL)
2080                         rr = TAILQ_LAST(&screens[i].rl, swm_region_list);
2081                 break;
2082         default:
2083                 return;
2084         };
2085         if (rr == NULL)
2086                 return;
2087
2088         /* move mouse to region */
2089         x = rr->g.x + 1;
2090         y = rr->g.y + 1 + (bar_enabled ? bar_height : 0);
2091         XWarpPointer(display, None, rr->s[i].root, 0, 0, 0, 0, x, y);
2092
2093         a.id = SWM_ARG_ID_FOCUSCUR;
2094         focus(rr, &a);
2095
2096         if (rr->ws->focus) {
2097                 /* move to focus window */
2098                 x = rr->ws->focus->g.x + 1;
2099                 y = rr->ws->focus->g.y + 1;
2100                 XWarpPointer(display, None, rr->s[i].root, 0, 0, 0, 0, x, y);
2101         }
2102 }
2103
2104 void
2105 sort_windows(struct ws_win_list *wl)
2106 {
2107         struct ws_win           *win, *parent, *nxt;
2108
2109         if (wl == NULL)
2110                 return;
2111
2112         for (win = TAILQ_FIRST(wl); win != TAILQ_END(wl); win = nxt) {
2113                 nxt = TAILQ_NEXT(win, entry);
2114                 if (win->transient) {
2115                         parent = find_window(win->transient);
2116                         if (parent == NULL) {
2117                                 fprintf(stderr, "not possible bug\n");
2118                                 continue;
2119                         }
2120                         TAILQ_REMOVE(wl, win, entry);
2121                         TAILQ_INSERT_AFTER(wl, parent, win, entry);
2122                 }
2123         }
2124
2125 }
2126
2127 void
2128 swapwin(struct swm_region *r, union arg *args)
2129 {
2130         struct ws_win           *target, *source;
2131         struct ws_win           *cur_focus;
2132         struct ws_win_list      *wl;
2133
2134
2135         DNPRINTF(SWM_D_WS, "swapwin id %d "
2136             "in screen %d region %dx%d+%d+%d ws %d\n", args->id,
2137             r->s->idx, WIDTH(r), HEIGHT(r), X(r), Y(r), r->ws->idx);
2138
2139         cur_focus = r->ws->focus;
2140         if (cur_focus == NULL)
2141                 return;
2142
2143         source = cur_focus;
2144         wl = &source->ws->winlist;
2145
2146         switch (args->id) {
2147         case SWM_ARG_ID_SWAPPREV:
2148                 if (source->transient)
2149                         source = find_window(source->transient);
2150                 target = TAILQ_PREV(source, ws_win_list, entry);
2151                 if (target && target->transient)
2152                         target = find_window(target->transient);
2153                 TAILQ_REMOVE(wl, source, entry);
2154                 if (target == NULL)
2155                         TAILQ_INSERT_TAIL(wl, source, entry);
2156                 else
2157                         TAILQ_INSERT_BEFORE(target, source, entry);
2158                 break;
2159         case SWM_ARG_ID_SWAPNEXT:
2160                 target = TAILQ_NEXT(source, entry);
2161                 /* move the parent and let the sort handle the move */
2162                 if (source->transient)
2163                         source = find_window(source->transient);
2164                 TAILQ_REMOVE(wl, source, entry);
2165                 if (target == NULL)
2166                         TAILQ_INSERT_HEAD(wl, source, entry);
2167                 else
2168                         TAILQ_INSERT_AFTER(wl, target, source, entry);
2169                 break;
2170         case SWM_ARG_ID_SWAPMAIN:
2171                 target = TAILQ_FIRST(wl);
2172                 if (target == source) {
2173                         if (source->ws->focus_prev != NULL &&
2174                             source->ws->focus_prev != target)
2175
2176                                 source = source->ws->focus_prev;
2177                         else
2178                                 return;
2179                 }
2180                 if (target == NULL || source == NULL)
2181                         return;
2182                 source->ws->focus_prev = target;
2183                 TAILQ_REMOVE(wl, target, entry);
2184                 TAILQ_INSERT_BEFORE(source, target, entry);
2185                 TAILQ_REMOVE(wl, source, entry);
2186                 TAILQ_INSERT_HEAD(wl, source, entry);
2187                 break;
2188         case SWM_ARG_ID_MOVELAST:
2189                 TAILQ_REMOVE(wl, source, entry);
2190                 TAILQ_INSERT_TAIL(wl, source, entry);
2191                 break;
2192         default:
2193                 DNPRINTF(SWM_D_MOVE, "invalid id: %d\n", args->id);
2194                 return;
2195         }
2196
2197         sort_windows(wl);
2198
2199         stack();
2200 }
2201
2202 void
2203 focus_prev(struct ws_win *win)
2204 {
2205         struct ws_win           *winfocus = NULL, *winlostfocus = NULL;
2206         struct ws_win           *cur_focus = NULL;
2207         struct ws_win_list      *wl = NULL;
2208         struct workspace        *ws = NULL;
2209
2210         DNPRINTF(SWM_D_FOCUS, "focus_prev: id %lu\n", WINID(win));
2211
2212         if (!(win && win->ws))
2213                 return;
2214
2215         ws = win->ws;
2216         wl = &ws->winlist;
2217         cur_focus = ws->focus;
2218         winlostfocus = cur_focus;
2219
2220         /* pickle, just focus on whatever */
2221         if (cur_focus == NULL) {
2222                 /* use prev_focus if valid */
2223                 if (ws->focus_prev && ws->focus_prev != cur_focus &&
2224                     find_window(WINID(ws->focus_prev)))
2225                         winfocus = ws->focus_prev;
2226                 if (winfocus == NULL)
2227                         winfocus = TAILQ_FIRST(wl);
2228                 goto done;
2229         }
2230
2231         /* if transient focus on parent */
2232         if (cur_focus->transient) {
2233                 winfocus = find_window(cur_focus->transient);
2234                 goto done;
2235         }
2236
2237         /* if in max_stack try harder */
2238         if ((win->quirks & SWM_Q_FOCUSPREV) ||
2239             (ws->cur_layout->flags & SWM_L_FOCUSPREV)) {
2240                 if (cur_focus != ws->focus_prev)
2241                         winfocus = ws->focus_prev;
2242                 else if (cur_focus != ws->focus)
2243                         winfocus = ws->focus;
2244                 else
2245                         winfocus = TAILQ_PREV(win, ws_win_list, entry);
2246                 if (winfocus)
2247                         goto done;
2248         }
2249
2250         if (cur_focus == win)
2251                 winfocus = TAILQ_PREV(win, ws_win_list, entry);
2252         if (winfocus == NULL)
2253                 winfocus = TAILQ_LAST(wl, ws_win_list);
2254         if (winfocus == NULL || winfocus == win)
2255                 winfocus = TAILQ_NEXT(cur_focus, entry);
2256 done:
2257         if (winfocus == winlostfocus || winfocus == NULL)
2258                 return;
2259
2260         focus_magic(winfocus);
2261 }
2262
2263 void
2264 focus(struct swm_region *r, union arg *args)
2265 {
2266         struct ws_win           *winfocus = NULL, *winlostfocus = NULL, *head;
2267         struct ws_win           *cur_focus = NULL;
2268         struct ws_win_list      *wl = NULL;
2269         struct workspace        *ws = NULL;
2270
2271         if (!(r && r->ws))
2272                 return;
2273
2274         DNPRINTF(SWM_D_FOCUS, "focus: id %d\n", args->id);
2275
2276         /* treat FOCUS_CUR special */
2277         if (args->id == SWM_ARG_ID_FOCUSCUR) {
2278                 if (r->ws->focus && r->ws->focus->iconic == 0)
2279                         winfocus = r->ws->focus;
2280                 else if (r->ws->focus_prev && r->ws->focus_prev->iconic == 0)
2281                         winfocus = r->ws->focus_prev;
2282                 else
2283                         TAILQ_FOREACH(winfocus, &r->ws->winlist, entry)
2284                                 if (winfocus->iconic == 0)
2285                                         break;
2286
2287                 focus_magic(winfocus);
2288                 return;
2289         }
2290
2291         if ((cur_focus = r->ws->focus) == NULL)
2292                 return;
2293         ws = r->ws;
2294         wl = &ws->winlist;
2295
2296         winlostfocus = cur_focus;
2297
2298         switch (args->id) {
2299         case SWM_ARG_ID_FOCUSPREV:
2300                 head = TAILQ_PREV(cur_focus, ws_win_list, entry);
2301                 if (head == NULL)
2302                         head = TAILQ_LAST(wl, ws_win_list);
2303                 winfocus = head;
2304                 if (WINID(winfocus) == cur_focus->transient) {
2305                         head = TAILQ_PREV(winfocus, ws_win_list, entry);
2306                         if (head == NULL)
2307                                 head = TAILQ_LAST(wl, ws_win_list);
2308                         winfocus = head;
2309                 }
2310
2311                 /* skip iconics */
2312                 if (winfocus && winfocus->iconic) {
2313                         TAILQ_FOREACH_REVERSE(winfocus, wl, ws_win_list, entry)
2314                                 if (winfocus->iconic == 0)
2315                                         break;
2316                 }
2317                 break;
2318
2319         case SWM_ARG_ID_FOCUSNEXT:
2320                 head = TAILQ_NEXT(cur_focus, entry);
2321                 if (head == NULL)
2322                         head = TAILQ_FIRST(wl);
2323                 winfocus = head;
2324
2325                 /* skip iconics */
2326                 if (winfocus && winfocus->iconic) {
2327                         TAILQ_FOREACH(winfocus, wl, entry)
2328                                 if (winfocus->iconic == 0)
2329                                         break;
2330                 }
2331                 break;
2332
2333         case SWM_ARG_ID_FOCUSMAIN:
2334                 winfocus = TAILQ_FIRST(wl);
2335                 if (winfocus == cur_focus)
2336                         winfocus = cur_focus->ws->focus_prev;
2337                 break;
2338
2339         default:
2340                 return;
2341         }
2342         if (winfocus == winlostfocus || winfocus == NULL)
2343                 return;
2344
2345         focus_magic(winfocus);
2346 }
2347
2348 void
2349 cycle_layout(struct swm_region *r, union arg *args)
2350 {
2351         struct workspace        *ws = r->ws;
2352         struct ws_win           *winfocus;
2353         union arg               a;
2354
2355         DNPRINTF(SWM_D_EVENT, "cycle_layout: workspace: %d\n", ws->idx);
2356
2357         winfocus = ws->focus;
2358
2359         ws->cur_layout++;
2360         if (ws->cur_layout->l_stack == NULL)
2361                 ws->cur_layout = &layouts[0];
2362
2363         stack();
2364         if (focus_mode == SWM_FOCUS_DEFAULT)
2365                 drain_enter_notify();
2366         a.id = SWM_ARG_ID_FOCUSCUR;
2367         focus(r, &a);
2368         bar_update();
2369 }
2370
2371 void
2372 stack_config(struct swm_region *r, union arg *args)
2373 {
2374         struct workspace        *ws = r->ws;
2375
2376         DNPRINTF(SWM_D_STACK, "stack_config for workspace %d (id %d\n",
2377             args->id, ws->idx);
2378
2379         if (ws->cur_layout->l_config != NULL)
2380                 ws->cur_layout->l_config(ws, args->id);
2381
2382         if (args->id != SWM_ARG_ID_STACKINIT);
2383                 stack();
2384 }
2385
2386 void
2387 stack(void) {
2388         struct swm_geometry     g;
2389         struct swm_region       *r;
2390         int                     i, j;
2391
2392         DNPRINTF(SWM_D_STACK, "stack\n");
2393
2394         for (i = 0; i < ScreenCount(display); i++) {
2395                 j = 0;
2396                 TAILQ_FOREACH(r, &screens[i].rl, entry) {
2397                         DNPRINTF(SWM_D_STACK, "stacking workspace %d "
2398                             "(screen %d, region %d)\n", r->ws->idx, i, j++);
2399
2400                         /* start with screen geometry, adjust for bar */
2401                         g = r->g;
2402                         g.w -= 2 * border_width;
2403                         g.h -= 2 * border_width;
2404                         if (bar_enabled) {
2405                                 if (!bar_at_bottom)
2406                                         g.y += bar_height;
2407                                 g.h -= bar_height;
2408                         }
2409                         r->ws->cur_layout->l_stack(r->ws, &g);
2410                         /* save r so we can track region changes */
2411                         r->ws->old_r = r;
2412                 }
2413         }
2414         if (font_adjusted)
2415                 font_adjusted--;
2416
2417         if (focus_mode == SWM_FOCUS_DEFAULT)
2418                 drain_enter_notify();
2419 }
2420
2421 void
2422 store_float_geom(struct ws_win *win, struct swm_region *r)
2423 {
2424         /* retain window geom and region geom */
2425         win->g_float.x = win->g.x;
2426         win->g_float.y = win->g.y;
2427         win->g_float.w = win->g.w;
2428         win->g_float.h = win->g.h;
2429         win->rg_float.x = r->g.x;
2430         win->rg_float.y = r->g.y;
2431         win->rg_float.w = r->g.w;
2432         win->rg_float.h = r->g.h;
2433         win->g_floatvalid = 1;
2434 }
2435
2436 void
2437 stack_floater(struct ws_win *win, struct swm_region *r)
2438 {
2439         unsigned int            mask;
2440         XWindowChanges          wc;
2441
2442         if (win == NULL)
2443                 return;
2444
2445         bzero(&wc, sizeof wc);
2446         mask = CWX | CWY | CWBorderWidth | CWWidth | CWHeight;
2447
2448         /*
2449          * to allow windows to change their size (e.g. mplayer fs) only retrieve
2450          * geom on ws switches or return from max mode
2451          */
2452
2453         if (win->floatmaxed || (r != r->ws->old_r && win->g_floatvalid
2454             && !(win->ewmh_flags & EWMH_F_FULLSCREEN))) {
2455                 /*
2456                  * use stored g and rg to set relative position and size
2457                  * as in old region or before max stack mode
2458                  */
2459                 win->g.x = win->g_float.x - win->rg_float.x + r->g.x;
2460                 win->g.y = win->g_float.y - win->rg_float.y + r->g.y;
2461                 win->g.w = win->g_float.w;
2462                 win->g.h = win->g_float.h;
2463                 win->g_floatvalid = 0;
2464         }
2465
2466         win->floatmaxed = 0;
2467
2468         if ((win->quirks & SWM_Q_FULLSCREEN) && (win->g.w >= WIDTH(r)) &&
2469             (win->g.h >= HEIGHT(r)))
2470                 wc.border_width = 0;
2471         else
2472                 wc.border_width = border_width;
2473         if (win->transient && (win->quirks & SWM_Q_TRANSSZ)) {
2474                 win->g.w = (double)WIDTH(r) * dialog_ratio;
2475                 win->g.h = (double)HEIGHT(r) * dialog_ratio;
2476         }
2477
2478         if (!win->manual) {
2479                 /*
2480                  * floaters and transients are auto-centred unless moved
2481                  * or resized
2482                  */
2483                 win->g.x = r->g.x + (WIDTH(r) - win->g.w) /
2484                     2 - wc.border_width;
2485                 win->g.y = r->g.y + (HEIGHT(r) - win->g.h) /
2486                     2 - wc.border_width;
2487         }
2488
2489         /* win can be outside r if new r smaller than old r */
2490         /* Ensure top left corner inside r (move probs otherwise) */
2491         if (win->g.x < r->g.x - wc.border_width)
2492                 win->g.x = r->g.x - wc.border_width;
2493         if (win->g.x > r->g.x + r->g.w - 1)
2494                 win->g.x = (win->g.w > r->g.w) ? r->g.x :
2495                     (r->g.x + r->g.w - win->g.w - 2 * wc.border_width);
2496         if (win->g.y < r->g.y - wc.border_width)
2497                 win->g.y = r->g.y - wc.border_width;
2498         if (win->g.y > r->g.y + r->g.h - 1)
2499                 win->g.y = (win->g.h > r->g.h) ? r->g.y :
2500                     (r->g.y + r->g.h - win->g.h - 2 * wc.border_width);
2501
2502         wc.x = win->g.x;
2503         wc.y = win->g.y;
2504         wc.width = win->g.w;
2505         wc.height = win->g.h;
2506
2507         /*
2508          * Retain floater and transient geometry for correct positioning
2509          * when ws changes region
2510          */
2511         if (!(win->ewmh_flags & EWMH_F_FULLSCREEN))
2512                 store_float_geom(win, r);
2513
2514         DNPRINTF(SWM_D_MISC, "stack_floater: win %lu x %d y %d w %d h %d\n",
2515             win->id, wc.x, wc.y, wc.width, wc.height);
2516
2517         XConfigureWindow(display, win->id, mask, &wc);
2518 }
2519
2520 /*
2521  * Send keystrokes to terminal to decrease/increase the font size as the
2522  * window size changes.
2523  */
2524 void
2525 adjust_font(struct ws_win *win)
2526 {
2527         if (!(win->quirks & SWM_Q_XTERM_FONTADJ) ||
2528             win->floating || win->transient)
2529                 return;
2530
2531         if (win->sh.width_inc && win->last_inc != win->sh.width_inc &&
2532             win->g.w / win->sh.width_inc < term_width &&
2533             win->font_steps < SWM_MAX_FONT_STEPS) {
2534                 win->font_size_boundary[win->font_steps] =
2535                     (win->sh.width_inc * term_width) + win->sh.base_width;
2536                 win->font_steps++;
2537                 font_adjusted++;
2538                 win->last_inc = win->sh.width_inc;
2539                 fake_keypress(win, XK_KP_Subtract, ShiftMask);
2540         } else if (win->font_steps && win->last_inc != win->sh.width_inc &&
2541             win->g.w > win->font_size_boundary[win->font_steps - 1]) {
2542                 win->font_steps--;
2543                 font_adjusted++;
2544                 win->last_inc = win->sh.width_inc;
2545                 fake_keypress(win, XK_KP_Add, ShiftMask);
2546         }
2547 }
2548
2549 #define SWAPXY(g)       do {                            \
2550         int tmp;                                        \
2551         tmp = (g)->y; (g)->y = (g)->x; (g)->x = tmp;    \
2552         tmp = (g)->h; (g)->h = (g)->w; (g)->w = tmp;    \
2553 } while (0)
2554 void
2555 stack_master(struct workspace *ws, struct swm_geometry *g, int rot, int flip)
2556 {
2557         XWindowChanges          wc;
2558         XWindowAttributes       wa;
2559         struct swm_geometry     win_g, r_g = *g;
2560         struct ws_win           *win, *fs_win = 0;
2561         int                     i, j, s, stacks;
2562         int                     w_inc = 1, h_inc, w_base = 1, h_base;
2563         int                     hrh, extra = 0, h_slice, last_h = 0;
2564         int                     split, colno, winno, mwin, msize, mscale;
2565         int                     remain, missing, v_slice, reconfigure;
2566         unsigned int            mask;
2567
2568         DNPRINTF(SWM_D_STACK, "stack_master: workspace: %d\n rot=%s flip=%s",
2569             ws->idx, rot ? "yes" : "no", flip ? "yes" : "no");
2570
2571         winno = count_win(ws, 0);
2572         if (winno == 0 && count_win(ws, 1) == 0)
2573                 return;
2574
2575         TAILQ_FOREACH(win, &ws->winlist, entry)
2576                 if (win->transient == 0 && win->floating == 0
2577                     && win->iconic == 0)
2578                         break;
2579
2580         if (win == NULL)
2581                 goto notiles;
2582
2583         if (rot) {
2584                 w_inc = win->sh.width_inc;
2585                 w_base = win->sh.base_width;
2586                 mwin = ws->l_state.horizontal_mwin;
2587                 mscale = ws->l_state.horizontal_msize;
2588                 stacks = ws->l_state.horizontal_stacks;
2589                 SWAPXY(&r_g);
2590         } else {
2591                 w_inc = win->sh.height_inc;
2592                 w_base = win->sh.base_height;
2593                 mwin = ws->l_state.vertical_mwin;
2594                 mscale = ws->l_state.vertical_msize;
2595                 stacks = ws->l_state.vertical_stacks;
2596         }
2597         win_g = r_g;
2598
2599         if (stacks > winno - mwin)
2600                 stacks = winno - mwin;
2601         if (stacks < 1)
2602                 stacks = 1;
2603
2604         h_slice = r_g.h / SWM_H_SLICE;
2605         if (mwin && winno > mwin) {
2606                 v_slice = r_g.w / SWM_V_SLICE;
2607
2608                 split = mwin;
2609                 colno = split;
2610                 win_g.w = v_slice * mscale;
2611
2612                 if (w_inc > 1 && w_inc < v_slice) {
2613                         /* adjust for window's requested size increment */
2614                         remain = (win_g.w - w_base) % w_inc;
2615                         missing = w_inc - remain;
2616                         win_g.w -= remain;
2617                         extra += remain;
2618                 }
2619
2620                 msize = win_g.w;
2621                 if (flip)
2622                         win_g.x += r_g.w - msize;
2623         } else {
2624                 msize = -2;
2625                 colno = split = winno / stacks;
2626                 win_g.w = ((r_g.w - (stacks * 2 * border_width) +
2627                     2 * border_width) / stacks);
2628         }
2629         hrh = r_g.h / colno;
2630         extra = r_g.h - (colno * hrh);
2631         win_g.h = hrh - 2 * border_width;
2632
2633         /*  stack all the tiled windows */
2634         i = j = 0, s = stacks;
2635         TAILQ_FOREACH(win, &ws->winlist, entry) {
2636                 if (win->transient != 0 || win->floating != 0)
2637                         continue;
2638                 if (win->iconic != 0)
2639                         continue;
2640
2641                 if (win->ewmh_flags & EWMH_F_FULLSCREEN) {
2642                         fs_win = win;
2643                         continue;
2644                 }
2645
2646                 if (split && i == split) {
2647                         colno = (winno - mwin) / stacks;
2648                         if (s <= (winno - mwin) % stacks)
2649                                 colno++;
2650                         split = split + colno;
2651                         hrh = (r_g.h / colno);
2652                         extra = r_g.h - (colno * hrh);
2653                         if (flip)
2654                                 win_g.x = r_g.x;
2655                         else
2656                                 win_g.x += win_g.w + 2 * border_width;
2657                         win_g.w = (r_g.w - msize -
2658                             (stacks * 2 * border_width)) / stacks;
2659                         if (s == 1)
2660                                 win_g.w += (r_g.w - msize -
2661                                     (stacks * 2 * border_width)) % stacks;
2662                         s--;
2663                         j = 0;
2664                 }
2665                 win_g.h = hrh - 2 * border_width;
2666                 if (rot) {
2667                         h_inc = win->sh.width_inc;
2668                         h_base = win->sh.base_width;
2669                 } else {
2670                         h_inc = win->sh.height_inc;
2671                         h_base = win->sh.base_height;
2672                 }
2673                 if (j == colno - 1) {
2674                         win_g.h = hrh + extra;
2675                 } else if (h_inc > 1 && h_inc < h_slice) {
2676                         /* adjust for window's requested size increment */
2677                         remain = (win_g.h - h_base) % h_inc;
2678                         missing = h_inc - remain;
2679
2680                         if (missing <= extra || j == 0) {
2681                                 extra -= missing;
2682                                 win_g.h += missing;
2683                         } else {
2684                                 win_g.h -= remain;
2685                                 extra += remain;
2686                         }
2687                 }
2688
2689                 if (j == 0)
2690                         win_g.y = r_g.y;
2691                 else
2692                         win_g.y += last_h + 2 * border_width;
2693
2694                 bzero(&wc, sizeof wc);
2695                 if (disable_border && bar_enabled == 0 && winno == 1){
2696                         wc.border_width = 0;
2697                         win_g.w += 2 * border_width;
2698                         win_g.h += 2 * border_width;
2699                 } else
2700                         wc.border_width = border_width;
2701                 reconfigure = 0;
2702                 if (rot) {
2703                         if (win->g.x != win_g.y || win->g.y != win_g.x ||
2704                             win->g.w != win_g.h || win->g.h != win_g.w) {
2705                                 reconfigure = 1;
2706                                 win->g.x = wc.x = win_g.y;
2707                                 win->g.y = wc.y = win_g.x;
2708                                 win->g.w = wc.width = win_g.h;
2709                                 win->g.h = wc.height = win_g.w;
2710                         }
2711                 } else {
2712                         if (win->g.x != win_g.x || win->g.y != win_g.y ||
2713                             win->g.w != win_g.w || win->g.h != win_g.h) {
2714                                 reconfigure = 1;
2715                                 win->g.x = wc.x = win_g.x;
2716                                 win->g.y = wc.y = win_g.y;
2717                                 win->g.w = wc.width = win_g.w;
2718                                 win->g.h = wc.height = win_g.h;
2719                         }
2720                 }
2721                 if (reconfigure) {
2722                         adjust_font(win);
2723                         mask = CWX | CWY | CWWidth | CWHeight | CWBorderWidth;
2724                         XConfigureWindow(display, win->id, mask, &wc);
2725                 }
2726
2727                 if (XGetWindowAttributes(display, win->id, &wa))
2728                         if (wa.map_state == IsUnmapped)
2729                                 XMapRaised(display, win->id);
2730
2731                 last_h = win_g.h;
2732                 i++;
2733                 j++;
2734         }
2735
2736 notiles:
2737         /* now, stack all the floaters and transients */
2738         TAILQ_FOREACH(win, &ws->winlist, entry) {
2739                 if (win->transient == 0 && win->floating == 0)
2740                         continue;
2741                 if (win->iconic == 1)
2742                         continue;
2743                 if (win->ewmh_flags & EWMH_F_FULLSCREEN) {
2744                         fs_win = win;
2745                         continue;
2746                 }
2747
2748                 stack_floater(win, ws->r);
2749                 XMapRaised(display, win->id);
2750         }
2751
2752         if (fs_win) {
2753                 stack_floater(fs_win, ws->r);
2754                 XMapRaised(display, fs_win->id);
2755         }
2756 }
2757
2758 void
2759 vertical_config(struct workspace *ws, int id)
2760 {
2761         DNPRINTF(SWM_D_STACK, "vertical_resize: workspace: %d\n", ws->idx);
2762
2763         switch (id) {
2764         case SWM_ARG_ID_STACKRESET:
2765         case SWM_ARG_ID_STACKINIT:
2766                 ws->l_state.vertical_msize = SWM_V_SLICE / 2;
2767                 ws->l_state.vertical_mwin = 1;
2768                 ws->l_state.vertical_stacks = 1;
2769                 break;
2770         case SWM_ARG_ID_MASTERSHRINK:
2771                 if (ws->l_state.vertical_msize > 1)
2772                         ws->l_state.vertical_msize--;
2773                 break;
2774         case SWM_ARG_ID_MASTERGROW:
2775                 if (ws->l_state.vertical_msize < SWM_V_SLICE - 1)
2776                         ws->l_state.vertical_msize++;
2777                 break;
2778         case SWM_ARG_ID_MASTERADD:
2779                 ws->l_state.vertical_mwin++;
2780                 break;
2781         case SWM_ARG_ID_MASTERDEL:
2782                 if (ws->l_state.vertical_mwin > 0)
2783                         ws->l_state.vertical_mwin--;
2784                 break;
2785         case SWM_ARG_ID_STACKINC:
2786                 ws->l_state.vertical_stacks++;
2787                 break;
2788         case SWM_ARG_ID_STACKDEC:
2789                 if (ws->l_state.vertical_stacks > 1)
2790                         ws->l_state.vertical_stacks--;
2791                 break;
2792         default:
2793                 return;
2794         }
2795 }
2796
2797 void
2798 vertical_stack(struct workspace *ws, struct swm_geometry *g)
2799 {
2800         DNPRINTF(SWM_D_STACK, "vertical_stack: workspace: %d\n", ws->idx);
2801
2802         stack_master(ws, g, 0, 0);
2803 }
2804
2805 void
2806 horizontal_config(struct workspace *ws, int id)
2807 {
2808         DNPRINTF(SWM_D_STACK, "horizontal_config: workspace: %d\n", ws->idx);
2809
2810         switch (id) {
2811         case SWM_ARG_ID_STACKRESET:
2812         case SWM_ARG_ID_STACKINIT:
2813                 ws->l_state.horizontal_mwin = 1;
2814                 ws->l_state.horizontal_msize = SWM_H_SLICE / 2;
2815                 ws->l_state.horizontal_stacks = 1;
2816                 break;
2817         case SWM_ARG_ID_MASTERSHRINK:
2818                 if (ws->l_state.horizontal_msize > 1)
2819                         ws->l_state.horizontal_msize--;
2820                 break;
2821         case SWM_ARG_ID_MASTERGROW:
2822                 if (ws->l_state.horizontal_msize < SWM_H_SLICE - 1)
2823                         ws->l_state.horizontal_msize++;
2824                 break;
2825         case SWM_ARG_ID_MASTERADD:
2826                 ws->l_state.horizontal_mwin++;
2827                 break;
2828         case SWM_ARG_ID_MASTERDEL:
2829                 if (ws->l_state.horizontal_mwin > 0)
2830                         ws->l_state.horizontal_mwin--;
2831                 break;
2832         case SWM_ARG_ID_STACKINC:
2833                 ws->l_state.horizontal_stacks++;
2834                 break;
2835         case SWM_ARG_ID_STACKDEC:
2836                 if (ws->l_state.horizontal_stacks > 1)
2837                         ws->l_state.horizontal_stacks--;
2838                 break;
2839         default:
2840                 return;
2841         }
2842 }
2843
2844 void
2845 horizontal_stack(struct workspace *ws, struct swm_geometry *g)
2846 {
2847         DNPRINTF(SWM_D_STACK, "horizontal_stack: workspace: %d\n", ws->idx);
2848
2849         stack_master(ws, g, 1, 0);
2850 }
2851
2852 /* fullscreen view */
2853 void
2854 max_stack(struct workspace *ws, struct swm_geometry *g)
2855 {
2856         XWindowChanges          wc;
2857         struct swm_geometry     gg = *g;
2858         struct ws_win           *win, *wintrans = NULL, *parent = NULL;
2859         unsigned int            mask;
2860         int                     winno;
2861
2862         DNPRINTF(SWM_D_STACK, "max_stack: workspace: %d\n", ws->idx);
2863
2864         if (ws == NULL)
2865                 return;
2866
2867         winno = count_win(ws, 0);
2868         if (winno == 0 && count_win(ws, 1) == 0)
2869                 return;
2870
2871         TAILQ_FOREACH(win, &ws->winlist, entry) {
2872                 if (win->transient) {
2873                         wintrans = win;
2874                         parent = find_window(win->transient);
2875                         continue;
2876                 }
2877
2878                 if (win->floating && win->floatmaxed == 0 ) {
2879                         /*
2880                          * retain geometry for retrieval on exit from
2881                          * max_stack mode
2882                          */
2883                         store_float_geom(win, ws->r);
2884                         win->floatmaxed = 1;
2885                 }
2886
2887                 /* only reconfigure if necessary */
2888                 if (win->g.x != gg.x || win->g.y != gg.y || win->g.w != gg.w ||
2889                     win->g.h != gg.h) {
2890                         bzero(&wc, sizeof wc);
2891                         win->g.x = wc.x = gg.x;
2892                         win->g.y = wc.y = gg.y;
2893                         if (bar_enabled){
2894                                 wc.border_width = border_width;
2895                                 win->g.w = wc.width = gg.w;
2896                                 win->g.h = wc.height = gg.h;
2897                         } else {
2898                                 wc.border_width = 0;
2899                                 win->g.w = wc.width = gg.w + 2 * border_width;
2900                                 win->g.h = wc.height = gg.h + 2 * border_width;
2901                         }
2902                         mask = CWX | CWY | CWWidth | CWHeight | CWBorderWidth;
2903                         XConfigureWindow(display, win->id, mask, &wc);
2904                 }
2905                 /* unmap only if we don't have multi screen */
2906                 if (win != ws->focus)
2907                         if (!(ScreenCount(display) > 1 || outputs > 1))
2908                                 unmap_window(win);
2909         }
2910
2911         /* put the last transient on top */
2912         if (wintrans) {
2913                 if (parent)
2914                         XMapRaised(display, parent->id);
2915                 stack_floater(wintrans, ws->r);
2916                 focus_magic(wintrans);
2917         }
2918 }
2919
2920 void
2921 send_to_ws(struct swm_region *r, union arg *args)
2922 {
2923         int                     wsid = args->id;
2924         struct ws_win           *win = NULL, *parent;
2925         struct workspace        *ws, *nws;
2926         Atom                    ws_idx_atom = 0;
2927         unsigned char           ws_idx_str[SWM_PROPLEN];
2928         union arg               a;
2929
2930         if (r && r->ws)
2931                 win = r->ws->focus;
2932         else
2933                 return;
2934         if (win == NULL)
2935                 return;
2936         if (win->ws->idx == wsid)
2937                 return;
2938
2939         DNPRINTF(SWM_D_MOVE, "send_to_ws: win: %lu\n", win->id);
2940
2941         ws = win->ws;
2942         nws = &win->s->ws[wsid];
2943
2944         a.id = SWM_ARG_ID_FOCUSPREV;
2945         focus(r, &a);
2946         if (win->transient) {
2947                 parent = find_window(win->transient);
2948                 if (parent) {
2949                         unmap_window(parent);
2950                         TAILQ_REMOVE(&ws->winlist, parent, entry);
2951                         TAILQ_INSERT_TAIL(&nws->winlist, parent, entry);
2952                         parent->ws = nws;
2953                 }
2954         }
2955         unmap_window(win);
2956         TAILQ_REMOVE(&ws->winlist, win, entry);
2957         TAILQ_INSERT_TAIL(&nws->winlist, win, entry);
2958         win->ws = nws;
2959
2960         /* Try to update the window's workspace property */
2961         ws_idx_atom = XInternAtom(display, "_SWM_WS", False);
2962         if (ws_idx_atom &&
2963             snprintf(ws_idx_str, SWM_PROPLEN, "%d", nws->idx) < SWM_PROPLEN) {
2964                 DNPRINTF(SWM_D_PROP, "setting property _SWM_WS to %s\n",
2965                     ws_idx_str);
2966                 XChangeProperty(display, win->id, ws_idx_atom, XA_STRING, 8,
2967                     PropModeReplace, ws_idx_str, SWM_PROPLEN);
2968         }
2969
2970         stack();
2971 }
2972
2973 void
2974 iconify(struct swm_region *r, union arg *args)
2975 {
2976         union arg a;
2977
2978         if (r->ws->focus == NULL)
2979                 return;
2980         unmap_window(r->ws->focus);
2981         update_iconic(r->ws->focus, 1);
2982         stack();
2983         if (focus_mode == SWM_FOCUS_DEFAULT)
2984                 drain_enter_notify();
2985         r->ws->focus = NULL;
2986         a.id = SWM_ARG_ID_FOCUSCUR;
2987         focus(r, &a);
2988 }
2989
2990 unsigned char *
2991 get_win_name(Display *dpy, Window win, Atom wname, Atom stype,
2992     unsigned long *slen)
2993 {
2994         int                     status, retfmt;
2995         unsigned long           nitems, nbytes, nextra;
2996         unsigned char           *prop = NULL;
2997         Atom                    rettype;
2998
2999         status = XGetWindowProperty(dpy, win, wname, 0L, 0L, False, stype,
3000             &rettype, &retfmt,  &nitems, &nbytes, &prop);
3001         if (status != Success)
3002                 return (NULL);
3003         XFree(prop);
3004
3005         status = XGetWindowProperty(dpy, win, wname, 0L, nbytes, False,
3006             stype, &rettype, &retfmt, &nitems, &nextra, &prop);
3007         if (status != Success) {
3008                 XFree(prop);
3009                 return (NULL);
3010         }
3011         if (rettype != stype) {
3012                 XFree(prop);
3013                 return (NULL);
3014         }
3015         *slen = nitems;
3016         return (prop);
3017 }
3018
3019 void
3020 uniconify(struct swm_region *r, union arg *args)
3021 {
3022         struct ws_win           *win;
3023         FILE                    *lfile;
3024         char                    *name;
3025         int                     count = 0;
3026         unsigned long           len;
3027
3028         DNPRINTF(SWM_D_MISC, "uniconify\n");
3029
3030         if (r && r->ws == NULL)
3031                 return;
3032
3033         /* make sure we have anything to uniconify */
3034         TAILQ_FOREACH(win, &r->ws->winlist, entry) {
3035                 if (win->ws == NULL)
3036                         continue; /* should never happen */
3037                 if (win->iconic == 0)
3038                         continue;
3039                 count++;
3040         }
3041         if (count == 0)
3042                 return;
3043
3044         search_r = r;
3045
3046         spawn_select(r, args, "uniconify", &searchpid);
3047
3048         if ((lfile = fdopen(select_list_pipe[1], "w")) == NULL)
3049                 return;
3050
3051         TAILQ_FOREACH(win, &r->ws->winlist, entry) {
3052                 if (win->ws == NULL)
3053                         continue; /* should never happen */
3054                 if (win->iconic == 0)
3055                         continue;
3056
3057                 name = get_win_name(display, win->id, a_wmname, a_string,
3058                     &len);
3059                 if (name == NULL)
3060                         continue;
3061                 fprintf(lfile, "%s.%lu\n", name, win->id);
3062                 XFree(name);
3063         }
3064
3065         fclose(lfile);
3066 }
3067
3068 #define MAX_RESP_LEN    1024
3069
3070 void
3071 search_do_resp(void)
3072 {
3073         ssize_t                 rbytes;
3074         struct ws_win           *win;
3075         char                    *name, *resp, *s;
3076         unsigned long           len;
3077
3078         DNPRINTF(SWM_D_MISC, "search_do_resp:\n");
3079
3080         search_resp = 0;
3081         searchpid = 0;
3082
3083         if ((resp = calloc(1, MAX_RESP_LEN + 1)) == NULL) {
3084                 fprintf(stderr, "search: calloc\n");
3085                 return;
3086         }
3087
3088         rbytes = read(select_resp_pipe[0], resp, MAX_RESP_LEN);
3089         if (rbytes <= 0) {
3090                 fprintf(stderr, "search: read error: %s\n", strerror(errno));
3091                 goto done;
3092         }
3093         resp[rbytes] = '\0';
3094         len = strlen(resp);
3095
3096         DNPRINTF(SWM_D_MISC, "search_do_resp: resp %s\n", resp);
3097         TAILQ_FOREACH(win, &search_r->ws->winlist, entry) {
3098                 if (win->iconic == 0)
3099                         continue;
3100                 name = get_win_name(display, win->id, a_wmname, a_string, &len);
3101                 if (name == NULL)
3102                         continue;
3103                 if (asprintf(&s, "%s.%lu", name, win->id) == -1) {
3104                         XFree(name);
3105                         continue;
3106                 }
3107                 XFree(name);
3108                 if (strncmp(s, resp, len) == 0) {
3109                         /* XXX this should be a callback to generalize */
3110                         update_iconic(win, 0);
3111                         free(s);
3112                         break;
3113                 }
3114                 free(s);
3115         }
3116 done:
3117         free(resp);
3118 }
3119
3120 void
3121 wkill(struct swm_region *r, union arg *args)
3122 {
3123         DNPRINTF(SWM_D_MISC, "wkill %d\n", args->id);
3124
3125         if (r->ws->focus == NULL)
3126                 return;
3127
3128         if (args->id == SWM_ARG_ID_KILLWINDOW)
3129                 XKillClient(display, r->ws->focus->id);
3130         else
3131                 if (r->ws->focus->can_delete)
3132                         client_msg(r->ws->focus, adelete);
3133 }
3134
3135
3136 int
3137 floating_toggle_win(struct ws_win *win)
3138 {
3139         struct swm_region       *r;
3140
3141         if (win == NULL)
3142                 return 0;
3143
3144         if (!win->ws->r)
3145                 return 0;
3146
3147         r = win->ws->r;
3148
3149         /* reject floating toggles in max stack mode */
3150         if (win->ws->cur_layout == &layouts[SWM_MAX_STACK])
3151                 return 0;
3152
3153         if (win->floating) {
3154                 if (!win->floatmaxed) {
3155                         /* retain position for refloat */
3156                         store_float_geom(win, r);
3157                 }
3158                 win->floating = 0;
3159         } else {
3160                 if (win->g_floatvalid) {
3161                         /* refloat at last floating relative position */
3162                         win->g.x = win->g_float.x - win->rg_float.x + r->g.x;
3163                         win->g.y = win->g_float.y - win->rg_float.y + r->g.y;
3164                         win->g.w = win->g_float.w;
3165                         win->g.h = win->g_float.h;
3166                 }
3167                 win->floating = 1;
3168         }
3169
3170         ewmh_update_actions(win);
3171
3172         return 1;
3173 }
3174
3175 void
3176 floating_toggle(struct swm_region *r, union arg *args)
3177 {
3178         struct ws_win           *win = r->ws->focus;
3179         union arg               a;
3180
3181         if (win == NULL)
3182                 return;
3183
3184         ewmh_update_win_state(win, ewmh[_NET_WM_STATE_ABOVE].atom,
3185             _NET_WM_STATE_TOGGLE);
3186
3187         stack();
3188         if (focus_mode == SWM_FOCUS_DEFAULT)
3189                 drain_enter_notify();
3190
3191         if (win == win->ws->focus) {
3192                 a.id = SWM_ARG_ID_FOCUSCUR;
3193                 focus(win->ws->r, &a);
3194         }
3195 }
3196
3197 void
3198 resize_window(struct ws_win *win, int center)
3199 {
3200         unsigned int            mask;
3201         XWindowChanges          wc;
3202         struct swm_region       *r;
3203
3204         r = root_to_region(win->wa.root);
3205         bzero(&wc, sizeof wc);
3206         mask = CWBorderWidth | CWWidth | CWHeight;
3207         wc.border_width = border_width;
3208         wc.width = win->g.w;
3209         wc.height = win->g.h;
3210         if (center == SWM_ARG_ID_CENTER) {
3211                 wc.x = (WIDTH(r) - win->g.w) / 2 - border_width;
3212                 wc.y = (HEIGHT(r) - win->g.h) / 2 - border_width;
3213                 mask |= CWX | CWY;
3214         }
3215
3216         DNPRINTF(SWM_D_STACK, "resize_window: win %lu x %d y %d w %d h %d\n",
3217             win->id, wc.x, wc.y, wc.width, wc.height);
3218
3219         XConfigureWindow(display, win->id, mask, &wc);
3220 }
3221
3222 void
3223 resize(struct ws_win *win, union arg *args)
3224 {
3225         XEvent                  ev;
3226         Time                    time = 0;
3227         struct swm_region       *r = win->ws->r;
3228         int                     relx, rely;
3229
3230
3231         DNPRINTF(SWM_D_MOUSE, "resize: win %lu floating %d trans %lu\n",
3232             win->id, win->floating, win->transient);
3233
3234         if (!(win->transient != 0 || win->floating != 0))
3235                 return;
3236
3237         /* reject resizes in max mode for floaters (transient ok) */
3238         if (win->floatmaxed)
3239                 return;
3240
3241         win->manual = 1;
3242         ewmh_update_win_state(win, ewmh[_SWM_WM_STATE_MANUAL].atom,
3243             _NET_WM_STATE_ADD);
3244
3245         stack();
3246         if (focus_mode == SWM_FOCUS_DEFAULT)
3247                 drain_enter_notify();
3248
3249         if (XGrabPointer(display, win->id, False, MOUSEMASK, GrabModeAsync,
3250             GrabModeAsync, None, None /* cursor */, CurrentTime) != GrabSuccess)
3251                 return;
3252
3253         /* place pointer at bottom left corner or nearest point inside r */
3254         if ( win->g.x + win->g.w < r->g.x + r->g.w - 1)
3255                 relx = win->g.w - 1;
3256         else
3257                 relx = r->g.x + r->g.w - win->g.x - 1;
3258
3259         if ( win->g.y + win->g.h < r->g.y + r->g.h - 1)
3260                 rely = win->g.h - 1;
3261         else
3262                 rely = r->g.y + r->g.h - win->g.y - 1;
3263
3264         XWarpPointer(display, None, win->id, 0, 0, 0, 0, relx, rely);
3265         do {
3266                 XMaskEvent(display, MOUSEMASK | ExposureMask |
3267                     SubstructureRedirectMask, &ev);
3268                 switch (ev.type) {
3269                 case ConfigureRequest:
3270                 case Expose:
3271                 case MapRequest:
3272                         handler[ev.type](&ev);
3273                         break;
3274                 case MotionNotify:
3275                         /* do not allow resize outside of region */
3276                         if (    ev.xmotion.x_root < r->g.x ||
3277                                 ev.xmotion.x_root > r->g.x + r->g.w - 1 ||
3278                                 ev.xmotion.y_root < r->g.y ||
3279                                 ev.xmotion.y_root > r->g.y + r->g.h - 1)
3280                                 continue;
3281
3282                         if (ev.xmotion.x <= 1)
3283                                 ev.xmotion.x = 1;
3284                         if (ev.xmotion.y <= 1)
3285                                 ev.xmotion.y = 1;
3286                         win->g.w = ev.xmotion.x + 1;
3287                         win->g.h = ev.xmotion.y + 1;
3288
3289                         /* not free, don't sync more than 120 times / second */
3290                         if ((ev.xmotion.time - time) > (1000 / 120) ) {
3291                                 time = ev.xmotion.time;
3292                                 XSync(display, False);
3293                                 resize_window(win, args->id);
3294                         }
3295                         break;
3296                 }
3297         } while (ev.type != ButtonRelease);
3298         if (time) {
3299                 XSync(display, False);
3300                 resize_window(win, args->id);
3301         }
3302         store_float_geom(win,r);
3303
3304         XWarpPointer(display, None, win->id, 0, 0, 0, 0, win->g.w - 1,
3305             win->g.h - 1);
3306         XUngrabPointer(display, CurrentTime);
3307
3308         /* drain events */
3309         drain_enter_notify();
3310 }
3311
3312 void
3313 move_window(struct ws_win *win)
3314 {
3315         unsigned int            mask;
3316         XWindowChanges          wc;
3317         struct swm_region       *r;
3318
3319         r = root_to_region(win->wa.root);
3320         bzero(&wc, sizeof wc);
3321         mask = CWX | CWY;
3322         wc.x = win->g.x;
3323         wc.y = win->g.y;
3324         wc.border_width = border_width;
3325
3326         DNPRINTF(SWM_D_STACK, "move_window: win %lu x %d y %d w %d h %d\n",
3327             win->id, wc.x, wc.y, wc.width, wc.height);
3328
3329         XConfigureWindow(display, win->id, mask, &wc);
3330 }
3331
3332 void
3333 move(struct ws_win *win, union arg *args)
3334 {
3335         XEvent                  ev;
3336         Time                    time = 0;
3337         struct swm_region       *r = win->ws->r;
3338
3339         DNPRINTF(SWM_D_MOUSE, "move: win %lu floating %d trans %lu\n",
3340             win->id, win->floating, win->transient);
3341
3342         /* in max_stack mode should only move transients */
3343         if (win->ws->cur_layout == &layouts[SWM_MAX_STACK] && !win->transient)
3344                 return;
3345
3346         win->manual = 1;
3347         if (win->floating == 0 && !win->transient) {
3348                 ewmh_update_win_state(win, ewmh[_NET_WM_STATE_ABOVE].atom,
3349                     _NET_WM_STATE_ADD);
3350         }
3351         ewmh_update_win_state(win, ewmh[_SWM_WM_STATE_MANUAL].atom,
3352             _NET_WM_STATE_ADD);
3353
3354         stack();
3355
3356         if (XGrabPointer(display, win->id, False, MOUSEMASK, GrabModeAsync,
3357             GrabModeAsync, None, None /* cursor */, CurrentTime) != GrabSuccess)
3358                 return;
3359         XWarpPointer(display, None, win->id, 0, 0, 0, 0, 0, 0);
3360         do {
3361                 XMaskEvent(display, MOUSEMASK | ExposureMask |
3362                     SubstructureRedirectMask, &ev);
3363                 switch (ev.type) {
3364                 case ConfigureRequest:
3365                 case Expose:
3366                 case MapRequest:
3367                         handler[ev.type](&ev);
3368                         break;
3369                 case MotionNotify:
3370                         /* don't allow to move window origin out of region */
3371                         if (    ev.xmotion.x_root < r->g.x ||
3372                                 ev.xmotion.x_root > r->g.x + r->g.w - 1 ||
3373                                 ev.xmotion.y_root < r->g.y ||
3374                                 ev.xmotion.y_root > r->g.y + r->g.h - 1)
3375                                 continue;
3376
3377                         win->g.x = ev.xmotion.x_root - border_width;
3378                         win->g.y = ev.xmotion.y_root - border_width;
3379
3380                         /* not free, don't sync more than 120 times / second */
3381                         if ((ev.xmotion.time - time) > (1000 / 120) ) {
3382                                 time = ev.xmotion.time;
3383                                 XSync(display, False);
3384                                 move_window(win);
3385                         }
3386                         break;
3387                 }
3388         } while (ev.type != ButtonRelease);
3389         if (time) {
3390                 XSync(display, False);
3391                 move_window(win);
3392         }
3393         store_float_geom(win,r);
3394         XWarpPointer(display, None, win->id, 0, 0, 0, 0, 0, 0);
3395         XUngrabPointer(display, CurrentTime);
3396
3397         /* drain events */
3398         drain_enter_notify();
3399 }
3400
3401 /* user/key callable function IDs */
3402 enum keyfuncid {
3403         kf_cycle_layout,
3404         kf_stack_reset,
3405         kf_master_shrink,
3406         kf_master_grow,
3407         kf_master_add,
3408         kf_master_del,
3409         kf_stack_inc,
3410         kf_stack_dec,
3411         kf_swap_main,
3412         kf_focus_next,
3413         kf_focus_prev,
3414         kf_swap_next,
3415         kf_swap_prev,
3416         kf_spawn_term,
3417         kf_spawn_menu,
3418         kf_quit,
3419         kf_restart,
3420         kf_focus_main,
3421         kf_ws_1,
3422         kf_ws_2,
3423         kf_ws_3,
3424         kf_ws_4,
3425         kf_ws_5,
3426         kf_ws_6,
3427         kf_ws_7,
3428         kf_ws_8,
3429         kf_ws_9,
3430         kf_ws_10,
3431         kf_ws_next,
3432         kf_ws_prev,
3433         kf_ws_prior,
3434         kf_screen_next,
3435         kf_screen_prev,
3436         kf_mvws_1,
3437         kf_mvws_2,
3438         kf_mvws_3,
3439         kf_mvws_4,
3440         kf_mvws_5,
3441         kf_mvws_6,
3442         kf_mvws_7,
3443         kf_mvws_8,
3444         kf_mvws_9,
3445         kf_mvws_10,
3446         kf_bar_toggle,
3447         kf_wind_kill,
3448         kf_wind_del,
3449         kf_screenshot_all,
3450         kf_screenshot_wind,
3451         kf_float_toggle,
3452         kf_version,
3453         kf_spawn_lock,
3454         kf_spawn_initscr,
3455         kf_spawn_custom,
3456         kf_iconify,
3457         kf_uniconify,
3458         kf_dumpwins, /* MUST BE LAST */
3459         kf_invalid
3460 };
3461
3462 /* key definitions */
3463 void
3464 dummykeyfunc(struct swm_region *r, union arg *args)
3465 {
3466 };
3467
3468 void
3469 legacyfunc(struct swm_region *r, union arg *args)
3470 {
3471 };
3472
3473 struct keyfunc {
3474         char                    name[SWM_FUNCNAME_LEN];
3475         void                    (*func)(struct swm_region *r, union arg *);
3476         union arg               args;
3477 } keyfuncs[kf_invalid + 1] = {
3478         /* name                 function        argument */
3479         { "cycle_layout",       cycle_layout,   {0} },
3480         { "stack_reset",        stack_config,   {.id = SWM_ARG_ID_STACKRESET} },
3481         { "master_shrink",      stack_config,   {.id = SWM_ARG_ID_MASTERSHRINK} },
3482         { "master_grow",        stack_config,   {.id = SWM_ARG_ID_MASTERGROW} },
3483         { "master_add",         stack_config,   {.id = SWM_ARG_ID_MASTERADD} },
3484         { "master_del",         stack_config,   {.id = SWM_ARG_ID_MASTERDEL} },
3485         { "stack_inc",          stack_config,   {.id = SWM_ARG_ID_STACKINC} },
3486         { "stack_dec",          stack_config,   {.id = SWM_ARG_ID_STACKDEC} },
3487         { "swap_main",          swapwin,        {.id = SWM_ARG_ID_SWAPMAIN} },
3488         { "focus_next",         focus,          {.id = SWM_ARG_ID_FOCUSNEXT} },
3489         { "focus_prev",         focus,          {.id = SWM_ARG_ID_FOCUSPREV} },
3490         { "swap_next",          swapwin,        {.id = SWM_ARG_ID_SWAPNEXT} },
3491         { "swap_prev",          swapwin,        {.id = SWM_ARG_ID_SWAPPREV} },
3492         { "spawn_term",         spawnterm,      {.argv = spawn_term} },
3493         { "spawn_menu",         legacyfunc,     {0} },
3494         { "quit",               quit,           {0} },
3495         { "restart",            restart,        {0} },
3496         { "focus_main",         focus,          {.id = SWM_ARG_ID_FOCUSMAIN} },
3497         { "ws_1",               switchws,       {.id = 0} },
3498         { "ws_2",               switchws,       {.id = 1} },
3499         { "ws_3",               switchws,       {.id = 2} },
3500         { "ws_4",               switchws,       {.id = 3} },
3501         { "ws_5",               switchws,       {.id = 4} },
3502         { "ws_6",               switchws,       {.id = 5} },
3503         { "ws_7",               switchws,       {.id = 6} },
3504         { "ws_8",               switchws,       {.id = 7} },
3505         { "ws_9",               switchws,       {.id = 8} },
3506         { "ws_10",              switchws,       {.id = 9} },
3507         { "ws_next",            cyclews,        {.id = SWM_ARG_ID_CYCLEWS_UP} },
3508         { "ws_prev",            cyclews,        {.id = SWM_ARG_ID_CYCLEWS_DOWN} },
3509         { "ws_prior",           priorws,        {0} },
3510         { "screen_next",        cyclescr,       {.id = SWM_ARG_ID_CYCLESC_UP} },
3511         { "screen_prev",        cyclescr,       {.id = SWM_ARG_ID_CYCLESC_DOWN} },
3512         { "mvws_1",             send_to_ws,     {.id = 0} },
3513         { "mvws_2",             send_to_ws,     {.id = 1} },
3514         { "mvws_3",             send_to_ws,     {.id = 2} },
3515         { "mvws_4",             send_to_ws,     {.id = 3} },
3516         { "mvws_5",             send_to_ws,     {.id = 4} },
3517         { "mvws_6",             send_to_ws,     {.id = 5} },
3518         { "mvws_7",             send_to_ws,     {.id = 6} },
3519         { "mvws_8",             send_to_ws,     {.id = 7} },
3520         { "mvws_9",             send_to_ws,     {.id = 8} },
3521         { "mvws_10",            send_to_ws,     {.id = 9} },
3522         { "bar_toggle",         bar_toggle,     {0} },
3523         { "wind_kill",          wkill,          {.id = SWM_ARG_ID_KILLWINDOW} },
3524         { "wind_del",           wkill,          {.id = SWM_ARG_ID_DELETEWINDOW} },
3525         { "screenshot_all",     legacyfunc,     {0} },
3526         { "screenshot_wind",    legacyfunc,     {0} },
3527         { "float_toggle",       floating_toggle,{0} },
3528         { "version",            version,        {0} },
3529         { "spawn_lock",         legacyfunc,     {0} },
3530         { "spawn_initscr",      legacyfunc,     {0} },
3531         { "spawn_custom",       dummykeyfunc,   {0} },
3532         { "iconify",            iconify,        {0} },
3533         { "uniconify",          uniconify,      {0} },
3534         { "dumpwins",           dumpwins,       {0} }, /* MUST BE LAST */
3535         { "invalid key func",   NULL,           {0} },
3536 };
3537 struct key {
3538         unsigned int            mod;
3539         KeySym                  keysym;
3540         enum keyfuncid          funcid;
3541         char                    *spawn_name;
3542 };
3543 int                             keys_size = 0, keys_length = 0;
3544 struct key                      *keys = NULL;
3545
3546 /* mouse */
3547 enum { client_click, root_click };
3548 struct button {
3549         unsigned int            action;
3550         unsigned int            mask;
3551         unsigned int            button;
3552         void                    (*func)(struct ws_win *, union arg *);
3553         union arg               args;
3554 } buttons[] = {
3555           /* action     key             mouse button    func    args */
3556         { client_click, MODKEY,         Button3,        resize, {.id = SWM_ARG_ID_DONTCENTER} },
3557         { client_click, MODKEY | ShiftMask, Button3,    resize, {.id = SWM_ARG_ID_CENTER} },
3558         { client_click, MODKEY,         Button1,        move,   {0} },
3559 };
3560
3561 void
3562 update_modkey(unsigned int mod)
3563 {
3564         int                     i;
3565
3566         mod_key = mod;
3567         for (i = 0; i < keys_length; i++)
3568                 if (keys[i].mod & ShiftMask)
3569                         keys[i].mod = mod | ShiftMask;
3570                 else
3571                         keys[i].mod = mod;
3572
3573         for (i = 0; i < LENGTH(buttons); i++)
3574                 if (buttons[i].mask & ShiftMask)
3575                         buttons[i].mask = mod | ShiftMask;
3576                 else
3577                         buttons[i].mask = mod;
3578 }
3579
3580 /* spawn */
3581 struct spawn_prog {
3582         char                    *name;
3583         int                     argc;
3584         char                    **argv;
3585 };
3586
3587 int                             spawns_size = 0, spawns_length = 0;
3588 struct spawn_prog               *spawns = NULL;
3589
3590 int
3591 spawn_expand(struct swm_region *r, union arg *args, char *spawn_name,
3592     char ***ret_args)
3593 {
3594         struct spawn_prog       *prog = NULL;
3595         int                     i;
3596         char                    *ap, **real_args;
3597
3598         DNPRINTF(SWM_D_SPAWN, "spawn_expand %s\n", spawn_name);
3599
3600         /* find program */
3601         for (i = 0; i < spawns_length; i++) {
3602                 if (!strcasecmp(spawn_name, spawns[i].name))
3603                         prog = &spawns[i];
3604         }
3605         if (prog == NULL) {
3606                 fprintf(stderr, "spawn_custom: program %s not found\n",
3607                     spawn_name);
3608                 return (-1);
3609         }
3610
3611         /* make room for expanded args */
3612         if ((real_args = calloc(prog->argc + 1, sizeof(char *))) == NULL)
3613                 err(1, "spawn_custom: calloc real_args");
3614
3615         /* expand spawn_args into real_args */
3616         for (i = 0; i < prog->argc; i++) {
3617                 ap = prog->argv[i];
3618                 DNPRINTF(SWM_D_SPAWN, "spawn_custom: raw arg = %s\n", ap);
3619                 if (!strcasecmp(ap, "$bar_border")) {
3620                         if ((real_args[i] =
3621                             strdup(r->s->c[SWM_S_COLOR_BAR_BORDER].name))
3622                             == NULL)
3623                                 err(1,  "spawn_custom border color");
3624                 } else if (!strcasecmp(ap, "$bar_color")) {
3625                         if ((real_args[i] =
3626                             strdup(r->s->c[SWM_S_COLOR_BAR].name))
3627                             == NULL)
3628                                 err(1, "spawn_custom bar color");
3629                 } else if (!strcasecmp(ap, "$bar_font")) {
3630                         if ((real_args[i] = strdup(bar_fonts[bar_fidx]))
3631                             == NULL)
3632                                 err(1, "spawn_custom bar fonts");
3633                 } else if (!strcasecmp(ap, "$bar_font_color")) {
3634                         if ((real_args[i] =
3635                             strdup(r->s->c[SWM_S_COLOR_BAR_FONT].name))
3636                             == NULL)
3637                                 err(1, "spawn_custom color font");
3638                 } else if (!strcasecmp(ap, "$color_focus")) {
3639                         if ((real_args[i] =
3640                             strdup(r->s->c[SWM_S_COLOR_FOCUS].name))
3641                             == NULL)
3642                                 err(1, "spawn_custom color focus");
3643                 } else if (!strcasecmp(ap, "$color_unfocus")) {
3644                         if ((real_args[i] =
3645                             strdup(r->s->c[SWM_S_COLOR_UNFOCUS].name))
3646                             == NULL)
3647                                 err(1, "spawn_custom color unfocus");
3648                 } else {
3649                         /* no match --> copy as is */
3650                         if ((real_args[i] = strdup(ap)) == NULL)
3651                                 err(1, "spawn_custom strdup(ap)");
3652                 }
3653                 DNPRINTF(SWM_D_SPAWN, "spawn_custom: cooked arg = %s\n",
3654                     real_args[i]);
3655         }
3656
3657 #ifdef SWM_DEBUG
3658         if ((swm_debug & SWM_D_SPAWN) != 0) {
3659                 fprintf(stderr, "spawn_custom: result = ");
3660                 for (i = 0; i < prog->argc; i++)
3661                         fprintf(stderr, "\"%s\" ", real_args[i]);
3662                 fprintf(stderr, "\n");
3663         }
3664 #endif
3665         *ret_args = real_args;
3666         return (prog->argc);
3667 }
3668
3669 void
3670 spawn_custom(struct swm_region *r, union arg *args, char *spawn_name)
3671 {
3672         union arg               a;
3673         char                    **real_args;
3674         int                     spawn_argc, i;
3675
3676         if ((spawn_argc = spawn_expand(r, args, spawn_name, &real_args)) < 0)
3677                 return;
3678         a.argv = real_args;
3679         if (fork() == 0)
3680                 spawn(r, &a, 1);
3681
3682         for (i = 0; i < spawn_argc; i++)
3683                 free(real_args[i]);
3684         free(real_args);
3685 }
3686
3687 void
3688 spawn_select(struct swm_region *r, union arg *args, char *spawn_name, int *pid)
3689 {
3690         union arg               a;
3691         char                    **real_args;
3692         int                     i, spawn_argc;
3693
3694         if ((spawn_argc = spawn_expand(r, args, spawn_name, &real_args)) < 0)
3695                 return;
3696         a.argv = real_args;
3697
3698         if (pipe(select_list_pipe) == -1)
3699                 err(1, "pipe error");
3700         if (pipe(select_resp_pipe) == -1)
3701                 err(1, "pipe error");
3702
3703         if (signal(SIGPIPE, SIG_IGN) == SIG_ERR)
3704                 err(1, "could not disable SIGPIPE");
3705         switch (*pid = fork()) {
3706         case -1:
3707                 err(1, "cannot fork");
3708                 break;
3709         case 0: /* child */
3710                 if (dup2(select_list_pipe[0], 0) == -1)
3711                         errx(1, "dup2");
3712                 if (dup2(select_resp_pipe[1], 1) == -1)
3713                         errx(1, "dup2");
3714                 close(select_list_pipe[1]);
3715                 close(select_resp_pipe[0]);
3716                 spawn(r, &a, 0);
3717                 break;
3718         default: /* parent */
3719                 close(select_list_pipe[0]);
3720                 close(select_resp_pipe[1]);
3721                 break;
3722         }
3723
3724         for (i = 0; i < spawn_argc; i++)
3725                 free(real_args[i]);
3726         free(real_args);
3727 }
3728
3729 void
3730 setspawn(struct spawn_prog *prog)
3731 {
3732         int                     i, j;
3733
3734         if (prog == NULL || prog->name == NULL)
3735                 return;
3736
3737         /* find existing */
3738         for (i = 0; i < spawns_length; i++) {
3739                 if (!strcmp(spawns[i].name, prog->name)) {
3740                         /* found */
3741                         if (prog->argv == NULL) {
3742                                 /* delete */
3743                                 DNPRINTF(SWM_D_SPAWN,
3744                                     "setspawn: delete #%d %s\n",
3745                                     i, spawns[i].name);
3746                                 free(spawns[i].name);
3747                                 for (j = 0; j < spawns[i].argc; j++)
3748                                         free(spawns[i].argv[j]);
3749                                 free(spawns[i].argv);
3750                                 j = spawns_length - 1;
3751                                 if (i < j)
3752                                         spawns[i] = spawns[j];
3753                                 spawns_length--;
3754                                 free(prog->name);
3755                         } else {
3756                                 /* replace */
3757                                 DNPRINTF(SWM_D_SPAWN,
3758                                     "setspawn: replace #%d %s\n",
3759                                     i, spawns[i].name);
3760                                 free(spawns[i].name);
3761                                 for (j = 0; j < spawns[i].argc; j++)
3762                                         free(spawns[i].argv[j]);
3763                                 free(spawns[i].argv);
3764                                 spawns[i] = *prog;
3765                         }
3766                         /* found case handled */
3767                         free(prog);
3768                         return;
3769                 }
3770         }
3771
3772         if (prog->argv == NULL) {
3773                 fprintf(stderr,
3774                     "error: setspawn: cannot find program %s", prog->name);
3775                 free(prog);
3776                 return;
3777         }
3778
3779         /* not found: add */
3780         if (spawns_size == 0 || spawns == NULL) {
3781                 spawns_size = 4;
3782                 DNPRINTF(SWM_D_SPAWN, "setspawn: init list %d\n", spawns_size);
3783                 spawns = malloc((size_t)spawns_size *
3784                     sizeof(struct spawn_prog));
3785                 if (spawns == NULL) {
3786                         fprintf(stderr, "setspawn: malloc failed\n");
3787                         perror(" failed");
3788                         quit(NULL, NULL);
3789                 }
3790         } else if (spawns_length == spawns_size) {
3791                 spawns_size *= 2;
3792                 DNPRINTF(SWM_D_SPAWN, "setspawn: grow list %d\n", spawns_size);
3793                 spawns = realloc(spawns, (size_t)spawns_size *
3794                     sizeof(struct spawn_prog));
3795                 if (spawns == NULL) {
3796                         fprintf(stderr, "setspawn: realloc failed\n");
3797                         perror(" failed");
3798                         quit(NULL, NULL);
3799                 }
3800         }
3801
3802         if (spawns_length < spawns_size) {
3803                 DNPRINTF(SWM_D_SPAWN, "setspawn: add #%d %s\n",
3804                     spawns_length, prog->name);
3805                 i = spawns_length++;
3806                 spawns[i] = *prog;
3807         } else {
3808                 fprintf(stderr, "spawns array problem?\n");
3809                 if (spawns == NULL) {
3810                         fprintf(stderr, "spawns array is NULL!\n");
3811                         quit(NULL, NULL);
3812                 }
3813         }
3814         free(prog);
3815 }
3816
3817 int
3818 setconfspawn(char *selector, char *value, int flags)
3819 {
3820         struct spawn_prog       *prog;
3821         char                    *vp, *cp, *word;
3822
3823         DNPRINTF(SWM_D_SPAWN, "setconfspawn: [%s] [%s]\n", selector, value);
3824         if ((prog = calloc(1, sizeof *prog)) == NULL)
3825                 err(1, "setconfspawn: calloc prog");
3826         prog->name = strdup(selector);
3827         if (prog->name == NULL)
3828                 err(1, "setconfspawn prog->name");
3829         if ((cp = vp = strdup(value)) == NULL)
3830                 err(1, "setconfspawn: strdup(value) ");
3831         while ((word = strsep(&cp, " \t")) != NULL) {
3832                 DNPRINTF(SWM_D_SPAWN, "setconfspawn: arg [%s]\n", word);
3833                 if (cp)
3834                         cp += (long)strspn(cp, " \t");
3835                 if (strlen(word) > 0) {
3836                         prog->argc++;
3837                         prog->argv = realloc(prog->argv,
3838                             prog->argc * sizeof(char *));
3839                         if ((prog->argv[prog->argc - 1] = strdup(word)) == NULL)
3840                                 err(1, "setconfspawn: strdup");
3841                 }
3842         }
3843         free(vp);
3844
3845         setspawn(prog);
3846
3847         DNPRINTF(SWM_D_SPAWN, "setconfspawn: done\n");
3848         return (0);
3849 }
3850
3851 void
3852 setup_spawn(void)
3853 {
3854         setconfspawn("term",            "xterm",                0);
3855         setconfspawn("screenshot_all",  "screenshot.sh full",   0);
3856         setconfspawn("screenshot_wind", "screenshot.sh window", 0);
3857         setconfspawn("lock",            "xlock",                0);
3858         setconfspawn("initscr",         "initscreen.sh",        0);
3859         setconfspawn("menu",            "dmenu_run"
3860                                         " -fn $bar_font"
3861                                         " -nb $bar_color"
3862                                         " -nf $bar_font_color"
3863                                         " -sb $bar_border"
3864                                         " -sf $bar_color",      0);
3865         setconfspawn("uniconify",       "dmenu"
3866                                         " -i"
3867                                         " -fn $bar_font"
3868                                         " -nb $bar_color"
3869                                         " -nf $bar_font_color"
3870                                         " -sb $bar_border"
3871                                         " -sf $bar_color",      0);
3872 }
3873
3874 /* key bindings */
3875 #define SWM_MODNAME_SIZE        32
3876 #define SWM_KEY_WS              "\n+ \t"
3877 int
3878 parsekeys(char *keystr, unsigned int currmod, unsigned int *mod, KeySym *ks)
3879 {
3880         char                    *cp, *name;
3881         KeySym                  uks;
3882         DNPRINTF(SWM_D_KEY, "parsekeys: enter [%s]\n", keystr);
3883         if (mod == NULL || ks == NULL) {
3884                 DNPRINTF(SWM_D_KEY, "parsekeys: no mod or key vars\n");
3885                 return (1);
3886         }
3887         if (keystr == NULL || strlen(keystr) == 0) {
3888                 DNPRINTF(SWM_D_KEY, "parsekeys: no keystr\n");
3889                 return (1);
3890         }
3891         cp = keystr;
3892         *ks = NoSymbol;
3893         *mod = 0;
3894         while ((name = strsep(&cp, SWM_KEY_WS)) != NULL) {
3895                 DNPRINTF(SWM_D_KEY, "parsekeys: key [%s]\n", name);
3896                 if (cp)
3897                         cp += (long)strspn(cp, SWM_KEY_WS);
3898                 if (strncasecmp(name, "MOD", SWM_MODNAME_SIZE) == 0)
3899                         *mod |= currmod;
3900                 else if (!strncasecmp(name, "Mod1", SWM_MODNAME_SIZE))
3901                         *mod |= Mod1Mask;
3902                 else if (!strncasecmp(name, "Mod2", SWM_MODNAME_SIZE))
3903                         *mod += Mod2Mask;
3904                 else if (!strncmp(name, "Mod3", SWM_MODNAME_SIZE))
3905                         *mod |= Mod3Mask;
3906                 else if (!strncmp(name, "Mod4", SWM_MODNAME_SIZE))
3907                         *mod |= Mod4Mask;
3908                 else if (strncasecmp(name, "SHIFT", SWM_MODNAME_SIZE) == 0)
3909                         *mod |= ShiftMask;
3910                 else if (strncasecmp(name, "CONTROL", SWM_MODNAME_SIZE) == 0)
3911                         *mod |= ControlMask;
3912                 else {
3913                         *ks = XStringToKeysym(name);
3914                         XConvertCase(*ks, ks, &uks);
3915                         if (ks == NoSymbol) {
3916                                 DNPRINTF(SWM_D_KEY,
3917                                     "parsekeys: invalid key %s\n",
3918                                     name);
3919                                 return (1);
3920                         }
3921                 }
3922         }
3923         DNPRINTF(SWM_D_KEY, "parsekeys: leave ok\n");
3924         return (0);
3925 }
3926
3927 char *
3928 strdupsafe(char *str)
3929 {
3930         if (str == NULL)
3931                 return (NULL);
3932         else
3933                 return (strdup(str));
3934 }
3935
3936 void
3937 setkeybinding(unsigned int mod, KeySym ks, enum keyfuncid kfid,
3938     char *spawn_name)
3939 {
3940         int                     i, j;
3941         DNPRINTF(SWM_D_KEY, "setkeybinding: enter %s [%s]\n",
3942             keyfuncs[kfid].name, spawn_name);
3943         /* find existing */
3944         for (i = 0; i < keys_length; i++) {
3945                 if (keys[i].mod == mod && keys[i].keysym == ks) {
3946                         if (kfid == kf_invalid) {
3947                                 /* found: delete */
3948                                 DNPRINTF(SWM_D_KEY,
3949                                     "setkeybinding: delete #%d %s\n",
3950                                     i, keyfuncs[keys[i].funcid].name);
3951                                 free(keys[i].spawn_name);
3952                                 j = keys_length - 1;
3953                                 if (i < j)
3954                                         keys[i] = keys[j];
3955                                 keys_length--;
3956                                 DNPRINTF(SWM_D_KEY, "setkeybinding: leave\n");
3957                                 return;
3958                         } else {
3959                                 /* found: replace */
3960                                 DNPRINTF(SWM_D_KEY,
3961                                     "setkeybinding: replace #%d %s %s\n",
3962                                     i, keyfuncs[keys[i].funcid].name,
3963                                     spawn_name);
3964                                 free(keys[i].spawn_name);
3965                                 keys[i].mod = mod;
3966                                 keys[i].keysym = ks;
3967                                 keys[i].funcid = kfid;
3968                                 keys[i].spawn_name = strdupsafe(spawn_name);
3969                                 DNPRINTF(SWM_D_KEY, "setkeybinding: leave\n");
3970                                 return;
3971                         }
3972                 }
3973         }
3974         if (kfid == kf_invalid) {
3975                 fprintf(stderr,
3976                     "error: setkeybinding: cannot find mod/key combination");
3977                 DNPRINTF(SWM_D_KEY, "setkeybinding: leave\n");
3978                 return;
3979         }
3980         /* not found: add */
3981         if (keys_size == 0 || keys == NULL) {
3982                 keys_size = 4;
3983                 DNPRINTF(SWM_D_KEY, "setkeybinding: init list %d\n", keys_size);
3984                 keys = malloc((size_t)keys_size * sizeof(struct key));
3985                 if (!keys) {
3986                         fprintf(stderr, "malloc failed\n");
3987                         perror(" failed");
3988                         quit(NULL, NULL);
3989                 }
3990         } else if (keys_length == keys_size) {
3991                 keys_size *= 2;
3992                 DNPRINTF(SWM_D_KEY, "setkeybinding: grow list %d\n", keys_size);
3993                 keys = realloc(keys, (size_t)keys_size * sizeof(struct key));
3994                 if (!keys) {
3995                         fprintf(stderr, "realloc failed\n");
3996                         perror(" failed");
3997                         quit(NULL, NULL);
3998                 }
3999         }
4000         if (keys_length < keys_size) {
4001                 j = keys_length++;
4002                 DNPRINTF(SWM_D_KEY, "setkeybinding: add #%d %s %s\n",
4003                     j, keyfuncs[kfid].name, spawn_name);
4004                 keys[j].mod = mod;
4005                 keys[j].keysym = ks;
4006                 keys[j].funcid = kfid;
4007                 keys[j].spawn_name = strdupsafe(spawn_name);
4008         } else {
4009                 fprintf(stderr, "keys array problem?\n");
4010                 if (!keys) {
4011                         fprintf(stderr, "keys array problem\n");
4012                         quit(NULL, NULL);
4013                 }
4014         }
4015         DNPRINTF(SWM_D_KEY, "setkeybinding: leave\n");
4016 }
4017
4018 int
4019 setconfbinding(char *selector, char *value, int flags)
4020 {
4021         enum keyfuncid          kfid;
4022         unsigned int            mod;
4023         KeySym                  ks;
4024         int                     i;
4025         DNPRINTF(SWM_D_KEY, "setconfbinding: enter\n");
4026         if (selector == NULL) {
4027                 DNPRINTF(SWM_D_KEY, "setconfbinding: unbind %s\n", value);
4028                 if (parsekeys(value, mod_key, &mod, &ks) == 0) {
4029                         kfid = kf_invalid;
4030                         setkeybinding(mod, ks, kfid, NULL);
4031                         return (0);
4032                 } else
4033                         return (1);
4034         }
4035         /* search by key function name */
4036         for (kfid = 0; kfid < kf_invalid; (kfid)++) {
4037                 if (strncasecmp(selector, keyfuncs[kfid].name,
4038                     SWM_FUNCNAME_LEN) == 0) {
4039                         DNPRINTF(SWM_D_KEY, "setconfbinding: %s: match\n",
4040                             selector);
4041                         if (parsekeys(value, mod_key, &mod, &ks) == 0) {
4042                                 setkeybinding(mod, ks, kfid, NULL);
4043                                 return (0);
4044                         } else
4045                                 return (1);
4046                 }
4047         }
4048         /* search by custom spawn name */
4049         for (i = 0; i < spawns_length; i++) {
4050                 if (strcasecmp(selector, spawns[i].name) == 0) {
4051                         DNPRINTF(SWM_D_KEY, "setconfbinding: %s: match\n",
4052                             selector);
4053                         if (parsekeys(value, mod_key, &mod, &ks) == 0) {
4054                                 setkeybinding(mod, ks, kf_spawn_custom,
4055                                     spawns[i].name);
4056                                 return (0);
4057                         } else
4058                                 return (1);
4059                 }
4060         }
4061         DNPRINTF(SWM_D_KEY, "setconfbinding: no match\n");
4062         return (1);
4063 }
4064
4065 void
4066 setup_keys(void)
4067 {
4068         setkeybinding(MODKEY,           XK_space,       kf_cycle_layout,NULL);
4069         setkeybinding(MODKEY|ShiftMask, XK_space,       kf_stack_reset, NULL);
4070         setkeybinding(MODKEY,           XK_h,           kf_master_shrink,NULL);
4071         setkeybinding(MODKEY,           XK_l,           kf_master_grow, NULL);
4072         setkeybinding(MODKEY,           XK_comma,       kf_master_add,  NULL);
4073         setkeybinding(MODKEY,           XK_period,      kf_master_del,  NULL);
4074         setkeybinding(MODKEY|ShiftMask, XK_comma,       kf_stack_inc,   NULL);
4075         setkeybinding(MODKEY|ShiftMask, XK_period,      kf_stack_dec,   NULL);
4076         setkeybinding(MODKEY,           XK_Return,      kf_swap_main,   NULL);
4077         setkeybinding(MODKEY,           XK_j,           kf_focus_next,  NULL);
4078         setkeybinding(MODKEY,           XK_k,           kf_focus_prev,  NULL);
4079         setkeybinding(MODKEY|ShiftMask, XK_j,           kf_swap_next,   NULL);
4080         setkeybinding(MODKEY|ShiftMask, XK_k,           kf_swap_prev,   NULL);
4081         setkeybinding(MODKEY|ShiftMask, XK_Return,      kf_spawn_term,  NULL);
4082         setkeybinding(MODKEY,           XK_p,           kf_spawn_custom,        "menu");
4083         setkeybinding(MODKEY|ShiftMask, XK_q,           kf_quit,        NULL);
4084         setkeybinding(MODKEY,           XK_q,           kf_restart,     NULL);
4085         setkeybinding(MODKEY,           XK_m,           kf_focus_main,  NULL);
4086         setkeybinding(MODKEY,           XK_1,           kf_ws_1,        NULL);
4087         setkeybinding(MODKEY,           XK_2,           kf_ws_2,        NULL);
4088         setkeybinding(MODKEY,           XK_3,           kf_ws_3,        NULL);
4089         setkeybinding(MODKEY,           XK_4,           kf_ws_4,        NULL);
4090         setkeybinding(MODKEY,           XK_5,           kf_ws_5,        NULL);
4091         setkeybinding(MODKEY,           XK_6,           kf_ws_6,        NULL);
4092         setkeybinding(MODKEY,           XK_7,           kf_ws_7,        NULL);
4093         setkeybinding(MODKEY,           XK_8,           kf_ws_8,        NULL);
4094         setkeybinding(MODKEY,           XK_9,           kf_ws_9,        NULL);
4095         setkeybinding(MODKEY,           XK_0,           kf_ws_10,       NULL);
4096         setkeybinding(MODKEY,           XK_Right,       kf_ws_next,     NULL);
4097         setkeybinding(MODKEY,           XK_Left,        kf_ws_prev,     NULL);
4098         setkeybinding(MODKEY,           XK_a,           kf_ws_prior,    NULL);
4099         setkeybinding(MODKEY|ShiftMask, XK_Right,       kf_screen_next, NULL);
4100         setkeybinding(MODKEY|ShiftMask, XK_Left,        kf_screen_prev, NULL);
4101         setkeybinding(MODKEY|ShiftMask, XK_1,           kf_mvws_1,      NULL);
4102         setkeybinding(MODKEY|ShiftMask, XK_2,           kf_mvws_2,      NULL);
4103         setkeybinding(MODKEY|ShiftMask, XK_3,           kf_mvws_3,      NULL);
4104         setkeybinding(MODKEY|ShiftMask, XK_4,           kf_mvws_4,      NULL);
4105         setkeybinding(MODKEY|ShiftMask, XK_5,           kf_mvws_5,      NULL);
4106         setkeybinding(MODKEY|ShiftMask, XK_6,           kf_mvws_6,      NULL);
4107         setkeybinding(MODKEY|ShiftMask, XK_7,           kf_mvws_7,      NULL);
4108         setkeybinding(MODKEY|ShiftMask, XK_8,           kf_mvws_8,      NULL);
4109         setkeybinding(MODKEY|ShiftMask, XK_9,           kf_mvws_9,      NULL);
4110         setkeybinding(MODKEY|ShiftMask, XK_0,           kf_mvws_10,     NULL);
4111         setkeybinding(MODKEY,           XK_b,           kf_bar_toggle,  NULL);
4112         setkeybinding(MODKEY,           XK_Tab,         kf_focus_next,  NULL);
4113         setkeybinding(MODKEY|ShiftMask, XK_Tab,         kf_focus_prev,  NULL);
4114         setkeybinding(MODKEY|ShiftMask, XK_x,           kf_wind_kill,   NULL);
4115         setkeybinding(MODKEY,           XK_x,           kf_wind_del,    NULL);
4116         setkeybinding(MODKEY,           XK_s,           kf_spawn_custom,        "screenshot_all");
4117         setkeybinding(MODKEY|ShiftMask, XK_s,           kf_spawn_custom,        "screenshot_wind");
4118         setkeybinding(MODKEY,           XK_t,           kf_float_toggle,NULL);
4119         setkeybinding(MODKEY|ShiftMask, XK_v,           kf_version,     NULL);
4120         setkeybinding(MODKEY|ShiftMask, XK_Delete,      kf_spawn_custom,        "lock");
4121         setkeybinding(MODKEY|ShiftMask, XK_i,           kf_spawn_custom,        "initscr");
4122         setkeybinding(MODKEY,           XK_w,           kf_iconify,     NULL);
4123         setkeybinding(MODKEY|ShiftMask, XK_w,           kf_uniconify,   NULL);
4124 #ifdef SWM_DEBUG
4125         setkeybinding(MODKEY|ShiftMask, XK_d,           kf_dumpwins,    NULL);
4126 #endif
4127 }
4128
4129 void
4130 updatenumlockmask(void)
4131 {
4132         unsigned int            i, j;
4133         XModifierKeymap         *modmap;
4134
4135         DNPRINTF(SWM_D_MISC, "updatenumlockmask\n");
4136         numlockmask = 0;
4137         modmap = XGetModifierMapping(display);
4138         for (i = 0; i < 8; i++)
4139                 for (j = 0; j < modmap->max_keypermod; j++)
4140                         if (modmap->modifiermap[i * modmap->max_keypermod + j]
4141                             == XKeysymToKeycode(display, XK_Num_Lock))
4142                                 numlockmask = (1 << i);
4143
4144         XFreeModifiermap(modmap);
4145 }
4146
4147 void
4148 grabkeys(void)
4149 {
4150         unsigned int            i, j, k;
4151         KeyCode                 code;
4152         unsigned int            modifiers[] =
4153             { 0, LockMask, numlockmask, numlockmask | LockMask };
4154
4155         DNPRINTF(SWM_D_MISC, "grabkeys\n");
4156         updatenumlockmask();
4157
4158         for (k = 0; k < ScreenCount(display); k++) {
4159                 if (TAILQ_EMPTY(&screens[k].rl))
4160                         continue;
4161                 XUngrabKey(display, AnyKey, AnyModifier, screens[k].root);
4162                 for (i = 0; i < keys_length; i++) {
4163                         if ((code = XKeysymToKeycode(display, keys[i].keysym)))
4164                                 for (j = 0; j < LENGTH(modifiers); j++)
4165                                         XGrabKey(display, code,
4166                                             keys[i].mod | modifiers[j],
4167                                             screens[k].root, True,
4168                                             GrabModeAsync, GrabModeAsync);
4169                 }
4170         }
4171 }
4172
4173 void
4174 grabbuttons(struct ws_win *win, int focused)
4175 {
4176         unsigned int            i, j;
4177         unsigned int            modifiers[] =
4178             { 0, LockMask, numlockmask, numlockmask|LockMask };
4179
4180         updatenumlockmask();
4181         XUngrabButton(display, AnyButton, AnyModifier, win->id);
4182         if (focused) {
4183                 for (i = 0; i < LENGTH(buttons); i++)
4184                         if (buttons[i].action == client_click)
4185                                 for (j = 0; j < LENGTH(modifiers); j++)
4186                                         XGrabButton(display, buttons[i].button,
4187                                             buttons[i].mask | modifiers[j],
4188                                             win->id, False, BUTTONMASK,
4189                                             GrabModeAsync, GrabModeSync, None,
4190                                             None);
4191         } else
4192                 XGrabButton(display, AnyButton, AnyModifier, win->id, False,
4193                     BUTTONMASK, GrabModeAsync, GrabModeSync, None, None);
4194 }
4195
4196 const char *quirkname[] = {
4197         "NONE",         /* config string for "no value" */
4198         "FLOAT",
4199         "TRANSSZ",
4200         "ANYWHERE",
4201         "XTERM_FONTADJ",
4202         "FULLSCREEN",
4203         "FOCUSPREV",
4204 };
4205
4206 /* SWM_Q_WS: retain '|' for back compat for now (2009-08-11) */
4207 #define SWM_Q_WS                "\n|+ \t"
4208 int
4209 parsequirks(char *qstr, unsigned long *quirk)
4210 {
4211         char                    *cp, *name;
4212         int                     i;
4213
4214         if (quirk == NULL)
4215                 return (1);
4216
4217         cp = qstr;
4218         *quirk = 0;
4219         while ((name = strsep(&cp, SWM_Q_WS)) != NULL) {
4220                 if (cp)
4221                         cp += (long)strspn(cp, SWM_Q_WS);
4222                 for (i = 0; i < LENGTH(quirkname); i++) {
4223                         if (!strncasecmp(name, quirkname[i], SWM_QUIRK_LEN)) {
4224                                 DNPRINTF(SWM_D_QUIRK,
4225                                     "parsequirks: %s\n", name);
4226                                 if (i == 0) {
4227                                         *quirk = 0;
4228                                         return (0);
4229                                 }
4230                                 *quirk |= 1 << (i-1);
4231                                 break;
4232                         }
4233                 }
4234                 if (i >= LENGTH(quirkname)) {
4235                         DNPRINTF(SWM_D_QUIRK,
4236                             "parsequirks: invalid quirk [%s]\n", name);
4237                         return (1);
4238                 }
4239         }
4240         return (0);
4241 }
4242
4243 void
4244 setquirk(const char *class, const char *name, const int quirk)
4245 {
4246         int                     i, j;
4247
4248         /* find existing */
4249         for (i = 0; i < quirks_length; i++) {
4250                 if (!strcmp(quirks[i].class, class) &&
4251                     !strcmp(quirks[i].name, name)) {
4252                         if (!quirk) {
4253                                 /* found: delete */
4254                                 DNPRINTF(SWM_D_QUIRK,
4255                                     "setquirk: delete #%d %s:%s\n",
4256                                     i, quirks[i].class, quirks[i].name);
4257                                 free(quirks[i].class);
4258                                 free(quirks[i].name);
4259                                 j = quirks_length - 1;
4260                                 if (i < j)
4261                                         quirks[i] = quirks[j];
4262                                 quirks_length--;
4263                                 return;
4264                         } else {
4265                                 /* found: replace */
4266                                 DNPRINTF(SWM_D_QUIRK,
4267                                     "setquirk: replace #%d %s:%s\n",
4268                                     i, quirks[i].class, quirks[i].name);
4269                                 free(quirks[i].class);
4270                                 free(quirks[i].name);
4271                                 quirks[i].class = strdup(class);
4272                                 quirks[i].name = strdup(name);
4273                                 quirks[i].quirk = quirk;
4274                                 return;
4275                         }
4276                 }
4277         }
4278         if (!quirk) {
4279                 fprintf(stderr,
4280                     "error: setquirk: cannot find class/name combination");
4281                 return;
4282         }
4283         /* not found: add */
4284         if (quirks_size == 0 || quirks == NULL) {
4285                 quirks_size = 4;
4286                 DNPRINTF(SWM_D_QUIRK, "setquirk: init list %d\n", quirks_size);
4287                 quirks = malloc((size_t)quirks_size * sizeof(struct quirk));
4288                 if (!quirks) {
4289                         fprintf(stderr, "setquirk: malloc failed\n");
4290                         perror(" failed");
4291                         quit(NULL, NULL);
4292                 }
4293         } else if (quirks_length == quirks_size) {
4294                 quirks_size *= 2;
4295                 DNPRINTF(SWM_D_QUIRK, "setquirk: grow list %d\n", quirks_size);
4296                 quirks = realloc(quirks,
4297                     (size_t)quirks_size * sizeof(struct quirk));
4298                 if (!quirks) {
4299                         fprintf(stderr, "setquirk: realloc failed\n");
4300                         perror(" failed");
4301                         quit(NULL, NULL);
4302                 }
4303         }
4304         if (quirks_length < quirks_size) {
4305                 DNPRINTF(SWM_D_QUIRK, "setquirk: add %d\n", quirks_length);
4306                 j = quirks_length++;
4307                 quirks[j].class = strdup(class);
4308                 quirks[j].name = strdup(name);
4309                 quirks[j].quirk = quirk;
4310         } else {
4311                 fprintf(stderr, "quirks array problem?\n");
4312                 if (!quirks) {
4313                         fprintf(stderr, "quirks array problem!\n");
4314                         quit(NULL, NULL);
4315                 }
4316         }
4317 }
4318
4319 int
4320 setconfquirk(char *selector, char *value, int flags)
4321 {
4322         char                    *cp, *class, *name;
4323         int                     retval;
4324         unsigned long           quirks;
4325         if (selector == NULL)
4326                 return (0);
4327         if ((cp = strchr(selector, ':')) == NULL)
4328                 return (0);
4329         *cp = '\0';
4330         class = selector;
4331         name = cp + 1;
4332         if ((retval = parsequirks(value, &quirks)) == 0)
4333                 setquirk(class, name, quirks);
4334         return (retval);
4335 }
4336
4337 void
4338 setup_quirks(void)
4339 {
4340         setquirk("MPlayer",             "xv",           SWM_Q_FLOAT | SWM_Q_FULLSCREEN | SWM_Q_FOCUSPREV);
4341         setquirk("OpenOffice.org 3.2",  "VCLSalFrame",  SWM_Q_FLOAT);
4342         setquirk("Firefox-bin",         "firefox-bin",  SWM_Q_TRANSSZ);
4343         setquirk("Firefox",             "Dialog",       SWM_Q_FLOAT);
4344         setquirk("Gimp",                "gimp",         SWM_Q_FLOAT | SWM_Q_ANYWHERE);
4345         setquirk("XTerm",               "xterm",        SWM_Q_XTERM_FONTADJ);
4346         setquirk("xine",                "Xine Window",  SWM_Q_FLOAT | SWM_Q_ANYWHERE);
4347         setquirk("Xitk",                "Xitk Combo",   SWM_Q_FLOAT | SWM_Q_ANYWHERE);
4348         setquirk("xine",                "xine Panel",   SWM_Q_FLOAT | SWM_Q_ANYWHERE);
4349         setquirk("Xitk",                "Xine Window",  SWM_Q_FLOAT | SWM_Q_ANYWHERE);
4350         setquirk("xine",                "xine Video Fullscreen Window", SWM_Q_FULLSCREEN | SWM_Q_FLOAT);
4351         setquirk("pcb",                 "pcb",          SWM_Q_FLOAT);
4352         setquirk("SDL_App",             "SDL_App",      SWM_Q_FLOAT | SWM_Q_FULLSCREEN);
4353 }
4354
4355 /* conf file stuff */
4356 #define SWM_CONF_FILE   "scrotwm.conf"
4357
4358 enum    { SWM_S_BAR_DELAY, SWM_S_BAR_ENABLED, SWM_S_BAR_BORDER_WIDTH,
4359           SWM_S_STACK_ENABLED, SWM_S_CLOCK_ENABLED, SWM_S_CLOCK_FORMAT,
4360           SWM_S_CYCLE_EMPTY, SWM_S_CYCLE_VISIBLE, SWM_S_SS_ENABLED,
4361           SWM_S_TERM_WIDTH, SWM_S_TITLE_CLASS_ENABLED,
4362           SWM_S_TITLE_NAME_ENABLED, SWM_S_WINDOW_NAME_ENABLED,
4363           SWM_S_FOCUS_MODE, SWM_S_DISABLE_BORDER, SWM_S_BORDER_WIDTH,
4364           SWM_S_BAR_FONT, SWM_S_BAR_ACTION, SWM_S_SPAWN_TERM,
4365           SWM_S_SS_APP, SWM_S_DIALOG_RATIO, SWM_S_BAR_AT_BOTTOM
4366         };
4367
4368 int
4369 setconfvalue(char *selector, char *value, int flags)
4370 {
4371         switch (flags) {
4372         case SWM_S_BAR_DELAY:
4373                 bar_delay = atoi(value);
4374                 break;
4375         case SWM_S_BAR_ENABLED:
4376                 bar_enabled = atoi(value);
4377                 break;
4378         case SWM_S_BAR_BORDER_WIDTH:
4379                 bar_border_width = atoi(value);
4380                 break;
4381         case SWM_S_BAR_AT_BOTTOM:
4382                 bar_at_bottom = atoi(value);
4383                 break;
4384         case SWM_S_STACK_ENABLED:
4385                 stack_enabled = atoi(value);
4386                 break;
4387         case SWM_S_CLOCK_ENABLED:
4388                 clock_enabled = atoi(value);
4389                 break;
4390         case SWM_S_CLOCK_FORMAT:
4391 #ifndef SWM_DENY_CLOCK_FORMAT
4392                 free(clock_format);
4393                 if ((clock_format = strdup(value)) == NULL)
4394                         err(1, "setconfvalue: clock_format");
4395 #endif
4396                 break;
4397         case SWM_S_CYCLE_EMPTY:
4398                 cycle_empty = atoi(value);
4399                 break;
4400         case SWM_S_CYCLE_VISIBLE:
4401                 cycle_visible = atoi(value);
4402                 break;
4403         case SWM_S_SS_ENABLED:
4404                 ss_enabled = atoi(value);
4405                 break;
4406         case SWM_S_TERM_WIDTH:
4407                 term_width = atoi(value);
4408                 break;
4409         case SWM_S_TITLE_CLASS_ENABLED:
4410                 title_class_enabled = atoi(value);
4411                 break;
4412         case SWM_S_WINDOW_NAME_ENABLED:
4413                 window_name_enabled = atoi(value);
4414                 break;
4415         case SWM_S_TITLE_NAME_ENABLED:
4416                 title_name_enabled = atoi(value);
4417                 break;
4418         case SWM_S_FOCUS_MODE:
4419                 if (!strcmp(value, "default"))
4420                         focus_mode = SWM_FOCUS_DEFAULT;
4421                 else if (!strcmp(value, "follow_cursor"))
4422                         focus_mode = SWM_FOCUS_FOLLOW;
4423                 else if (!strcmp(value, "synergy"))
4424                         focus_mode = SWM_FOCUS_SYNERGY;
4425                 else
4426                         err(1, "focus_mode");
4427                 break;
4428         case SWM_S_DISABLE_BORDER:
4429                 disable_border = atoi(value);
4430                 break;
4431         case SWM_S_BORDER_WIDTH:
4432                 border_width = atoi(value);
4433                 break;
4434         case SWM_S_BAR_FONT:
4435                 free(bar_fonts[0]);
4436                 if ((bar_fonts[0] = strdup(value)) == NULL)
4437                         err(1, "setconfvalue: bar_font");
4438                 break;
4439         case SWM_S_BAR_ACTION:
4440                 free(bar_argv[0]);
4441                 if ((bar_argv[0] = strdup(value)) == NULL)
4442                         err(1, "setconfvalue: bar_action");
4443                 break;
4444         case SWM_S_SPAWN_TERM:
4445                 free(spawn_term[0]);
4446                 if ((spawn_term[0] = strdup(value)) == NULL)
4447                         err(1, "setconfvalue: spawn_term");
4448                 break;
4449         case SWM_S_SS_APP:
4450                 break;
4451         case SWM_S_DIALOG_RATIO:
4452                 dialog_ratio = atof(value);
4453                 if (dialog_ratio > 1.0 || dialog_ratio <= .3)
4454                         dialog_ratio = .6;
4455                 break;
4456         default:
4457                 return (1);
4458         }
4459         return (0);
4460 }
4461
4462 int
4463 setconfmodkey(char *selector, char *value, int flags)
4464 {
4465         if (!strncasecmp(value, "Mod1", strlen("Mod1")))
4466                 update_modkey(Mod1Mask);
4467         else if (!strncasecmp(value, "Mod2", strlen("Mod2")))
4468                 update_modkey(Mod2Mask);
4469         else if (!strncasecmp(value, "Mod3", strlen("Mod3")))
4470                 update_modkey(Mod3Mask);
4471         else if (!strncasecmp(value, "Mod4", strlen("Mod4")))
4472                 update_modkey(Mod4Mask);
4473         else
4474                 return (1);
4475         return (0);
4476 }
4477
4478 int
4479 setconfcolor(char *selector, char *value, int flags)
4480 {
4481         setscreencolor(value, ((selector == NULL)?-1:atoi(selector)), flags);
4482         return (0);
4483 }
4484
4485 int
4486 setconfregion(char *selector, char *value, int flags)
4487 {
4488         custom_region(value);
4489         return (0);
4490 }
4491
4492 /* config options */
4493 struct config_option {
4494         char                    *optname;
4495         int (*func)(char*, char*, int);
4496         int funcflags;
4497 };
4498 struct config_option configopt[] = {
4499         { "bar_enabled",                setconfvalue,   SWM_S_BAR_ENABLED },
4500         { "bar_at_bottom",              setconfvalue,   SWM_S_BAR_AT_BOTTOM },
4501         { "bar_border",                 setconfcolor,   SWM_S_COLOR_BAR_BORDER },
4502         { "bar_border_width",                   setconfvalue,   SWM_S_BAR_BORDER_WIDTH },
4503         { "bar_color",                  setconfcolor,   SWM_S_COLOR_BAR },
4504         { "bar_font_color",             setconfcolor,   SWM_S_COLOR_BAR_FONT },
4505         { "bar_font",                   setconfvalue,   SWM_S_BAR_FONT },
4506         { "bar_action",                 setconfvalue,   SWM_S_BAR_ACTION },
4507         { "bar_delay",                  setconfvalue,   SWM_S_BAR_DELAY },
4508         { "bind",                       setconfbinding, 0 },
4509         { "stack_enabled",              setconfvalue,   SWM_S_STACK_ENABLED },
4510         { "clock_enabled",              setconfvalue,   SWM_S_CLOCK_ENABLED },
4511         { "clock_format",               setconfvalue,   SWM_S_CLOCK_FORMAT },
4512         { "color_focus",                setconfcolor,   SWM_S_COLOR_FOCUS },
4513         { "color_unfocus",              setconfcolor,   SWM_S_COLOR_UNFOCUS },
4514         { "cycle_empty",                setconfvalue,   SWM_S_CYCLE_EMPTY },
4515         { "cycle_visible",              setconfvalue,   SWM_S_CYCLE_VISIBLE },
4516         { "dialog_ratio",               setconfvalue,   SWM_S_DIALOG_RATIO },
4517         { "modkey",                     setconfmodkey,  0 },
4518         { "program",                    setconfspawn,   0 },
4519         { "quirk",                      setconfquirk,   0 },
4520         { "region",                     setconfregion,  0 },
4521         { "spawn_term",                 setconfvalue,   SWM_S_SPAWN_TERM },
4522         { "screenshot_enabled",         setconfvalue,   SWM_S_SS_ENABLED },
4523         { "screenshot_app",             setconfvalue,   SWM_S_SS_APP },
4524         { "window_name_enabled",        setconfvalue,   SWM_S_WINDOW_NAME_ENABLED },
4525         { "term_width",                 setconfvalue,   SWM_S_TERM_WIDTH },
4526         { "title_class_enabled",        setconfvalue,   SWM_S_TITLE_CLASS_ENABLED },
4527         { "title_name_enabled",         setconfvalue,   SWM_S_TITLE_NAME_ENABLED },
4528         { "focus_mode",                 setconfvalue,   SWM_S_FOCUS_MODE },
4529         { "disable_border",             setconfvalue,   SWM_S_DISABLE_BORDER },
4530         { "border_width",               setconfvalue,   SWM_S_BORDER_WIDTH },
4531 };
4532
4533
4534 int
4535 conf_load(char *filename)
4536 {
4537         FILE                    *config;
4538         char                    *line, *cp, *optsub, *optval;
4539         size_t                  linelen, lineno = 0;
4540         int                     wordlen, i, optind;
4541         struct config_option    *opt;
4542
4543         DNPRINTF(SWM_D_CONF, "conf_load begin\n");
4544
4545         if (filename == NULL) {
4546                 fprintf(stderr, "conf_load: no filename\n");
4547                 return (1);
4548         }
4549         if ((config = fopen(filename, "r")) == NULL) {
4550                 warn("conf_load: fopen");
4551                 return (1);
4552         }
4553
4554         while (!feof(config)) {
4555                 if ((line = fparseln(config, &linelen, &lineno, NULL, 0))
4556                     == NULL) {
4557                         if (ferror(config))
4558                                 err(1, "%s", filename);
4559                         else
4560                                 continue;
4561                 }
4562                 cp = line;
4563                 cp += strspn(cp, " \t\n"); /* eat whitespace */
4564                 if (cp[0] == '\0') {
4565                         /* empty line */
4566                         free(line);
4567                         continue;
4568                 }
4569                 /* get config option */
4570                 wordlen = strcspn(cp, "=[ \t\n");
4571                 if (wordlen == 0) {
4572                         warnx("%s: line %zd: no option found",
4573                             filename, lineno);
4574                         return (1);
4575                 }
4576                 optind = -1;
4577                 for (i = 0; i < LENGTH(configopt); i++) {
4578                         opt = &configopt[i];
4579                         if (!strncasecmp(cp, opt->optname, wordlen) &&
4580                             strlen(opt->optname) == wordlen) {
4581                                 optind = i;
4582                                 break;
4583                         }
4584                 }
4585                 if (optind == -1) {
4586                         warnx("%s: line %zd: unknown option %.*s",
4587                             filename, lineno, wordlen, cp);
4588                         return (1);
4589                 }
4590                 cp += wordlen;
4591                 cp += strspn(cp, " \t\n"); /* eat whitespace */
4592                 /* get [selector] if any */
4593                 optsub = NULL;
4594                 if (*cp == '[') {
4595                         cp++;
4596                         wordlen = strcspn(cp, "]");
4597                         if (*cp != ']') {
4598                                 if (wordlen == 0) {
4599                                         warnx("%s: line %zd: syntax error",
4600                                             filename, lineno);
4601                                         return (1);
4602                                 }
4603                                 asprintf(&optsub, "%.*s", wordlen, cp);
4604                         }
4605                         cp += wordlen;
4606                         cp += strspn(cp, "] \t\n"); /* eat trailing */
4607                 }
4608                 cp += strspn(cp, "= \t\n"); /* eat trailing */
4609                 /* get RHS value */
4610                 optval = strdup(cp);
4611                 /* call function to deal with it all */
4612                 if (configopt[optind].func(optsub, optval,
4613                     configopt[optind].funcflags) != 0) {
4614                         fprintf(stderr, "%s line %zd: %s\n",
4615                             filename, lineno, line);
4616                         errx(1, "%s: line %zd: invalid data for %s",
4617                             filename, lineno, configopt[optind].optname);
4618                 }
4619                 free(optval);
4620                 free(optsub);
4621                 free(line);
4622         }
4623
4624         fclose(config);
4625         DNPRINTF(SWM_D_CONF, "conf_load end\n");
4626
4627         return (0);
4628 }
4629
4630 void
4631 set_child_transient(struct ws_win *win, Window *trans)
4632 {
4633         struct ws_win           *parent, *w;
4634         XWMHints                *wmh = NULL;
4635         struct swm_region       *r;
4636         struct workspace        *ws;
4637
4638         parent = find_window(win->transient);
4639         if (parent)
4640                 parent->child_trans = win;
4641         else {
4642                 DNPRINTF(SWM_D_MISC, "set_child_transient: parent doesn't exist"
4643                     " for %lu trans %lu\n", win->id, win->transient);
4644
4645                 if (win->hints == NULL) {
4646                         fprintf(stderr, "no hints for %lu\n", win->id);
4647                         return;
4648                 }
4649
4650                 r = root_to_region(win->wa.root);
4651                 ws = r->ws;
4652                 /* parent doen't exist in our window list */
4653                 TAILQ_FOREACH(w, &ws->winlist, entry) {
4654                         if (wmh)
4655                                 XFree(wmh);
4656
4657                         if ((wmh = XGetWMHints(display, w->id)) == NULL) {
4658                                 fprintf(stderr, "can't get hints for %lu\n",
4659                                     w->id);
4660                                 continue;
4661                         }
4662
4663                         if (win->hints->window_group != wmh->window_group)
4664                                 continue;
4665
4666                         w->child_trans = win;
4667                         win->transient = w->id;
4668                         *trans = w->id;
4669                         DNPRINTF(SWM_D_MISC, "set_child_transient: asjusting "
4670                             "transient to %lu\n", win->transient);
4671                         break;
4672                 }
4673         }
4674
4675         if (wmh)
4676                 XFree(wmh);
4677 }
4678
4679 struct ws_win *
4680 manage_window(Window id)
4681 {
4682         Window                  trans = 0;
4683         struct workspace        *ws;
4684         struct ws_win           *win, *ww;
4685         int                     format, i, ws_idx, n, border_me = 0;
4686         unsigned long           nitems, bytes;
4687         Atom                    ws_idx_atom = 0, type;
4688         Atom                    *prot = NULL, *pp;
4689         unsigned char           ws_idx_str[SWM_PROPLEN], *prop = NULL;
4690         struct swm_region       *r;
4691         long                    mask;
4692         const char              *errstr;
4693         XWindowChanges          wc;
4694
4695         if ((win = find_window(id)) != NULL)
4696                 return (win);   /* already being managed */
4697
4698         /* see if we are on the unmanaged list */
4699         if ((win = find_unmanaged_window(id)) != NULL) {
4700                 DNPRINTF(SWM_D_MISC, "manage previously unmanaged window "
4701                     "%lu\n", win->id);
4702                 TAILQ_REMOVE(&win->ws->unmanagedlist, win, entry);
4703                 if (win->transient) {
4704                         set_child_transient(win, &trans);
4705                 } if (trans && (ww = find_window(trans)))
4706                         TAILQ_INSERT_AFTER(&win->ws->winlist, ww, win, entry);
4707                 else
4708                         TAILQ_INSERT_TAIL(&win->ws->winlist, win, entry);
4709                 ewmh_update_actions(win);
4710                 return (win);
4711         }
4712
4713         if ((win = calloc(1, sizeof(struct ws_win))) == NULL)
4714                 errx(1, "calloc: failed to allocate memory for new window");
4715
4716         win->id = id;
4717
4718         /* Get all the window data in one shot */
4719         ws_idx_atom = XInternAtom(display, "_SWM_WS", False);
4720         if (ws_idx_atom)
4721                 XGetWindowProperty(display, id, ws_idx_atom, 0, SWM_PROPLEN,
4722                     False, XA_STRING, &type, &format, &nitems, &bytes, &prop);
4723         XGetWindowAttributes(display, id, &win->wa);
4724         XGetWMNormalHints(display, id, &win->sh, &mask);
4725         win->hints = XGetWMHints(display, id);
4726         XGetTransientForHint(display, id, &trans);
4727         if (trans) {
4728                 win->transient = trans;
4729                 set_child_transient(win, &trans);
4730                 DNPRINTF(SWM_D_MISC, "manage_window: win %lu transient %lu\n",
4731                     win->id, win->transient);
4732         }
4733
4734         /* get supported protocols */
4735         if (XGetWMProtocols(display, id, &prot, &n)) {
4736                 for (i = 0, pp = prot; i < n; i++, pp++) {
4737                         if (*pp == takefocus)
4738                                 win->take_focus = 1;
4739                         if (*pp == adelete)
4740                                 win->can_delete = 1;
4741                 }
4742                 if (prot)
4743                         XFree(prot);
4744         }
4745
4746         win->iconic = get_iconic(win);
4747
4748         /*
4749          * Figure out where to put the window. If it was previously assigned to
4750          * a workspace (either by spawn() or manually moving), and isn't
4751          * transient, * put it in the same workspace
4752          */
4753         r = root_to_region(win->wa.root);
4754         if (prop && win->transient == 0) {
4755                 DNPRINTF(SWM_D_PROP, "got property _SWM_WS=%s\n", prop);
4756                 ws_idx = strtonum(prop, 0, 9, &errstr);
4757                 if (errstr) {
4758                         DNPRINTF(SWM_D_EVENT, "window idx is %s: %s",
4759                             errstr, prop);
4760                 }
4761                 ws = &r->s->ws[ws_idx];
4762         } else {
4763                 ws = r->ws;
4764                 /* this should launch transients in the same ws as parent */
4765                 if (id && trans)
4766                         if ((ww = find_window(trans)) != NULL)
4767                                 if (ws->r) {
4768                                         ws = ww->ws;
4769                                         if (ww->ws->r)
4770                                                 r = ww->ws->r;
4771                                         else
4772                                                 fprintf(stderr,
4773                                                     "fix this bug mcbride\n");
4774                                         border_me = 1;
4775                                 }
4776         }
4777
4778         /* set up the window layout */
4779         win->id = id;
4780         win->ws = ws;
4781         win->s = r->s;  /* this never changes */
4782         if (trans && (ww = find_window(trans)))
4783                 TAILQ_INSERT_AFTER(&ws->winlist, ww, win, entry);
4784         else
4785                 TAILQ_INSERT_TAIL(&ws->winlist, win, entry);
4786
4787         win->g.w = win->wa.width;
4788         win->g.h = win->wa.height;
4789         win->g.x = win->wa.x;
4790         win->g.y = win->wa.y;
4791         win->g_floatvalid = 0;
4792         win->floatmaxed = 0;
4793         win->ewmh_flags = 0;
4794
4795         /* Set window properties so we can remember this after reincarnation */
4796         if (ws_idx_atom && prop == NULL &&
4797             snprintf(ws_idx_str, SWM_PROPLEN, "%d", ws->idx) < SWM_PROPLEN) {
4798                 DNPRINTF(SWM_D_PROP, "setting property _SWM_WS to %s\n",
4799                     ws_idx_str);
4800                 XChangeProperty(display, win->id, ws_idx_atom, XA_STRING, 8,
4801                     PropModeReplace, ws_idx_str, SWM_PROPLEN);
4802         }
4803         if (prop)
4804                 XFree(prop);
4805
4806         ewmh_autoquirk(win);
4807
4808         if (XGetClassHint(display, win->id, &win->ch)) {
4809                 DNPRINTF(SWM_D_CLASS, "class: %s name: %s\n",
4810                     win->ch.res_class, win->ch.res_name);
4811
4812                 /* java is retarded so treat it special */
4813                 if (strstr(win->ch.res_name, "sun-awt")) {
4814                         win->java = 1;
4815                         border_me = 1;
4816                 }
4817
4818                 for (i = 0; i < quirks_length; i++){
4819                         if (!strcmp(win->ch.res_class, quirks[i].class) &&
4820                             !strcmp(win->ch.res_name, quirks[i].name)) {
4821                                 DNPRINTF(SWM_D_CLASS, "found: %s name: %s\n",
4822                                     win->ch.res_class, win->ch.res_name);
4823                                 if (quirks[i].quirk & SWM_Q_FLOAT) {
4824                                         win->floating = 1;
4825                                         border_me = 1;
4826                                 }
4827                                 win->quirks = quirks[i].quirk;
4828                         }
4829                 }
4830         }
4831
4832         /* alter window position if quirky */
4833         if (win->quirks & SWM_Q_ANYWHERE) {
4834                 win->manual = 1; /* don't center the quirky windows */
4835                 bzero(&wc, sizeof wc);
4836                 mask = 0;
4837                 if (bar_enabled && win->g.y < bar_height) {
4838                         win->g.y = wc.y = bar_height;
4839                         mask |= CWY;
4840                 }
4841                 if (win->g.w + win->g.x > WIDTH(r)) {
4842                         win->g.x = wc.x = WIDTH(r) - win->g.w - 2;
4843                         mask |= CWX;
4844                 }
4845                 border_me = 1;
4846         }
4847
4848         /* Reset font sizes (the bruteforce way; no default keybinding). */
4849         if (win->quirks & SWM_Q_XTERM_FONTADJ) {
4850                 for (i = 0; i < SWM_MAX_FONT_STEPS; i++)
4851                         fake_keypress(win, XK_KP_Subtract, ShiftMask);
4852                 for (i = 0; i < SWM_MAX_FONT_STEPS; i++)
4853                         fake_keypress(win, XK_KP_Add, ShiftMask);
4854         }
4855
4856         ewmh_get_win_state(win);
4857         ewmh_update_actions(win);
4858         ewmh_update_win_state(win, None, _NET_WM_STATE_REMOVE);
4859
4860         /* border me */
4861         if (border_me) {
4862                 bzero(&wc, sizeof wc);
4863                 wc.border_width = border_width;
4864                 mask = CWBorderWidth;
4865                 XConfigureWindow(display, win->id, mask, &wc);
4866         }
4867
4868         XSelectInput(display, id, EnterWindowMask | FocusChangeMask |
4869             PropertyChangeMask | StructureNotifyMask);
4870
4871         /* floaters need to be mapped if they are in the current workspace */
4872         if ((win->floating || win->transient) && (ws->idx == r->ws->idx))
4873                 XMapRaised(display, win->id);
4874
4875         return (win);
4876 }
4877
4878 void
4879 free_window(struct ws_win *win)
4880 {
4881         DNPRINTF(SWM_D_MISC, "free_window:  %lu\n", win->id);
4882
4883         if (win == NULL)
4884                 return;
4885
4886         /* needed for restart wm */
4887         set_win_state(win, WithdrawnState);
4888
4889         TAILQ_REMOVE(&win->ws->unmanagedlist, win, entry);
4890
4891         if (win->ch.res_class)
4892                 XFree(win->ch.res_class);
4893         if (win->ch.res_name)
4894                 XFree(win->ch.res_name);
4895
4896         kill_refs(win);
4897
4898         /* paint memory */
4899         memset(win, 0xff, sizeof *win); /* XXX kill later */
4900
4901         free(win);
4902 }
4903
4904 void
4905 unmanage_window(struct ws_win *win)
4906 {
4907         struct ws_win           *parent;
4908
4909         if (win == NULL)
4910                 return;
4911
4912         DNPRINTF(SWM_D_MISC, "unmanage_window:  %lu\n", win->id);
4913
4914         if (win->transient) {
4915                 parent = find_window(win->transient);
4916                 if (parent)
4917                         parent->child_trans = NULL;
4918         }
4919
4920         /* focus on root just in case */
4921         XSetInputFocus(display, PointerRoot, PointerRoot, CurrentTime);
4922
4923         focus_prev(win);
4924
4925         TAILQ_REMOVE(&win->ws->winlist, win, entry);
4926         TAILQ_INSERT_TAIL(&win->ws->unmanagedlist, win, entry);
4927
4928         kill_refs(win);
4929 }
4930
4931 void
4932 focus_magic(struct ws_win *win)
4933 {
4934         DNPRINTF(SWM_D_FOCUS, "focus_magic: %lu\n", WINID(win));
4935
4936         if (win == NULL)
4937                 return;
4938
4939         if (win->child_trans) {
4940                 /* win = parent & has a transient so focus on that */
4941                 if (win->java) {
4942                         focus_win(win->child_trans);
4943                         if (win->child_trans->take_focus)
4944                                 client_msg(win, takefocus);
4945                 } else {
4946                         /* make sure transient hasn't dissapeared */
4947                         if (validate_win(win->child_trans) == 0) {
4948                                 focus_win(win->child_trans);
4949                                 if (win->child_trans->take_focus)
4950                                         client_msg(win->child_trans, takefocus);
4951                         } else {
4952                                 win->child_trans = NULL;
4953                                 focus_win(win);
4954                                 if (win->take_focus)
4955                                         client_msg(win, takefocus);
4956                         }
4957                 }
4958         } else {
4959                 /* regular focus */
4960                 focus_win(win);
4961                 if (win->take_focus)
4962                         client_msg(win, takefocus);
4963         }
4964 }
4965
4966 void
4967 expose(XEvent *e)
4968 {
4969         DNPRINTF(SWM_D_EVENT, "expose: window: %lu\n", e->xexpose.window);
4970 }
4971
4972 void
4973 keypress(XEvent *e)
4974 {
4975         unsigned int            i;
4976         KeySym                  keysym;
4977         XKeyEvent               *ev = &e->xkey;
4978
4979         DNPRINTF(SWM_D_EVENT, "keypress: window: %lu\n", ev->window);
4980
4981         keysym = XKeycodeToKeysym(display, (KeyCode)ev->keycode, 0);
4982         for (i = 0; i < keys_length; i++)
4983                 if (keysym == keys[i].keysym
4984                     && CLEANMASK(keys[i].mod) == CLEANMASK(ev->state)
4985                     && keyfuncs[keys[i].funcid].func) {
4986                         if (keys[i].funcid == kf_spawn_custom)
4987                                 spawn_custom(
4988                                     root_to_region(ev->root),
4989                                     &(keyfuncs[keys[i].funcid].args),
4990                                     keys[i].spawn_name
4991                                     );
4992                         else
4993                                 keyfuncs[keys[i].funcid].func(
4994                                     root_to_region(ev->root),
4995                                     &(keyfuncs[keys[i].funcid].args)
4996                                     );
4997                 }
4998 }
4999
5000 void
5001 buttonpress(XEvent *e)
5002 {
5003         struct ws_win           *win;
5004         int                     i, action;
5005         XButtonPressedEvent     *ev = &e->xbutton;
5006
5007         DNPRINTF(SWM_D_EVENT, "buttonpress: window: %lu\n", ev->window);
5008
5009         action = root_click;
5010         if ((win = find_window(ev->window)) == NULL)
5011                 return;
5012
5013         focus_magic(win);
5014         action = client_click;
5015
5016         for (i = 0; i < LENGTH(buttons); i++)
5017                 if (action == buttons[i].action && buttons[i].func &&
5018                     buttons[i].button == ev->button &&
5019                     CLEANMASK(buttons[i].mask) == CLEANMASK(ev->state))
5020                         buttons[i].func(win, &buttons[i].args);
5021 }
5022
5023 void
5024 configurerequest(XEvent *e)
5025 {
5026         XConfigureRequestEvent  *ev = &e->xconfigurerequest;
5027         struct ws_win           *win;
5028         int                     new = 0;
5029         XWindowChanges          wc;
5030
5031         if ((win = find_window(ev->window)) == NULL)
5032                 if ((win = find_unmanaged_window(ev->window)) == NULL)
5033                         new = 1;
5034
5035         if (new) {
5036                 DNPRINTF(SWM_D_EVENT, "configurerequest: new window: %lu\n",
5037                     ev->window);
5038                 bzero(&wc, sizeof wc);
5039                 wc.x = ev->x;
5040                 wc.y = ev->y;
5041                 wc.width = ev->width;
5042                 wc.height = ev->height;
5043                 wc.border_width = ev->border_width;
5044                 wc.sibling = ev->above;
5045                 wc.stack_mode = ev->detail;
5046                 XConfigureWindow(display, ev->window, ev->value_mask, &wc);
5047         } else {
5048                 DNPRINTF(SWM_D_EVENT, "configurerequest: change window: %lu\n",
5049                     ev->window);
5050                 config_win(win, ev);
5051         }
5052 }
5053
5054 void
5055 configurenotify(XEvent *e)
5056 {
5057         struct ws_win           *win;
5058         long                    mask;
5059
5060         DNPRINTF(SWM_D_EVENT, "configurenotify: window: %lu\n",
5061             e->xconfigure.window);
5062
5063         win = find_window(e->xconfigure.window);
5064         if (win) {
5065                 XGetWMNormalHints(display, win->id, &win->sh, &mask);
5066                 adjust_font(win);
5067                 if (font_adjusted)
5068                         stack();
5069                 if (focus_mode == SWM_FOCUS_DEFAULT)
5070                         drain_enter_notify();
5071         }
5072 }
5073
5074 void
5075 destroynotify(XEvent *e)
5076 {
5077         struct ws_win           *win;
5078         XDestroyWindowEvent     *ev = &e->xdestroywindow;
5079
5080         DNPRINTF(SWM_D_EVENT, "destroynotify: window %lu\n", ev->window);
5081
5082         if ((win = find_window(ev->window)) == NULL) {
5083                 if ((win = find_unmanaged_window(ev->window)) == NULL)
5084                         return;
5085                 free_window(win);
5086                 return;
5087         }
5088
5089         /* make sure we focus on something */
5090         win->floating = 0;
5091
5092         unmanage_window(win);
5093         stack();
5094         if (focus_mode == SWM_FOCUS_DEFAULT)
5095                 drain_enter_notify();
5096         free_window(win);
5097 }
5098
5099 void
5100 enternotify(XEvent *e)
5101 {
5102         XCrossingEvent          *ev = &e->xcrossing;
5103         XEvent                  cne;
5104         struct ws_win           *win;
5105 #if 0
5106         struct ws_win           *w;
5107         Window                  focus_return;
5108         int                     revert_to_return;
5109 #endif
5110         DNPRINTF(SWM_D_FOCUS, "enternotify: window: %lu mode %d detail %d root "
5111             "%lu subwindow %lu same_screen %d focus %d state %d\n",
5112             ev->window, ev->mode, ev->detail, ev->root, ev->subwindow,
5113             ev->same_screen, ev->focus, ev->state);
5114
5115         switch (focus_mode) {
5116         case SWM_FOCUS_DEFAULT:
5117                 break;
5118         case SWM_FOCUS_FOLLOW:
5119                 break;
5120         case SWM_FOCUS_SYNERGY:
5121 #if 0
5122         /*
5123          * all these checks need to be in this order because the
5124          * XCheckTypedWindowEvent relies on weeding out the previous events
5125          *
5126          * making this code an option would enable a follow mouse for focus
5127          * feature
5128          */
5129
5130         /*
5131          * state is set when we are switching workspaces and focus is set when
5132          * the window or a subwindow already has focus (occurs during restart).
5133          *
5134          * Only honor the focus flag if last_focus_event is not FocusOut,
5135          * this allows scrotwm to continue to control focus when another
5136          * program is also playing with it.
5137          */
5138         if (ev->state || (ev->focus && last_focus_event != FocusOut)) {
5139                 DNPRINTF(SWM_D_EVENT, "ignoring enternotify: focus\n");
5140                 return;
5141         }
5142
5143         /*
5144          * happens when a window is created or destroyed and the border
5145          * crosses the mouse pointer and when switching ws
5146          *
5147          * we need the subwindow test to see if we came from root in order
5148          * to give focus to floaters
5149          */
5150         if (ev->mode == NotifyNormal && ev->detail == NotifyVirtual &&
5151             ev->subwindow == 0) {
5152                 DNPRINTF(SWM_D_EVENT, "ignoring enternotify: NotifyVirtual\n");
5153                 return;
5154         }
5155
5156         /* this window already has focus */
5157         if (ev->mode == NotifyNormal && ev->detail == NotifyInferior) {
5158                 DNPRINTF(SWM_D_EVENT, "ignoring enternotify: win has focus\n");
5159                 return;
5160         }
5161
5162         /* this window is being deleted or moved to another ws */
5163         if (XCheckTypedWindowEvent(display, ev->window, ConfigureNotify,
5164             &cne) == True) {
5165                 DNPRINTF(SWM_D_EVENT, "ignoring enternotify: configurenotify\n");
5166                 XPutBackEvent(display, &cne);
5167                 return;
5168         }
5169
5170         if ((win = find_window(ev->window)) == NULL) {
5171                 DNPRINTF(SWM_D_EVENT, "ignoring enternotify: win == NULL\n");
5172                 return;
5173         }
5174
5175         /*
5176          * In fullstack kill all enters unless they come from a different ws
5177          * (i.e. another region) or focus has been grabbed externally.
5178          */
5179         if (win->ws->cur_layout->flags & SWM_L_FOCUSPREV &&
5180             last_focus_event != FocusOut) {
5181                 XGetInputFocus(display, &focus_return, &revert_to_return);
5182                 if ((w = find_window(focus_return)) == NULL ||
5183                     w->ws == win->ws) {
5184                         DNPRINTF(SWM_D_EVENT, "ignoring event: fullstack\n");
5185                         return;
5186                 }
5187         }
5188 #endif
5189                 break;
5190         }
5191
5192         if ((win = find_window(ev->window)) == NULL) {
5193                 DNPRINTF(SWM_D_EVENT, "ignoring enternotify: win == NULL\n");
5194                 return;
5195         }
5196
5197         /*
5198          * if we have more enternotifies let them handle it in due time
5199          */
5200         if (XCheckTypedEvent(display, EnterNotify, &cne) == True) {
5201                 DNPRINTF(SWM_D_EVENT,
5202                     "ignoring enternotify: got more enternotify\n");
5203                 XPutBackEvent(display, &cne);
5204                 return;
5205         }
5206
5207         focus_magic(win);
5208 }
5209
5210 /* lets us use one switch statement for arbitrary mode/detail combinations */
5211 #define MERGE_MEMBERS(a,b)      (((a & 0xffff) << 16) | (b & 0xffff))
5212
5213 void
5214 focusevent(XEvent *e)
5215 {
5216 #if 0
5217         struct ws_win           *win;
5218         u_int32_t               mode_detail;
5219         XFocusChangeEvent       *ev = &e->xfocus;
5220
5221         DNPRINTF(SWM_D_EVENT, "focusevent: %s window: %lu mode %d detail %d\n",
5222             ev->type == FocusIn ? "entering" : "leaving",
5223             ev->window, ev->mode, ev->detail);
5224
5225         if (last_focus_event == ev->type) {
5226                 DNPRINTF(SWM_D_FOCUS, "ignoring focusevent: bad ordering\n");
5227                 return;
5228         }
5229
5230         last_focus_event = ev->type;
5231         mode_detail = MERGE_MEMBERS(ev->mode, ev->detail);
5232
5233         switch (mode_detail) {
5234         /* synergy client focus operations */
5235         case MERGE_MEMBERS(NotifyNormal, NotifyNonlinear):
5236         case MERGE_MEMBERS(NotifyNormal, NotifyNonlinearVirtual):
5237
5238         /* synergy server focus operations */
5239         case MERGE_MEMBERS(NotifyWhileGrabbed, NotifyNonlinear):
5240
5241         /* Entering applications like rdesktop that mangle the pointer */
5242         case MERGE_MEMBERS(NotifyNormal, NotifyPointer):
5243
5244                 if ((win = find_window(e->xfocus.window)) != NULL && win->ws->r)
5245                         XSetWindowBorder(display, win->id,
5246                             win->ws->r->s->c[ev->type == FocusIn ?
5247                             SWM_S_COLOR_FOCUS : SWM_S_COLOR_UNFOCUS].color);
5248                 break;
5249         default:
5250                 fprintf(stderr, "ignoring focusevent\n");
5251                 DNPRINTF(SWM_D_FOCUS, "ignoring focusevent\n");
5252                 break;
5253         }
5254 #endif
5255 }
5256
5257 void
5258 mapnotify(XEvent *e)
5259 {
5260         struct ws_win           *win;
5261         XMapEvent               *ev = &e->xmap;
5262
5263         DNPRINTF(SWM_D_EVENT, "mapnotify: window: %lu\n", ev->window);
5264
5265         win = manage_window(ev->window);
5266         if (win)
5267                 set_win_state(win, NormalState);
5268 }
5269
5270 void
5271 mappingnotify(XEvent *e)
5272 {
5273         XMappingEvent           *ev = &e->xmapping;
5274
5275         XRefreshKeyboardMapping(ev);
5276         if (ev->request == MappingKeyboard)
5277                 grabkeys();
5278 }
5279
5280 void
5281 maprequest(XEvent *e)
5282 {
5283         struct ws_win           *win;
5284         struct swm_region       *r;
5285         XWindowAttributes       wa;
5286         XMapRequestEvent        *ev = &e->xmaprequest;
5287
5288         DNPRINTF(SWM_D_EVENT, "maprequest: window: %lu\n",
5289             e->xmaprequest.window);
5290
5291         if (!XGetWindowAttributes(display, ev->window, &wa))
5292                 return;
5293         if (wa.override_redirect)
5294                 return;
5295
5296         win = manage_window(e->xmaprequest.window);
5297         if (win == NULL)
5298                 return; /* can't happen */
5299
5300         stack();
5301
5302         /* make new win focused */
5303         r = root_to_region(win->wa.root);
5304         if (win->ws == r->ws)
5305                 focus_magic(win);
5306 }
5307
5308 void
5309 propertynotify(XEvent *e)
5310 {
5311         struct ws_win           *win;
5312         XPropertyEvent          *ev = &e->xproperty;
5313
5314         DNPRINTF(SWM_D_EVENT, "propertynotify: window: %lu\n",
5315             ev->window);
5316
5317         win = find_window(ev->window);
5318         if (win == NULL)
5319                 return;
5320
5321         if (ev->state == PropertyDelete && ev->atom == a_swm_iconic) {
5322                 update_iconic(win, 0);
5323                 XMapRaised(display, win->id);
5324                 stack();
5325                 focus_win(win);
5326                 return;
5327         }
5328
5329         switch (ev->atom) {
5330         case XA_WM_NORMAL_HINTS:
5331 #if 0
5332                 long            mask;
5333                 XGetWMNormalHints(display, win->id, &win->sh, &mask);
5334                 fprintf(stderr, "normal hints: flag 0x%x\n", win->sh.flags);
5335                 if (win->sh.flags & PMinSize) {
5336                         win->g.w = win->sh.min_width;
5337                         win->g.h = win->sh.min_height;
5338                         fprintf(stderr, "min %d %d\n", win->g.w, win->g.h);
5339                 }
5340                 XMoveResizeWindow(display, win->id,
5341                     win->g.x, win->g.y, win->g.w, win->g.h);
5342 #endif
5343                 if (window_name_enabled)
5344                         bar_update();
5345                 break;
5346         default:
5347                 break;
5348         }
5349 }
5350
5351 void
5352 unmapnotify(XEvent *e)
5353 {
5354         struct ws_win           *win;
5355
5356         DNPRINTF(SWM_D_EVENT, "unmapnotify: window: %lu\n", e->xunmap.window);
5357
5358         /* determine if we need to help unmanage this window */
5359         win = find_window(e->xunmap.window);
5360         if (win == NULL)
5361                 return;
5362
5363         if (getstate(e->xunmap.window) == NormalState) {
5364                 unmanage_window(win);
5365                 stack();
5366
5367                 /* giant hack for apps that don't destroy transient windows */
5368                 /* eat a bunch of events to prevent remanaging the window */
5369                 XEvent                  cne;
5370                 while (XCheckWindowEvent(display, e->xunmap.window,
5371                     EnterWindowMask, &cne))
5372                         ;
5373                 while (XCheckWindowEvent(display, e->xunmap.window,
5374                     StructureNotifyMask, &cne))
5375                         ;
5376                 while (XCheckWindowEvent(display, e->xunmap.window,
5377                     SubstructureNotifyMask, &cne))
5378                         ;
5379                 /* resend unmap because we ated it */
5380                 XUnmapWindow(display, e->xunmap.window);
5381         }
5382
5383         if (focus_mode == SWM_FOCUS_DEFAULT)
5384                 drain_enter_notify();
5385 }
5386
5387 void
5388 visibilitynotify(XEvent *e)
5389 {
5390         int                     i;
5391         struct swm_region       *r;
5392
5393         DNPRINTF(SWM_D_EVENT, "visibilitynotify: window: %lu\n",
5394             e->xvisibility.window);
5395         if (e->xvisibility.state == VisibilityUnobscured)
5396                 for (i = 0; i < ScreenCount(display); i++)
5397                         TAILQ_FOREACH(r, &screens[i].rl, entry)
5398                                 if (e->xvisibility.window == r->bar_window)
5399                                         bar_update();
5400 }
5401
5402 void
5403 clientmessage(XEvent *e)
5404 {
5405         XClientMessageEvent *ev;
5406         struct ws_win *win;
5407
5408         ev = &e->xclient;
5409
5410         win = find_window(ev->window);
5411         if (win == NULL)
5412                 return;
5413
5414         DNPRINTF(SWM_D_EVENT, "clientmessage: window: 0x%lx type: %ld \n",
5415             ev->window, ev->message_type);
5416
5417         if (ev->message_type == ewmh[_NET_ACTIVE_WINDOW].atom) {
5418                 DNPRINTF(SWM_D_EVENT, "clientmessage: _NET_ACTIVE_WINDOW \n");
5419                 focus_win(win);
5420         }
5421         if (ev->message_type == ewmh[_NET_CLOSE_WINDOW].atom) {
5422                 DNPRINTF(SWM_D_EVENT, "clientmessage: _NET_CLOSE_WINDOW \n");
5423                 if (win->can_delete)
5424                         client_msg(win, adelete);
5425                 else
5426                         XKillClient(display, win->id);
5427         }
5428         if (ev->message_type == ewmh[_NET_MOVERESIZE_WINDOW].atom) {
5429                 DNPRINTF(SWM_D_EVENT,
5430                     "clientmessage: _NET_MOVERESIZE_WINDOW \n");
5431                 if (win->floating) {
5432                         if (ev->data.l[0] & (1<<8)) /* x */
5433                                 win->g.x = ev->data.l[1];
5434                         if (ev->data.l[0] & (1<<9)) /* y */
5435                                 win->g.y = ev->data.l[2];
5436                         if (ev->data.l[0] & (1<<10)) /* width */
5437                                 win->g.w = ev->data.l[3];
5438                         if (ev->data.l[0] & (1<<11)) /* height */
5439                                 win->g.h = ev->data.l[4];
5440                 }
5441                 else {
5442                         /* TODO: Change stack sizes */
5443                 }
5444                 config_win(win, NULL);
5445         }
5446         if (ev->message_type == ewmh[_NET_WM_STATE].atom) {
5447                 DNPRINTF(SWM_D_EVENT, "clientmessage: _NET_WM_STATE \n");
5448                 ewmh_update_win_state(win, ev->data.l[1], ev->data.l[0]);
5449                 if (ev->data.l[2])
5450                         ewmh_update_win_state(win, ev->data.l[2],
5451                             ev->data.l[0]);
5452
5453                 stack();
5454         }
5455 }
5456
5457 int
5458 xerror_start(Display *d, XErrorEvent *ee)
5459 {
5460         other_wm = 1;
5461         return (-1);
5462 }
5463
5464 int
5465 xerror(Display *d, XErrorEvent *ee)
5466 {
5467         /* fprintf(stderr, "error: %p %p\n", display, ee); */
5468         return (-1);
5469 }
5470
5471 int
5472 active_wm(void)
5473 {
5474         other_wm = 0;
5475         xerrorxlib = XSetErrorHandler(xerror_start);
5476
5477         /* this causes an error if some other window manager is running */
5478         XSelectInput(display, DefaultRootWindow(display),
5479             SubstructureRedirectMask);
5480         XSync(display, False);
5481         if (other_wm)
5482                 return (1);
5483
5484         XSetErrorHandler(xerror);
5485         XSync(display, False);
5486         return (0);
5487 }
5488
5489 void
5490 new_region(struct swm_screen *s, int x, int y, int w, int h)
5491 {
5492         struct swm_region       *r, *n;
5493         struct workspace        *ws = NULL;
5494         int                     i;
5495
5496         DNPRINTF(SWM_D_MISC, "new region: screen[%d]:%dx%d+%d+%d\n",
5497              s->idx, w, h, x, y);
5498
5499         /* remove any conflicting regions */
5500         n = TAILQ_FIRST(&s->rl);
5501         while (n) {
5502                 r = n;
5503                 n = TAILQ_NEXT(r, entry);
5504                 if (X(r) < (x + w) &&
5505                     (X(r) + WIDTH(r)) > x &&
5506                     Y(r) < (y + h) &&
5507                     (Y(r) + HEIGHT(r)) > y) {
5508                         if (r->ws->r != NULL)
5509                                 r->ws->old_r = r->ws->r;
5510                         r->ws->r = NULL;
5511                         XDestroyWindow(display, r->bar_window);
5512                         TAILQ_REMOVE(&s->rl, r, entry);
5513                         TAILQ_INSERT_TAIL(&s->orl, r, entry);
5514                 }
5515         }
5516
5517         /* search old regions for one to reuse */
5518
5519         /* size + location match */
5520         TAILQ_FOREACH(r, &s->orl, entry)
5521                 if (X(r) == x && Y(r) == y &&
5522                     HEIGHT(r) == h && WIDTH(r) == w)
5523                         break;
5524
5525         /* size match */
5526         TAILQ_FOREACH(r, &s->orl, entry)
5527                 if (HEIGHT(r) == h && WIDTH(r) == w)
5528                         break;
5529
5530         if (r != NULL) {
5531                 TAILQ_REMOVE(&s->orl, r, entry);
5532                 /* try to use old region's workspace */
5533                 if (r->ws->r == NULL)
5534                         ws = r->ws;
5535         } else
5536                 if ((r = calloc(1, sizeof(struct swm_region))) == NULL)
5537                         errx(1, "calloc: failed to allocate memory for screen");
5538
5539         /* if we don't have a workspace already, find one */
5540         if (ws == NULL) {
5541                 for (i = 0; i < SWM_WS_MAX; i++)
5542                         if (s->ws[i].r == NULL) {
5543                                 ws = &s->ws[i];
5544                                 break;
5545                         }
5546         }
5547
5548         if (ws == NULL)
5549                 errx(1, "no free workspaces\n");
5550
5551         X(r) = x;
5552         Y(r) = y;
5553         WIDTH(r) = w;
5554         HEIGHT(r) = h;
5555         r->s = s;
5556         r->ws = ws;
5557         r->ws_prior = NULL;
5558         ws->r = r;
5559         outputs++;
5560         TAILQ_INSERT_TAIL(&s->rl, r, entry);
5561 }
5562
5563 void
5564 scan_xrandr(int i)
5565 {
5566 #ifdef SWM_XRR_HAS_CRTC
5567         XRRCrtcInfo             *ci;
5568         XRRScreenResources      *sr;
5569         int                     c;
5570         int                     ncrtc = 0;
5571 #endif /* SWM_XRR_HAS_CRTC */
5572         struct swm_region       *r;
5573
5574
5575         if (i >= ScreenCount(display))
5576                 errx(1, "invalid screen");
5577
5578         /* remove any old regions */
5579         while ((r = TAILQ_FIRST(&screens[i].rl)) != NULL) {
5580                 r->ws->old_r = r->ws->r = NULL;
5581                 XDestroyWindow(display, r->bar_window);
5582                 TAILQ_REMOVE(&screens[i].rl, r, entry);
5583                 TAILQ_INSERT_TAIL(&screens[i].orl, r, entry);
5584         }
5585         outputs = 0;
5586
5587         /* map virtual screens onto physical screens */
5588 #ifdef SWM_XRR_HAS_CRTC
5589         if (xrandr_support) {
5590                 sr = XRRGetScreenResources(display, screens[i].root);
5591                 if (sr == NULL)
5592                         new_region(&screens[i], 0, 0,
5593                             DisplayWidth(display, i),
5594                             DisplayHeight(display, i));
5595                 else
5596                         ncrtc = sr->ncrtc;
5597
5598                 for (c = 0, ci = NULL; c < ncrtc; c++) {
5599                         ci = XRRGetCrtcInfo(display, sr, sr->crtcs[c]);
5600                         if (ci->noutput == 0)
5601                                 continue;
5602
5603                         if (ci != NULL && ci->mode == None)
5604                                 new_region(&screens[i], 0, 0,
5605                                     DisplayWidth(display, i),
5606                                     DisplayHeight(display, i));
5607                         else
5608                                 new_region(&screens[i],
5609                                     ci->x, ci->y, ci->width, ci->height);
5610                 }
5611                 if (ci)
5612                         XRRFreeCrtcInfo(ci);
5613                 XRRFreeScreenResources(sr);
5614         } else
5615 #endif /* SWM_XRR_HAS_CRTC */
5616         {
5617                 new_region(&screens[i], 0, 0, DisplayWidth(display, i),
5618                     DisplayHeight(display, i));
5619         }
5620 }
5621
5622 void
5623 screenchange(XEvent *e) {
5624         XRRScreenChangeNotifyEvent      *xe = (XRRScreenChangeNotifyEvent *)e;
5625         struct swm_region               *r;
5626         int                             i;
5627
5628         DNPRINTF(SWM_D_EVENT, "screenchange: %lu\n", xe->root);
5629
5630         if (!XRRUpdateConfiguration(e))
5631                 return;
5632
5633         /* silly event doesn't include the screen index */
5634         for (i = 0; i < ScreenCount(display); i++)
5635                 if (screens[i].root == xe->root)
5636                         break;
5637         if (i >= ScreenCount(display))
5638                 errx(1, "screenchange: screen not found\n");
5639
5640         /* brute force for now, just re-enumerate the regions */
5641         scan_xrandr(i);
5642
5643         /* add bars to all regions */
5644         for (i = 0; i < ScreenCount(display); i++)
5645                 TAILQ_FOREACH(r, &screens[i].rl, entry)
5646                         bar_setup(r);
5647         stack();
5648         if (focus_mode == SWM_FOCUS_DEFAULT)
5649                 drain_enter_notify();
5650 }
5651
5652 void
5653 grab_windows(void)
5654 {
5655         Window                  d1, d2, *wins = NULL;
5656         XWindowAttributes       wa;
5657         unsigned int            no;
5658         int                     i, j;
5659         long                    state, manage;
5660
5661         for (i = 0; i < ScreenCount(display); i++) {
5662                 if (!XQueryTree(display, screens[i].root, &d1, &d2, &wins, &no))
5663                         continue;
5664
5665                 /* attach windows to a region */
5666                 /* normal windows */
5667                 for (j = 0; j < no; j++) {
5668                         if (!XGetWindowAttributes(display, wins[j], &wa) ||
5669                             wa.override_redirect ||
5670                             XGetTransientForHint(display, wins[j], &d1))
5671                                 continue;
5672
5673                         state = getstate(wins[j]);
5674                         manage = state == IconicState;
5675                         if (wa.map_state == IsViewable || manage)
5676                                 manage_window(wins[j]);
5677                 }
5678                 /* transient windows */
5679                 for (j = 0; j < no; j++) {
5680                         if (!XGetWindowAttributes(display, wins[j], &wa) ||
5681                             wa.override_redirect)
5682                                 continue;
5683
5684                         state = getstate(wins[j]);
5685                         manage = state == IconicState;
5686                         if (XGetTransientForHint(display, wins[j], &d1) &&
5687                             manage)
5688                                 manage_window(wins[j]);
5689                 }
5690                 if (wins) {
5691                         XFree(wins);
5692                         wins = NULL;
5693                 }
5694         }
5695 }
5696
5697 void
5698 setup_screens(void)
5699 {
5700         int                     i, j, k;
5701         int                     errorbase, major, minor;
5702         struct workspace        *ws;
5703         int                     ws_idx_atom;
5704
5705         if ((screens = calloc(ScreenCount(display),
5706              sizeof(struct swm_screen))) == NULL)
5707                 errx(1, "calloc: screens");
5708
5709         ws_idx_atom = XInternAtom(display, "_SWM_WS", False);
5710
5711         /* initial Xrandr setup */
5712         xrandr_support = XRRQueryExtension(display,
5713             &xrandr_eventbase, &errorbase);
5714         if (xrandr_support)
5715                 if (XRRQueryVersion(display, &major, &minor) && major < 1)
5716                         xrandr_support = 0;
5717
5718         /* map physical screens */
5719         for (i = 0; i < ScreenCount(display); i++) {
5720                 DNPRINTF(SWM_D_WS, "setup_screens: init screen %d\n", i);
5721                 screens[i].idx = i;
5722                 TAILQ_INIT(&screens[i].rl);
5723                 TAILQ_INIT(&screens[i].orl);
5724                 screens[i].root = RootWindow(display, i);
5725
5726                 /* set default colors */
5727                 setscreencolor("red", i + 1, SWM_S_COLOR_FOCUS);
5728                 setscreencolor("rgb:88/88/88", i + 1, SWM_S_COLOR_UNFOCUS);
5729                 setscreencolor("rgb:00/80/80", i + 1, SWM_S_COLOR_BAR_BORDER);
5730                 setscreencolor("black", i + 1, SWM_S_COLOR_BAR);
5731                 setscreencolor("rgb:a0/a0/a0", i + 1, SWM_S_COLOR_BAR_FONT);
5732
5733                 /* set default cursor */
5734                 XDefineCursor(display, screens[i].root,
5735                     XCreateFontCursor(display, XC_left_ptr));
5736
5737                 /* init all workspaces */
5738                 /* XXX these should be dynamically allocated too */
5739                 for (j = 0; j < SWM_WS_MAX; j++) {
5740                         ws = &screens[i].ws[j];
5741                         ws->idx = j;
5742                         ws->focus = NULL;
5743                         ws->r = NULL;
5744                         ws->old_r = NULL;
5745                         TAILQ_INIT(&ws->winlist);
5746                         TAILQ_INIT(&ws->unmanagedlist);
5747
5748                         for (k = 0; layouts[k].l_stack != NULL; k++)
5749                                 if (layouts[k].l_config != NULL)
5750                                         layouts[k].l_config(ws,
5751                                             SWM_ARG_ID_STACKINIT);
5752                         ws->cur_layout = &layouts[0];
5753                 }
5754
5755                 scan_xrandr(i);
5756
5757                 if (xrandr_support)
5758                         XRRSelectInput(display, screens[i].root,
5759                             RRScreenChangeNotifyMask);
5760         }
5761 }
5762
5763 void
5764 setup_globals(void)
5765 {
5766         if ((bar_fonts[0] = strdup("-*-terminus-medium-*-*-*-*-*-*-*-*-*-*-*"))
5767             == NULL)
5768                 err(1, "setup_globals: strdup");
5769         if ((bar_fonts[1] = strdup("-*-times-medium-r-*-*-*-*-*-*-*-*-*-*"))
5770             == NULL)
5771                 err(1, "setup_globals: strdup");
5772         if ((bar_fonts[2] = strdup("-misc-fixed-medium-r-*-*-*-*-*-*-*-*-*-*"))
5773             == NULL)
5774                 err(1, "setup_globals: strdup");
5775         if ((spawn_term[0] = strdup("xterm")) == NULL)
5776                 err(1, "setup_globals: strdup");
5777         if ((clock_format = strdup("%a %b %d %R %Z %Y")) == NULL)
5778                 errx(1, "strdup");
5779 }
5780
5781 void
5782 workaround(void)
5783 {
5784         int                     i;
5785         Atom                    netwmcheck, netwmname, utf8_string;
5786         Window                  root, win;
5787
5788         /* work around sun jdk bugs, code from wmname */
5789         netwmcheck = XInternAtom(display, "_NET_SUPPORTING_WM_CHECK", False);
5790         netwmname = XInternAtom(display, "_NET_WM_NAME", False);
5791         utf8_string = XInternAtom(display, "UTF8_STRING", False);
5792         for (i = 0; i < ScreenCount(display); i++) {
5793                 root = screens[i].root;
5794                 win = XCreateSimpleWindow(display,root, 0, 0, 1, 1, 0,
5795                     screens[i].c[SWM_S_COLOR_UNFOCUS].color,
5796                     screens[i].c[SWM_S_COLOR_UNFOCUS].color);
5797
5798                 XChangeProperty(display, root, netwmcheck, XA_WINDOW, 32,
5799                     PropModeReplace, (unsigned char *)&win,1);
5800                 XChangeProperty(display, win, netwmcheck, XA_WINDOW, 32,
5801                     PropModeReplace, (unsigned char *)&win,1);
5802                 XChangeProperty(display, win, netwmname, utf8_string, 8,
5803                     PropModeReplace, (unsigned char*)"LG3D", strlen("LG3D"));
5804         }
5805 }
5806
5807 int
5808 main(int argc, char *argv[])
5809 {
5810         struct passwd           *pwd;
5811         struct swm_region       *r, *rr;
5812         struct ws_win           *winfocus = NULL;
5813         struct timeval          tv;
5814         union arg               a;
5815         char                    conf[PATH_MAX], *cfile = NULL;
5816         struct stat             sb;
5817         XEvent                  e;
5818         int                     xfd, i;
5819         fd_set                  rd;
5820         struct sigaction        sact;
5821
5822         start_argv = argv;
5823         fprintf(stderr, "Welcome to scrotwm V%s cvs tag: %s\n",
5824             SWM_VERSION, cvstag);
5825         if (!setlocale(LC_CTYPE, "") || !XSupportsLocale())
5826                 warnx("no locale support");
5827
5828         if (!(display = XOpenDisplay(0)))
5829                 errx(1, "can not open display");
5830
5831         if (active_wm())
5832                 errx(1, "other wm running");
5833
5834         /* handle some signals */
5835         bzero(&sact, sizeof(sact));
5836         sigemptyset(&sact.sa_mask);
5837         sact.sa_flags = 0;
5838         sact.sa_handler = sighdlr;
5839         sigaction(SIGINT, &sact, NULL);
5840         sigaction(SIGQUIT, &sact, NULL);
5841         sigaction(SIGTERM, &sact, NULL);
5842         sigaction(SIGHUP, &sact, NULL);
5843
5844         sact.sa_handler = sighdlr;
5845         sact.sa_flags = SA_NOCLDSTOP;
5846         sigaction(SIGCHLD, &sact, NULL);
5847
5848         astate = XInternAtom(display, "WM_STATE", False);
5849         aprot = XInternAtom(display, "WM_PROTOCOLS", False);
5850         adelete = XInternAtom(display, "WM_DELETE_WINDOW", False);
5851         takefocus = XInternAtom(display, "WM_TAKE_FOCUS", False);
5852         a_wmname = XInternAtom(display, "WM_NAME", False);
5853         a_utf8_string = XInternAtom(display, "UTF8_STRING", False);
5854         a_string = XInternAtom(display, "STRING", False);
5855         a_swm_iconic = XInternAtom(display, "_SWM_ICONIC", False);
5856
5857         /* look for local and global conf file */
5858         pwd = getpwuid(getuid());
5859         if (pwd == NULL)
5860                 errx(1, "invalid user %d", getuid());
5861
5862         setup_screens();
5863         setup_globals();
5864         setup_keys();
5865         setup_quirks();
5866         setup_spawn();
5867
5868         /* load config */
5869         snprintf(conf, sizeof conf, "%s/.%s", pwd->pw_dir, SWM_CONF_FILE);
5870         if (stat(conf, &sb) != -1) {
5871                 if (S_ISREG(sb.st_mode))
5872                         cfile = conf;
5873         } else {
5874                 /* try global conf file */
5875                 snprintf(conf, sizeof conf, "/etc/%s", SWM_CONF_FILE);
5876                 if (!stat(conf, &sb))
5877                         if (S_ISREG(sb.st_mode))
5878                                 cfile = conf;
5879         }
5880         if (cfile)
5881                 conf_load(cfile);
5882
5883         setup_ewmh();
5884         /* set some values to work around bad programs */
5885         workaround();
5886
5887         /* grab existing windows (before we build the bars) */
5888         grab_windows();
5889
5890         /* setup all bars */
5891         for (i = 0; i < ScreenCount(display); i++)
5892                 TAILQ_FOREACH(r, &screens[i].rl, entry) {
5893                         if (winfocus == NULL)
5894                                 winfocus = TAILQ_FIRST(&r->ws->winlist);
5895                         bar_setup(r);
5896                 }
5897
5898         unfocus_all();
5899
5900         grabkeys();
5901         stack();
5902         if (focus_mode == SWM_FOCUS_DEFAULT)
5903                 drain_enter_notify();
5904
5905         xfd = ConnectionNumber(display);
5906         while (running) {
5907                 while (XPending(display)) {
5908                         XNextEvent(display, &e);
5909                         if (running == 0)
5910                                 goto done;
5911                         if (e.type < LASTEvent) {
5912                                 dumpevent(&e);
5913                                 if (handler[e.type])
5914                                         handler[e.type](&e);
5915                                 else
5916                                         DNPRINTF(SWM_D_EVENT,
5917                                             "win: %lu unknown event: %d\n",
5918                                             e.xany.window, e.type);
5919                         } else {
5920                                 switch (e.type - xrandr_eventbase) {
5921                                 case RRScreenChangeNotify:
5922                                         screenchange(&e);
5923                                         break;
5924                                 default:
5925                                         DNPRINTF(SWM_D_EVENT,
5926                                             "win: %lu unknown xrandr event: "
5927                                             "%d\n", e.xany.window, e.type);
5928                                         break;
5929                                 }
5930                         }
5931                 }
5932
5933                 /* if we are being restarted go focus on first window */
5934                 if (winfocus) {
5935                         rr = winfocus->ws->r;
5936                         if (rr == NULL) {
5937                                 /* not a visible window */
5938                                 winfocus = NULL;
5939                                 continue;
5940                         }
5941                         /* move pointer to first screen if multi screen */
5942                         if (ScreenCount(display) > 1 || outputs > 1)
5943                                 XWarpPointer(display, None, rr->s[0].root,
5944                                     0, 0, 0, 0, rr->g.x,
5945                                     rr->g.y + (bar_enabled ? bar_height : 0));
5946
5947                         a.id = SWM_ARG_ID_FOCUSCUR;
5948                         focus(rr, &a);
5949                         winfocus = NULL;
5950                         continue;
5951                 }
5952
5953                 FD_ZERO(&rd);
5954                 FD_SET(xfd, &rd);
5955                 tv.tv_sec = 1;
5956                 tv.tv_usec = 0;
5957                 if (select(xfd + 1, &rd, NULL, NULL, &tv) == -1)
5958                         if (errno != EINTR)
5959                                 DNPRINTF(SWM_D_MISC, "select failed");
5960                 if (restart_wm == 1)
5961                         restart(NULL, NULL);
5962                 if (search_resp == 1)
5963                         search_do_resp();
5964                 if (running == 0)
5965                         goto done;
5966                 if (bar_alarm) {
5967                         bar_alarm = 0;
5968                         bar_update();
5969                 }
5970         }
5971 done:
5972         teardown_ewmh();
5973         bar_extra_stop();
5974         XFreeGC(display, bar_gc);
5975         XCloseDisplay(display);
5976
5977         return (0);
5978 }