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