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