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