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