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