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