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