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