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