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