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