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