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