JasonWoof Got questions, comments, patches, etc.? Contact Jason Woofenden
KNF
[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 static const char       *cvstag = "$scrotwm$";
52
53 #define SWM_VERSION     "0.6"
54
55 #include <stdio.h>
56 #include <stdlib.h>
57 #include <err.h>
58 #include <errno.h>
59 #include <fcntl.h>
60 #include <locale.h>
61 #include <unistd.h>
62 #include <time.h>
63 #include <signal.h>
64 #include <string.h>
65 #include <util.h>
66 #include <pwd.h>
67 #include <ctype.h>
68
69 #include <sys/types.h>
70 #include <sys/time.h>
71 #include <sys/stat.h>
72 #include <sys/wait.h>
73 #include <sys/queue.h>
74 #include <sys/param.h>
75 #include <sys/select.h>
76
77 #include <X11/cursorfont.h>
78 #include <X11/keysym.h>
79 #include <X11/Xatom.h>
80 #include <X11/Xlib.h>
81 #include <X11/Xproto.h>
82 #include <X11/Xutil.h>
83 #include <X11/extensions/Xrandr.h>
84
85 #if RANDR_MAJOR < 1
86 #  error XRandR versions less than 1.0 are not supported
87 #endif
88
89 #if RANDR_MAJOR >= 1
90 #if RANDR_MINOR >= 2
91 #define SWM_XRR_HAS_CRTC
92 #endif
93 #endif
94
95 /* #define SWM_DEBUG */
96 #ifdef SWM_DEBUG
97 #define DPRINTF(x...)           do { if (swm_debug) fprintf(stderr, x); } while(0)
98 #define DNPRINTF(n,x...)        do { if (swm_debug & n) fprintf(stderr, x); } while(0)
99 #define SWM_D_MISC              0x0001
100 #define SWM_D_EVENT             0x0002
101 #define SWM_D_WS                0x0004
102 #define SWM_D_FOCUS             0x0008
103 #define SWM_D_MOVE              0x0010
104 #define SWM_D_STACK             0x0020
105 #define SWM_D_MOUSE             0x0040
106 #define SWM_D_PROP              0x0080
107
108 u_int32_t               swm_debug = 0
109                             | SWM_D_MISC
110                             | SWM_D_EVENT
111                             | SWM_D_WS
112                             | SWM_D_FOCUS
113                             | SWM_D_MOVE
114                             | SWM_D_STACK
115                             | SWM_D_MOUSE
116                             | SWM_D_PROP
117                             ;
118 #else
119 #define DPRINTF(x...)
120 #define DNPRINTF(n,x...)
121 #endif
122
123 #define LENGTH(x)               (sizeof x / sizeof x[0])
124 #define MODKEY                  Mod1Mask
125 #define CLEANMASK(mask)         (mask & ~(numlockmask | LockMask))
126 #define BUTTONMASK              (ButtonPressMask|ButtonReleaseMask)
127 #define SWM_PROPLEN             (16)
128 #define X(r)                    (r)->g.x        
129 #define Y(r)                    (r)->g.y
130 #define WIDTH(r)                (r)->g.w        
131 #define HEIGHT(r)               (r)->g.h
132
133 #ifndef SWM_LIB
134 #define SWM_LIB                 "/usr/X11R6/lib/swmhack.so"
135 #endif
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, "-nb", NULL,
180                             "-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         int                     si;
808
809         DNPRINTF(SWM_D_MISC, "spawn: %s\n", args->argv[0]);
810         /*
811          * The double-fork construct avoids zombie processes and keeps the code
812          * clean from stupid signal handlers.
813          */
814         if (fork() == 0) {
815                 if (fork() == 0) {
816                         if (display)
817                                 close(ConnectionNumber(display));
818                         setenv("LD_PRELOAD", SWM_LIB, 1);
819                         if (asprintf(&ret, "%d", r->ws->idx)) {
820                                 setenv("_SWM_WS", ret, 1);
821                                 free(ret);
822                         }
823                         if (asprintf(&ret, "%d", getpid())) {
824                                 setenv("_SWM_PID", ret, 1);
825                                 free(ret);
826                         }
827                         setsid();
828                         /* kill stdin, mplayer, ssh-add etc. need that */
829                         si = open("/dev/null", O_RDONLY, 0);
830                         if (si == -1)
831                                 err(1, "open /dev/null");
832                         if (dup2(si, 0) == -1)
833                                 err(1, "dup2 /dev/null");
834                         execvp(args->argv[0], args->argv);
835                         fprintf(stderr, "execvp failed\n");
836                         perror(" failed");
837                 }
838                 exit(0);
839         }
840         wait(0);
841 }
842
843 void
844 spawnmenu(struct swm_region *r, union arg *args)
845 {
846         DNPRINTF(SWM_D_MISC, "spawnmenu\n");
847
848         spawn_menu[SWM_MENU_FN] = bar_fonts[bar_fidx];
849         spawn_menu[SWM_MENU_NB] = r->s->c[SWM_S_COLOR_BAR].name;
850         spawn_menu[SWM_MENU_NF] = r->s->c[SWM_S_COLOR_BAR_FONT].name;
851         spawn_menu[SWM_MENU_SB] = r->s->c[SWM_S_COLOR_BAR_BORDER].name;
852         spawn_menu[SWM_MENU_SF] = r->s->c[SWM_S_COLOR_BAR].name;
853
854         spawn(r, args);
855 }
856
857 void
858 unfocus_all(void)
859 {
860         struct ws_win           *win;
861         int                     i, j;
862
863         DNPRINTF(SWM_D_FOCUS, "unfocus_all:\n");
864
865         for (i = 0; i < ScreenCount(display); i++)
866                 for (j = 0; j < SWM_WS_MAX; j++)
867                         TAILQ_FOREACH(win, &screens[i].ws[j].winlist, entry) {
868                                 if (win->ws->r == NULL)
869                                         continue;
870                                 grabbuttons(win, 0);
871                                 XSetWindowBorder(display, win->id,
872                                     win->ws->r->s->c[SWM_S_COLOR_UNFOCUS].color);
873                                 win->got_focus = 0;
874                                 win->ws->focus = NULL;
875                                 cur_focus = NULL;
876                         }
877 }
878
879 void
880 focus_win(struct ws_win *win)
881 {
882         DNPRINTF(SWM_D_FOCUS, "focus_win: id: %lu\n", win ? win->id : 0);
883
884         if (win == NULL)
885                 return;
886
887         unfocus_all();
888         win->ws->focus = win;
889         if (win->ws->r != NULL) {
890                 cur_focus = win;
891                 if (!win->got_focus) {
892                         XSetWindowBorder(display, win->id,
893                             win->ws->r->s->c[SWM_S_COLOR_FOCUS].color);
894                         grabbuttons(win, 1);
895                 }
896                 win->got_focus = 1;
897                 XSetInputFocus(display, win->id,
898                     RevertToPointerRoot, CurrentTime);
899         }
900 }
901
902 void
903 switchws(struct swm_region *r, union arg *args)
904 {
905         int                     wsid = args->id;
906         struct swm_region       *this_r, *other_r;
907         struct ws_win           *win;
908         struct workspace        *new_ws, *old_ws;
909
910         this_r = r;
911         old_ws = this_r->ws;
912         new_ws = &this_r->s->ws[wsid];
913
914         DNPRINTF(SWM_D_WS, "switchws screen %d region %dx%d+%d+%d: "
915             "%d -> %d\n", r->s->idx, WIDTH(r), HEIGHT(r), X(r), Y(r),
916             old_ws->idx, wsid);
917
918         if (new_ws == old_ws)
919                 return;
920
921         other_r = new_ws->r;
922         if (!other_r) {
923                 /* if the other workspace is hidden, switch windows */
924                 /* map new window first to prevent ugly blinking */
925                 TAILQ_FOREACH(win, &new_ws->winlist, entry)
926                         XMapRaised(display, win->id);
927
928                 TAILQ_FOREACH(win, &old_ws->winlist, entry)
929                         XUnmapWindow(display, win->id);
930                 old_ws->r = NULL;
931                 old_ws->restack = 1;
932         } else {
933                 other_r->ws = old_ws;
934                 old_ws->r = other_r;
935         }
936         this_r->ws = new_ws;
937         new_ws->r = this_r;
938
939         ignore_enter = 1;
940         /* set focus */
941         if (new_ws->focus)
942                 focus_win(new_ws->focus);
943         stack();
944         bar_update();
945 }
946
947 void
948 cyclews(struct swm_region *r, union arg *args)
949 {
950         union                   arg a;
951         struct swm_screen       *s = r->s;
952
953         DNPRINTF(SWM_D_WS, "cyclews id %d "
954             "in screen %d region %dx%d+%d+%d ws %d\n", args->id,
955             r->s->idx, WIDTH(r), HEIGHT(r), X(r), Y(r), r->ws->idx);
956
957         a.id = r->ws->idx;
958         do {
959                 switch (args->id) {
960                 case SWM_ARG_ID_CYCLEWS_UP:
961                         if (a.id < SWM_WS_MAX - 1)
962                                 a.id++;
963                         else
964                                 a.id = 0;
965                         break;
966                 case SWM_ARG_ID_CYCLEWS_DOWN:
967                         if (a.id > 0)
968                                 a.id--;
969                         else
970                                 a.id = SWM_WS_MAX - 1;
971                         break;
972                 default:
973                         return;
974                 };
975
976                 if (cycle_empty == 0 && TAILQ_EMPTY(&s->ws[a.id].winlist))
977                         continue;
978                 if (cycle_visible == 0 && s->ws[a.id].r != NULL)
979                         continue;
980
981                 switchws(r, &a);
982         } while (a.id != r->ws->idx);
983 }
984
985 void
986 cyclescr(struct swm_region *r, union arg *args)
987 {
988         struct swm_region       *rr;
989         int                     i;
990
991         i = r->s->idx;
992         switch (args->id) {
993         case SWM_ARG_ID_CYCLESC_UP:
994                 rr = TAILQ_NEXT(r, entry);
995                 if (rr == NULL)
996                         rr = TAILQ_FIRST(&screens[i].rl);
997                 break;
998         case SWM_ARG_ID_CYCLESC_DOWN:
999                 rr = TAILQ_PREV(r, swm_region_list, entry);
1000                 if (rr == NULL)
1001                         rr = TAILQ_LAST(&screens[i].rl, swm_region_list);
1002                 break;
1003         default:
1004                 return;
1005         };
1006         unfocus_all();
1007         XSetInputFocus(display, PointerRoot, RevertToPointerRoot, CurrentTime);
1008         XWarpPointer(display, None, rr->s[i].root, 0, 0, 0, 0, rr->g.x,
1009             rr->g.y + bar_enabled ? bar_height : 0);
1010 }
1011
1012 void
1013 swapwin(struct swm_region *r, union arg *args)
1014 {
1015         struct ws_win           *target;
1016         struct ws_win_list      *wl;
1017
1018
1019         DNPRINTF(SWM_D_WS, "swapwin id %d "
1020             "in screen %d region %dx%d+%d+%d ws %d\n", args->id,
1021             r->s->idx, WIDTH(r), HEIGHT(r), X(r), Y(r), r->ws->idx);
1022         if (cur_focus == NULL)
1023                 return;
1024
1025         wl = &cur_focus->ws->winlist;
1026
1027         switch (args->id) {
1028         case SWM_ARG_ID_SWAPPREV:
1029                 target = TAILQ_PREV(cur_focus, ws_win_list, entry);
1030                 TAILQ_REMOVE(wl, cur_focus, entry);
1031                 if (target == NULL)
1032                         TAILQ_INSERT_TAIL(wl, cur_focus, entry);
1033                 else
1034                         TAILQ_INSERT_BEFORE(target, cur_focus, entry);
1035                 break;
1036         case SWM_ARG_ID_SWAPNEXT: 
1037                 target = TAILQ_NEXT(cur_focus, entry);
1038                 TAILQ_REMOVE(wl, cur_focus, entry);
1039                 if (target == NULL)
1040                         TAILQ_INSERT_HEAD(wl, cur_focus, entry);
1041                 else
1042                         TAILQ_INSERT_AFTER(wl, target, cur_focus, entry);
1043                 break;
1044         case SWM_ARG_ID_SWAPMAIN:
1045                 target = TAILQ_FIRST(wl);
1046                 if (target == cur_focus)
1047                         return;
1048                 TAILQ_REMOVE(wl, target, entry);
1049                 TAILQ_INSERT_BEFORE(cur_focus, target, entry);
1050                 TAILQ_REMOVE(wl, cur_focus, entry);
1051                 TAILQ_INSERT_HEAD(wl, cur_focus, entry);
1052                 break;
1053         default:
1054                 DNPRINTF(SWM_D_MOVE, "invalid id: %d\n", args->id);
1055                 return;
1056         }
1057
1058         ignore_enter = 2;
1059         stack();
1060 }
1061
1062 void
1063 focus(struct swm_region *r, union arg *args)
1064 {
1065         struct ws_win           *winfocus, *winlostfocus;
1066         struct ws_win_list      *wl;
1067
1068         DNPRINTF(SWM_D_FOCUS, "focus: id %d\n", args->id);
1069         if (cur_focus == NULL)
1070                 return;
1071
1072         wl = &cur_focus->ws->winlist;
1073
1074         winlostfocus = cur_focus;
1075
1076         switch (args->id) {
1077         case SWM_ARG_ID_FOCUSPREV:
1078                 winfocus = TAILQ_PREV(cur_focus, ws_win_list, entry);
1079                 if (winfocus == NULL)
1080                         winfocus = TAILQ_LAST(wl, ws_win_list);
1081                 break;
1082
1083         case SWM_ARG_ID_FOCUSNEXT:
1084                 winfocus = TAILQ_NEXT(cur_focus, entry);
1085                 if (winfocus == NULL)
1086                         winfocus = TAILQ_FIRST(wl);
1087                 break;
1088
1089         case SWM_ARG_ID_FOCUSMAIN:
1090                 winfocus = TAILQ_FIRST(wl);
1091                 break;
1092
1093         default:
1094                 return;
1095         }
1096
1097         if (winfocus == winlostfocus || winfocus == NULL)
1098                 return;
1099
1100         XMapRaised(display, winfocus->id);
1101         focus_win(winfocus);
1102         XSync(display, False);
1103 }
1104
1105 void
1106 cycle_layout(struct swm_region *r, union arg *args)
1107 {
1108         struct workspace        *ws = r->ws;
1109
1110         DNPRINTF(SWM_D_EVENT, "cycle_layout: workspace: %d\n", ws->idx);
1111
1112         ws->cur_layout++;
1113         if (ws->cur_layout->l_stack == NULL)
1114                 ws->cur_layout = &layouts[0];
1115         ignore_enter = 1;
1116         stack();
1117 }
1118
1119 void
1120 stack_config(struct swm_region *r, union arg *args)
1121 {
1122         struct workspace        *ws = r->ws;
1123
1124         DNPRINTF(SWM_D_STACK, "stack_config for workspace %d (id %d\n",
1125             args->id, ws->idx);
1126
1127         if (ws->cur_layout->l_config != NULL)
1128                 ws->cur_layout->l_config(ws, args->id);
1129
1130         if (args->id != SWM_ARG_ID_STACKINIT);
1131                 stack();
1132 }
1133
1134 void
1135 stack(void) {
1136         struct swm_geometry     g;
1137         struct swm_region       *r;
1138         int                     i, j;
1139
1140         DNPRINTF(SWM_D_STACK, "stack\n");
1141
1142         for (i = 0; i < ScreenCount(display); i++) {
1143                 j = 0;
1144                 TAILQ_FOREACH(r, &screens[i].rl, entry) {
1145                         DNPRINTF(SWM_D_STACK, "stacking workspace %d "
1146                             "(screen %d, region %d)\n", r->ws->idx, i, j++);
1147
1148                         /* start with screen geometry, adjust for bar */
1149                         g = r->g;
1150                         g.w -= 2;
1151                         g.h -= 2;
1152                         if (bar_enabled) {
1153                                 g.y += bar_height;
1154                                 g.h -= bar_height;
1155                         } 
1156
1157                         r->ws->restack = 0;
1158                         r->ws->cur_layout->l_stack(r->ws, &g);
1159                 }
1160         }
1161         XSync(display, False);
1162 }
1163
1164 void
1165 stack_floater(struct ws_win *win, struct swm_region *r)
1166 {
1167         unsigned int            mask;
1168         XWindowChanges          wc;
1169
1170         bzero(&wc, sizeof wc);
1171         mask = CWX | CWY | CWBorderWidth | CWWidth | CWHeight;
1172         wc.border_width = 1;
1173         if (win->transient) {
1174                 win->g.w = (double)WIDTH(r) * dialog_ratio;
1175                 win->g.h = (double)HEIGHT(r) * dialog_ratio;
1176         }
1177         wc.width = win->g.w;
1178         wc.height = win->g.h;
1179         wc.x = (WIDTH(r) - win->g.w) / 2;
1180         wc.y = (HEIGHT(r) - win->g.h) / 2;
1181
1182         DNPRINTF(SWM_D_STACK, "stack_floater: win %lu x %d y %d w %d h %d\n",
1183             win->id, wc.x, wc.y, wc.width, wc.height);
1184
1185         XConfigureWindow(display, win->id, mask, &wc);
1186 }
1187
1188 #define SWAPXY(g)       do {                            \
1189         int tmp;                                        \
1190         tmp = (g)->y; (g)->y = (g)->x; (g)->x = tmp;    \
1191         tmp = (g)->h; (g)->h = (g)->w; (g)->w = tmp;    \
1192 } while (0)
1193 void
1194 stack_master(struct workspace *ws, struct swm_geometry *g, int rot, int flip)
1195 {
1196         XWindowChanges          wc;
1197         struct swm_geometry     win_g, r_g = *g;
1198         struct ws_win           *win, *winfocus;
1199         int                     i, j, w_inc, h_inc, w_base, h_base;
1200         int                     hrh, extra, h_slice, last_h = 0;
1201         int                     split, colno, winno, mwin, msize, mscale;
1202         int                     remain, missing, v_slice;;
1203         unsigned int            mask;
1204
1205         DNPRINTF(SWM_D_STACK, "stack_master: workspace: %d\n rot=%s flip=%s",
1206             ws->idx, rot ? "yes" : "no", flip ? "yes" : "no");
1207
1208         if ((winno = count_win(ws, 0)) == 0)
1209                 return;
1210
1211         if (ws->focus == NULL)
1212                 ws->focus = TAILQ_FIRST(&ws->winlist);
1213         winfocus = cur_focus ? cur_focus : ws->focus;
1214
1215         win = TAILQ_FIRST(&ws->winlist);
1216         if (rot) {
1217                 w_inc = win->sh.width_inc;
1218                 w_base = win->sh.base_width;
1219                 mwin = ws->l_state.horizontal_mwin;
1220                 mscale = ws->l_state.horizontal_msize;
1221                 SWAPXY(&r_g);
1222         } else {
1223                 w_inc = win->sh.height_inc;
1224                 w_base = win->sh.base_height;
1225                 mwin = ws->l_state.vertical_mwin;
1226                 mscale = ws->l_state.vertical_msize;
1227         }
1228         win_g = r_g;
1229
1230         h_slice = r_g.h / SWM_H_SLICE;
1231         if (mwin && winno > mwin) {
1232                 v_slice = r_g.w / SWM_V_SLICE;
1233
1234                 split = mwin;
1235                 colno = split;
1236                 msize = v_slice * mscale;
1237
1238                 if (w_inc > 1 && w_inc < v_slice) {
1239                         /* adjust for window's requested size increment */
1240                         remain = (win_g.w - w_base) % w_inc;
1241                         missing = w_inc - remain;
1242
1243                         if (missing <= extra || j == 0) {
1244                                 extra -= missing;
1245                                 win_g.w += missing;
1246                         } else {
1247                                 win_g.w -= remain;
1248                                 extra += remain;
1249                         }
1250                 }
1251
1252                 win_g.w = msize;
1253                 if (flip) 
1254                         win_g.x += r_g.w - msize;
1255         } else {
1256                 colno = winno;
1257                 split = 0;
1258         }
1259         hrh = r_g.h / colno;
1260         extra = r_g.h - (colno * hrh);
1261         win_g.h = hrh - 2;
1262
1263         i = j = 0;
1264         TAILQ_FOREACH(win, &ws->winlist, entry) {
1265                 if (split && i == split) {
1266                         colno = winno - split;
1267                         hrh = (r_g.h / colno);
1268                         extra = r_g.h - (colno * hrh);
1269                         if (flip)
1270                                 win_g.x = r_g.x;
1271                         else
1272                                 win_g.x += msize + 2;
1273                         win_g.w = r_g.w - (msize + 2);
1274                         j = 0;
1275                 }
1276                 win_g.h = hrh - 2;
1277                 if (rot) {
1278                         h_inc = win->sh.width_inc;
1279                         h_base = win->sh.base_width;
1280                 } else {
1281                         h_inc = win->sh.height_inc;     
1282                         h_base = win->sh.base_height;
1283                 }
1284                 if (j == colno - 1) {
1285                         win_g.h = hrh + extra;
1286                 } else if (h_inc > 1 && h_inc < h_slice) {
1287                         /* adjust for window's requested size increment */
1288                         remain = (win_g.h - h_base) % h_inc;
1289                         missing = h_inc - remain;
1290
1291                         if (missing <= extra || j == 0) {
1292                                 extra -= missing;
1293                                 win_g.h += missing;
1294                         } else {
1295                                 win_g.h -= remain;
1296                                 extra += remain;
1297                         }
1298                 }
1299                  
1300                 if (j == 0)
1301                         win_g.y = r_g.y;
1302                 else
1303                         win_g.y += last_h + 2;
1304
1305                 if (win->transient != 0 || win->floating != 0)
1306                         stack_floater(win, ws->r);
1307                 else {
1308                         bzero(&wc, sizeof wc);
1309                         wc.border_width = 1;
1310                         if (rot) {
1311                                 win->g.x = wc.x = win_g.y;
1312                                 win->g.y = wc.y = win_g.x;
1313                                 win->g.w = wc.width = win_g.h;
1314                                 win->g.h = wc.height = win_g.w;
1315                         } else {
1316                                 win->g.x = wc.x = win_g.x;
1317                                 win->g.y = wc.y = win_g.y;
1318                                 win->g.w = wc.width = win_g.w;
1319                                 win->g.h = wc.height = win_g.h;
1320                         }
1321                         mask = CWX | CWY | CWWidth | CWHeight | CWBorderWidth;
1322                         XConfigureWindow(display, win->id, mask, &wc);
1323                         /*
1324                         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);
1325                         */
1326                 }
1327
1328                 XMapRaised(display, win->id);
1329                 last_h = win_g.h;
1330                 i++;
1331                 j++;
1332         }
1333
1334         if (winfocus)
1335                 focus_win(winfocus); /* has to be done outside of the loop */
1336 }
1337
1338 void
1339 vertical_config(struct workspace *ws, int id)
1340 {
1341         DNPRINTF(SWM_D_STACK, "vertical_resize: workspace: %d\n", ws->idx);
1342
1343         switch (id) {
1344         case SWM_ARG_ID_STACKRESET:
1345         case SWM_ARG_ID_STACKINIT:
1346                 ws->l_state.vertical_msize = SWM_V_SLICE / 2;
1347                 ws->l_state.vertical_mwin = 1;
1348                 break;
1349         case SWM_ARG_ID_MASTERSHRINK:
1350                 if (ws->l_state.vertical_msize > 1)
1351                         ws->l_state.vertical_msize--;
1352                 break;
1353         case SWM_ARG_ID_MASTERGROW:
1354                 if (ws->l_state.vertical_msize < SWM_V_SLICE - 1)
1355                         ws->l_state.vertical_msize++;
1356                 break;
1357         case SWM_ARG_ID_MASTERADD:
1358                 ws->l_state.vertical_mwin++;
1359                 break;
1360         case SWM_ARG_ID_MASTERDEL:
1361                 if (ws->l_state.vertical_mwin > 0)
1362                         ws->l_state.vertical_mwin--;
1363                 break;
1364         default:
1365                 return;
1366         }
1367 }
1368
1369 void
1370 vertical_stack(struct workspace *ws, struct swm_geometry *g)
1371 {
1372         DNPRINTF(SWM_D_STACK, "vertical_stack: workspace: %d\n", ws->idx);
1373
1374         stack_master(ws, g, 0, 0);
1375 }
1376
1377 void
1378 horizontal_config(struct workspace *ws, int id)
1379 {
1380         DNPRINTF(SWM_D_STACK, "horizontal_config: workspace: %d\n", ws->idx);
1381
1382         switch (id) {
1383         case SWM_ARG_ID_STACKRESET:
1384         case SWM_ARG_ID_STACKINIT:
1385                 ws->l_state.horizontal_mwin = 1;
1386                 ws->l_state.horizontal_msize = SWM_H_SLICE / 2;
1387                 break;
1388         case SWM_ARG_ID_MASTERSHRINK:
1389                 if (ws->l_state.horizontal_msize > 1)
1390                         ws->l_state.horizontal_msize--;
1391                 break;
1392         case SWM_ARG_ID_MASTERGROW:
1393                 if (ws->l_state.horizontal_msize < SWM_H_SLICE - 1)
1394                         ws->l_state.horizontal_msize++;
1395                 break;
1396         case SWM_ARG_ID_MASTERADD:
1397                 ws->l_state.horizontal_mwin++;
1398                 break;
1399         case SWM_ARG_ID_MASTERDEL:
1400                 if (ws->l_state.horizontal_mwin > 0)
1401                         ws->l_state.horizontal_mwin--;
1402                 break;
1403         default:
1404                 return;
1405         }
1406 }
1407
1408 void
1409 horizontal_stack(struct workspace *ws, struct swm_geometry *g)
1410 {
1411         DNPRINTF(SWM_D_STACK, "vertical_stack: workspace: %d\n", ws->idx);
1412
1413         stack_master(ws, g, 1, 0);
1414 }
1415
1416 /* fullscreen view */
1417 void
1418 max_stack(struct workspace *ws, struct swm_geometry *g) {
1419         XWindowChanges          wc;
1420         struct swm_geometry     gg = *g;
1421         struct ws_win           *win, *winfocus;
1422         unsigned int            mask;
1423
1424         DNPRINTF(SWM_D_STACK, "max_stack: workspace: %d\n", ws->idx);
1425
1426         if (count_win(ws, 0) == 0)
1427                 return;
1428
1429         if (ws->focus == NULL)
1430                 ws->focus = TAILQ_FIRST(&ws->winlist);
1431         winfocus = cur_focus ? cur_focus : ws->focus;
1432
1433         TAILQ_FOREACH(win, &ws->winlist, entry) {
1434                 if (win->transient != 0 || win->floating != 0) {
1435                         if (win == ws->focus) {
1436                                 /* XXX maximize? */
1437                                 stack_floater(win, ws->r);
1438                                 XMapRaised(display, win->id);
1439                         } else
1440                                 XUnmapWindow(display, win->id);
1441                 } else {
1442                         bzero(&wc, sizeof wc);
1443                         wc.border_width = 1;
1444                         win->g.x = wc.x = gg.x;
1445                         win->g.y = wc.y = gg.y;
1446                         win->g.w = wc.width = gg.w;
1447                         win->g.h = wc.height = gg.h;
1448                         mask = CWX | CWY | CWWidth | CWHeight | CWBorderWidth;
1449                         XConfigureWindow(display, win->id, mask, &wc);
1450
1451                         if (win == ws->focus) {
1452                                 XMapRaised(display, win->id);
1453                         } else
1454                                 XUnmapWindow(display, win->id);
1455                 }
1456         }
1457
1458         if (winfocus)
1459                 focus_win(winfocus); /* has to be done outside of the loop */
1460 }
1461
1462 void
1463 send_to_ws(struct swm_region *r, union arg *args)
1464 {
1465         int                     wsid = args->id;
1466         struct ws_win           *win = cur_focus;
1467         struct workspace        *ws, *nws;
1468         Atom                    ws_idx_atom = 0;
1469         unsigned char           ws_idx_str[SWM_PROPLEN];
1470
1471         DNPRINTF(SWM_D_MOVE, "send_to_ws: win: %lu\n", win->id);
1472
1473         ws = win->ws;
1474         nws = &win->s->ws[wsid];
1475
1476         XUnmapWindow(display, win->id);
1477
1478         /* find a window to focus */
1479         ws->focus = TAILQ_PREV(win, ws_win_list, entry);
1480         if (ws->focus == NULL)
1481                 ws->focus = TAILQ_FIRST(&ws->winlist);
1482         if (ws->focus == win)
1483                 ws->focus = NULL;
1484
1485         TAILQ_REMOVE(&ws->winlist, win, entry);
1486
1487         TAILQ_INSERT_TAIL(&nws->winlist, win, entry);
1488         win->ws = nws;
1489
1490         /* Try to update the window's workspace property */
1491         ws_idx_atom = XInternAtom(display, "_SWM_WS", False);
1492         if (ws_idx_atom &&
1493             snprintf(ws_idx_str, SWM_PROPLEN, "%d", nws->idx) < SWM_PROPLEN) {
1494                 DNPRINTF(SWM_D_PROP, "setting property _SWM_WS to %s\n",
1495                     ws_idx_str);
1496                 XChangeProperty(display, win->id, ws_idx_atom, XA_STRING, 8,
1497                     PropModeReplace, ws_idx_str, SWM_PROPLEN);
1498         }
1499
1500         if (count_win(nws, 1) == 1)
1501                 nws->focus = win;
1502         ws->restack = 1;
1503         nws->restack = 1;
1504
1505         stack();
1506 }
1507
1508 void
1509 wkill(struct swm_region *r, union arg *args)
1510 {
1511         DNPRINTF(SWM_D_MISC, "wkill\n");
1512         if(r->ws->focus != NULL)
1513                 XKillClient(display, r->ws->focus->id);
1514 }
1515
1516 void
1517 screenshot(struct swm_region *r, union arg *args)
1518 {
1519         union arg                       a;
1520
1521         DNPRINTF(SWM_D_MISC, "screenshot\n");
1522
1523         if (ss_enabled == 0)
1524                 return;
1525
1526         switch (args->id) {
1527         case SWM_ARG_ID_SS_ALL:
1528                 spawn_screenshot[1] = "full";
1529                 break;
1530         case SWM_ARG_ID_SS_WINDOW:
1531                 spawn_screenshot[1] = "window";
1532                 break;
1533         default:
1534                 return;
1535         }
1536         a.argv = spawn_screenshot;
1537         spawn(r, &a);
1538 }
1539
1540 /* key definitions */
1541 struct key {
1542         unsigned int            mod;
1543         KeySym                  keysym;
1544         void                    (*func)(struct swm_region *r, union arg *);
1545         union arg               args;
1546 } keys[] = {
1547         /* modifier             key     function                argument */
1548         { MODKEY,               XK_space,       cycle_layout,   {0} }, 
1549         { MODKEY | ShiftMask,   XK_space,       stack_config,   {.id = SWM_ARG_ID_STACKRESET} }, 
1550         { MODKEY,               XK_h,           stack_config,   {.id = SWM_ARG_ID_MASTERSHRINK} },
1551         { MODKEY,               XK_l,           stack_config,   {.id = SWM_ARG_ID_MASTERGROW} },
1552         { MODKEY,               XK_comma,       stack_config,   {.id = SWM_ARG_ID_MASTERADD} },
1553         { MODKEY,               XK_period,      stack_config,   {.id = SWM_ARG_ID_MASTERDEL} },
1554         { MODKEY,               XK_Return,      swapwin,        {.id = SWM_ARG_ID_SWAPMAIN} },
1555         { MODKEY,               XK_j,           focus,          {.id = SWM_ARG_ID_FOCUSNEXT} },
1556         { MODKEY,               XK_k,           focus,          {.id = SWM_ARG_ID_FOCUSPREV} },
1557         { MODKEY | ShiftMask,   XK_j,           swapwin,        {.id = SWM_ARG_ID_SWAPNEXT} },
1558         { MODKEY | ShiftMask,   XK_k,           swapwin,        {.id = SWM_ARG_ID_SWAPPREV} },
1559         { MODKEY | ShiftMask,   XK_Return,      spawn,          {.argv = spawn_term} },
1560         { MODKEY,               XK_p,           spawnmenu,      {.argv = spawn_menu} },
1561         { MODKEY | ShiftMask,   XK_q,           quit,           {0} },
1562         { MODKEY,               XK_q,           restart,        {0} },
1563         { MODKEY,               XK_m,           focus,          {.id = SWM_ARG_ID_FOCUSMAIN} },
1564         { MODKEY,               XK_1,           switchws,       {.id = 0} },
1565         { MODKEY,               XK_2,           switchws,       {.id = 1} },
1566         { MODKEY,               XK_3,           switchws,       {.id = 2} },
1567         { MODKEY,               XK_4,           switchws,       {.id = 3} },
1568         { MODKEY,               XK_5,           switchws,       {.id = 4} },
1569         { MODKEY,               XK_6,           switchws,       {.id = 5} },
1570         { MODKEY,               XK_7,           switchws,       {.id = 6} },
1571         { MODKEY,               XK_8,           switchws,       {.id = 7} },
1572         { MODKEY,               XK_9,           switchws,       {.id = 8} },
1573         { MODKEY,               XK_0,           switchws,       {.id = 9} },
1574         { MODKEY,               XK_Right,       cyclews,        {.id = SWM_ARG_ID_CYCLEWS_UP} }, 
1575         { MODKEY,               XK_Left,        cyclews,        {.id = SWM_ARG_ID_CYCLEWS_DOWN} }, 
1576         { MODKEY | ShiftMask,   XK_Right,       cyclescr,       {.id = SWM_ARG_ID_CYCLESC_UP} }, 
1577         { MODKEY | ShiftMask,   XK_Left,        cyclescr,       {.id = SWM_ARG_ID_CYCLESC_DOWN} }, 
1578         { MODKEY | ShiftMask,   XK_1,           send_to_ws,     {.id = 0} },
1579         { MODKEY | ShiftMask,   XK_2,           send_to_ws,     {.id = 1} },
1580         { MODKEY | ShiftMask,   XK_3,           send_to_ws,     {.id = 2} },
1581         { MODKEY | ShiftMask,   XK_4,           send_to_ws,     {.id = 3} },
1582         { MODKEY | ShiftMask,   XK_5,           send_to_ws,     {.id = 4} },
1583         { MODKEY | ShiftMask,   XK_6,           send_to_ws,     {.id = 5} },
1584         { MODKEY | ShiftMask,   XK_7,           send_to_ws,     {.id = 6} },
1585         { MODKEY | ShiftMask,   XK_8,           send_to_ws,     {.id = 7} },
1586         { MODKEY | ShiftMask,   XK_9,           send_to_ws,     {.id = 8} },
1587         { MODKEY | ShiftMask,   XK_0,           send_to_ws,     {.id = 9} },
1588         { MODKEY,               XK_b,           bar_toggle,     {0} },
1589         { MODKEY,               XK_Tab,         focus,          {.id = SWM_ARG_ID_FOCUSNEXT} },
1590         { MODKEY | ShiftMask,   XK_Tab,         focus,          {.id = SWM_ARG_ID_FOCUSPREV} },
1591         { MODKEY | ShiftMask,   XK_x,           wkill,          {0} },
1592         { MODKEY,               XK_s,           screenshot,     {.id = SWM_ARG_ID_SS_ALL} },
1593         { MODKEY | ShiftMask,   XK_s,           screenshot,     {.id = SWM_ARG_ID_SS_WINDOW} },
1594 };
1595
1596 void
1597 click(struct swm_region *r, union arg *args)
1598 {
1599         DNPRINTF(SWM_D_MOUSE, "click: button: %d\n", args->id);
1600
1601         switch (args->id) {
1602         case Button1:
1603                 break;
1604         case Button2:
1605                 break;
1606         case Button3:
1607                 break;
1608         default:
1609                 return;
1610         }
1611 }
1612
1613 /* mouse */
1614 enum { client_click, root_click };
1615 struct button {
1616         unsigned int            action;
1617         unsigned int            mask;
1618         unsigned int            button;
1619         void                    (*func)(struct swm_region *r, union arg *);
1620         union arg               args;
1621 } buttons[] = {
1622           /* action             key             mouse button    func            args */
1623         { client_click,         MODKEY,         Button1,        click, {.id=Button1} },
1624 };
1625
1626 void
1627 updatenumlockmask(void)
1628 {
1629         unsigned int            i, j;
1630         XModifierKeymap         *modmap;
1631
1632         DNPRINTF(SWM_D_MISC, "updatenumlockmask\n");
1633         numlockmask = 0;
1634         modmap = XGetModifierMapping(display);
1635         for (i = 0; i < 8; i++)
1636                 for (j = 0; j < modmap->max_keypermod; j++)
1637                         if (modmap->modifiermap[i * modmap->max_keypermod + j]
1638                           == XKeysymToKeycode(display, XK_Num_Lock))
1639                                 numlockmask = (1 << i);
1640
1641         XFreeModifiermap(modmap);
1642 }
1643
1644 void
1645 grabkeys(void)
1646 {
1647         unsigned int            i, j, k;
1648         KeyCode                 code;
1649         unsigned int            modifiers[] =
1650             { 0, LockMask, numlockmask, numlockmask | LockMask };
1651
1652         DNPRINTF(SWM_D_MISC, "grabkeys\n");
1653         updatenumlockmask();
1654
1655         for (k = 0; k < ScreenCount(display); k++) {
1656                 if (TAILQ_EMPTY(&screens[k].rl))
1657                         continue;
1658                 XUngrabKey(display, AnyKey, AnyModifier, screens[k].root);
1659                 for (i = 0; i < LENGTH(keys); i++) {
1660                         if ((code = XKeysymToKeycode(display, keys[i].keysym)))
1661                                 for (j = 0; j < LENGTH(modifiers); j++)
1662                                         XGrabKey(display, code,
1663                                             keys[i].mod | modifiers[j],
1664                                             screens[k].root, True,
1665                                             GrabModeAsync, GrabModeAsync);
1666                 }
1667         }
1668 }
1669
1670 void
1671 grabbuttons(struct ws_win *win, int focused)
1672 {
1673         unsigned int            i, j;
1674         unsigned int            modifiers[] =
1675             { 0, LockMask, numlockmask, numlockmask|LockMask };
1676
1677         updatenumlockmask();
1678         XUngrabButton(display, AnyButton, AnyModifier, win->id);
1679         if(focused) {
1680                 for (i = 0; i < LENGTH(buttons); i++)
1681                         if (buttons[i].action == client_click)
1682                                 for (j = 0; j < LENGTH(modifiers); j++)
1683                                         XGrabButton(display, buttons[i].button,
1684                                             buttons[i].mask | modifiers[j],
1685                                             win->id, False, BUTTONMASK,
1686                                             GrabModeAsync, GrabModeSync, None,
1687                                             None);
1688         } else
1689                 XGrabButton(display, AnyButton, AnyModifier, win->id, False,
1690                     BUTTONMASK, GrabModeAsync, GrabModeSync, None, None);
1691 }
1692
1693 void
1694 expose(XEvent *e)
1695 {
1696         DNPRINTF(SWM_D_EVENT, "expose: window: %lu\n", e->xexpose.window);
1697 }
1698
1699 void
1700 keypress(XEvent *e)
1701 {
1702         unsigned int            i;
1703         KeySym                  keysym;
1704         XKeyEvent               *ev = &e->xkey;
1705
1706         DNPRINTF(SWM_D_EVENT, "keypress: window: %lu\n", ev->window);
1707
1708         keysym = XKeycodeToKeysym(display, (KeyCode)ev->keycode, 0);
1709         for (i = 0; i < LENGTH(keys); i++)
1710                 if (keysym == keys[i].keysym
1711                    && CLEANMASK(keys[i].mod) == CLEANMASK(ev->state)
1712                    && keys[i].func)
1713                         keys[i].func(root_to_region(ev->root),
1714                             &(keys[i].args));
1715 }
1716
1717 void
1718 buttonpress(XEvent *e)
1719 {
1720         XButtonPressedEvent     *ev = &e->xbutton;
1721
1722         struct ws_win           *win;
1723         int                     i, action;
1724
1725         DNPRINTF(SWM_D_EVENT, "buttonpress: window: %lu\n", ev->window);
1726
1727         action = root_click;
1728         if ((win = find_window(ev->window)) == NULL)
1729                 return;
1730         else {
1731                 focus_win(win);
1732                 action = client_click;
1733         }
1734
1735         for (i = 0; i < LENGTH(buttons); i++)
1736                 if (action == buttons[i].action && buttons[i].func &&
1737                     buttons[i].button == ev->button &&
1738                     CLEANMASK(buttons[i].mask) == CLEANMASK(ev->state))
1739                         buttons[i].func(root_to_region(ev->root),
1740                         &buttons[i].args);
1741 }
1742
1743 void
1744 set_win_state(struct ws_win *win, long state)
1745 {
1746         long                    data[] = {state, None};
1747
1748         DNPRINTF(SWM_D_EVENT, "set_win_state: window: %lu\n", win->id);
1749
1750         XChangeProperty(display, win->id, astate, astate, 32, PropModeReplace,
1751             (unsigned char *)data, 2);
1752 }
1753
1754 struct ws_win *
1755 manage_window(Window id)
1756 {
1757         Window                  trans;
1758         struct workspace        *ws;
1759         struct ws_win           *win;
1760         XClassHint              ch;
1761         int                     format;
1762         unsigned long           nitems, bytes;
1763         Atom                    ws_idx_atom = 0, type;
1764         unsigned char           ws_idx_str[SWM_PROPLEN], *prop = NULL;
1765         struct swm_region       *r;
1766         long                    mask;
1767         int                     ws_idx;
1768         const char              *errstr;
1769
1770         if ((win = find_window(id)) != NULL)
1771                         return (win);   /* already being managed */
1772
1773         if ((win = calloc(1, sizeof(struct ws_win))) == NULL)
1774                 errx(1, "calloc: failed to allocate memory for new window");
1775
1776         ws_idx_atom = XInternAtom(display, "_SWM_WS", False);
1777         if (ws_idx_atom)
1778                 XGetWindowProperty(display, id, ws_idx_atom, 0, SWM_PROPLEN,
1779                     False, XA_STRING, &type, &format, &nitems, &bytes, &prop);
1780
1781         XGetWindowAttributes(display, id, &win->wa);
1782         r = root_to_region(win->wa.root);
1783         /* If the window was managed before, put it in the same workspace */
1784         if (prop) {
1785                 DNPRINTF(SWM_D_PROP, "got property _SWM_WS=%s\n", prop);
1786                 ws_idx = strtonum(prop, 0, 9, &errstr);
1787                 if (errstr)
1788                         DNPRINTF(SWM_D_EVENT, "window idx is %s: %s",
1789                             errstr, prop);
1790                 ws = &r->s->ws[ws_idx];
1791         } else
1792                 ws = r->ws;
1793
1794         win->id = id;
1795         win->ws = ws;
1796         win->s = r->s;  /* this never changes */
1797         TAILQ_INSERT_TAIL(&ws->winlist, win, entry);
1798
1799         XGetTransientForHint(display, win->id, &trans);
1800         if (trans) {
1801                 win->transient = trans;
1802                 DNPRINTF(SWM_D_MISC, "manage_window: win %u transient %u\n",
1803                     (unsigned)win->id, win->transient);
1804         }
1805         win->g.w = win->wa.width;
1806         win->g.h = win->wa.height;
1807         win->g.x = win->wa.x;
1808         win->g.y = win->wa.y;
1809
1810         XGetWMNormalHints(display, win->id, &win->sh, &mask);
1811
1812         if (ws_idx_atom && prop == NULL &&
1813             snprintf(ws_idx_str, SWM_PROPLEN, "%d", ws->idx) < SWM_PROPLEN) {
1814                 DNPRINTF(SWM_D_PROP, "setting property _SWM_WS to %s\n",
1815                     ws_idx_str);
1816                 XChangeProperty(display, win->id, ws_idx_atom, XA_STRING, 8,
1817                     PropModeReplace, ws_idx_str, SWM_PROPLEN);
1818         }
1819         XFree(prop);
1820
1821         /*
1822         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);
1823         */
1824
1825         /* XXX make this a table */
1826         bzero(&ch, sizeof ch);
1827         if (XGetClassHint(display, win->id, &ch)) {
1828                 /*fprintf(stderr, "class: %s name: %s\n", ch.res_class, ch.res_name); */
1829                 if (!strcmp(ch.res_class, "MPlayer") && !strcmp(ch.res_name, "xv")) {
1830                         win->floating = 1;
1831                 }
1832                 if (ch.res_class)
1833                         XFree(ch.res_class);
1834                 if (ch.res_name)
1835                         XFree(ch.res_name);
1836         }
1837
1838         XSelectInput(display, id, EnterWindowMask | FocusChangeMask |
1839             PropertyChangeMask | StructureNotifyMask);
1840
1841         set_win_state(win, NormalState);
1842
1843         /* make new win focused */
1844         focus_win(win);
1845
1846
1847         return (win);
1848 }
1849
1850 void
1851 configurerequest(XEvent *e)
1852 {
1853         XConfigureRequestEvent  *ev = &e->xconfigurerequest;
1854         struct ws_win           *win;
1855         int                     new = 0;
1856         XWindowChanges          wc;
1857
1858         if ((win = find_window(ev->window)) == NULL)
1859                 new = 1;
1860
1861         if (new) {
1862                 DNPRINTF(SWM_D_EVENT, "configurerequest: new window: %lu\n",
1863                     ev->window);
1864                 /*
1865                 fprintf(stderr, "configurerequest: new window: %lu x %d y %d w %d h %d bw %d s %d sm %d\n",
1866                     ev->window, ev->x, ev->y, ev->width, ev->height, ev->border_width, ev->above, ev->detail);
1867                 */
1868                 bzero(&wc, sizeof wc);
1869                 wc.x = ev->x;
1870                 wc.y = ev->y;
1871                 wc.width = ev->width;
1872                 wc.height = ev->height;
1873                 wc.border_width = ev->border_width;
1874                 wc.sibling = ev->above;
1875                 wc.stack_mode = ev->detail;
1876                 XConfigureWindow(display, ev->window, ev->value_mask, &wc);
1877         } else {
1878                 /*
1879                 fprintf(stderr, "configurerequest: change window: %lu\n",
1880                     ev->window);
1881                 */
1882                 DNPRINTF(SWM_D_EVENT, "configurerequest: change window: %lu\n",
1883                     ev->window);
1884                 if (win->floating) {
1885                         if (ev->value_mask & CWX)
1886                                 win->g.x = ev->x;
1887                         if (ev->value_mask & CWY)
1888                                 win->g.y = ev->y;
1889                         if (ev->value_mask & CWWidth)
1890                                 win->g.w = ev->width;
1891                         if (ev->value_mask & CWHeight)
1892                                 win->g.h = ev->height;
1893                         if (win->ws->r != NULL) {
1894                                 /* this seems to be full screen */
1895                                 if (win->g.w > WIDTH(win->ws->r)) {
1896                                         /* kill border */
1897                                         win->g.x -= 1;
1898                                         win->g.w += 1;
1899                                 }
1900                                 if (win->g.h > HEIGHT(win->ws->r)) {
1901                                         /* kill border */
1902                                         win->g.y -= 1;
1903                                         win->g.h += 1;
1904                                 }
1905                         }
1906                         if ((ev->value_mask & (CWX|CWY)) &&
1907                             !(ev->value_mask & (CWWidth|CWHeight)))
1908                                 config_win(win);
1909                         XMoveResizeWindow(display, win->id,
1910                             win->g.x, win->g.y, win->g.w, win->g.h);
1911                 } else
1912                         config_win(win);
1913         }
1914 }
1915
1916 void
1917 configurenotify(XEvent *e)
1918 {
1919         DNPRINTF(SWM_D_EVENT, "configurenotify: window: %lu\n",
1920             e->xconfigure.window);
1921 }
1922
1923 void
1924 destroynotify(XEvent *e)
1925 {
1926         struct ws_win           *win;
1927         XDestroyWindowEvent     *ev = &e->xdestroywindow;
1928         struct workspace        *ws;
1929
1930         DNPRINTF(SWM_D_EVENT, "destroynotify: window %lu\n", ev->window);
1931
1932         if ((win = find_window(ev->window)) != NULL) {
1933                 ws = win->ws;
1934                 /* find a window to focus */
1935                 if (ws->focus == win)
1936                         ws->focus = TAILQ_PREV(win, ws_win_list, entry);
1937                 if (ws->focus == NULL)
1938                         ws->focus = TAILQ_FIRST(&ws->winlist);
1939                 if (ws->focus == NULL || ws->focus == win) {
1940                         ws->focus = NULL;
1941                         unfocus_all();
1942                 } else
1943                         focus_win(ws->focus);
1944                 TAILQ_REMOVE(&ws->winlist, win, entry);
1945                 set_win_state(win, WithdrawnState);
1946                 free(win);
1947                 stack();
1948         }
1949 }
1950
1951 void
1952 enternotify(XEvent *e)
1953 {
1954         XCrossingEvent          *ev = &e->xcrossing;
1955         struct ws_win           *win;
1956
1957         DNPRINTF(SWM_D_EVENT, "enternotify: window: %lu\n", ev->window);
1958
1959         if (ignore_enter) {
1960                 /* eat event(r) to prevent autofocus */
1961                 ignore_enter--;
1962                 return;
1963         }
1964
1965         if ((win = find_window(ev->window)) != NULL)
1966                 focus_win(win);
1967 }
1968
1969 void
1970 focusin(XEvent *e)
1971 {
1972         DNPRINTF(SWM_D_EVENT, "focusin: window: %lu\n", e->xfocus.window);
1973 }
1974
1975 void
1976 mappingnotify(XEvent *e)
1977 {
1978         XMappingEvent           *ev = &e->xmapping;
1979
1980         DNPRINTF(SWM_D_EVENT, "mappingnotify: window: %lu\n", ev->window);
1981
1982         XRefreshKeyboardMapping(ev);
1983         if (ev->request == MappingKeyboard)
1984                 grabkeys();
1985 }
1986
1987 void
1988 maprequest(XEvent *e)
1989 {
1990         XMapRequestEvent        *ev = &e->xmaprequest;
1991         XWindowAttributes       wa;
1992
1993         DNPRINTF(SWM_D_EVENT, "maprequest: window: %lu\n",
1994             e->xmaprequest.window);
1995
1996         if (!XGetWindowAttributes(display, ev->window, &wa))
1997                 return;
1998         if (wa.override_redirect)
1999                 return;
2000         manage_window(e->xmaprequest.window);
2001         stack();
2002 }
2003
2004 void
2005 propertynotify(XEvent *e)
2006 {
2007         DNPRINTF(SWM_D_EVENT, "propertynotify: window: %lu\n",
2008             e->xproperty.window);
2009 }
2010
2011 void
2012 unmapnotify(XEvent *e)
2013 {
2014         DNPRINTF(SWM_D_EVENT, "unmapnotify: window: %lu\n", e->xunmap.window);
2015 }
2016
2017 void
2018 visibilitynotify(XEvent *e)
2019 {
2020         int                     i;
2021         struct swm_region       *r;
2022
2023         DNPRINTF(SWM_D_EVENT, "visibilitynotify: window: %lu\n",
2024             e->xvisibility.window);
2025         if (e->xvisibility.state == VisibilityUnobscured)
2026                 for (i = 0; i < ScreenCount(display); i++) 
2027                         TAILQ_FOREACH(r, &screens[i].rl, entry)
2028                                 if (e->xvisibility.window == r->bar_window)
2029                                         bar_update();
2030 }
2031
2032 void                    (*handler[LASTEvent])(XEvent *) = {
2033                                 [Expose] = expose,
2034                                 [KeyPress] = keypress,
2035                                 [ButtonPress] = buttonpress,
2036                                 [ConfigureRequest] = configurerequest,
2037                                 [ConfigureNotify] = configurenotify,
2038                                 [DestroyNotify] = destroynotify,
2039                                 [EnterNotify] = enternotify,
2040                                 [FocusIn] = focusin,
2041                                 [MappingNotify] = mappingnotify,
2042                                 [MapRequest] = maprequest,
2043                                 [PropertyNotify] = propertynotify,
2044                                 [UnmapNotify] = unmapnotify,
2045                                 [VisibilityNotify] = visibilitynotify,
2046 };
2047
2048 int
2049 xerror_start(Display *d, XErrorEvent *ee)
2050 {
2051         other_wm = 1;
2052         return (-1);
2053 }
2054
2055 int
2056 xerror(Display *d, XErrorEvent *ee)
2057 {
2058         /* fprintf(stderr, "error: %p %p\n", display, ee); */
2059         return (-1);
2060 }
2061
2062 int
2063 active_wm(void)
2064 {
2065         other_wm = 0;
2066         xerrorxlib = XSetErrorHandler(xerror_start);
2067
2068         /* this causes an error if some other window manager is running */
2069         XSelectInput(display, DefaultRootWindow(display),
2070             SubstructureRedirectMask);
2071         XSync(display, False);
2072         if (other_wm)
2073                 return (1);
2074
2075         XSetErrorHandler(xerror);
2076         XSync(display, False);
2077         return (0);
2078 }
2079
2080 long
2081 getstate(Window w)
2082 {
2083         int                     format, status;
2084         long                    result = -1;
2085         unsigned char           *p = NULL;
2086         unsigned long           n, extra;
2087         Atom                    real;
2088
2089         astate = XInternAtom(display, "WM_STATE", False);
2090         status = XGetWindowProperty(display, w, astate, 0L, 2L, False, astate,
2091             &real, &format, &n, &extra, (unsigned char **)&p);
2092         if (status != Success)
2093                 return (-1);
2094         if (n != 0)
2095                 result = *p;
2096         XFree(p);
2097         return (result);
2098 }
2099
2100 void
2101 new_region(struct swm_screen *s, struct workspace *ws,
2102     int x, int y, int w, int h)
2103 {
2104         struct swm_region       *r;
2105
2106         DNPRINTF(SWM_D_MISC, "new region on screen %d: %dx%d (%d, %d)\n",
2107              s->idx, x, y, w, h);
2108
2109         if ((r = calloc(1, sizeof(struct swm_region))) == NULL)
2110                 errx(1, "calloc: failed to allocate memory for screen");
2111
2112         X(r) = x;
2113         Y(r) = y;
2114         WIDTH(r) = w;
2115         HEIGHT(r) = h;
2116         r->s = s;
2117         r->ws = ws;
2118         ws->r = r;
2119         TAILQ_INSERT_TAIL(&s->rl, r, entry);
2120         bar_setup(r);
2121 }
2122
2123 void
2124 setup_screens(void)
2125 {
2126 #ifdef SWM_XRR_HAS_CRTC
2127         XRRCrtcInfo             *ci;
2128         XRRScreenResources      *sr;
2129         int                     c;
2130 #endif /* SWM_XRR_HAS_CRTC */
2131         Window                  d1, d2, *wins = NULL;
2132         XWindowAttributes       wa;
2133         struct swm_region       *r;
2134         unsigned int            no;
2135         int                     errorbase, major, minor;
2136         int                     ncrtc = 0, w = 0;
2137         int                     i, j, k;
2138         struct workspace        *ws;
2139         int                     ws_idx_atom;
2140
2141
2142         if ((screens = calloc(ScreenCount(display),
2143              sizeof(struct swm_screen))) == NULL)
2144                 errx(1, "calloc: screens");
2145
2146         ws_idx_atom = XInternAtom(display, "_SWM_WS", False);
2147         
2148
2149         /* map physical screens */
2150         for (i = 0; i < ScreenCount(display); i++) {
2151                 DNPRINTF(SWM_D_WS, "setup_screens: init screen %d\n", i);
2152                 screens[i].idx = i;
2153                 TAILQ_INIT(&screens[i].rl);
2154                 screens[i].root = RootWindow(display, i);
2155
2156                 /* set default colors */
2157                 setscreencolor("red", i + 1, SWM_S_COLOR_FOCUS);
2158                 setscreencolor("rgb:88/88/88", i + 1, SWM_S_COLOR_UNFOCUS);
2159                 setscreencolor("rgb:00/80/80", i + 1, SWM_S_COLOR_BAR_BORDER);
2160                 setscreencolor("black", i + 1, SWM_S_COLOR_BAR);
2161                 setscreencolor("rgb:a0/a0/a0", i + 1, SWM_S_COLOR_BAR_FONT);
2162
2163                 /* init all workspaces */
2164                 for (j = 0; j < SWM_WS_MAX; j++) {
2165                         ws = &screens[i].ws[j];
2166                         ws->idx = j;
2167                         ws->restack = 1;
2168                         ws->focus = NULL;
2169                         ws->r = NULL;
2170                         TAILQ_INIT(&ws->winlist);
2171
2172                         for (k = 0; layouts[k].l_stack != NULL; k++)
2173                                 if (layouts[k].l_config != NULL)
2174                                         layouts[k].l_config(ws,
2175                                             SWM_ARG_ID_STACKINIT);
2176                         ws->cur_layout = &layouts[0];
2177                 }
2178
2179                 /* map virtual screens onto physical screens */
2180                 screens[i].xrandr_support = XRRQueryExtension(display,
2181                     &xrandr_eventbase, &errorbase);
2182                 if (screens[i].xrandr_support)
2183                         if (XRRQueryVersion(display, &major, &minor) &&
2184                             major < 1)
2185                                 screens[i].xrandr_support = 0;
2186
2187 #if 0   /* not ready for dynamic screen changes */
2188                 if (screens[i].xrandr_support)
2189                         XRRSelectInput(display,
2190                             screens[r->s].root,
2191                             RRScreenChangeNotifyMask);
2192 #endif
2193
2194                 /* grab existing windows (before we build the bars)*/
2195                 if (!XQueryTree(display, screens[i].root, &d1, &d2, &wins, &no))
2196                         continue;
2197
2198 #ifdef SWM_XRR_HAS_CRTC
2199                 sr = XRRGetScreenResources(display, screens[i].root);
2200                 if (sr == NULL)
2201                         new_region(&screens[i], &screens[i].ws[w],
2202                             0, 0, DisplayWidth(display, i),
2203                             DisplayHeight(display, i)); 
2204                 else 
2205                         ncrtc = sr->ncrtc;
2206
2207                 for (c = 0, ci = NULL; c < ncrtc; c++) {
2208                         ci = XRRGetCrtcInfo(display, sr, sr->crtcs[c]);
2209                         if (ci->noutput == 0)
2210                                 continue;
2211
2212                         if (ci != NULL && ci->mode == None)
2213                                 new_region(&screens[i], &screens[i].ws[w], 0, 0,
2214                                     DisplayWidth(display, i),
2215                                     DisplayHeight(display, i)); 
2216                         else
2217                                 new_region(&screens[i], &screens[i].ws[w],
2218                                     ci->x, ci->y, ci->width, ci->height);
2219                         w++;
2220                 }
2221                 if (ci)
2222                         XRRFreeCrtcInfo(ci);
2223                 XRRFreeScreenResources(sr);
2224 #else
2225                 new_region(&screens[i], &screens[i].ws[w], 0, 0,
2226                     DisplayWidth(display, i),
2227                     DisplayHeight(display, i)); 
2228 #endif /* SWM_XRR_HAS_CRTC */
2229
2230                 /* attach windows to a region */
2231                 /* normal windows */
2232                 if ((r = TAILQ_FIRST(&screens[i].rl)) == NULL)
2233                         errx(1, "no regions on screen %d", i);
2234
2235                 for (i = 0; i < no; i++) {
2236                         XGetWindowAttributes(display, wins[i], &wa);
2237                         if (!XGetWindowAttributes(display, wins[i], &wa) ||
2238                             wa.override_redirect ||
2239                             XGetTransientForHint(display, wins[i], &d1))
2240                                 continue;
2241
2242                         if (wa.map_state == IsViewable ||
2243                             getstate(wins[i]) == NormalState)
2244                                 manage_window(wins[i]);
2245                 }
2246                 /* transient windows */
2247                 for (i = 0; i < no; i++) {
2248                         if (!XGetWindowAttributes(display, wins[i], &wa))
2249                                 continue;
2250
2251                         if (XGetTransientForHint(display, wins[i], &d1) &&
2252                             (wa.map_state == IsViewable || getstate(wins[i]) ==
2253                             NormalState))
2254                                 manage_window(wins[i]);
2255                 }
2256                 if (wins) {
2257                         XFree(wins);
2258                         wins = NULL;
2259                 }
2260         }
2261 }
2262
2263 int
2264 main(int argc, char *argv[])
2265 {
2266         struct passwd           *pwd;
2267         char                    conf[PATH_MAX], *cfile = NULL;
2268         struct stat             sb;
2269         XEvent                  e;
2270         int                     xfd;
2271         fd_set                  rd;
2272
2273         start_argv = argv;
2274         fprintf(stderr, "Welcome to scrotwm V%s cvs tag: %s\n",
2275             SWM_VERSION, cvstag);
2276         if (!setlocale(LC_CTYPE, "") || !XSupportsLocale())
2277                 warnx("no locale support");
2278
2279         if (!(display = XOpenDisplay(0)))
2280                 errx(1, "can not open display");
2281
2282         if (active_wm())
2283                 errx(1, "other wm running");
2284
2285         astate = XInternAtom(display, "WM_STATE", False);
2286
2287         /* look for local and global conf file */
2288         pwd = getpwuid(getuid());
2289         if (pwd == NULL)
2290                 errx(1, "invalid user %d", getuid());
2291
2292         setup_screens();
2293
2294         snprintf(conf, sizeof conf, "%s/.%s", pwd->pw_dir, SWM_CONF_FILE);
2295         if (stat(conf, &sb) != -1) {
2296                 if (S_ISREG(sb.st_mode))
2297                         cfile = conf;
2298         } else {
2299                 /* try global conf file */
2300                 snprintf(conf, sizeof conf, "/etc/%s", SWM_CONF_FILE);
2301                 if (!stat(conf, &sb))
2302                         if (S_ISREG(sb.st_mode))
2303                                 cfile = conf;
2304         }
2305         if (cfile)
2306                 conf_load(cfile);
2307         bar_refresh();
2308
2309         /* ws[0].focus = TAILQ_FIRST(&ws[0].winlist); */
2310
2311         grabkeys();
2312         stack();
2313
2314         xfd = ConnectionNumber(display);
2315         while (running) {
2316                 FD_ZERO(&rd);
2317                 FD_SET(xfd, &rd);
2318                 if (select(xfd + 1, &rd, NULL, NULL, NULL) == -1)
2319                         if (errno != EINTR)
2320                                 errx(1, "select failed");
2321                 if (bar_alarm) {
2322                         bar_alarm = 0;
2323                         bar_update();
2324                 }
2325                 while(XPending(display)) {
2326                         XNextEvent(display, &e);
2327                         if (handler[e.type])
2328                                 handler[e.type](&e);
2329                 }
2330         }
2331
2332         XCloseDisplay(display);
2333
2334         return (0);
2335 }