JasonWoof Got questions, comments, patches, etc.? Contact Jason Woofenden
Move class names into ws_win; this will make debug easy because now we
[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  *
6  * Permission to use, copy, modify, and distribute this software for any
7  * purpose with or without fee is hereby granted, provided that the above
8  * copyright notice and this permission notice appear in all copies.
9  *
10  * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
11  * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
12  * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
13  * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
14  * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
15  * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
16  * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
17  */
18 /*
19  * Much code and ideas taken from dwm under the following license:
20  * MIT/X Consortium License
21  * 
22  * 2006-2008 Anselm R Garbe <garbeam at gmail dot com>
23  * 2006-2007 Sander van Dijk <a dot h dot vandijk at gmail dot com>
24  * 2006-2007 Jukka Salmi <jukka at salmi dot ch>
25  * 2007 Premysl Hruby <dfenze at gmail dot com>
26  * 2007 Szabolcs Nagy <nszabolcs at gmail dot com>
27  * 2007 Christof Musik <christof at sendfax dot de>
28  * 2007-2008 Enno Gottox Boland <gottox at s01 dot de>
29  * 2007-2008 Peter Hartlich <sgkkr at hartlich dot com>
30  * 2008 Martin Hurton <martin dot hurton at gmail dot com>
31  * 
32  * Permission is hereby granted, free of charge, to any person obtaining a
33  * copy of this software and associated documentation files (the "Software"),
34  * to deal in the Software without restriction, including without limitation
35  * the rights to use, copy, modify, merge, publish, distribute, sublicense,
36  * and/or sell copies of the Software, and to permit persons to whom the
37  * Software is furnished to do so, subject to the following conditions:
38  * 
39  * The above copyright notice and this permission notice shall be included in
40  * all copies or substantial portions of the Software.
41  * 
42  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
43  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
44  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
45  * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
46  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
47  * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
48  * DEALINGS IN THE SOFTWARE.
49  */
50
51 static const char       *cvstag = "$scrotwm$";
52
53 #define SWM_VERSION     "0.6"
54
55 #include <stdio.h>
56 #include <stdlib.h>
57 #include <err.h>
58 #include <errno.h>
59 #include <fcntl.h>
60 #include <locale.h>
61 #include <unistd.h>
62 #include <time.h>
63 #include <signal.h>
64 #include <string.h>
65 #include <util.h>
66 #include <pwd.h>
67 #include <ctype.h>
68
69 #include <sys/types.h>
70 #include <sys/time.h>
71 #include <sys/stat.h>
72 #include <sys/wait.h>
73 #include <sys/queue.h>
74 #include <sys/param.h>
75 #include <sys/select.h>
76
77 #include <X11/cursorfont.h>
78 #include <X11/keysym.h>
79 #include <X11/Xatom.h>
80 #include <X11/Xlib.h>
81 #include <X11/Xproto.h>
82 #include <X11/Xutil.h>
83 #include <X11/extensions/Xrandr.h>
84
85 #if RANDR_MAJOR < 1
86 #  error XRandR versions less than 1.0 are not supported
87 #endif
88
89 #if RANDR_MAJOR >= 1
90 #if RANDR_MINOR >= 2
91 #define SWM_XRR_HAS_CRTC
92 #endif
93 #endif
94
95 /* #define SWM_DEBUG */
96 #ifdef SWM_DEBUG
97 #define DPRINTF(x...)           do { if (swm_debug) fprintf(stderr, x); } while(0)
98 #define DNPRINTF(n,x...)        do { if (swm_debug & n) fprintf(stderr, x); } while(0)
99 #define SWM_D_MISC              0x0001
100 #define SWM_D_EVENT             0x0002
101 #define SWM_D_WS                0x0004
102 #define SWM_D_FOCUS             0x0008
103 #define SWM_D_MOVE              0x0010
104 #define SWM_D_STACK             0x0020
105 #define SWM_D_MOUSE             0x0040
106 #define SWM_D_PROP              0x0080
107 #define SWM_D_CLASS             0x0100
108
109 u_int32_t               swm_debug = 0
110                             | SWM_D_MISC
111                             | SWM_D_EVENT
112                             | SWM_D_WS
113                             | SWM_D_FOCUS
114                             | SWM_D_MOVE
115                             | SWM_D_STACK
116                             | SWM_D_MOUSE
117                             | SWM_D_PROP
118                             | SWM_D_CLASS
119                             ;
120 #else
121 #define DPRINTF(x...)
122 #define DNPRINTF(n,x...)
123 #endif
124
125 #define LENGTH(x)               (sizeof x / sizeof x[0])
126 #define MODKEY                  Mod1Mask
127 #define CLEANMASK(mask)         (mask & ~(numlockmask | LockMask))
128 #define BUTTONMASK              (ButtonPressMask|ButtonReleaseMask)
129 #define SWM_PROPLEN             (16)
130 #define X(r)                    (r)->g.x        
131 #define Y(r)                    (r)->g.y
132 #define WIDTH(r)                (r)->g.w        
133 #define HEIGHT(r)               (r)->g.h
134
135 #ifndef SWM_LIB
136 #define SWM_LIB                 "/usr/X11R6/lib/swmhack.so"
137 #endif
138
139 char                    **start_argv;
140 Atom                    astate;
141 int                     (*xerrorxlib)(Display *, XErrorEvent *);
142 int                     other_wm;
143 int                     running = 1;
144 int                     ss_enabled = 0;
145 int                     xrandr_eventbase;
146 int                     ignore_enter = 0;
147 unsigned int            numlockmask = 0;
148 Display                 *display;
149
150 int                     cycle_empty = 0;
151 int                     cycle_visible = 0;
152
153 /* dialog windows */
154 double                  dialog_ratio = .6;
155 /* status bar */
156 #define SWM_BAR_MAX     (128)
157 char                    *bar_argv[] = { NULL, NULL };
158 int                     bar_pipe[2];
159 char                    bar_ext[SWM_BAR_MAX];
160 sig_atomic_t            bar_alarm = 0;
161 int                     bar_delay = 30;
162 int                     bar_enabled = 1;
163 int                     bar_extra = 1;
164 int                     bar_extra_running = 0;
165 int                     bar_verbose = 1;
166 int                     bar_height = 0;
167 pid_t                   bar_pid;
168 GC                      bar_gc;
169 XGCValues               bar_gcv;
170 int                     bar_fidx = 0;
171 XFontStruct             *bar_fs;
172 char                    *bar_fonts[] = {
173                             "-*-terminus-*-*-*-*-*-*-*-*-*-*-*-*",
174                             "-*-times-medium-r-*-*-*-*-*-*-*-*-*-*",
175                             NULL
176 };
177
178 /* terminal + args */
179 char                    *spawn_term[] = { "xterm", NULL };
180 char                    *spawn_screenshot[] = { "screenshot.sh", NULL, NULL };
181 char                    *spawn_menu[] = { "dmenu_run", "-fn", NULL, "-nb", NULL,
182                             "-nf", NULL, "-sb", NULL, "-sf", NULL, NULL };
183
184 #define SWM_MENU_FN     (2)
185 #define SWM_MENU_NB     (4)
186 #define SWM_MENU_NF     (6)
187 #define SWM_MENU_SB     (8)
188 #define SWM_MENU_SF     (10)
189
190 /* layout manager data */
191 struct swm_geometry {
192         int                     x;
193         int                     y;
194         int                     w;
195         int                     h;
196 };
197
198 struct swm_screen;
199 struct workspace;
200
201 /* virtual "screens" */
202 struct swm_region {
203         TAILQ_ENTRY(swm_region) entry;
204         struct swm_geometry     g;
205         Window                  bar_window;
206         struct workspace        *ws;    /* current workspace on this region */
207         struct swm_screen       *s;     /* screen idx */
208 }; 
209 TAILQ_HEAD(swm_region_list, swm_region);
210
211 struct ws_win {
212         TAILQ_ENTRY(ws_win)     entry;
213         Window                  id;
214         struct swm_geometry     g;
215         int                     got_focus;
216         int                     floating;
217         int                     transient;
218         struct workspace        *ws;    /* always valid */
219         struct swm_screen       *s;     /* always valid, never changes */
220         XWindowAttributes       wa;
221         XSizeHints              sh;
222         XClassHint              ch;
223 };
224 TAILQ_HEAD(ws_win_list, ws_win);
225
226 /* layout handlers */
227 void    stack(void);
228 void    vertical_config(struct workspace *, int);
229 void    vertical_stack(struct workspace *, struct swm_geometry *);
230 void    horizontal_config(struct workspace *, int);
231 void    horizontal_stack(struct workspace *, struct swm_geometry *);
232 void    max_stack(struct workspace *, struct swm_geometry *);
233
234 void    grabbuttons(struct ws_win *, int);
235
236 struct layout {
237         void            (*l_stack)(struct workspace *, struct swm_geometry *);
238         void            (*l_config)(struct workspace *, int);
239 } layouts[] =  {
240         /* stack,               configure */
241         { vertical_stack,       vertical_config},
242         { horizontal_stack,     horizontal_config},
243         { max_stack,            NULL},
244         { NULL,                 NULL},
245 };
246
247 #define SWM_H_SLICE             (32)
248 #define SWM_V_SLICE             (32)
249
250 /* define work spaces */
251 struct workspace {
252         int                     idx;            /* workspace index */
253         int                     restack;        /* restack on switch */
254         struct layout           *cur_layout;    /* current layout handlers */
255         struct ws_win           *focus;         /* may be NULL */
256         struct swm_region       *r;             /* may be NULL */
257         struct ws_win_list      winlist;        /* list of windows in ws */
258
259         /* stacker state */
260         struct {
261                                 int horizontal_msize;
262                                 int horizontal_mwin;
263                                 int vertical_msize;
264                                 int vertical_mwin;
265         } l_state;
266 };
267
268 enum    { SWM_S_COLOR_BAR, SWM_S_COLOR_BAR_BORDER, SWM_S_COLOR_BAR_FONT,
269           SWM_S_COLOR_FOCUS, SWM_S_COLOR_UNFOCUS, SWM_S_COLOR_MAX };
270
271 /* physical screen mapping */
272 #define SWM_WS_MAX              (10)            /* XXX Too small? */
273 struct swm_screen {
274         int                     idx;            /* screen index */
275         struct swm_region_list  rl;     /* list of regions on this screen */
276         Window                  root;
277         int                     xrandr_support;
278         struct workspace        ws[SWM_WS_MAX];
279
280         /* colors */
281         struct {
282                 unsigned long   color;
283                 char            *name;
284         } c[SWM_S_COLOR_MAX];
285 };
286 struct swm_screen       *screens;
287 int                     num_screens;
288
289 struct ws_win           *cur_focus = NULL;
290
291 /* args to functions */
292 union arg {
293         int                     id;
294 #define SWM_ARG_ID_FOCUSNEXT    (0)
295 #define SWM_ARG_ID_FOCUSPREV    (1)
296 #define SWM_ARG_ID_FOCUSMAIN    (2)
297 #define SWM_ARG_ID_SWAPNEXT     (3)
298 #define SWM_ARG_ID_SWAPPREV     (4)
299 #define SWM_ARG_ID_SWAPMAIN     (5)
300 #define SWM_ARG_ID_MASTERSHRINK (6)
301 #define SWM_ARG_ID_MASTERGROW   (7)
302 #define SWM_ARG_ID_MASTERADD    (8)
303 #define SWM_ARG_ID_MASTERDEL    (9)
304 #define SWM_ARG_ID_STACKRESET   (10)
305 #define SWM_ARG_ID_STACKINIT    (11)
306 #define SWM_ARG_ID_CYCLEWS_UP   (12)
307 #define SWM_ARG_ID_CYCLEWS_DOWN (13)
308 #define SWM_ARG_ID_CYCLESC_UP   (14)
309 #define SWM_ARG_ID_CYCLESC_DOWN (15)
310 #define SWM_ARG_ID_SS_ALL       (0)
311 #define SWM_ARG_ID_SS_WINDOW    (1)
312         char                    **argv;
313 };
314
315 struct quirk {
316         char                    *class;
317         char                    *name;
318         unsigned long           quirk;
319 #define SWM_Q_FLOAT             (1<<0)
320 } quirks[] = {
321         { "MPlayer",            "xv",           SWM_Q_FLOAT },
322         { "OpenOffice.org 2.4", "VCLSalFrame",  SWM_Q_FLOAT },
323         { NULL,         NULL,           0},
324 };
325
326 unsigned long
327 name_to_color(char *colorname)
328 {
329         Colormap                cmap;
330         Status                  status;
331         XColor                  screen_def, exact_def;
332         unsigned long           result = 0;
333         char                    cname[32] = "#";
334
335         cmap = DefaultColormap(display, screens[0].idx);
336         status = XAllocNamedColor(display, cmap, colorname,
337             &screen_def, &exact_def);
338         if (!status) {
339                 strlcat(cname, colorname + 2, sizeof cname - 1);
340                 status = XAllocNamedColor(display, cmap, cname, &screen_def,
341                     &exact_def);
342         }
343         if (status)
344                 result = screen_def.pixel;
345         else
346                 fprintf(stderr, "color '%s' not found.\n", colorname);
347
348         return (result);
349 }
350
351 void
352 setscreencolor(char *val, int i, int c)
353 {
354         if (i > 0 && i <= ScreenCount(display)) {
355                 screens[i - 1].c[c].color = name_to_color(val);
356                 if ((screens[i - 1].c[c].name = strdup(val)) == NULL)
357                         errx(1, "strdup");
358         } else if (i == -1) {
359                 for (i = 0; i < ScreenCount(display); i++)
360                         screens[i].c[c].color = name_to_color(val);
361                         if ((screens[i - 1].c[c].name = strdup(val)) == NULL)
362                                 errx(1, "strdup");
363         } else
364                 errx(1, "invalid screen index: %d out of bounds (maximum %d)\n",
365                     i, ScreenCount(display));
366 }
367
368 int
369 varmatch(char *var, char *name, int *index)
370 {
371         char                    *p, buf[5];
372         int                     i;
373
374         i = strncmp(var, name, 255);
375         if (index == NULL)
376                 return (i);
377
378         *index = -1;
379         if (i <= 0)
380                 return (i);
381         p = var + strlen(name);
382         if (*p++ != '[')
383                 return (i);
384         bzero(buf, sizeof buf);
385         i = 0;
386         while (isdigit(*p) && i < sizeof buf)
387                 buf[i++] = *p++;
388         if (i == 0 || i >= sizeof buf || *p != ']')
389                 return (1);
390         *index = strtonum(buf, 0, 99, NULL);
391         return (0);
392 }
393
394 /* conf file stuff */
395 #define SWM_CONF_WS     "\n= \t"
396 #define SWM_CONF_FILE   "scrotwm.conf"
397 int
398 conf_load(char *filename)
399 {
400         FILE                    *config;
401         char                    *line, *cp, *var, *val;
402         size_t                  len, lineno = 0;
403         int                     i, sc;
404
405         DNPRINTF(SWM_D_MISC, "conf_load: filename %s\n", filename);
406
407         if (filename == NULL)
408                 return (1);
409
410         if ((config = fopen(filename, "r")) == NULL)
411                 return (1);
412
413         for (sc = ScreenCount(display);;) {
414                 if ((line = fparseln(config, &len, &lineno, NULL, 0)) == NULL)
415                         if (feof(config))
416                                 break;
417                 cp = line;
418                 cp += (long)strspn(cp, SWM_CONF_WS);
419                 if (cp[0] == '\0') {
420                         /* empty line */
421                         free(line);
422                         continue;
423                 }
424                 if ((var = strsep(&cp, SWM_CONF_WS)) == NULL || cp == NULL)
425                         break;
426                 cp += (long)strspn(cp, SWM_CONF_WS);
427                 if ((val = strsep(&cp, SWM_CONF_WS)) == NULL)
428                         break;
429
430                 DNPRINTF(SWM_D_MISC, "conf_load: %s=%s\n",var ,val);
431                 switch (var[0]) {
432                 case 'b':
433                         if (!strncmp(var, "bar_enabled", strlen("bar_enabled")))
434                                 bar_enabled = atoi(val);
435                         else if (!varmatch(var, "bar_border", &i))
436                                 setscreencolor(val, i, SWM_S_COLOR_BAR_BORDER);
437                         else if (!varmatch(var, "bar_color", &i))
438                                 setscreencolor(val, i, SWM_S_COLOR_BAR);
439                         else if (!varmatch(var, "bar_font_color", &i))
440                                 setscreencolor(val, i, SWM_S_COLOR_BAR_FONT);
441                         else if (!strncmp(var, "bar_font", strlen("bar_font")))
442                                 asprintf(&bar_fonts[0], "%s", val);
443                         else if (!strncmp(var, "bar_action", strlen("bar_action")))
444                                 asprintf(&bar_argv[0], "%s", val);
445                         else if (!strncmp(var, "bar_delay", strlen("bar_delay")))
446                                 bar_delay = atoi(val);
447                         else
448                                 goto bad;
449                         break;
450
451                 case 'c':
452                         if (!varmatch(var, "color_focus", &i))
453                                 setscreencolor(val, i, SWM_S_COLOR_FOCUS);
454                         else if (!varmatch(var, "color_unfocus", &i))
455                                 setscreencolor(val, i, SWM_S_COLOR_UNFOCUS);
456                         else if (!strncmp(var, "cycle_empty", strlen("cycle_empty")))
457                                 cycle_visible = atoi(val);
458                         else if (!strncmp(var, "cycle_visible", strlen("cycle_visible")))
459                                 cycle_visible = atoi(val);
460                         else
461                                 goto bad;
462                         break;
463
464                 case 'd':
465                         if (!strncmp(var, "dialog_ratio",
466                             strlen("dialog_ratio"))) {
467                                 dialog_ratio = atof(val);
468                                 if (dialog_ratio > 1.0 || dialog_ratio <= .3)
469                                         dialog_ratio = .6;
470                         } else
471                                 goto bad;
472                         break;
473
474                 case 's':
475                         if (!strncmp(var, "spawn_term", strlen("spawn_term")))
476                                 asprintf(&spawn_term[0], "%s", val);
477                         if (!strncmp(var, "screenshot_enabled",
478                             strlen("screenshot_enabled")))
479                                 ss_enabled = atoi(val);
480                         if (!strncmp(var, "screenshot_app",
481                             strlen("screenshot_app")))
482                                 asprintf(&spawn_screenshot[0], "%s", val);
483                         break;
484                 default:
485                         goto bad;
486                 }
487                 free(line);
488         }
489
490         fclose(config);
491         return (0);
492
493 bad:
494         errx(1, "invalid conf file entry: %s=%s", var, val);
495 }
496
497 void
498 socket_setnonblock(int fd)
499 {
500         int                     flags;
501
502         if ((flags = fcntl(fd, F_GETFL, 0)) == -1)
503                 err(1, "fcntl F_GETFL");
504         flags |= O_NONBLOCK;
505         if ((flags = fcntl(fd, F_SETFL, flags)) == -1)
506                 err(1, "fcntl F_SETFL");
507 }
508
509 void
510 bar_print(struct swm_region *r, char *s)
511 {
512         XClearWindow(display, r->bar_window);
513         XSetForeground(display, bar_gc, r->s->c[SWM_S_COLOR_BAR_FONT].color);
514         XDrawString(display, r->bar_window, bar_gc, 4, bar_fs->ascent, s,
515             strlen(s));
516 }
517
518 void
519 bar_extra_stop(void)
520 {
521         if (bar_pipe[0]) {
522                 close(bar_pipe[0]);
523                 bzero(bar_pipe, sizeof bar_pipe);
524         }
525         if (bar_pid) {
526                 kill(bar_pid, SIGTERM);
527                 bar_pid = 0;
528         }
529         strlcpy(bar_ext, "", sizeof bar_ext);
530         bar_extra = 0;
531 }
532
533 void
534 bar_update(void)
535 {
536         time_t                  tmt;
537         struct tm               tm;
538         struct swm_region       *r;
539         int                     i, x;
540         size_t                  len;
541         char                    s[SWM_BAR_MAX];
542         char                    loc[SWM_BAR_MAX];
543         char                    *b;
544
545         if (bar_enabled == 0)
546                 return;
547
548         if (bar_extra && bar_extra_running) {
549                 /* ignore short reads; it'll correct itself */
550                 while ((b = fgetln(stdin, &len)) != NULL)
551                         if (b && b[len - 1] == '\n') {
552                                 b[len - 1] = '\0';
553                                 strlcpy(bar_ext, b, sizeof bar_ext);
554                         }
555                 if (b == NULL && errno != EAGAIN) {
556                         fprintf(stderr, "bar_extra failed: errno: %d %s\n",
557                             errno, strerror(errno));
558                         bar_extra_stop();
559                 }
560         } else
561                 strlcpy(bar_ext, "", sizeof bar_ext);
562
563         time(&tmt);
564         localtime_r(&tmt, &tm);
565         strftime(s, sizeof s, "%a %b %d %R %Z %Y", &tm);
566         for (i = 0; i < ScreenCount(display); i++) {
567                 x = 1;
568                 TAILQ_FOREACH(r, &screens[i].rl, entry) {
569                         snprintf(loc, sizeof loc, "%s     %d:%d    %s",
570                             s, x++, r->ws->idx + 1, bar_ext);
571                         bar_print(r, loc);
572                 }
573         }
574         XSync(display, False);
575         alarm(bar_delay);
576 }
577
578 void
579 bar_signal(int sig)
580 {
581         bar_alarm = 1;
582 }
583
584 void
585 bar_toggle(struct swm_region *r, union arg *args)
586 {
587         struct swm_region       *tmpr;
588         int                     i, j, sc = ScreenCount(display);
589
590         DNPRINTF(SWM_D_MISC, "bar_toggle\n");
591
592         if (bar_enabled) {
593                 for (i = 0; i < sc; i++)
594                         TAILQ_FOREACH(tmpr, &screens[i].rl, entry)
595                                 XUnmapWindow(display, tmpr->bar_window);
596         } else {
597                 for (i = 0; i < sc; i++)
598                         TAILQ_FOREACH(tmpr, &screens[i].rl, entry)
599                                 XMapRaised(display, tmpr->bar_window);
600         }
601         bar_enabled = !bar_enabled;
602         XSync(display, False);
603         for (i = 0; i < sc; i++)
604                 for (j = 0; j < SWM_WS_MAX; j++)
605                         screens[i].ws[j].restack = 1;
606
607         stack();
608         /* must be after stack */
609         for (i = 0; i < sc; i++)
610                 TAILQ_FOREACH(tmpr, &screens[i].rl, entry)
611                         bar_update();
612 }
613
614 void
615 bar_refresh(void)
616 {
617         XSetWindowAttributes    wa;
618         struct swm_region       *r;
619         int                     i;
620
621         /* do this here because the conf file is in memory */
622         if (bar_extra && bar_extra_running == 0 && bar_argv[0]) {
623                 /* launch external status app */
624                 bar_extra_running = 1;
625                 if (pipe(bar_pipe) == -1)
626                         err(1, "pipe error");
627                 socket_setnonblock(bar_pipe[0]);
628                 socket_setnonblock(bar_pipe[1]); /* XXX hmmm, really? */
629                 if (dup2(bar_pipe[0], 0) == -1)
630                         errx(1, "dup2");
631                 if (dup2(bar_pipe[1], 1) == -1)
632                         errx(1, "dup2");
633                 if (signal(SIGPIPE, SIG_IGN) == SIG_ERR)
634                         err(1, "could not disable SIGPIPE");
635                 switch (bar_pid = fork()) {
636                 case -1:
637                         err(1, "cannot fork");
638                         break;
639                 case 0: /* child */
640                         close(bar_pipe[0]);
641                         execvp(bar_argv[0], bar_argv);
642                         err(1, "%s external app failed", bar_argv[0]);
643                         break;
644                 default: /* parent */
645                         close(bar_pipe[1]);
646                         break;
647                 }
648         }
649
650         bzero(&wa, sizeof wa);
651         for (i = 0; i < ScreenCount(display); i++)
652                 TAILQ_FOREACH(r, &screens[i].rl, entry) {
653                         wa.border_pixel =
654                             screens[i].c[SWM_S_COLOR_BAR_BORDER].color;
655                         wa.background_pixel =
656                             screens[i].c[SWM_S_COLOR_BAR].color;
657                         XChangeWindowAttributes(display, r->bar_window,
658                             CWBackPixel | CWBorderPixel, &wa);
659                 }
660         bar_update();
661 }
662
663 void
664 bar_setup(struct swm_region *r)
665 {
666         int                     i;
667
668         for (i = 0; bar_fonts[i] != NULL; i++) {
669                 bar_fs = XLoadQueryFont(display, bar_fonts[i]);
670                 if (bar_fs) {
671                         bar_fidx = i;
672                         break;
673                 }
674         }
675         if (bar_fonts[i] == NULL)
676                         errx(1, "couldn't load font");
677         bar_height = bar_fs->ascent + bar_fs->descent + 3;
678
679         r->bar_window = XCreateSimpleWindow(display, 
680             r->s->root, X(r), Y(r), WIDTH(r) - 2, bar_height - 2,
681             1, r->s->c[SWM_S_COLOR_BAR_BORDER].color,
682             r->s->c[SWM_S_COLOR_BAR].color);
683         bar_gc = XCreateGC(display, r->bar_window, 0, &bar_gcv);
684         XSetFont(display, bar_gc, bar_fs->fid);
685         XSelectInput(display, r->bar_window, VisibilityChangeMask);
686         if (bar_enabled)
687                 XMapRaised(display, r->bar_window);
688         DNPRINTF(SWM_D_MISC, "bar_setup: bar_window %lu\n", r->bar_window);
689
690         if (signal(SIGALRM, bar_signal) == SIG_ERR)
691                 err(1, "could not install bar_signal");
692         bar_refresh();
693 }
694
695 void
696 config_win(struct ws_win *win)
697 {
698         XConfigureEvent         ce;
699
700         DNPRINTF(SWM_D_MISC, "config_win: win %lu x %d y %d w %d h %d\n",
701             win->id, win->g.x, win->g.y, win->g.w, win->g.h);
702         ce.type = ConfigureNotify;
703         ce.display = display;
704         ce.event = win->id;
705         ce.window = win->id;
706         ce.x = win->g.x;
707         ce.y = win->g.y;
708         ce.width = win->g.w;
709         ce.height = win->g.h;
710         ce.border_width = 1; /* XXX store this! */
711         ce.above = None;
712         ce.override_redirect = False;
713         XSendEvent(display, win->id, False, StructureNotifyMask, (XEvent *)&ce);
714 }
715
716 int
717 count_win(struct workspace *ws, int count_transient)
718 {
719         struct ws_win           *win;
720         int                     count = 0;
721
722         TAILQ_FOREACH(win, &ws->winlist, entry) {
723                 if (count_transient == 0 && win->floating)
724                         continue;
725                 if (count_transient == 0 && win->transient)
726                         continue;
727                 count++;
728         }
729         DNPRINTF(SWM_D_MISC, "count_win: %d\n", count);
730
731         return (count);
732 }
733
734 void
735 quit(struct swm_region *r, union arg *args)
736 {
737         DNPRINTF(SWM_D_MISC, "quit\n");
738         running = 0;
739 }
740
741 void
742 unmap_all(void)
743 {
744         struct ws_win           *win;
745         int                     i, j;
746
747         for (i = 0; i < ScreenCount(display); i++)
748                 for (j = 0; j < SWM_WS_MAX; j++)
749                         TAILQ_FOREACH(win, &screens[i].ws[j].winlist, entry)
750                                 XUnmapWindow(display, win->id);
751 }
752
753 void
754 restart(struct swm_region *r, union arg *args)
755 {
756         DNPRINTF(SWM_D_MISC, "restart: %s\n", start_argv[0]);
757
758         /* disable alarm because the following code may not be interrupted */
759         alarm(0);
760         if (signal(SIGALRM, SIG_IGN) == SIG_ERR)
761                 errx(1, "can't disable alarm");
762
763         bar_extra_stop();
764         bar_extra = 1;
765         unmap_all();
766         XCloseDisplay(display);
767         execvp(start_argv[0], start_argv);
768         fprintf(stderr, "execvp failed\n");
769         perror(" failed");
770         quit(NULL, NULL);
771 }
772
773 struct swm_region *
774 root_to_region(Window root)
775 {
776         struct swm_region       *r;
777         Window                  rr, cr;
778         int                     i, x, y, wx, wy;
779         unsigned int            mask;
780
781         for (i = 0; i < ScreenCount(display); i++)
782                 if (screens[i].root == root)
783                         break;
784
785         if (XQueryPointer(display, screens[i].root, 
786             &rr, &cr, &x, &y, &wx, &wy, &mask) == False) {
787                 /* if we can't query the pointer, grab the first region */
788                 r = TAILQ_FIRST(&screens[i].rl);
789         } else {
790                 /* otherwise, choose a region based on pointer location */
791                 TAILQ_FOREACH(r, &screens[i].rl, entry) {
792                         if (x >= X(r) && x <= X(r) + WIDTH(r) &&
793                             y >= Y(r) && y <= Y(r) + HEIGHT(r))
794                                 break;
795                 }
796
797                 if (r == NULL)
798                         r = TAILQ_FIRST(&screens[i].rl);
799         }
800         return (r);
801 }
802
803 struct ws_win *
804 find_window(Window id)
805 {
806         struct ws_win           *win;
807         int                     i, j;
808
809         for (i = 0; i < ScreenCount(display); i++)
810                 for (j = 0; j < SWM_WS_MAX; j++)
811                         TAILQ_FOREACH(win, &screens[i].ws[j].winlist, entry)
812                                 if (id == win->id)
813                                         return (win);
814         return (NULL);
815 }
816
817 void
818 spawn(struct swm_region *r, union arg *args)
819 {
820         char                    *ret;
821         int                     si;
822
823         DNPRINTF(SWM_D_MISC, "spawn: %s\n", args->argv[0]);
824         /*
825          * The double-fork construct avoids zombie processes and keeps the code
826          * clean from stupid signal handlers.
827          */
828         if (fork() == 0) {
829                 if (fork() == 0) {
830                         if (display)
831                                 close(ConnectionNumber(display));
832                         setenv("LD_PRELOAD", SWM_LIB, 1);
833                         if (asprintf(&ret, "%d", r->ws->idx)) {
834                                 setenv("_SWM_WS", ret, 1);
835                                 free(ret);
836                         }
837                         if (asprintf(&ret, "%d", getpid())) {
838                                 setenv("_SWM_PID", ret, 1);
839                                 free(ret);
840                         }
841                         setsid();
842                         /* kill stdin, mplayer, ssh-add etc. need that */
843                         si = open("/dev/null", O_RDONLY, 0);
844                         if (si == -1)
845                                 err(1, "open /dev/null");
846                         if (dup2(si, 0) == -1)
847                                 err(1, "dup2 /dev/null");
848                         execvp(args->argv[0], args->argv);
849                         fprintf(stderr, "execvp failed\n");
850                         perror(" failed");
851                 }
852                 exit(0);
853         }
854         wait(0);
855 }
856
857 void
858 spawnmenu(struct swm_region *r, union arg *args)
859 {
860         DNPRINTF(SWM_D_MISC, "spawnmenu\n");
861
862         spawn_menu[SWM_MENU_FN] = bar_fonts[bar_fidx];
863         spawn_menu[SWM_MENU_NB] = r->s->c[SWM_S_COLOR_BAR].name;
864         spawn_menu[SWM_MENU_NF] = r->s->c[SWM_S_COLOR_BAR_FONT].name;
865         spawn_menu[SWM_MENU_SB] = r->s->c[SWM_S_COLOR_BAR_BORDER].name;
866         spawn_menu[SWM_MENU_SF] = r->s->c[SWM_S_COLOR_BAR].name;
867
868         spawn(r, args);
869 }
870
871 void
872 unfocus_all(void)
873 {
874         struct ws_win           *win;
875         int                     i, j;
876
877         DNPRINTF(SWM_D_FOCUS, "unfocus_all:\n");
878
879         for (i = 0; i < ScreenCount(display); i++)
880                 for (j = 0; j < SWM_WS_MAX; j++)
881                         TAILQ_FOREACH(win, &screens[i].ws[j].winlist, entry) {
882                                 if (win->ws->r == NULL)
883                                         continue;
884                                 grabbuttons(win, 0);
885                                 XSetWindowBorder(display, win->id,
886                                     win->ws->r->s->c[SWM_S_COLOR_UNFOCUS].color);
887                                 win->got_focus = 0;
888                                 win->ws->focus = NULL;
889                                 cur_focus = NULL;
890                         }
891 }
892
893 void
894 focus_win(struct ws_win *win)
895 {
896         DNPRINTF(SWM_D_FOCUS, "focus_win: id: %lu\n", win ? win->id : 0);
897
898         if (win == NULL)
899                 return;
900
901         unfocus_all();
902         win->ws->focus = win;
903         if (win->ws->r != NULL) {
904                 cur_focus = win;
905                 if (!win->got_focus) {
906                         XSetWindowBorder(display, win->id,
907                             win->ws->r->s->c[SWM_S_COLOR_FOCUS].color);
908                         grabbuttons(win, 1);
909                 }
910                 win->got_focus = 1;
911                 XSetInputFocus(display, win->id,
912                     RevertToPointerRoot, CurrentTime);
913         }
914 }
915
916 void
917 switchws(struct swm_region *r, union arg *args)
918 {
919         int                     wsid = args->id;
920         struct swm_region       *this_r, *other_r;
921         struct ws_win           *win;
922         struct workspace        *new_ws, *old_ws;
923
924         this_r = r;
925         old_ws = this_r->ws;
926         new_ws = &this_r->s->ws[wsid];
927
928         DNPRINTF(SWM_D_WS, "switchws screen %d region %dx%d+%d+%d: "
929             "%d -> %d\n", r->s->idx, WIDTH(r), HEIGHT(r), X(r), Y(r),
930             old_ws->idx, wsid);
931
932         if (new_ws == old_ws)
933                 return;
934
935         other_r = new_ws->r;
936         if (!other_r) {
937                 /* if the other workspace is hidden, switch windows */
938                 /* map new window first to prevent ugly blinking */
939                 TAILQ_FOREACH(win, &new_ws->winlist, entry)
940                         XMapRaised(display, win->id);
941
942                 TAILQ_FOREACH(win, &old_ws->winlist, entry)
943                         XUnmapWindow(display, win->id);
944                 old_ws->r = NULL;
945                 old_ws->restack = 1;
946         } else {
947                 other_r->ws = old_ws;
948                 old_ws->r = other_r;
949         }
950         this_r->ws = new_ws;
951         new_ws->r = this_r;
952
953         ignore_enter = 1;
954         /* set focus */
955         if (new_ws->focus)
956                 focus_win(new_ws->focus);
957         stack();
958         bar_update();
959 }
960
961 void
962 cyclews(struct swm_region *r, union arg *args)
963 {
964         union                   arg a;
965         struct swm_screen       *s = r->s;
966
967         DNPRINTF(SWM_D_WS, "cyclews id %d "
968             "in screen %d region %dx%d+%d+%d ws %d\n", args->id,
969             r->s->idx, WIDTH(r), HEIGHT(r), X(r), Y(r), r->ws->idx);
970
971         a.id = r->ws->idx;
972         do {
973                 switch (args->id) {
974                 case SWM_ARG_ID_CYCLEWS_UP:
975                         if (a.id < SWM_WS_MAX - 1)
976                                 a.id++;
977                         else
978                                 a.id = 0;
979                         break;
980                 case SWM_ARG_ID_CYCLEWS_DOWN:
981                         if (a.id > 0)
982                                 a.id--;
983                         else
984                                 a.id = SWM_WS_MAX - 1;
985                         break;
986                 default:
987                         return;
988                 };
989
990                 if (cycle_empty == 0 && TAILQ_EMPTY(&s->ws[a.id].winlist))
991                         continue;
992                 if (cycle_visible == 0 && s->ws[a.id].r != NULL)
993                         continue;
994
995                 switchws(r, &a);
996         } while (a.id != r->ws->idx);
997 }
998
999 void
1000 cyclescr(struct swm_region *r, union arg *args)
1001 {
1002         struct swm_region       *rr;
1003         int                     i;
1004
1005         i = r->s->idx;
1006         switch (args->id) {
1007         case SWM_ARG_ID_CYCLESC_UP:
1008                 rr = TAILQ_NEXT(r, entry);
1009                 if (rr == NULL)
1010                         rr = TAILQ_FIRST(&screens[i].rl);
1011                 break;
1012         case SWM_ARG_ID_CYCLESC_DOWN:
1013                 rr = TAILQ_PREV(r, swm_region_list, entry);
1014                 if (rr == NULL)
1015                         rr = TAILQ_LAST(&screens[i].rl, swm_region_list);
1016                 break;
1017         default:
1018                 return;
1019         };
1020         unfocus_all();
1021         XSetInputFocus(display, PointerRoot, RevertToPointerRoot, CurrentTime);
1022         XWarpPointer(display, None, rr->s[i].root, 0, 0, 0, 0, rr->g.x,
1023             rr->g.y + bar_enabled ? bar_height : 0);
1024 }
1025
1026 void
1027 swapwin(struct swm_region *r, union arg *args)
1028 {
1029         struct ws_win           *target;
1030         struct ws_win_list      *wl;
1031
1032
1033         DNPRINTF(SWM_D_WS, "swapwin id %d "
1034             "in screen %d region %dx%d+%d+%d ws %d\n", args->id,
1035             r->s->idx, WIDTH(r), HEIGHT(r), X(r), Y(r), r->ws->idx);
1036         if (cur_focus == NULL)
1037                 return;
1038
1039         wl = &cur_focus->ws->winlist;
1040
1041         switch (args->id) {
1042         case SWM_ARG_ID_SWAPPREV:
1043                 target = TAILQ_PREV(cur_focus, ws_win_list, entry);
1044                 TAILQ_REMOVE(wl, cur_focus, entry);
1045                 if (target == NULL)
1046                         TAILQ_INSERT_TAIL(wl, cur_focus, entry);
1047                 else
1048                         TAILQ_INSERT_BEFORE(target, cur_focus, entry);
1049                 break;
1050         case SWM_ARG_ID_SWAPNEXT: 
1051                 target = TAILQ_NEXT(cur_focus, entry);
1052                 TAILQ_REMOVE(wl, cur_focus, entry);
1053                 if (target == NULL)
1054                         TAILQ_INSERT_HEAD(wl, cur_focus, entry);
1055                 else
1056                         TAILQ_INSERT_AFTER(wl, target, cur_focus, entry);
1057                 break;
1058         case SWM_ARG_ID_SWAPMAIN:
1059                 target = TAILQ_FIRST(wl);
1060                 if (target == cur_focus)
1061                         return;
1062                 TAILQ_REMOVE(wl, target, entry);
1063                 TAILQ_INSERT_BEFORE(cur_focus, target, entry);
1064                 TAILQ_REMOVE(wl, cur_focus, entry);
1065                 TAILQ_INSERT_HEAD(wl, cur_focus, entry);
1066                 break;
1067         default:
1068                 DNPRINTF(SWM_D_MOVE, "invalid id: %d\n", args->id);
1069                 return;
1070         }
1071
1072         ignore_enter = 2;
1073         stack();
1074 }
1075
1076 void
1077 focus(struct swm_region *r, union arg *args)
1078 {
1079         struct ws_win           *winfocus, *winlostfocus;
1080         struct ws_win_list      *wl;
1081
1082         DNPRINTF(SWM_D_FOCUS, "focus: id %d\n", args->id);
1083         if (cur_focus == NULL)
1084                 return;
1085
1086         wl = &cur_focus->ws->winlist;
1087
1088         winlostfocus = cur_focus;
1089
1090         switch (args->id) {
1091         case SWM_ARG_ID_FOCUSPREV:
1092                 winfocus = TAILQ_PREV(cur_focus, ws_win_list, entry);
1093                 if (winfocus == NULL)
1094                         winfocus = TAILQ_LAST(wl, ws_win_list);
1095                 break;
1096
1097         case SWM_ARG_ID_FOCUSNEXT:
1098                 winfocus = TAILQ_NEXT(cur_focus, entry);
1099                 if (winfocus == NULL)
1100                         winfocus = TAILQ_FIRST(wl);
1101                 break;
1102
1103         case SWM_ARG_ID_FOCUSMAIN:
1104                 winfocus = TAILQ_FIRST(wl);
1105                 break;
1106
1107         default:
1108                 return;
1109         }
1110
1111         if (winfocus == winlostfocus || winfocus == NULL)
1112                 return;
1113
1114         XMapRaised(display, winfocus->id);
1115         focus_win(winfocus);
1116         XSync(display, False);
1117 }
1118
1119 void
1120 cycle_layout(struct swm_region *r, union arg *args)
1121 {
1122         struct workspace        *ws = r->ws;
1123
1124         DNPRINTF(SWM_D_EVENT, "cycle_layout: workspace: %d\n", ws->idx);
1125
1126         ws->cur_layout++;
1127         if (ws->cur_layout->l_stack == NULL)
1128                 ws->cur_layout = &layouts[0];
1129         ignore_enter = 1;
1130         stack();
1131 }
1132
1133 void
1134 stack_config(struct swm_region *r, union arg *args)
1135 {
1136         struct workspace        *ws = r->ws;
1137
1138         DNPRINTF(SWM_D_STACK, "stack_config for workspace %d (id %d\n",
1139             args->id, ws->idx);
1140
1141         if (ws->cur_layout->l_config != NULL)
1142                 ws->cur_layout->l_config(ws, args->id);
1143
1144         if (args->id != SWM_ARG_ID_STACKINIT);
1145                 stack();
1146 }
1147
1148 void
1149 stack(void) {
1150         struct swm_geometry     g;
1151         struct swm_region       *r;
1152         int                     i, j;
1153
1154         DNPRINTF(SWM_D_STACK, "stack\n");
1155
1156         for (i = 0; i < ScreenCount(display); i++) {
1157                 j = 0;
1158                 TAILQ_FOREACH(r, &screens[i].rl, entry) {
1159                         DNPRINTF(SWM_D_STACK, "stacking workspace %d "
1160                             "(screen %d, region %d)\n", r->ws->idx, i, j++);
1161
1162                         /* start with screen geometry, adjust for bar */
1163                         g = r->g;
1164                         g.w -= 2;
1165                         g.h -= 2;
1166                         if (bar_enabled) {
1167                                 g.y += bar_height;
1168                                 g.h -= bar_height;
1169                         } 
1170
1171                         r->ws->restack = 0;
1172                         r->ws->cur_layout->l_stack(r->ws, &g);
1173                 }
1174         }
1175         XSync(display, False);
1176 }
1177
1178 void
1179 stack_floater(struct ws_win *win, struct swm_region *r)
1180 {
1181         unsigned int            mask;
1182         XWindowChanges          wc;
1183
1184         bzero(&wc, sizeof wc);
1185         mask = CWX | CWY | CWBorderWidth | CWWidth | CWHeight;
1186         wc.border_width = 1;
1187         if (win->transient) {
1188                 win->g.w = (double)WIDTH(r) * dialog_ratio;
1189                 win->g.h = (double)HEIGHT(r) * dialog_ratio;
1190         }
1191         wc.width = win->g.w;
1192         wc.height = win->g.h;
1193         wc.x = (WIDTH(r) - win->g.w) / 2;
1194         wc.y = (HEIGHT(r) - win->g.h) / 2;
1195
1196         DNPRINTF(SWM_D_STACK, "stack_floater: win %lu x %d y %d w %d h %d\n",
1197             win->id, wc.x, wc.y, wc.width, wc.height);
1198
1199         XConfigureWindow(display, win->id, mask, &wc);
1200 }
1201
1202 #define SWAPXY(g)       do {                            \
1203         int tmp;                                        \
1204         tmp = (g)->y; (g)->y = (g)->x; (g)->x = tmp;    \
1205         tmp = (g)->h; (g)->h = (g)->w; (g)->w = tmp;    \
1206 } while (0)
1207 void
1208 stack_master(struct workspace *ws, struct swm_geometry *g, int rot, int flip)
1209 {
1210         XWindowChanges          wc;
1211         struct swm_geometry     win_g, r_g = *g;
1212         struct ws_win           *win, *winfocus;
1213         int                     i, j, w_inc, h_inc, w_base, h_base;
1214         int                     hrh, extra, h_slice, last_h = 0;
1215         int                     split, colno, winno, mwin, msize, mscale;
1216         int                     remain, missing, v_slice;;
1217         unsigned int            mask;
1218
1219         DNPRINTF(SWM_D_STACK, "stack_master: workspace: %d\n rot=%s flip=%s",
1220             ws->idx, rot ? "yes" : "no", flip ? "yes" : "no");
1221
1222         if ((winno = count_win(ws, 0)) == 0)
1223                 return;
1224
1225         if (ws->focus == NULL)
1226                 ws->focus = TAILQ_FIRST(&ws->winlist);
1227         winfocus = cur_focus ? cur_focus : ws->focus;
1228
1229         win = TAILQ_FIRST(&ws->winlist);
1230         if (rot) {
1231                 w_inc = win->sh.width_inc;
1232                 w_base = win->sh.base_width;
1233                 mwin = ws->l_state.horizontal_mwin;
1234                 mscale = ws->l_state.horizontal_msize;
1235                 SWAPXY(&r_g);
1236         } else {
1237                 w_inc = win->sh.height_inc;
1238                 w_base = win->sh.base_height;
1239                 mwin = ws->l_state.vertical_mwin;
1240                 mscale = ws->l_state.vertical_msize;
1241         }
1242         win_g = r_g;
1243
1244         h_slice = r_g.h / SWM_H_SLICE;
1245         if (mwin && winno > mwin) {
1246                 v_slice = r_g.w / SWM_V_SLICE;
1247
1248                 split = mwin;
1249                 colno = split;
1250                 msize = v_slice * mscale;
1251
1252                 if (w_inc > 1 && w_inc < v_slice) {
1253                         /* adjust for window's requested size increment */
1254                         remain = (win_g.w - w_base) % w_inc;
1255                         missing = w_inc - remain;
1256
1257                         if (missing <= extra || j == 0) {
1258                                 extra -= missing;
1259                                 win_g.w += missing;
1260                         } else {
1261                                 win_g.w -= remain;
1262                                 extra += remain;
1263                         }
1264                 }
1265
1266                 win_g.w = msize;
1267                 if (flip) 
1268                         win_g.x += r_g.w - msize;
1269         } else {
1270                 colno = winno;
1271                 split = 0;
1272         }
1273         hrh = r_g.h / colno;
1274         extra = r_g.h - (colno * hrh);
1275         win_g.h = hrh - 2;
1276
1277         i = j = 0;
1278         TAILQ_FOREACH(win, &ws->winlist, entry) {
1279                 if (split && i == split) {
1280                         colno = winno - split;
1281                         hrh = (r_g.h / colno);
1282                         extra = r_g.h - (colno * hrh);
1283                         if (flip)
1284                                 win_g.x = r_g.x;
1285                         else
1286                                 win_g.x += msize + 2;
1287                         win_g.w = r_g.w - (msize + 2);
1288                         j = 0;
1289                 }
1290                 win_g.h = hrh - 2;
1291                 if (rot) {
1292                         h_inc = win->sh.width_inc;
1293                         h_base = win->sh.base_width;
1294                 } else {
1295                         h_inc = win->sh.height_inc;     
1296                         h_base = win->sh.base_height;
1297                 }
1298                 if (j == colno - 1) {
1299                         win_g.h = hrh + extra;
1300                 } else if (h_inc > 1 && h_inc < h_slice) {
1301                         /* adjust for window's requested size increment */
1302                         remain = (win_g.h - h_base) % h_inc;
1303                         missing = h_inc - remain;
1304
1305                         if (missing <= extra || j == 0) {
1306                                 extra -= missing;
1307                                 win_g.h += missing;
1308                         } else {
1309                                 win_g.h -= remain;
1310                                 extra += remain;
1311                         }
1312                 }
1313                  
1314                 if (j == 0)
1315                         win_g.y = r_g.y;
1316                 else
1317                         win_g.y += last_h + 2;
1318
1319                 if (win->transient != 0 || win->floating != 0)
1320                         stack_floater(win, ws->r);
1321                 else {
1322                         bzero(&wc, sizeof wc);
1323                         wc.border_width = 1;
1324                         if (rot) {
1325                                 win->g.x = wc.x = win_g.y;
1326                                 win->g.y = wc.y = win_g.x;
1327                                 win->g.w = wc.width = win_g.h;
1328                                 win->g.h = wc.height = win_g.w;
1329                         } else {
1330                                 win->g.x = wc.x = win_g.x;
1331                                 win->g.y = wc.y = win_g.y;
1332                                 win->g.w = wc.width = win_g.w;
1333                                 win->g.h = wc.height = win_g.h;
1334                         }
1335                         mask = CWX | CWY | CWWidth | CWHeight | CWBorderWidth;
1336                         XConfigureWindow(display, win->id, mask, &wc);
1337                         /*
1338                         fprintf(stderr, "vertical_stack: win %d x %d y %d w %d h %d bw %d\n", win->id, win->g.x, win->g.y, win->g.w , win->g.h, wc.border_width);
1339                         */
1340                 }
1341
1342                 XMapRaised(display, win->id);
1343                 last_h = win_g.h;
1344                 i++;
1345                 j++;
1346         }
1347
1348         if (winfocus)
1349                 focus_win(winfocus); /* has to be done outside of the loop */
1350 }
1351
1352 void
1353 vertical_config(struct workspace *ws, int id)
1354 {
1355         DNPRINTF(SWM_D_STACK, "vertical_resize: workspace: %d\n", ws->idx);
1356
1357         switch (id) {
1358         case SWM_ARG_ID_STACKRESET:
1359         case SWM_ARG_ID_STACKINIT:
1360                 ws->l_state.vertical_msize = SWM_V_SLICE / 2;
1361                 ws->l_state.vertical_mwin = 1;
1362                 break;
1363         case SWM_ARG_ID_MASTERSHRINK:
1364                 if (ws->l_state.vertical_msize > 1)
1365                         ws->l_state.vertical_msize--;
1366                 break;
1367         case SWM_ARG_ID_MASTERGROW:
1368                 if (ws->l_state.vertical_msize < SWM_V_SLICE - 1)
1369                         ws->l_state.vertical_msize++;
1370                 break;
1371         case SWM_ARG_ID_MASTERADD:
1372                 ws->l_state.vertical_mwin++;
1373                 break;
1374         case SWM_ARG_ID_MASTERDEL:
1375                 if (ws->l_state.vertical_mwin > 0)
1376                         ws->l_state.vertical_mwin--;
1377                 break;
1378         default:
1379                 return;
1380         }
1381 }
1382
1383 void
1384 vertical_stack(struct workspace *ws, struct swm_geometry *g)
1385 {
1386         DNPRINTF(SWM_D_STACK, "vertical_stack: workspace: %d\n", ws->idx);
1387
1388         stack_master(ws, g, 0, 0);
1389 }
1390
1391 void
1392 horizontal_config(struct workspace *ws, int id)
1393 {
1394         DNPRINTF(SWM_D_STACK, "horizontal_config: workspace: %d\n", ws->idx);
1395
1396         switch (id) {
1397         case SWM_ARG_ID_STACKRESET:
1398         case SWM_ARG_ID_STACKINIT:
1399                 ws->l_state.horizontal_mwin = 1;
1400                 ws->l_state.horizontal_msize = SWM_H_SLICE / 2;
1401                 break;
1402         case SWM_ARG_ID_MASTERSHRINK:
1403                 if (ws->l_state.horizontal_msize > 1)
1404                         ws->l_state.horizontal_msize--;
1405                 break;
1406         case SWM_ARG_ID_MASTERGROW:
1407                 if (ws->l_state.horizontal_msize < SWM_H_SLICE - 1)
1408                         ws->l_state.horizontal_msize++;
1409                 break;
1410         case SWM_ARG_ID_MASTERADD:
1411                 ws->l_state.horizontal_mwin++;
1412                 break;
1413         case SWM_ARG_ID_MASTERDEL:
1414                 if (ws->l_state.horizontal_mwin > 0)
1415                         ws->l_state.horizontal_mwin--;
1416                 break;
1417         default:
1418                 return;
1419         }
1420 }
1421
1422 void
1423 horizontal_stack(struct workspace *ws, struct swm_geometry *g)
1424 {
1425         DNPRINTF(SWM_D_STACK, "vertical_stack: workspace: %d\n", ws->idx);
1426
1427         stack_master(ws, g, 1, 0);
1428 }
1429
1430 /* fullscreen view */
1431 void
1432 max_stack(struct workspace *ws, struct swm_geometry *g) {
1433         XWindowChanges          wc;
1434         struct swm_geometry     gg = *g;
1435         struct ws_win           *win, *winfocus;
1436         unsigned int            mask;
1437
1438         DNPRINTF(SWM_D_STACK, "max_stack: workspace: %d\n", ws->idx);
1439
1440         if (count_win(ws, 0) == 0)
1441                 return;
1442
1443         if (ws->focus == NULL)
1444                 ws->focus = TAILQ_FIRST(&ws->winlist);
1445         winfocus = cur_focus ? cur_focus : ws->focus;
1446
1447         TAILQ_FOREACH(win, &ws->winlist, entry) {
1448                 if (win->transient != 0 || win->floating != 0) {
1449                         if (win == ws->focus) {
1450                                 /* XXX maximize? */
1451                                 stack_floater(win, ws->r);
1452                                 XMapRaised(display, win->id);
1453                         } else
1454                                 XUnmapWindow(display, win->id);
1455                 } else {
1456                         bzero(&wc, sizeof wc);
1457                         wc.border_width = 1;
1458                         win->g.x = wc.x = gg.x;
1459                         win->g.y = wc.y = gg.y;
1460                         win->g.w = wc.width = gg.w;
1461                         win->g.h = wc.height = gg.h;
1462                         mask = CWX | CWY | CWWidth | CWHeight | CWBorderWidth;
1463                         XConfigureWindow(display, win->id, mask, &wc);
1464
1465                         if (win == ws->focus) {
1466                                 XMapRaised(display, win->id);
1467                         } else
1468                                 XUnmapWindow(display, win->id);
1469                 }
1470         }
1471
1472         if (winfocus)
1473                 focus_win(winfocus); /* has to be done outside of the loop */
1474 }
1475
1476 void
1477 send_to_ws(struct swm_region *r, union arg *args)
1478 {
1479         int                     wsid = args->id;
1480         struct ws_win           *win = cur_focus;
1481         struct workspace        *ws, *nws;
1482         Atom                    ws_idx_atom = 0;
1483         unsigned char           ws_idx_str[SWM_PROPLEN];
1484
1485         DNPRINTF(SWM_D_MOVE, "send_to_ws: win: %lu\n", win->id);
1486
1487         ws = win->ws;
1488         nws = &win->s->ws[wsid];
1489
1490         XUnmapWindow(display, win->id);
1491
1492         /* find a window to focus */
1493         ws->focus = TAILQ_PREV(win, ws_win_list, entry);
1494         if (ws->focus == NULL)
1495                 ws->focus = TAILQ_FIRST(&ws->winlist);
1496         if (ws->focus == win)
1497                 ws->focus = NULL;
1498
1499         TAILQ_REMOVE(&ws->winlist, win, entry);
1500
1501         TAILQ_INSERT_TAIL(&nws->winlist, win, entry);
1502         win->ws = nws;
1503
1504         /* Try to update the window's workspace property */
1505         ws_idx_atom = XInternAtom(display, "_SWM_WS", False);
1506         if (ws_idx_atom &&
1507             snprintf(ws_idx_str, SWM_PROPLEN, "%d", nws->idx) < SWM_PROPLEN) {
1508                 DNPRINTF(SWM_D_PROP, "setting property _SWM_WS to %s\n",
1509                     ws_idx_str);
1510                 XChangeProperty(display, win->id, ws_idx_atom, XA_STRING, 8,
1511                     PropModeReplace, ws_idx_str, SWM_PROPLEN);
1512         }
1513
1514         if (count_win(nws, 1) == 1)
1515                 nws->focus = win;
1516         ws->restack = 1;
1517         nws->restack = 1;
1518
1519         stack();
1520 }
1521
1522 void
1523 wkill(struct swm_region *r, union arg *args)
1524 {
1525         DNPRINTF(SWM_D_MISC, "wkill\n");
1526         if(r->ws->focus != NULL)
1527                 XKillClient(display, r->ws->focus->id);
1528 }
1529
1530 void
1531 screenshot(struct swm_region *r, union arg *args)
1532 {
1533         union arg                       a;
1534
1535         DNPRINTF(SWM_D_MISC, "screenshot\n");
1536
1537         if (ss_enabled == 0)
1538                 return;
1539
1540         switch (args->id) {
1541         case SWM_ARG_ID_SS_ALL:
1542                 spawn_screenshot[1] = "full";
1543                 break;
1544         case SWM_ARG_ID_SS_WINDOW:
1545                 spawn_screenshot[1] = "window";
1546                 break;
1547         default:
1548                 return;
1549         }
1550         a.argv = spawn_screenshot;
1551         spawn(r, &a);
1552 }
1553
1554 /* key definitions */
1555 struct key {
1556         unsigned int            mod;
1557         KeySym                  keysym;
1558         void                    (*func)(struct swm_region *r, union arg *);
1559         union arg               args;
1560 } keys[] = {
1561         /* modifier             key     function                argument */
1562         { MODKEY,               XK_space,       cycle_layout,   {0} }, 
1563         { MODKEY | ShiftMask,   XK_space,       stack_config,   {.id = SWM_ARG_ID_STACKRESET} }, 
1564         { MODKEY,               XK_h,           stack_config,   {.id = SWM_ARG_ID_MASTERSHRINK} },
1565         { MODKEY,               XK_l,           stack_config,   {.id = SWM_ARG_ID_MASTERGROW} },
1566         { MODKEY,               XK_comma,       stack_config,   {.id = SWM_ARG_ID_MASTERADD} },
1567         { MODKEY,               XK_period,      stack_config,   {.id = SWM_ARG_ID_MASTERDEL} },
1568         { MODKEY,               XK_Return,      swapwin,        {.id = SWM_ARG_ID_SWAPMAIN} },
1569         { MODKEY,               XK_j,           focus,          {.id = SWM_ARG_ID_FOCUSNEXT} },
1570         { MODKEY,               XK_k,           focus,          {.id = SWM_ARG_ID_FOCUSPREV} },
1571         { MODKEY | ShiftMask,   XK_j,           swapwin,        {.id = SWM_ARG_ID_SWAPNEXT} },
1572         { MODKEY | ShiftMask,   XK_k,           swapwin,        {.id = SWM_ARG_ID_SWAPPREV} },
1573         { MODKEY | ShiftMask,   XK_Return,      spawn,          {.argv = spawn_term} },
1574         { MODKEY,               XK_p,           spawnmenu,      {.argv = spawn_menu} },
1575         { MODKEY | ShiftMask,   XK_q,           quit,           {0} },
1576         { MODKEY,               XK_q,           restart,        {0} },
1577         { MODKEY,               XK_m,           focus,          {.id = SWM_ARG_ID_FOCUSMAIN} },
1578         { MODKEY,               XK_1,           switchws,       {.id = 0} },
1579         { MODKEY,               XK_2,           switchws,       {.id = 1} },
1580         { MODKEY,               XK_3,           switchws,       {.id = 2} },
1581         { MODKEY,               XK_4,           switchws,       {.id = 3} },
1582         { MODKEY,               XK_5,           switchws,       {.id = 4} },
1583         { MODKEY,               XK_6,           switchws,       {.id = 5} },
1584         { MODKEY,               XK_7,           switchws,       {.id = 6} },
1585         { MODKEY,               XK_8,           switchws,       {.id = 7} },
1586         { MODKEY,               XK_9,           switchws,       {.id = 8} },
1587         { MODKEY,               XK_0,           switchws,       {.id = 9} },
1588         { MODKEY,               XK_Right,       cyclews,        {.id = SWM_ARG_ID_CYCLEWS_UP} }, 
1589         { MODKEY,               XK_Left,        cyclews,        {.id = SWM_ARG_ID_CYCLEWS_DOWN} }, 
1590         { MODKEY | ShiftMask,   XK_Right,       cyclescr,       {.id = SWM_ARG_ID_CYCLESC_UP} }, 
1591         { MODKEY | ShiftMask,   XK_Left,        cyclescr,       {.id = SWM_ARG_ID_CYCLESC_DOWN} }, 
1592         { MODKEY | ShiftMask,   XK_1,           send_to_ws,     {.id = 0} },
1593         { MODKEY | ShiftMask,   XK_2,           send_to_ws,     {.id = 1} },
1594         { MODKEY | ShiftMask,   XK_3,           send_to_ws,     {.id = 2} },
1595         { MODKEY | ShiftMask,   XK_4,           send_to_ws,     {.id = 3} },
1596         { MODKEY | ShiftMask,   XK_5,           send_to_ws,     {.id = 4} },
1597         { MODKEY | ShiftMask,   XK_6,           send_to_ws,     {.id = 5} },
1598         { MODKEY | ShiftMask,   XK_7,           send_to_ws,     {.id = 6} },
1599         { MODKEY | ShiftMask,   XK_8,           send_to_ws,     {.id = 7} },
1600         { MODKEY | ShiftMask,   XK_9,           send_to_ws,     {.id = 8} },
1601         { MODKEY | ShiftMask,   XK_0,           send_to_ws,     {.id = 9} },
1602         { MODKEY,               XK_b,           bar_toggle,     {0} },
1603         { MODKEY,               XK_Tab,         focus,          {.id = SWM_ARG_ID_FOCUSNEXT} },
1604         { MODKEY | ShiftMask,   XK_Tab,         focus,          {.id = SWM_ARG_ID_FOCUSPREV} },
1605         { MODKEY | ShiftMask,   XK_x,           wkill,          {0} },
1606         { MODKEY,               XK_s,           screenshot,     {.id = SWM_ARG_ID_SS_ALL} },
1607         { MODKEY | ShiftMask,   XK_s,           screenshot,     {.id = SWM_ARG_ID_SS_WINDOW} },
1608 };
1609
1610 void
1611 click(struct swm_region *r, union arg *args)
1612 {
1613         DNPRINTF(SWM_D_MOUSE, "click: button: %d\n", args->id);
1614
1615         switch (args->id) {
1616         case Button1:
1617                 break;
1618         case Button2:
1619                 break;
1620         case Button3:
1621                 break;
1622         default:
1623                 return;
1624         }
1625 }
1626
1627 /* mouse */
1628 enum { client_click, root_click };
1629 struct button {
1630         unsigned int            action;
1631         unsigned int            mask;
1632         unsigned int            button;
1633         void                    (*func)(struct swm_region *r, union arg *);
1634         union arg               args;
1635 } buttons[] = {
1636           /* action             key             mouse button    func            args */
1637         { client_click,         MODKEY,         Button1,        click, {.id=Button1} },
1638 };
1639
1640 void
1641 updatenumlockmask(void)
1642 {
1643         unsigned int            i, j;
1644         XModifierKeymap         *modmap;
1645
1646         DNPRINTF(SWM_D_MISC, "updatenumlockmask\n");
1647         numlockmask = 0;
1648         modmap = XGetModifierMapping(display);
1649         for (i = 0; i < 8; i++)
1650                 for (j = 0; j < modmap->max_keypermod; j++)
1651                         if (modmap->modifiermap[i * modmap->max_keypermod + j]
1652                           == XKeysymToKeycode(display, XK_Num_Lock))
1653                                 numlockmask = (1 << i);
1654
1655         XFreeModifiermap(modmap);
1656 }
1657
1658 void
1659 grabkeys(void)
1660 {
1661         unsigned int            i, j, k;
1662         KeyCode                 code;
1663         unsigned int            modifiers[] =
1664             { 0, LockMask, numlockmask, numlockmask | LockMask };
1665
1666         DNPRINTF(SWM_D_MISC, "grabkeys\n");
1667         updatenumlockmask();
1668
1669         for (k = 0; k < ScreenCount(display); k++) {
1670                 if (TAILQ_EMPTY(&screens[k].rl))
1671                         continue;
1672                 XUngrabKey(display, AnyKey, AnyModifier, screens[k].root);
1673                 for (i = 0; i < LENGTH(keys); i++) {
1674                         if ((code = XKeysymToKeycode(display, keys[i].keysym)))
1675                                 for (j = 0; j < LENGTH(modifiers); j++)
1676                                         XGrabKey(display, code,
1677                                             keys[i].mod | modifiers[j],
1678                                             screens[k].root, True,
1679                                             GrabModeAsync, GrabModeAsync);
1680                 }
1681         }
1682 }
1683
1684 void
1685 grabbuttons(struct ws_win *win, int focused)
1686 {
1687         unsigned int            i, j;
1688         unsigned int            modifiers[] =
1689             { 0, LockMask, numlockmask, numlockmask|LockMask };
1690
1691         updatenumlockmask();
1692         XUngrabButton(display, AnyButton, AnyModifier, win->id);
1693         if(focused) {
1694                 for (i = 0; i < LENGTH(buttons); i++)
1695                         if (buttons[i].action == client_click)
1696                                 for (j = 0; j < LENGTH(modifiers); j++)
1697                                         XGrabButton(display, buttons[i].button,
1698                                             buttons[i].mask | modifiers[j],
1699                                             win->id, False, BUTTONMASK,
1700                                             GrabModeAsync, GrabModeSync, None,
1701                                             None);
1702         } else
1703                 XGrabButton(display, AnyButton, AnyModifier, win->id, False,
1704                     BUTTONMASK, GrabModeAsync, GrabModeSync, None, None);
1705 }
1706
1707 void
1708 expose(XEvent *e)
1709 {
1710         DNPRINTF(SWM_D_EVENT, "expose: window: %lu\n", e->xexpose.window);
1711 }
1712
1713 void
1714 keypress(XEvent *e)
1715 {
1716         unsigned int            i;
1717         KeySym                  keysym;
1718         XKeyEvent               *ev = &e->xkey;
1719
1720         DNPRINTF(SWM_D_EVENT, "keypress: window: %lu\n", ev->window);
1721
1722         keysym = XKeycodeToKeysym(display, (KeyCode)ev->keycode, 0);
1723         for (i = 0; i < LENGTH(keys); i++)
1724                 if (keysym == keys[i].keysym
1725                    && CLEANMASK(keys[i].mod) == CLEANMASK(ev->state)
1726                    && keys[i].func)
1727                         keys[i].func(root_to_region(ev->root),
1728                             &(keys[i].args));
1729 }
1730
1731 void
1732 buttonpress(XEvent *e)
1733 {
1734         XButtonPressedEvent     *ev = &e->xbutton;
1735
1736         struct ws_win           *win;
1737         int                     i, action;
1738
1739         DNPRINTF(SWM_D_EVENT, "buttonpress: window: %lu\n", ev->window);
1740
1741         action = root_click;
1742         if ((win = find_window(ev->window)) == NULL)
1743                 return;
1744         else {
1745                 focus_win(win);
1746                 action = client_click;
1747         }
1748
1749         for (i = 0; i < LENGTH(buttons); i++)
1750                 if (action == buttons[i].action && buttons[i].func &&
1751                     buttons[i].button == ev->button &&
1752                     CLEANMASK(buttons[i].mask) == CLEANMASK(ev->state))
1753                         buttons[i].func(root_to_region(ev->root),
1754                         &buttons[i].args);
1755 }
1756
1757 void
1758 set_win_state(struct ws_win *win, long state)
1759 {
1760         long                    data[] = {state, None};
1761
1762         DNPRINTF(SWM_D_EVENT, "set_win_state: window: %lu\n", win->id);
1763
1764         XChangeProperty(display, win->id, astate, astate, 32, PropModeReplace,
1765             (unsigned char *)data, 2);
1766 }
1767
1768 struct ws_win *
1769 manage_window(Window id)
1770 {
1771         Window                  trans;
1772         struct workspace        *ws;
1773         struct ws_win           *win;
1774         int                     format, i, ws_idx;
1775         unsigned long           nitems, bytes;
1776         Atom                    ws_idx_atom = 0, type;
1777         unsigned char           ws_idx_str[SWM_PROPLEN], *prop = NULL;
1778         struct swm_region       *r;
1779         long                    mask;
1780         const char              *errstr;
1781
1782         if ((win = find_window(id)) != NULL)
1783                         return (win);   /* already being managed */
1784
1785         if ((win = calloc(1, sizeof(struct ws_win))) == NULL)
1786                 errx(1, "calloc: failed to allocate memory for new window");
1787
1788         ws_idx_atom = XInternAtom(display, "_SWM_WS", False);
1789         if (ws_idx_atom)
1790                 XGetWindowProperty(display, id, ws_idx_atom, 0, SWM_PROPLEN,
1791                     False, XA_STRING, &type, &format, &nitems, &bytes, &prop);
1792
1793         XGetWindowAttributes(display, id, &win->wa);
1794         r = root_to_region(win->wa.root);
1795         /* If the window was managed before, put it in the same workspace */
1796         if (prop) {
1797                 DNPRINTF(SWM_D_PROP, "got property _SWM_WS=%s\n", prop);
1798                 ws_idx = strtonum(prop, 0, 9, &errstr);
1799                 if (errstr)
1800                         DNPRINTF(SWM_D_EVENT, "window idx is %s: %s",
1801                             errstr, prop);
1802                 ws = &r->s->ws[ws_idx];
1803         } else
1804                 ws = r->ws;
1805
1806         win->id = id;
1807         win->ws = ws;
1808         win->s = r->s;  /* this never changes */
1809         TAILQ_INSERT_TAIL(&ws->winlist, win, entry);
1810
1811         XGetTransientForHint(display, win->id, &trans);
1812         if (trans) {
1813                 win->transient = trans;
1814                 DNPRINTF(SWM_D_MISC, "manage_window: win %u transient %u\n",
1815                     (unsigned)win->id, win->transient);
1816         }
1817         win->g.w = win->wa.width;
1818         win->g.h = win->wa.height;
1819         win->g.x = win->wa.x;
1820         win->g.y = win->wa.y;
1821
1822         XGetWMNormalHints(display, win->id, &win->sh, &mask); /* XXX function? */
1823
1824         if (ws_idx_atom && prop == NULL &&
1825             snprintf(ws_idx_str, SWM_PROPLEN, "%d", ws->idx) < SWM_PROPLEN) {
1826                 DNPRINTF(SWM_D_PROP, "setting property _SWM_WS to %s\n",
1827                     ws_idx_str);
1828                 XChangeProperty(display, win->id, ws_idx_atom, XA_STRING, 8,
1829                     PropModeReplace, ws_idx_str, SWM_PROPLEN);
1830         }
1831         XFree(prop);
1832
1833         /*
1834         fprintf(stderr, "manage window: %d x %d y %d w %d h %d\n", win->id, win->g.x, win->g.y, win->g.w, win->g.h);
1835         */
1836
1837         if (XGetClassHint(display, win->id, &win->ch)) {
1838                 DNPRINTF(SWM_D_CLASS, "class: %s name: %s\n",
1839                     win->ch.res_class, win->ch.res_name);
1840                 for (i = 0; quirks[i].class != NULL && quirks[i].name != NULL &&
1841                     quirks[i].quirk != 0; i++){
1842                         if (!strcmp(win->ch.res_class, quirks[i].class) &&
1843                             !strcmp(win->ch.res_name, quirks[i].name)) {
1844                                 DNPRINTF(SWM_D_CLASS, "found: %s name: %s\n",
1845                                     win->ch.res_class, win->ch.res_name);
1846                                 if (quirks[i].quirk & SWM_Q_FLOAT)
1847                                         win->floating = 1;
1848                         }
1849                 }
1850         }
1851
1852         XSelectInput(display, id, EnterWindowMask | FocusChangeMask |
1853             PropertyChangeMask | StructureNotifyMask);
1854
1855         set_win_state(win, NormalState);
1856
1857         /* make new win focused */
1858         focus_win(win);
1859
1860         return (win);
1861 }
1862
1863 void
1864 configurerequest(XEvent *e)
1865 {
1866         XConfigureRequestEvent  *ev = &e->xconfigurerequest;
1867         struct ws_win           *win;
1868         int                     new = 0;
1869         XWindowChanges          wc;
1870
1871         if ((win = find_window(ev->window)) == NULL)
1872                 new = 1;
1873
1874         if (new) {
1875                 DNPRINTF(SWM_D_EVENT, "configurerequest: new window: %lu\n",
1876                     ev->window);
1877                 /*
1878                 fprintf(stderr, "configurerequest: new window: %lu x %d y %d w %d h %d bw %d s %d sm %d\n",
1879                     ev->window, ev->x, ev->y, ev->width, ev->height, ev->border_width, ev->above, ev->detail);
1880                 */
1881                 bzero(&wc, sizeof wc);
1882                 wc.x = ev->x;
1883                 wc.y = ev->y;
1884                 wc.width = ev->width;
1885                 wc.height = ev->height;
1886                 wc.border_width = ev->border_width;
1887                 wc.sibling = ev->above;
1888                 wc.stack_mode = ev->detail;
1889                 XConfigureWindow(display, ev->window, ev->value_mask, &wc);
1890         } else {
1891                 /*
1892                 fprintf(stderr, "configurerequest: change window: %lu\n",
1893                     ev->window);
1894                 */
1895                 DNPRINTF(SWM_D_EVENT, "configurerequest: change window: %lu\n",
1896                     ev->window);
1897                 if (win->floating) {
1898                         if (ev->value_mask & CWX)
1899                                 win->g.x = ev->x;
1900                         if (ev->value_mask & CWY)
1901                                 win->g.y = ev->y;
1902                         if (ev->value_mask & CWWidth)
1903                                 win->g.w = ev->width;
1904                         if (ev->value_mask & CWHeight)
1905                                 win->g.h = ev->height;
1906                         if (win->ws->r != NULL) {
1907                                 /* this seems to be full screen */
1908                                 if (win->g.w >= WIDTH(win->ws->r)) {
1909                                         win->g.x = -1;
1910                                         win->g.w = WIDTH(win->ws->r);
1911                                         ev->value_mask |= CWX | CWWidth;
1912                                 }
1913                                 if (win->g.h >= HEIGHT(win->ws->r)) {
1914                                         /* kill border */
1915                                         win->g.y = -1;
1916                                         win->g.h = HEIGHT(win->ws->r);
1917                                         ev->value_mask |= CWY | CWHeight;
1918                                 }
1919                         }
1920                         if ((ev->value_mask & (CWX|CWY)) &&
1921                             !(ev->value_mask & (CWWidth|CWHeight)))
1922                                 config_win(win);
1923                         XMoveResizeWindow(display, win->id,
1924                             win->g.x, win->g.y, win->g.w, win->g.h);
1925                 } else
1926                         config_win(win);
1927         }
1928 }
1929
1930 void
1931 configurenotify(XEvent *e)
1932 {
1933         DNPRINTF(SWM_D_EVENT, "configurenotify: window: %lu\n",
1934             e->xconfigure.window);
1935 }
1936
1937 void
1938 destroynotify(XEvent *e)
1939 {
1940         struct ws_win           *win;
1941         XDestroyWindowEvent     *ev = &e->xdestroywindow;
1942         struct workspace        *ws;
1943
1944         DNPRINTF(SWM_D_EVENT, "destroynotify: window %lu\n", ev->window);
1945
1946         if ((win = find_window(ev->window)) != NULL) {
1947                 ws = win->ws;
1948                 /* find a window to focus */
1949                 if (ws->focus == win)
1950                         ws->focus = TAILQ_PREV(win, ws_win_list, entry);
1951                 if (ws->focus == NULL)
1952                         ws->focus = TAILQ_FIRST(&ws->winlist);
1953                 if (ws->focus == NULL || ws->focus == win) {
1954                         ws->focus = NULL;
1955                         unfocus_all();
1956                 } else
1957                         focus_win(ws->focus);
1958                 TAILQ_REMOVE(&ws->winlist, win, entry);
1959                 set_win_state(win, WithdrawnState);
1960                 if (win->ch.res_class)
1961                         XFree(win->ch.res_class);
1962                 if (win->ch.res_name)
1963                         XFree(win->ch.res_name);
1964                 free(win);
1965                 stack();
1966         }
1967 }
1968
1969 void
1970 enternotify(XEvent *e)
1971 {
1972         XCrossingEvent          *ev = &e->xcrossing;
1973         struct ws_win           *win;
1974
1975         DNPRINTF(SWM_D_EVENT, "enternotify: window: %lu\n", ev->window);
1976
1977         if (ignore_enter) {
1978                 /* eat event(r) to prevent autofocus */
1979                 ignore_enter--;
1980                 return;
1981         }
1982
1983         if ((win = find_window(ev->window)) != NULL)
1984                 focus_win(win);
1985 }
1986
1987 void
1988 focusin(XEvent *e)
1989 {
1990         DNPRINTF(SWM_D_EVENT, "focusin: window: %lu\n", e->xfocus.window);
1991 }
1992
1993 void
1994 mappingnotify(XEvent *e)
1995 {
1996         XMappingEvent           *ev = &e->xmapping;
1997
1998         DNPRINTF(SWM_D_EVENT, "mappingnotify: window: %lu\n", ev->window);
1999
2000         XRefreshKeyboardMapping(ev);
2001         if (ev->request == MappingKeyboard)
2002                 grabkeys();
2003 }
2004
2005 void
2006 maprequest(XEvent *e)
2007 {
2008         XMapRequestEvent        *ev = &e->xmaprequest;
2009         XWindowAttributes       wa;
2010
2011         DNPRINTF(SWM_D_EVENT, "maprequest: window: %lu\n",
2012             e->xmaprequest.window);
2013
2014         if (!XGetWindowAttributes(display, ev->window, &wa))
2015                 return;
2016         if (wa.override_redirect)
2017                 return;
2018         manage_window(e->xmaprequest.window);
2019         stack();
2020 }
2021
2022 void
2023 propertynotify(XEvent *e)
2024 {
2025         struct ws_win           *win;
2026         XPropertyEvent          *ev = &e->xproperty;
2027
2028         DNPRINTF(SWM_D_EVENT, "propertynotify: window: %lu\n",
2029             ev->window);
2030
2031         if (ev->state == PropertyDelete)
2032                 return; /* ignore */
2033         win = find_window(ev->window);
2034         if (win == NULL)
2035                 return;
2036
2037         switch (ev->atom) {
2038         case XA_WM_NORMAL_HINTS:
2039 #if 0
2040                 long            mask;
2041                 XGetWMNormalHints(display, win->id, &win->sh, &mask);
2042                 fprintf(stderr, "normal hints: flag 0x%x\n", win->sh.flags);
2043                 if (win->sh.flags & PMinSize) {
2044                         win->g.w = win->sh.min_width;
2045                         win->g.h = win->sh.min_height;
2046                         fprintf(stderr, "min %d %d\n", win->g.w, win->g.h);
2047                 }
2048                 XMoveResizeWindow(display, win->id,
2049                     win->g.x, win->g.y, win->g.w, win->g.h);
2050 #endif
2051                 break;
2052         default:
2053                 break;
2054         }
2055 }
2056
2057 void
2058 unmapnotify(XEvent *e)
2059 {
2060         DNPRINTF(SWM_D_EVENT, "unmapnotify: window: %lu\n", e->xunmap.window);
2061 }
2062
2063 void
2064 visibilitynotify(XEvent *e)
2065 {
2066         int                     i;
2067         struct swm_region       *r;
2068
2069         DNPRINTF(SWM_D_EVENT, "visibilitynotify: window: %lu\n",
2070             e->xvisibility.window);
2071         if (e->xvisibility.state == VisibilityUnobscured)
2072                 for (i = 0; i < ScreenCount(display); i++) 
2073                         TAILQ_FOREACH(r, &screens[i].rl, entry)
2074                                 if (e->xvisibility.window == r->bar_window)
2075                                         bar_update();
2076 }
2077
2078 void                    (*handler[LASTEvent])(XEvent *) = {
2079                                 [Expose] = expose,
2080                                 [KeyPress] = keypress,
2081                                 [ButtonPress] = buttonpress,
2082                                 [ConfigureRequest] = configurerequest,
2083                                 [ConfigureNotify] = configurenotify,
2084                                 [DestroyNotify] = destroynotify,
2085                                 [EnterNotify] = enternotify,
2086                                 [FocusIn] = focusin,
2087                                 [MappingNotify] = mappingnotify,
2088                                 [MapRequest] = maprequest,
2089                                 [PropertyNotify] = propertynotify,
2090                                 [UnmapNotify] = unmapnotify,
2091                                 [VisibilityNotify] = visibilitynotify,
2092 };
2093
2094 int
2095 xerror_start(Display *d, XErrorEvent *ee)
2096 {
2097         other_wm = 1;
2098         return (-1);
2099 }
2100
2101 int
2102 xerror(Display *d, XErrorEvent *ee)
2103 {
2104         /* fprintf(stderr, "error: %p %p\n", display, ee); */
2105         return (-1);
2106 }
2107
2108 int
2109 active_wm(void)
2110 {
2111         other_wm = 0;
2112         xerrorxlib = XSetErrorHandler(xerror_start);
2113
2114         /* this causes an error if some other window manager is running */
2115         XSelectInput(display, DefaultRootWindow(display),
2116             SubstructureRedirectMask);
2117         XSync(display, False);
2118         if (other_wm)
2119                 return (1);
2120
2121         XSetErrorHandler(xerror);
2122         XSync(display, False);
2123         return (0);
2124 }
2125
2126 long
2127 getstate(Window w)
2128 {
2129         int                     format, status;
2130         long                    result = -1;
2131         unsigned char           *p = NULL;
2132         unsigned long           n, extra;
2133         Atom                    real;
2134
2135         astate = XInternAtom(display, "WM_STATE", False);
2136         status = XGetWindowProperty(display, w, astate, 0L, 2L, False, astate,
2137             &real, &format, &n, &extra, (unsigned char **)&p);
2138         if (status != Success)
2139                 return (-1);
2140         if (n != 0)
2141                 result = *p;
2142         XFree(p);
2143         return (result);
2144 }
2145
2146 void
2147 new_region(struct swm_screen *s, struct workspace *ws,
2148     int x, int y, int w, int h)
2149 {
2150         struct swm_region       *r;
2151
2152         DNPRINTF(SWM_D_MISC, "new region on screen %d: %dx%d (%d, %d)\n",
2153              s->idx, x, y, w, h);
2154
2155         if ((r = calloc(1, sizeof(struct swm_region))) == NULL)
2156                 errx(1, "calloc: failed to allocate memory for screen");
2157
2158         X(r) = x;
2159         Y(r) = y;
2160         WIDTH(r) = w;
2161         HEIGHT(r) = h;
2162         r->s = s;
2163         r->ws = ws;
2164         ws->r = r;
2165         TAILQ_INSERT_TAIL(&s->rl, r, entry);
2166         bar_setup(r);
2167 }
2168
2169 void
2170 setup_screens(void)
2171 {
2172 #ifdef SWM_XRR_HAS_CRTC
2173         XRRCrtcInfo             *ci;
2174         XRRScreenResources      *sr;
2175         int                     c;
2176 #endif /* SWM_XRR_HAS_CRTC */
2177         Window                  d1, d2, *wins = NULL;
2178         XWindowAttributes       wa;
2179         struct swm_region       *r;
2180         unsigned int            no;
2181         int                     errorbase, major, minor;
2182         int                     ncrtc = 0, w = 0;
2183         int                     i, j, k;
2184         struct workspace        *ws;
2185         int                     ws_idx_atom;
2186
2187
2188         if ((screens = calloc(ScreenCount(display),
2189              sizeof(struct swm_screen))) == NULL)
2190                 errx(1, "calloc: screens");
2191
2192         ws_idx_atom = XInternAtom(display, "_SWM_WS", False);
2193         
2194
2195         /* map physical screens */
2196         for (i = 0; i < ScreenCount(display); i++) {
2197                 DNPRINTF(SWM_D_WS, "setup_screens: init screen %d\n", i);
2198                 screens[i].idx = i;
2199                 TAILQ_INIT(&screens[i].rl);
2200                 screens[i].root = RootWindow(display, i);
2201
2202                 /* set default colors */
2203                 setscreencolor("red", i + 1, SWM_S_COLOR_FOCUS);
2204                 setscreencolor("rgb:88/88/88", i + 1, SWM_S_COLOR_UNFOCUS);
2205                 setscreencolor("rgb:00/80/80", i + 1, SWM_S_COLOR_BAR_BORDER);
2206                 setscreencolor("black", i + 1, SWM_S_COLOR_BAR);
2207                 setscreencolor("rgb:a0/a0/a0", i + 1, SWM_S_COLOR_BAR_FONT);
2208
2209                 /* init all workspaces */
2210                 for (j = 0; j < SWM_WS_MAX; j++) {
2211                         ws = &screens[i].ws[j];
2212                         ws->idx = j;
2213                         ws->restack = 1;
2214                         ws->focus = NULL;
2215                         ws->r = NULL;
2216                         TAILQ_INIT(&ws->winlist);
2217
2218                         for (k = 0; layouts[k].l_stack != NULL; k++)
2219                                 if (layouts[k].l_config != NULL)
2220                                         layouts[k].l_config(ws,
2221                                             SWM_ARG_ID_STACKINIT);
2222                         ws->cur_layout = &layouts[0];
2223                 }
2224
2225                 /* map virtual screens onto physical screens */
2226                 screens[i].xrandr_support = XRRQueryExtension(display,
2227                     &xrandr_eventbase, &errorbase);
2228                 if (screens[i].xrandr_support)
2229                         if (XRRQueryVersion(display, &major, &minor) &&
2230                             major < 1)
2231                                 screens[i].xrandr_support = 0;
2232
2233 #if 0   /* not ready for dynamic screen changes */
2234                 if (screens[i].xrandr_support)
2235                         XRRSelectInput(display,
2236                             screens[r->s].root,
2237                             RRScreenChangeNotifyMask);
2238 #endif
2239
2240                 /* grab existing windows (before we build the bars)*/
2241                 if (!XQueryTree(display, screens[i].root, &d1, &d2, &wins, &no))
2242                         continue;
2243
2244 #ifdef SWM_XRR_HAS_CRTC
2245                 sr = XRRGetScreenResources(display, screens[i].root);
2246                 if (sr == NULL)
2247                         new_region(&screens[i], &screens[i].ws[w],
2248                             0, 0, DisplayWidth(display, i),
2249                             DisplayHeight(display, i)); 
2250                 else 
2251                         ncrtc = sr->ncrtc;
2252
2253                 for (c = 0, ci = NULL; c < ncrtc; c++) {
2254                         ci = XRRGetCrtcInfo(display, sr, sr->crtcs[c]);
2255                         if (ci->noutput == 0)
2256                                 continue;
2257
2258                         if (ci != NULL && ci->mode == None)
2259                                 new_region(&screens[i], &screens[i].ws[w], 0, 0,
2260                                     DisplayWidth(display, i),
2261                                     DisplayHeight(display, i)); 
2262                         else
2263                                 new_region(&screens[i], &screens[i].ws[w],
2264                                     ci->x, ci->y, ci->width, ci->height);
2265                         w++;
2266                 }
2267                 if (ci)
2268                         XRRFreeCrtcInfo(ci);
2269                 XRRFreeScreenResources(sr);
2270 #else
2271                 new_region(&screens[i], &screens[i].ws[w], 0, 0,
2272                     DisplayWidth(display, i),
2273                     DisplayHeight(display, i)); 
2274 #endif /* SWM_XRR_HAS_CRTC */
2275
2276                 /* attach windows to a region */
2277                 /* normal windows */
2278                 if ((r = TAILQ_FIRST(&screens[i].rl)) == NULL)
2279                         errx(1, "no regions on screen %d", i);
2280
2281                 for (i = 0; i < no; i++) {
2282                         XGetWindowAttributes(display, wins[i], &wa);
2283                         if (!XGetWindowAttributes(display, wins[i], &wa) ||
2284                             wa.override_redirect ||
2285                             XGetTransientForHint(display, wins[i], &d1))
2286                                 continue;
2287
2288                         if (wa.map_state == IsViewable ||
2289                             getstate(wins[i]) == NormalState)
2290                                 manage_window(wins[i]);
2291                 }
2292                 /* transient windows */
2293                 for (i = 0; i < no; i++) {
2294                         if (!XGetWindowAttributes(display, wins[i], &wa))
2295                                 continue;
2296
2297                         if (XGetTransientForHint(display, wins[i], &d1) &&
2298                             (wa.map_state == IsViewable || getstate(wins[i]) ==
2299                             NormalState))
2300                                 manage_window(wins[i]);
2301                 }
2302                 if (wins) {
2303                         XFree(wins);
2304                         wins = NULL;
2305                 }
2306         }
2307 }
2308
2309 int
2310 main(int argc, char *argv[])
2311 {
2312         struct passwd           *pwd;
2313         char                    conf[PATH_MAX], *cfile = NULL;
2314         struct stat             sb;
2315         XEvent                  e;
2316         int                     xfd;
2317         fd_set                  rd;
2318
2319         start_argv = argv;
2320         fprintf(stderr, "Welcome to scrotwm V%s cvs tag: %s\n",
2321             SWM_VERSION, cvstag);
2322         if (!setlocale(LC_CTYPE, "") || !XSupportsLocale())
2323                 warnx("no locale support");
2324
2325         if (!(display = XOpenDisplay(0)))
2326                 errx(1, "can not open display");
2327
2328         if (active_wm())
2329                 errx(1, "other wm running");
2330
2331         astate = XInternAtom(display, "WM_STATE", False);
2332
2333         /* look for local and global conf file */
2334         pwd = getpwuid(getuid());
2335         if (pwd == NULL)
2336                 errx(1, "invalid user %d", getuid());
2337
2338         setup_screens();
2339
2340         snprintf(conf, sizeof conf, "%s/.%s", pwd->pw_dir, SWM_CONF_FILE);
2341         if (stat(conf, &sb) != -1) {
2342                 if (S_ISREG(sb.st_mode))
2343                         cfile = conf;
2344         } else {
2345                 /* try global conf file */
2346                 snprintf(conf, sizeof conf, "/etc/%s", SWM_CONF_FILE);
2347                 if (!stat(conf, &sb))
2348                         if (S_ISREG(sb.st_mode))
2349                                 cfile = conf;
2350         }
2351         if (cfile)
2352                 conf_load(cfile);
2353         bar_refresh();
2354
2355         /* ws[0].focus = TAILQ_FIRST(&ws[0].winlist); */
2356
2357         grabkeys();
2358         stack();
2359
2360         xfd = ConnectionNumber(display);
2361         while (running) {
2362                 FD_ZERO(&rd);
2363                 FD_SET(xfd, &rd);
2364                 if (select(xfd + 1, &rd, NULL, NULL, NULL) == -1)
2365                         if (errno != EINTR)
2366                                 errx(1, "select failed");
2367                 if (bar_alarm) {
2368                         bar_alarm = 0;
2369                         bar_update();
2370                 }
2371                 while(XPending(display)) {
2372                         XNextEvent(display, &e);
2373                         if (handler[e.type])
2374                                 handler[e.type](&e);
2375                 }
2376         }
2377
2378         XCloseDisplay(display);
2379
2380         return (0);
2381 }