JasonWoof Got questions, comments, patches, etc.? Contact Jason Woofenden
Remove screenshot since we have it; just not as pretty as one would like.
[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 void
1134 vertical_config(struct workspace *ws, int id)
1135 {
1136         DNPRINTF(SWM_D_STACK, "vertical_resize: workspace: %d\n", ws->idx);
1137
1138         switch (id) {
1139         case SWM_ARG_ID_STACKRESET:
1140         case SWM_ARG_ID_STACKINIT:
1141                 ws->l_state.vertical_msize = SWM_V_SLICE / 2;
1142                 ws->l_state.vertical_mwin = 1;
1143                 break;
1144         case SWM_ARG_ID_MASTERSHRINK:
1145                 if (ws->l_state.vertical_msize > 1)
1146                         ws->l_state.vertical_msize--;
1147                 break;
1148         case SWM_ARG_ID_MASTERGROW:
1149                 if (ws->l_state.vertical_msize < SWM_V_SLICE - 1)
1150                         ws->l_state.vertical_msize++;
1151                 break;
1152         case SWM_ARG_ID_MASTERADD:
1153                 ws->l_state.vertical_mwin++;
1154                 break;
1155         case SWM_ARG_ID_MASTERDEL:
1156                 if (ws->l_state.vertical_mwin > 0)
1157                         ws->l_state.vertical_mwin--;
1158                 break;
1159         default:
1160                 return;
1161         }
1162 }
1163
1164 void
1165 vertical_stack(struct workspace *ws, struct swm_geometry *g) {
1166         XWindowChanges          wc;
1167         struct swm_geometry     gg = *g;
1168         struct ws_win           *win, *winfocus;
1169         int                     i, j, split, colno, hrh, winno, main_width;
1170         unsigned int            mask;
1171
1172         DNPRINTF(SWM_D_STACK, "vertical_stack: workspace: %d\n", ws->idx);
1173
1174         if ((winno = count_win(ws, 0)) == 0)
1175                 return;
1176
1177         if (ws->focus == NULL)
1178                 ws->focus = TAILQ_FIRST(&ws->winlist);
1179         winfocus = cur_focus ? cur_focus : ws->focus;
1180
1181         if (ws->l_state.vertical_mwin &&
1182             winno > ws->l_state.vertical_mwin) {
1183                 split = ws->l_state.vertical_mwin;
1184                 colno = split;
1185                 main_width = (g->w / SWM_V_SLICE) *
1186                    ws->l_state.vertical_msize;
1187                 gg.w = main_width;
1188         } else {
1189                 colno = winno;
1190                 split = 0;
1191         }
1192         hrh = g->h / colno;
1193         gg.h = hrh - 2;
1194
1195         i = j = 0;
1196         TAILQ_FOREACH(win, &ws->winlist, entry) {
1197                 if (split && i == split) {
1198                         colno = winno - split;
1199                         hrh = (g->h / colno);
1200                         gg.x += main_width + 2;
1201                         gg.w = g->w - (main_width + 2);
1202                         gg.h = hrh - 2;
1203                         j = 0;
1204                 }
1205                 if (j == colno - 1)
1206                         gg.h = (hrh + (g->h - (colno * hrh)));
1207                  
1208                 if (j == 0)
1209                         gg.y = g->y;
1210                 else
1211                         gg.y += hrh;
1212
1213
1214                 if (win->transient != 0 || win->floating != 0)
1215                         stack_floater(win, ws->r);
1216                 else {
1217                         bzero(&wc, sizeof wc);
1218                         wc.border_width = 1;
1219                         win->g.x = wc.x = gg.x;
1220                         win->g.y = wc.y = gg.y;
1221                         win->g.w = wc.width = gg.w;
1222                         win->g.h = wc.height = gg.h;
1223                         mask = CWX | CWY | CWWidth | CWHeight | CWBorderWidth;
1224                         XConfigureWindow(display, win->id, mask, &wc);
1225                         /*
1226                         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);
1227                         */
1228                 }
1229
1230                 XMapRaised(display, win->id);
1231                 i++;
1232                 j++;
1233         }
1234
1235         if (winfocus)
1236                 focus_win(winfocus); /* has to be done outside of the loop */
1237 }
1238
1239 void
1240 horizontal_config(struct workspace *ws, int id)
1241 {
1242         DNPRINTF(SWM_D_STACK, "horizontal_config: workspace: %d\n", ws->idx);
1243
1244         switch (id) {
1245         case SWM_ARG_ID_STACKRESET:
1246         case SWM_ARG_ID_STACKINIT:
1247                 ws->l_state.horizontal_mwin = 1;
1248                 ws->l_state.horizontal_msize = SWM_H_SLICE / 2;
1249                 break;
1250         case SWM_ARG_ID_MASTERSHRINK:
1251                 if (ws->l_state.horizontal_msize > 1)
1252                         ws->l_state.horizontal_msize--;
1253                 break;
1254         case SWM_ARG_ID_MASTERGROW:
1255                 if (ws->l_state.horizontal_msize < SWM_H_SLICE - 1)
1256                         ws->l_state.horizontal_msize++;
1257                 break;
1258         case SWM_ARG_ID_MASTERADD:
1259                 ws->l_state.horizontal_mwin++;
1260                 break;
1261         case SWM_ARG_ID_MASTERDEL:
1262                 if (ws->l_state.horizontal_mwin > 0)
1263                         ws->l_state.horizontal_mwin--;
1264                 break;
1265         default:
1266                 return;
1267         }
1268 }
1269
1270 void
1271 horizontal_stack(struct workspace *ws, struct swm_geometry *g) {
1272         XWindowChanges          wc;
1273         struct swm_geometry     gg = *g;
1274         struct ws_win           *win, *winfocus;
1275         int                     i, j, split, rowno, hrw, winno, main_height;
1276         unsigned int            mask;
1277
1278         DNPRINTF(SWM_D_STACK, "horizontal_stack: workspace: %d\n", ws->idx);
1279
1280         if ((winno = count_win(ws, 0)) == 0)
1281                 return;
1282
1283         if (ws->focus == NULL)
1284                 ws->focus = TAILQ_FIRST(&ws->winlist);
1285         winfocus = cur_focus ? cur_focus : ws->focus;
1286
1287         if (ws->l_state.horizontal_mwin &&
1288             winno > ws->l_state.horizontal_mwin) {
1289                 split = ws->l_state.horizontal_mwin;
1290                 rowno = split;
1291                 main_height = (g->h / SWM_V_SLICE) *
1292                    ws->l_state.horizontal_msize;
1293                 gg.h = main_height;
1294         } else {
1295                 rowno = winno;
1296                 split = 0;
1297         }
1298         hrw = g->w / rowno;
1299         gg.w = hrw - 2;
1300
1301         i = j = 0;
1302         TAILQ_FOREACH(win, &ws->winlist, entry) {
1303                 if (split && i == split) {
1304                         rowno = winno - split;
1305                         hrw = (g->w / rowno);
1306                         gg.y += main_height + 2;
1307                         gg.h = g->h - (main_height + 2);
1308                         gg.w = hrw - 2;
1309                         j = 0;
1310                 }
1311                 if (j == rowno - 1)
1312                         gg.w = (hrw + (g->w - (rowno * hrw)));
1313
1314                 if (j == 0)
1315                         gg.x = g->x;
1316                 else
1317                         gg.x += hrw;
1318
1319                 if (win->transient != 0 || win->floating != 0)
1320                         stack_floater(win, ws->r);
1321                 else {
1322                         bzero(&wc, sizeof wc);
1323                         wc.border_width = 1;
1324                         win->g.x = wc.x = gg.x;
1325                         win->g.y = wc.y = gg.y;
1326                         win->g.w = wc.width = gg.w;
1327                         win->g.h = wc.height = gg.h;
1328                         mask = CWX | CWY | CWWidth | CWHeight | CWBorderWidth;
1329                         XConfigureWindow(display, win->id, mask, &wc);
1330                 }
1331
1332                 XMapRaised(display, win->id);
1333                 j++;
1334                 i++;
1335         }
1336
1337         if (winfocus)
1338                 focus_win(winfocus); /* this has to be done outside of the loop */
1339 }
1340
1341 /* fullscreen view */
1342 void
1343 max_stack(struct workspace *ws, struct swm_geometry *g) {
1344         XWindowChanges          wc;
1345         struct swm_geometry     gg = *g;
1346         struct ws_win           *win, *winfocus;
1347         unsigned int            mask;
1348
1349         DNPRINTF(SWM_D_STACK, "max_stack: workspace: %d\n", ws->idx);
1350
1351         if (count_win(ws, 0) == 0)
1352                 return;
1353
1354         if (ws->focus == NULL)
1355                 ws->focus = TAILQ_FIRST(&ws->winlist);
1356         winfocus = cur_focus ? cur_focus : ws->focus;
1357
1358         TAILQ_FOREACH(win, &ws->winlist, entry) {
1359                 if (win->transient != 0 || win->floating != 0) {
1360                         if (win == ws->focus) {
1361                                 /* XXX maximize? */
1362                                 stack_floater(win, ws->r);
1363                                 XMapRaised(display, win->id);
1364                         } else
1365                                 XUnmapWindow(display, win->id);
1366                 } else {
1367                         bzero(&wc, sizeof wc);
1368                         wc.border_width = 1;
1369                         win->g.x = wc.x = gg.x;
1370                         win->g.y = wc.y = gg.y;
1371                         win->g.w = wc.width = gg.w;
1372                         win->g.h = wc.height = gg.h;
1373                         mask = CWX | CWY | CWWidth | CWHeight | CWBorderWidth;
1374                         XConfigureWindow(display, win->id, mask, &wc);
1375
1376                         if (win == ws->focus) {
1377                                 XMapRaised(display, win->id);
1378                         } else
1379                                 XUnmapWindow(display, win->id);
1380                 }
1381         }
1382
1383         if (winfocus)
1384                 focus_win(winfocus); /* has to be done outside of the loop */
1385 }
1386
1387 void
1388 send_to_ws(struct swm_region *r, union arg *args)
1389 {
1390         int                     wsid = args->id;
1391         struct ws_win           *win = cur_focus;
1392         struct workspace        *ws, *nws;
1393         Atom                    ws_idx_atom = 0;
1394         unsigned char           ws_idx_str[SWM_PROPLEN];
1395
1396         DNPRINTF(SWM_D_MOVE, "send_to_ws: win: %lu\n", win->id);
1397
1398         ws = win->ws;
1399         nws = &win->s->ws[wsid];
1400
1401         XUnmapWindow(display, win->id);
1402
1403         /* find a window to focus */
1404         ws->focus = TAILQ_PREV(win, ws_win_list, entry);
1405         if (ws->focus == NULL)
1406                 ws->focus = TAILQ_FIRST(&ws->winlist);
1407         if (ws->focus == win)
1408                 ws->focus = NULL;
1409
1410         TAILQ_REMOVE(&ws->winlist, win, entry);
1411
1412         TAILQ_INSERT_TAIL(&nws->winlist, win, entry);
1413         win->ws = nws;
1414
1415         /* Try to update the window's workspace property */
1416         ws_idx_atom = XInternAtom(display, "_SWM_WS", False);
1417         if (ws_idx_atom &&
1418             snprintf(ws_idx_str, SWM_PROPLEN, "%d", nws->idx) < SWM_PROPLEN) {
1419                 DNPRINTF(SWM_D_PROP, "setting property _SWM_WS to %s\n",
1420                     ws_idx_str);
1421                 XChangeProperty(display, win->id, ws_idx_atom, XA_STRING, 8,
1422                     PropModeReplace, ws_idx_str, SWM_PROPLEN);
1423         }
1424
1425         if (count_win(nws, 1) == 1)
1426                 nws->focus = win;
1427         ws->restack = 1;
1428         nws->restack = 1;
1429
1430         stack();
1431 }
1432
1433 void
1434 wkill(struct swm_region *r, union arg *args)
1435 {
1436         DNPRINTF(SWM_D_MISC, "wkill\n");
1437         if(r->ws->focus != NULL)
1438                 XKillClient(display, r->ws->focus->id);
1439 }
1440
1441 void
1442 screenshot(struct swm_region *r, union arg *args)
1443 {
1444         union arg                       a;
1445
1446         DNPRINTF(SWM_D_MISC, "screenshot\n");
1447
1448         if (ss_enabled == 0)
1449                 return;
1450
1451         switch (args->id) {
1452         case SWM_ARG_ID_SS_ALL:
1453                 spawn_screenshot[1] = "-m";
1454                 break;
1455         case SWM_ARG_ID_SS_WINDOW:
1456                 spawn_screenshot[1] = "-s"; /* XXX doesn't work with scrot */
1457                 break;
1458         default:
1459                 return;
1460         }
1461         a.argv = spawn_screenshot;
1462         spawn(r, &a);
1463 }
1464
1465 /* key definitions */
1466 struct key {
1467         unsigned int            mod;
1468         KeySym                  keysym;
1469         void                    (*func)(struct swm_region *r, union arg *);
1470         union arg               args;
1471 } keys[] = {
1472         /* modifier             key     function                argument */
1473         { MODKEY,               XK_space,       cycle_layout,   {0} }, 
1474         { MODKEY | ShiftMask,   XK_space,       stack_config,   {.id = SWM_ARG_ID_STACKRESET} }, 
1475         { MODKEY,               XK_h,           stack_config,   {.id = SWM_ARG_ID_MASTERSHRINK} },
1476         { MODKEY,               XK_l,           stack_config,   {.id = SWM_ARG_ID_MASTERGROW} },
1477         { MODKEY,               XK_comma,       stack_config,   {.id = SWM_ARG_ID_MASTERADD} },
1478         { MODKEY,               XK_period,      stack_config,   {.id = SWM_ARG_ID_MASTERDEL} },
1479         { MODKEY,               XK_Return,      swapwin,        {.id = SWM_ARG_ID_SWAPMAIN} },
1480         { MODKEY,               XK_j,           focus,          {.id = SWM_ARG_ID_FOCUSNEXT} },
1481         { MODKEY,               XK_k,           focus,          {.id = SWM_ARG_ID_FOCUSPREV} },
1482         { MODKEY | ShiftMask,   XK_j,           swapwin,        {.id = SWM_ARG_ID_SWAPNEXT} },
1483         { MODKEY | ShiftMask,   XK_k,           swapwin,        {.id = SWM_ARG_ID_SWAPPREV} },
1484         { MODKEY | ShiftMask,   XK_Return,      spawn,          {.argv = spawn_term} },
1485         { MODKEY,               XK_p,           spawnmenu,      {.argv = spawn_menu} },
1486         { MODKEY | ShiftMask,   XK_q,           quit,           {0} },
1487         { MODKEY,               XK_q,           restart,        {0} },
1488         { MODKEY,               XK_m,           focus,          {.id = SWM_ARG_ID_FOCUSMAIN} },
1489         { MODKEY,               XK_1,           switchws,       {.id = 0} },
1490         { MODKEY,               XK_2,           switchws,       {.id = 1} },
1491         { MODKEY,               XK_3,           switchws,       {.id = 2} },
1492         { MODKEY,               XK_4,           switchws,       {.id = 3} },
1493         { MODKEY,               XK_5,           switchws,       {.id = 4} },
1494         { MODKEY,               XK_6,           switchws,       {.id = 5} },
1495         { MODKEY,               XK_7,           switchws,       {.id = 6} },
1496         { MODKEY,               XK_8,           switchws,       {.id = 7} },
1497         { MODKEY,               XK_9,           switchws,       {.id = 8} },
1498         { MODKEY,               XK_0,           switchws,       {.id = 9} },
1499         { MODKEY,               XK_Right,       cyclews,        {.id = SWM_ARG_ID_CYCLEWS_UP} }, 
1500         { MODKEY,               XK_Left,        cyclews,        {.id = SWM_ARG_ID_CYCLEWS_DOWN} }, 
1501         { MODKEY | ShiftMask,   XK_1,           send_to_ws,     {.id = 0} },
1502         { MODKEY | ShiftMask,   XK_2,           send_to_ws,     {.id = 1} },
1503         { MODKEY | ShiftMask,   XK_3,           send_to_ws,     {.id = 2} },
1504         { MODKEY | ShiftMask,   XK_4,           send_to_ws,     {.id = 3} },
1505         { MODKEY | ShiftMask,   XK_5,           send_to_ws,     {.id = 4} },
1506         { MODKEY | ShiftMask,   XK_6,           send_to_ws,     {.id = 5} },
1507         { MODKEY | ShiftMask,   XK_7,           send_to_ws,     {.id = 6} },
1508         { MODKEY | ShiftMask,   XK_8,           send_to_ws,     {.id = 7} },
1509         { MODKEY | ShiftMask,   XK_9,           send_to_ws,     {.id = 8} },
1510         { MODKEY | ShiftMask,   XK_0,           send_to_ws,     {.id = 9} },
1511         { MODKEY,               XK_b,           bar_toggle,     {0} },
1512         { MODKEY,               XK_Tab,         focus,          {.id = SWM_ARG_ID_FOCUSNEXT} },
1513         { MODKEY | ShiftMask,   XK_Tab,         focus,          {.id = SWM_ARG_ID_FOCUSPREV} },
1514         { MODKEY | ShiftMask,   XK_x,           wkill,          {0} },
1515         { MODKEY,               XK_s,           screenshot,     {.id = SWM_ARG_ID_SS_ALL} },
1516         { MODKEY | ShiftMask,   XK_s,           screenshot,     {.id = SWM_ARG_ID_SS_WINDOW} },
1517 };
1518
1519 void
1520 click(struct swm_region *r, union arg *args)
1521 {
1522         DNPRINTF(SWM_D_MOUSE, "click: button: %d\n", args->id);
1523
1524         switch (args->id) {
1525         case Button1:
1526                 break;
1527         case Button2:
1528                 break;
1529         case Button3:
1530                 break;
1531         default:
1532                 return;
1533         }
1534 }
1535
1536 /* mouse */
1537 enum { client_click, root_click };
1538 struct button {
1539         unsigned int            action;
1540         unsigned int            mask;
1541         unsigned int            button;
1542         void                    (*func)(struct swm_region *r, union arg *);
1543         union arg               args;
1544 } buttons[] = {
1545           /* action             key             mouse button    func            args */
1546         { client_click,         MODKEY,         Button1,        click, {.id=Button1} },
1547 };
1548
1549 void
1550 updatenumlockmask(void)
1551 {
1552         unsigned int            i, j;
1553         XModifierKeymap         *modmap;
1554
1555         DNPRINTF(SWM_D_MISC, "updatenumlockmask\n");
1556         numlockmask = 0;
1557         modmap = XGetModifierMapping(display);
1558         for (i = 0; i < 8; i++)
1559                 for (j = 0; j < modmap->max_keypermod; j++)
1560                         if (modmap->modifiermap[i * modmap->max_keypermod + j]
1561                           == XKeysymToKeycode(display, XK_Num_Lock))
1562                                 numlockmask = (1 << i);
1563
1564         XFreeModifiermap(modmap);
1565 }
1566
1567 void
1568 grabkeys(void)
1569 {
1570         unsigned int            i, j, k;
1571         KeyCode                 code;
1572         unsigned int            modifiers[] =
1573             { 0, LockMask, numlockmask, numlockmask | LockMask };
1574
1575         DNPRINTF(SWM_D_MISC, "grabkeys\n");
1576         updatenumlockmask();
1577
1578         for (k = 0; k < ScreenCount(display); k++) {
1579                 if (TAILQ_EMPTY(&screens[k].rl))
1580                         continue;
1581                 XUngrabKey(display, AnyKey, AnyModifier, screens[k].root);
1582                 for (i = 0; i < LENGTH(keys); i++) {
1583                         if ((code = XKeysymToKeycode(display, keys[i].keysym)))
1584                                 for (j = 0; j < LENGTH(modifiers); j++)
1585                                         XGrabKey(display, code,
1586                                             keys[i].mod | modifiers[j],
1587                                             screens[k].root, True,
1588                                             GrabModeAsync, GrabModeAsync);
1589                 }
1590         }
1591 }
1592
1593 void
1594 grabbuttons(struct ws_win *win, int focused)
1595 {
1596         unsigned int            i, j;
1597         unsigned int            modifiers[] =
1598             { 0, LockMask, numlockmask, numlockmask|LockMask };
1599
1600         updatenumlockmask();
1601         XUngrabButton(display, AnyButton, AnyModifier, win->id);
1602         if(focused) {
1603                 for (i = 0; i < LENGTH(buttons); i++)
1604                         if (buttons[i].action == client_click)
1605                                 for (j = 0; j < LENGTH(modifiers); j++)
1606                                         XGrabButton(display, buttons[i].button,
1607                                             buttons[i].mask | modifiers[j],
1608                                             win->id, False, BUTTONMASK,
1609                                             GrabModeAsync, GrabModeSync, None,
1610                                             None);
1611         } else
1612                 XGrabButton(display, AnyButton, AnyModifier, win->id, False,
1613                     BUTTONMASK, GrabModeAsync, GrabModeSync, None, None);
1614 }
1615
1616 void
1617 expose(XEvent *e)
1618 {
1619         DNPRINTF(SWM_D_EVENT, "expose: window: %lu\n", e->xexpose.window);
1620 }
1621
1622 void
1623 keypress(XEvent *e)
1624 {
1625         unsigned int            i;
1626         KeySym                  keysym;
1627         XKeyEvent               *ev = &e->xkey;
1628
1629         DNPRINTF(SWM_D_EVENT, "keypress: window: %lu\n", ev->window);
1630
1631         keysym = XKeycodeToKeysym(display, (KeyCode)ev->keycode, 0);
1632         for (i = 0; i < LENGTH(keys); i++)
1633                 if (keysym == keys[i].keysym
1634                    && CLEANMASK(keys[i].mod) == CLEANMASK(ev->state)
1635                    && keys[i].func)
1636                         keys[i].func(root_to_region(ev->root),
1637                             &(keys[i].args));
1638 }
1639
1640 void
1641 buttonpress(XEvent *e)
1642 {
1643         XButtonPressedEvent     *ev = &e->xbutton;
1644
1645         struct ws_win           *win;
1646         int                     i, action;
1647
1648         DNPRINTF(SWM_D_EVENT, "buttonpress: window: %lu\n", ev->window);
1649
1650         action = root_click;
1651         if ((win = find_window(ev->window)) == NULL)
1652                 return;
1653         else {
1654                 focus_win(win);
1655                 action = client_click;
1656         }
1657
1658         for (i = 0; i < LENGTH(buttons); i++)
1659                 if (action == buttons[i].action && buttons[i].func &&
1660                     buttons[i].button == ev->button &&
1661                     CLEANMASK(buttons[i].mask) == CLEANMASK(ev->state))
1662                         buttons[i].func(root_to_region(ev->root),
1663                         &buttons[i].args);
1664 }
1665
1666 void
1667 set_win_state(struct ws_win *win, long state)
1668 {
1669         long                    data[] = {state, None};
1670
1671         DNPRINTF(SWM_D_EVENT, "set_win_state: window: %lu\n", win->id);
1672
1673         XChangeProperty(display, win->id, astate, astate, 32, PropModeReplace,
1674             (unsigned char *)data, 2);
1675 }
1676
1677 struct ws_win *
1678 manage_window(Window id)
1679 {
1680         Window                  trans;
1681         struct workspace        *ws;
1682         struct ws_win           *win;
1683         XClassHint              ch;
1684         int                     format;
1685         unsigned long           nitems, bytes;
1686         Atom                    ws_idx_atom = 0, type;
1687         unsigned char           ws_idx_str[SWM_PROPLEN], *prop = NULL;
1688         struct swm_region       *r;
1689
1690         if ((win = find_window(id)) != NULL)
1691                         return (win);   /* already being managed */
1692
1693         if ((win = calloc(1, sizeof(struct ws_win))) == NULL)
1694                 errx(1, "calloc: failed to allocate memory for new window");
1695
1696         ws_idx_atom = XInternAtom(display, "_SWM_WS", False);
1697         if (ws_idx_atom)
1698                 XGetWindowProperty(display, id, ws_idx_atom, 0, SWM_PROPLEN,
1699                     False, XA_STRING, &type, &format, &nitems, &bytes, &prop);
1700
1701         XGetWindowAttributes(display, id, &win->wa);
1702         r = root_to_region(win->wa.root);
1703         /* If the window was managed before, put it in the same workspace */
1704         if (prop) {
1705                 int             ws_idx;
1706                 const char      *errstr;
1707
1708                 DNPRINTF(SWM_D_PROP, "got property _SWM_WS=%s\n", prop);
1709                 ws_idx = strtonum(prop, 0, 9, &errstr);
1710                 if (errstr)
1711                         DNPRINTF(SWM_D_EVENT, "window idx is %s: %s",
1712                             errstr, prop);
1713                 ws = &r->s->ws[ws_idx];
1714         } else
1715                 ws = r->ws;
1716
1717         win->id = id;
1718         win->ws = ws;
1719         win->s = r->s;  /* this never changes */
1720         TAILQ_INSERT_TAIL(&ws->winlist, win, entry);
1721
1722         /* make new win focused */
1723         focus_win(win);
1724
1725         XGetTransientForHint(display, win->id, &trans);
1726         if (trans) {
1727                 win->transient = trans;
1728                 DNPRINTF(SWM_D_MISC, "manage_window: win %u transient %u\n",
1729                     (unsigned)win->id, win->transient);
1730         }
1731         win->g.w = win->wa.width;
1732         win->g.h = win->wa.height;
1733         win->g.x = win->wa.x;
1734         win->g.y = win->wa.y;
1735
1736         if (ws_idx_atom && prop == NULL &&
1737             snprintf(ws_idx_str, SWM_PROPLEN, "%d", ws->idx) < SWM_PROPLEN) {
1738                 DNPRINTF(SWM_D_PROP, "setting property _SWM_WS to %s\n",
1739                     ws_idx_str);
1740                 XChangeProperty(display, win->id, ws_idx_atom, XA_STRING, 8,
1741                     PropModeReplace, ws_idx_str, SWM_PROPLEN);
1742         }
1743         XFree(prop);
1744
1745         /*
1746         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);
1747         */
1748
1749         /* XXX make this a table */
1750         bzero(&ch, sizeof ch);
1751         if (XGetClassHint(display, win->id, &ch)) {
1752                 /*fprintf(stderr, "class: %s name: %s\n", ch.res_class, ch.res_name); */
1753                 if (!strcmp(ch.res_class, "MPlayer") && !strcmp(ch.res_name, "xv")) {
1754                         win->floating = 1;
1755                 }
1756                 if (ch.res_class)
1757                         XFree(ch.res_class);
1758                 if (ch.res_name)
1759                         XFree(ch.res_name);
1760         }
1761
1762         XSelectInput(display, id, EnterWindowMask | FocusChangeMask |
1763             PropertyChangeMask | StructureNotifyMask);
1764
1765         set_win_state(win, NormalState);
1766
1767         return (win);
1768 }
1769
1770 void
1771 configurerequest(XEvent *e)
1772 {
1773         XConfigureRequestEvent  *ev = &e->xconfigurerequest;
1774         struct ws_win           *win;
1775         int                     new = 0;
1776         XWindowChanges          wc;
1777
1778         if ((win = find_window(ev->window)) == NULL)
1779                 new = 1;
1780
1781         if (new) {
1782                 DNPRINTF(SWM_D_EVENT, "configurerequest: new window: %lu\n",
1783                     ev->window);
1784                 /*
1785                 fprintf(stderr, "configurerequest: new window: %lu x %d y %d w %d h %d bw %d s %d sm %d\n",
1786                     ev->window, ev->x, ev->y, ev->width, ev->height, ev->border_width, ev->above, ev->detail);
1787                 */
1788                 bzero(&wc, sizeof wc);
1789                 wc.x = ev->x;
1790                 wc.y = ev->y;
1791                 wc.width = ev->width;
1792                 wc.height = ev->height;
1793                 wc.border_width = ev->border_width;
1794                 wc.sibling = ev->above;
1795                 wc.stack_mode = ev->detail;
1796                 XConfigureWindow(display, ev->window, ev->value_mask, &wc);
1797         } else {
1798                 /*
1799                 fprintf(stderr, "configurerequest: change window: %lu\n",
1800                     ev->window);
1801                 */
1802                 DNPRINTF(SWM_D_EVENT, "configurerequest: change window: %lu\n",
1803                     ev->window);
1804                 if (win->floating) {
1805                         if (ev->value_mask & CWX)
1806                                 win->g.x = ev->x;
1807                         if (ev->value_mask & CWY)
1808                                 win->g.y = ev->y;
1809                         if (ev->value_mask & CWWidth)
1810                                 win->g.w = ev->width;
1811                         if (ev->value_mask & CWHeight)
1812                                 win->g.h = ev->height;
1813                         if (win->ws->r != NULL) {
1814                                 /* this seems to be full screen */
1815                                 if (win->g.w > WIDTH(win->ws->r)) {
1816                                         /* kill border */
1817                                         win->g.x -= 1;
1818                                         win->g.w += 1;
1819                                 }
1820                                 if (win->g.h > HEIGHT(win->ws->r)) {
1821                                         /* kill border */
1822                                         win->g.y -= 1;
1823                                         win->g.h += 1;
1824                                 }
1825                         }
1826                         if ((ev->value_mask & (CWX|CWY)) &&
1827                             !(ev->value_mask & (CWWidth|CWHeight)))
1828                                 config_win(win);
1829                         XMoveResizeWindow(display, win->id,
1830                             win->g.x, win->g.y, win->g.w, win->g.h);
1831                 } else
1832                         config_win(win);
1833         }
1834 }
1835
1836 void
1837 configurenotify(XEvent *e)
1838 {
1839         DNPRINTF(SWM_D_EVENT, "configurenotify: window: %lu\n",
1840             e->xconfigure.window);
1841 }
1842
1843 void
1844 destroynotify(XEvent *e)
1845 {
1846         struct ws_win           *win;
1847         XDestroyWindowEvent     *ev = &e->xdestroywindow;
1848         struct workspace        *ws;
1849
1850         DNPRINTF(SWM_D_EVENT, "destroynotify: window %lu\n", ev->window);
1851
1852         if ((win = find_window(ev->window)) != NULL) {
1853                 ws = win->ws;
1854                 /* find a window to focus */
1855                 if (ws->focus == win)
1856                         ws->focus = TAILQ_PREV(win, ws_win_list, entry);
1857                 if (ws->focus == NULL)
1858                         ws->focus = TAILQ_FIRST(&ws->winlist);
1859                 if (ws->focus == win)
1860                         ws->focus = NULL;
1861                 if (cur_focus == win)
1862                         focus_win(ws->focus);
1863
1864                 TAILQ_REMOVE(&ws->winlist, win, entry);
1865                 set_win_state(win, WithdrawnState);
1866                 free(win);
1867         }
1868         stack();
1869 }
1870
1871 void
1872 enternotify(XEvent *e)
1873 {
1874         XCrossingEvent          *ev = &e->xcrossing;
1875         struct ws_win           *win;
1876
1877         DNPRINTF(SWM_D_EVENT, "enternotify: window: %lu\n", ev->window);
1878
1879         if (ignore_enter) {
1880                 /* eat event(r) to prevent autofocus */
1881                 ignore_enter--;
1882                 return;
1883         }
1884
1885         if ((win = find_window(ev->window)) != NULL)
1886                 focus_win(win);
1887 }
1888
1889 void
1890 focusin(XEvent *e)
1891 {
1892         DNPRINTF(SWM_D_EVENT, "focusin: window: %lu\n", e->xfocus.window);
1893 }
1894
1895 void
1896 mappingnotify(XEvent *e)
1897 {
1898         XMappingEvent           *ev = &e->xmapping;
1899
1900         DNPRINTF(SWM_D_EVENT, "mappingnotify: window: %lu\n", ev->window);
1901
1902         XRefreshKeyboardMapping(ev);
1903         if (ev->request == MappingKeyboard)
1904                 grabkeys();
1905 }
1906
1907 void
1908 maprequest(XEvent *e)
1909 {
1910         XMapRequestEvent        *ev = &e->xmaprequest;
1911         XWindowAttributes       wa;
1912
1913         DNPRINTF(SWM_D_EVENT, "maprequest: window: %lu\n",
1914             e->xmaprequest.window);
1915
1916         if (!XGetWindowAttributes(display, ev->window, &wa))
1917                 return;
1918         if (wa.override_redirect)
1919                 return;
1920         manage_window(e->xmaprequest.window);
1921         stack();
1922 }
1923
1924 void
1925 propertynotify(XEvent *e)
1926 {
1927         DNPRINTF(SWM_D_EVENT, "propertynotify: window: %lu\n",
1928             e->xproperty.window);
1929 }
1930
1931 void
1932 unmapnotify(XEvent *e)
1933 {
1934         DNPRINTF(SWM_D_EVENT, "unmapnotify: window: %lu\n", e->xunmap.window);
1935 }
1936
1937 void
1938 visibilitynotify(XEvent *e)
1939 {
1940         int                     i;
1941         struct swm_region       *r;
1942
1943         DNPRINTF(SWM_D_EVENT, "visibilitynotify: window: %lu\n",
1944             e->xvisibility.window);
1945         if (e->xvisibility.state == VisibilityUnobscured)
1946                 for (i = 0; i < ScreenCount(display); i++) 
1947                         TAILQ_FOREACH(r, &screens[i].rl, entry)
1948                                 if (e->xvisibility.window == r->bar_window)
1949                                         bar_update();
1950 }
1951
1952 void                    (*handler[LASTEvent])(XEvent *) = {
1953                                 [Expose] = expose,
1954                                 [KeyPress] = keypress,
1955                                 [ButtonPress] = buttonpress,
1956                                 [ConfigureRequest] = configurerequest,
1957                                 [ConfigureNotify] = configurenotify,
1958                                 [DestroyNotify] = destroynotify,
1959                                 [EnterNotify] = enternotify,
1960                                 [FocusIn] = focusin,
1961                                 [MappingNotify] = mappingnotify,
1962                                 [MapRequest] = maprequest,
1963                                 [PropertyNotify] = propertynotify,
1964                                 [UnmapNotify] = unmapnotify,
1965                                 [VisibilityNotify] = visibilitynotify,
1966 };
1967
1968 int
1969 xerror_start(Display *d, XErrorEvent *ee)
1970 {
1971         other_wm = 1;
1972         return (-1);
1973 }
1974
1975 int
1976 xerror(Display *d, XErrorEvent *ee)
1977 {
1978         /* fprintf(stderr, "error: %p %p\n", display, ee); */
1979         return (-1);
1980 }
1981
1982 int
1983 active_wm(void)
1984 {
1985         other_wm = 0;
1986         xerrorxlib = XSetErrorHandler(xerror_start);
1987
1988         /* this causes an error if some other window manager is running */
1989         XSelectInput(display, DefaultRootWindow(display),
1990             SubstructureRedirectMask);
1991         XSync(display, False);
1992         if (other_wm)
1993                 return (1);
1994
1995         XSetErrorHandler(xerror);
1996         XSync(display, False);
1997         return (0);
1998 }
1999
2000 long
2001 getstate(Window w)
2002 {
2003         int                     format, status;
2004         long                    result = -1;
2005         unsigned char           *p = NULL;
2006         unsigned long           n, extra;
2007         Atom                    real;
2008
2009         astate = XInternAtom(display, "WM_STATE", False);
2010         status = XGetWindowProperty(display, w, astate, 0L, 2L, False, astate,
2011             &real, &format, &n, &extra, (unsigned char **)&p);
2012         if (status != Success)
2013                 return (-1);
2014         if (n != 0)
2015                 result = *p;
2016         XFree(p);
2017         return (result);
2018 }
2019
2020 void
2021 new_region(struct swm_screen *s, struct workspace *ws,
2022     int x, int y, int w, int h)
2023 {
2024         struct swm_region       *r;
2025
2026         DNPRINTF(SWM_D_MISC, "new region on screen %d: %dx%d (%d, %d)\n",
2027              s->idx, x, y, w, h);
2028
2029         if ((r = calloc(1, sizeof(struct swm_region))) == NULL)
2030                 errx(1, "calloc: failed to allocate memory for screen");
2031
2032         X(r) = x;
2033         Y(r) = y;
2034         WIDTH(r) = w;
2035         HEIGHT(r) = h;
2036         r->s = s;
2037         r->ws = ws;
2038         ws->r = r;
2039         TAILQ_INSERT_TAIL(&s->rl, r, entry);
2040         bar_setup(r);
2041 }
2042
2043 void
2044 setup_screens(void)
2045 {
2046 #ifdef SWM_XRR_HAS_CRTC
2047         XRRCrtcInfo             *ci;
2048         XRRScreenResources      *sr;
2049         int                     c;
2050 #endif /* SWM_XRR_HAS_CRTC */
2051         Window                  d1, d2, *wins = NULL;
2052         XWindowAttributes       wa;
2053         struct swm_region       *r;
2054         unsigned int            no;
2055         int                     errorbase, major, minor;
2056         int                     ncrtc = 0, w = 0;
2057         int                     i, j, k;
2058         struct workspace        *ws;
2059         int                     ws_idx_atom;
2060
2061
2062         if ((screens = calloc(ScreenCount(display),
2063              sizeof(struct swm_screen))) == NULL)
2064                 errx(1, "calloc: screens");
2065
2066         ws_idx_atom = XInternAtom(display, "_SWM_WS", False);
2067         
2068
2069         /* map physical screens */
2070         for (i = 0; i < ScreenCount(display); i++) {
2071                 DNPRINTF(SWM_D_WS, "setup_screens: init screen %d\n", i);
2072                 screens[i].idx = i;
2073                 TAILQ_INIT(&screens[i].rl);
2074                 screens[i].root = RootWindow(display, i);
2075
2076                 /* set default colors */
2077                 setscreencolor("red", i + 1, SWM_S_COLOR_FOCUS);
2078                 setscreencolor("rgb:88/88/88", i + 1, SWM_S_COLOR_UNFOCUS);
2079                 setscreencolor("rgb:00/80/80", i + 1, SWM_S_COLOR_BAR_BORDER);
2080                 setscreencolor("black", i + 1, SWM_S_COLOR_BAR);
2081                 setscreencolor("rgb:a0/a0/a0", i + 1, SWM_S_COLOR_BAR_FONT);
2082
2083                 /* init all workspaces */
2084                 for (j = 0; j < SWM_WS_MAX; j++) {
2085                         ws = &screens[i].ws[j];
2086                         ws->idx = j;
2087                         ws->restack = 1;
2088                         ws->focus = NULL;
2089                         ws->r = NULL;
2090                         TAILQ_INIT(&ws->winlist);
2091
2092                         for (k = 0; layouts[k].l_stack != NULL; k++)
2093                                 if (layouts[k].l_config != NULL)
2094                                         layouts[k].l_config(ws,
2095                                             SWM_ARG_ID_STACKINIT);
2096                         ws->cur_layout = &layouts[0];
2097                 }
2098
2099                 /* map virtual screens onto physical screens */
2100                 screens[i].xrandr_support = XRRQueryExtension(display,
2101                     &xrandr_eventbase, &errorbase);
2102                 if (screens[i].xrandr_support)
2103                         if (XRRQueryVersion(display, &major, &minor) &&
2104                             major < 1)
2105                                 screens[i].xrandr_support = 0;
2106
2107 #if 0   /* not ready for dynamic screen changes */
2108                 if (screens[i].xrandr_support)
2109                         XRRSelectInput(display,
2110                             screens[r->s].root,
2111                             RRScreenChangeNotifyMask);
2112 #endif
2113
2114                 /* grab existing windows (before we build the bars)*/
2115                 if (!XQueryTree(display, screens[i].root, &d1, &d2, &wins, &no))
2116                         continue;
2117
2118 #ifdef SWM_XRR_HAS_CRTC
2119                 sr = XRRGetScreenResources(display, screens[i].root);
2120                 if (sr == NULL)
2121                         new_region(&screens[i], &screens[i].ws[w],
2122                             0, 0, DisplayWidth(display, i),
2123                             DisplayHeight(display, i)); 
2124                 else 
2125                         ncrtc = sr->ncrtc;
2126
2127                 for (c = 0, ci = NULL; c < ncrtc; c++) {
2128                         ci = XRRGetCrtcInfo(display, sr, sr->crtcs[c]);
2129                         if (ci->noutput == 0)
2130                                 continue;
2131
2132                         if (ci != NULL && ci->mode == None)
2133                                 new_region(&screens[i], &screens[i].ws[w], 0, 0,
2134                                     DisplayWidth(display, i),
2135                                     DisplayHeight(display, i)); 
2136                         else
2137                                 new_region(&screens[i], &screens[i].ws[w],
2138                                     ci->x, ci->y, ci->width, ci->height);
2139                         w++;
2140                 }
2141                 if (ci)
2142                         XRRFreeCrtcInfo(ci);
2143                 XRRFreeScreenResources(sr);
2144 #else
2145                 new_region(&screens[i], &screens[i].ws[w], 0, 0,
2146                     DisplayWidth(display, i),
2147                     DisplayHeight(display, i)); 
2148 #endif /* SWM_XRR_HAS_CRTC */
2149
2150                 /* attach windows to a region */
2151                 /* normal windows */
2152                 if ((r = TAILQ_FIRST(&screens[i].rl)) == NULL)
2153                         errx(1, "no regions on screen %d", i);
2154
2155                 for (i = 0; i < no; i++) {
2156                         XGetWindowAttributes(display, wins[i], &wa);
2157                         if (!XGetWindowAttributes(display, wins[i], &wa) ||
2158                             wa.override_redirect ||
2159                             XGetTransientForHint(display, wins[i], &d1))
2160                                 continue;
2161
2162                         if (wa.map_state == IsViewable ||
2163                             getstate(wins[i]) == NormalState)
2164                                 manage_window(wins[i]);
2165                 }
2166                 /* transient windows */
2167                 for (i = 0; i < no; i++) {
2168                         if (!XGetWindowAttributes(display, wins[i], &wa))
2169                                 continue;
2170
2171                         if (XGetTransientForHint(display, wins[i], &d1) &&
2172                             (wa.map_state == IsViewable || getstate(wins[i]) ==
2173                             NormalState))
2174                                 manage_window(wins[i]);
2175                 }
2176                 if (wins) {
2177                         XFree(wins);
2178                         wins = NULL;
2179                 }
2180         }
2181 }
2182
2183 int
2184 main(int argc, char *argv[])
2185 {
2186         struct passwd           *pwd;
2187         char                    conf[PATH_MAX], *cfile = NULL;
2188         struct stat             sb;
2189         XEvent                  e;
2190         int                     xfd;
2191         fd_set                  rd;
2192
2193         start_argv = argv;
2194         fprintf(stderr, "Welcome to scrotwm V%s\n", SWM_VERSION);
2195         if (!setlocale(LC_CTYPE, "") || !XSupportsLocale())
2196                 warnx("no locale support");
2197
2198         if (!(display = XOpenDisplay(0)))
2199                 errx(1, "can not open display");
2200
2201         if (active_wm())
2202                 errx(1, "other wm running");
2203
2204         astate = XInternAtom(display, "WM_STATE", False);
2205
2206         /* look for local and global conf file */
2207         pwd = getpwuid(getuid());
2208         if (pwd == NULL)
2209                 errx(1, "invalid user %d", getuid());
2210
2211         setup_screens();
2212
2213         snprintf(conf, sizeof conf, "%s/.%s", pwd->pw_dir, SWM_CONF_FILE);
2214         if (stat(conf, &sb) != -1) {
2215                 if (S_ISREG(sb.st_mode))
2216                         cfile = conf;
2217         } else {
2218                 /* try global conf file */
2219                 snprintf(conf, sizeof conf, "/etc/%s", SWM_CONF_FILE);
2220                 if (!stat(conf, &sb))
2221                         if (S_ISREG(sb.st_mode))
2222                                 cfile = conf;
2223         }
2224         if (cfile)
2225                 conf_load(cfile);
2226         bar_refresh();
2227
2228         /* ws[0].focus = TAILQ_FIRST(&ws[0].winlist); */
2229
2230         grabkeys();
2231         stack();
2232
2233         xfd = ConnectionNumber(display);
2234         while (running) {
2235                 FD_ZERO(&rd);
2236                 FD_SET(xfd, &rd);
2237                 if (select(xfd + 1, &rd, NULL, NULL, NULL) == -1)
2238                         if (errno != EINTR)
2239                                 errx(1, "select failed");
2240                 if (bar_alarm) {
2241                         bar_alarm = 0;
2242                         bar_update();
2243                 }
2244                 while(XPending(display)) {
2245                         XNextEvent(display, &e);
2246                         if (handler[e.type])
2247                                 handler[e.type](&e);
2248                 }
2249         }
2250
2251         XCloseDisplay(display);
2252
2253         return (0);
2254 }