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