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