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