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