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