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