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