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