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