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