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