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