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