JasonWoof Got questions, comments, patches, etc.? Contact Jason Woofenden
Fix some workspace switching nits:
[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 swm_region       *prev_r;        /* may be NULL */
224         struct ws_win_list      winlist;        /* list of windows in ws */
225
226         /* stacker state */
227         struct {
228                                 int horizontal_msize;
229                                 int horizontal_mwin;
230                                 int vertical_msize;
231                                 int vertical_mwin;
232         } l_state;
233 };
234
235 /* physical screen mapping */
236 #define SWM_WS_MAX              (10)            /* XXX Too small? */
237 struct swm_screen {
238         int                     idx;            /* screen index */
239         struct swm_region_list  rl;     /* list of regions on this screen */
240         Window                  root;
241         int                     xrandr_support;
242         struct workspace        ws[SWM_WS_MAX];
243
244         /* colors */
245         unsigned long           bar_border;
246         unsigned long           bar_color;
247         unsigned long           bar_font_color;
248         unsigned long           color_focus;            /* XXX should this be per ws? */
249         unsigned long           color_unfocus;
250 };
251 struct swm_screen       *screens;
252 int                     num_screens;
253 Window rootclick = 0;
254
255 struct ws_win           *cur_focus = NULL;
256
257 /* args to functions */
258 union arg {
259         int                     id;
260 #define SWM_ARG_ID_FOCUSNEXT    (0)
261 #define SWM_ARG_ID_FOCUSPREV    (1)
262 #define SWM_ARG_ID_FOCUSMAIN    (2)
263 #define SWM_ARG_ID_SWAPNEXT     (3)
264 #define SWM_ARG_ID_SWAPPREV     (4)
265 #define SWM_ARG_ID_SWAPMAIN     (5)
266 #define SWM_ARG_ID_MASTERSHRINK (6)
267 #define SWM_ARG_ID_MASTERGROW   (7)
268 #define SWM_ARG_ID_MASTERADD    (8)
269 #define SWM_ARG_ID_MASTERDEL    (9)
270 #define SWM_ARG_ID_STACKRESET   (10)
271 #define SWM_ARG_ID_STACKINIT    (11)
272 #define SWM_ARG_ID_CYCLEWS_UP   (12)
273 #define SWM_ARG_ID_CYCLEWS_DOWN (13)
274         char                    **argv;
275 };
276
277 unsigned long
278 name_to_color(char *colorname)
279 {
280         Colormap                cmap;
281         Status                  status;
282         XColor                  screen_def, exact_def;
283         unsigned long           result = 0;
284         char                    cname[32] = "#";
285
286         cmap = DefaultColormap(display, screens[0].idx);
287         status = XAllocNamedColor(display, cmap, colorname,
288             &screen_def, &exact_def);
289         if (!status) {
290                 strlcat(cname, colorname + 2, sizeof cname - 1);
291                 status = XAllocNamedColor(display, cmap, cname, &screen_def,
292                     &exact_def);
293         }
294         if (status)
295                 result = screen_def.pixel;
296         else
297                 fprintf(stderr, "color '%s' not found.\n", colorname);
298
299         return (result);
300 }
301
302 int
303 varmatch(char *var, char *name, int *index)
304 {
305         char                    *p, buf[5];
306         int                     i;
307
308         i = strncmp(var, name, 255);
309         if (index == NULL)
310                 return (i);
311
312         *index = -1;
313         if (i <= 0)
314                 return (i);
315         p = var + strlen(name);
316         if (*p++ != '[')
317                 return (i);
318         bzero(buf, sizeof buf);
319         i = 0;
320         while (isdigit(*p) && i < sizeof buf)
321                 buf[i++] = *p++;
322         if (i == 0 || i >= sizeof buf || *p != ']')
323                 return (1);
324         *index = strtonum(buf, 0, 99, NULL);
325         return (0);
326 }
327
328 /* conf file stuff */
329 #define SWM_CONF_WS     "\n= \t"
330 #define SWM_CONF_FILE   "scrotwm.conf"
331 int
332 conf_load(char *filename)
333 {
334         FILE                    *config;
335         char                    *line, *cp, *var, *val;
336         size_t                  len, lineno = 0;
337         int                     i, sc;
338
339         DNPRINTF(SWM_D_MISC, "conf_load: filename %s\n", filename);
340
341         if (filename == NULL)
342                 return (1);
343
344         if ((config = fopen(filename, "r")) == NULL)
345                 return (1);
346
347         for (sc = ScreenCount(display);;) {
348                 if ((line = fparseln(config, &len, &lineno, NULL, 0)) == NULL)
349                         if (feof(config))
350                                 break;
351                 cp = line;
352                 cp += (long)strspn(cp, SWM_CONF_WS);
353                 if (cp[0] == '\0') {
354                         /* empty line */
355                         free(line);
356                         continue;
357                 }
358                 if ((var = strsep(&cp, SWM_CONF_WS)) == NULL || cp == 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                 /* 
773                  * If the other workspace is hidden and the workspace was
774                  * previously mapped here, just swap switch windows.
775                  * map new window first to prevent ugly blinking
776                  */
777                 if (new_ws->restack == 0 && new_ws->prev_r == this_r) {
778                         TAILQ_FOREACH(win, &new_ws->winlist, entry)
779                                 XMapRaised(display, win->id);
780
781                         TAILQ_FOREACH(win, &old_ws->winlist, entry)
782                                 XUnmapWindow(display, win->id);
783                 }
784                 old_ws->prev_r = old_ws->r;
785                 old_ws->r = NULL;
786         } else {
787                 other_r->ws = old_ws;
788                 old_ws->r = other_r;
789         }
790         this_r->ws = new_ws;
791         new_ws->prev_r = new_ws->r;
792         new_ws->r = this_r;
793
794         ignore_enter = 1;
795         /* set focus */
796         if (!new_ws->focus)
797                 new_ws->focus = TAILQ_FIRST(&new_ws->winlist);
798         if (new_ws->focus )
799                 focus_win(new_ws->focus);
800         stack();
801         bar_update();
802 }
803
804 void
805 cyclews(struct swm_region *r, union arg *args)
806 {
807         union                   arg a;
808         struct swm_screen       *s = r->s;
809
810         DNPRINTF(SWM_D_WS, "cyclews id %d "
811             "in screen %d region %dx%d+%d+%d ws %d\n", args->id,
812             r->s->idx, WIDTH(r), HEIGHT(r), X(r), Y(r), r->ws->idx);
813
814         a.id = r->ws->idx;
815
816         do {
817                 switch (args->id) {
818                 case SWM_ARG_ID_CYCLEWS_UP:
819                         if (a.id < SWM_WS_MAX - 1)
820                                 a.id++;
821                         else
822                                 a.id = 0;
823                         break;
824                 case SWM_ARG_ID_CYCLEWS_DOWN:
825                         if (a.id > 0)
826                                 a.id--;
827                         else
828                                 a.id = SWM_WS_MAX - 1;
829                         break;
830                 default:
831                         return;
832                 };
833
834                 if (cycle_empty == 0 && TAILQ_EMPTY(&s->ws[a.id].winlist))
835                         continue;
836                 if (cycle_visible == 0 && s->ws[a.id].r != NULL)
837                         continue;
838
839                 switchws(r, &a);
840         } while (a.id != r->ws->idx);
841 }
842
843 void
844 swapwin(struct swm_region *r, union arg *args)
845 {
846         struct ws_win           *target;
847         struct ws_win_list      *wl;
848
849
850         DNPRINTF(SWM_D_WS, "swapwin id %d "
851             "in screen %d region %dx%d+%d+%d ws %d\n", args->id,
852             r->s->idx, WIDTH(r), HEIGHT(r), X(r), Y(r), r->ws->idx);
853         if (cur_focus == NULL)
854                 return;
855
856         wl = &cur_focus->ws->winlist;
857
858         switch (args->id) {
859         case SWM_ARG_ID_SWAPPREV:
860                 target = TAILQ_PREV(cur_focus, ws_win_list, entry);
861                 TAILQ_REMOVE(wl, cur_focus, entry);
862                 if (target == NULL)
863                         TAILQ_INSERT_TAIL(wl, cur_focus, entry);
864                 else
865                         TAILQ_INSERT_BEFORE(target, cur_focus, entry);
866                 break;
867         case SWM_ARG_ID_SWAPNEXT: 
868                 target = TAILQ_NEXT(cur_focus, entry);
869                 TAILQ_REMOVE(wl, cur_focus, entry);
870                 if (target == NULL)
871                         TAILQ_INSERT_HEAD(wl, cur_focus, entry);
872                 else
873                         TAILQ_INSERT_AFTER(wl, target, cur_focus, entry);
874                 break;
875         case SWM_ARG_ID_SWAPMAIN:
876                 target = TAILQ_FIRST(wl);
877                 if (target == cur_focus)
878                         return;
879                 TAILQ_REMOVE(wl, target, entry);
880                 TAILQ_INSERT_BEFORE(cur_focus, target, entry);
881                 TAILQ_REMOVE(wl, cur_focus, entry);
882                 TAILQ_INSERT_HEAD(wl, cur_focus, entry);
883                 break;
884         default:
885                 DNPRINTF(SWM_D_MOVE, "invalid id: %d\n", args->id);
886                 return;
887         }
888
889         ignore_enter = 2;
890         stack();
891 }
892
893 void
894 focus(struct swm_region *r, union arg *args)
895 {
896         struct ws_win           *winfocus, *winlostfocus;
897         struct ws_win_list      *wl;
898
899         DNPRINTF(SWM_D_FOCUS, "focus: id %d\n", args->id);
900         if (cur_focus == NULL)
901                 return;
902
903         wl = &cur_focus->ws->winlist;
904
905         winlostfocus = cur_focus;
906
907         switch (args->id) {
908         case SWM_ARG_ID_FOCUSPREV:
909                 winfocus = TAILQ_PREV(cur_focus, ws_win_list, entry);
910                 if (winfocus == NULL)
911                         winfocus = TAILQ_LAST(wl, ws_win_list);
912                 break;
913
914         case SWM_ARG_ID_FOCUSNEXT:
915                 winfocus = TAILQ_NEXT(cur_focus, entry);
916                 if (winfocus == NULL)
917                         winfocus = TAILQ_FIRST(wl);
918                 break;
919
920         case SWM_ARG_ID_FOCUSMAIN:
921                 winfocus = TAILQ_FIRST(wl);
922                 break;
923
924         default:
925                 return;
926         }
927
928         if (winfocus == winlostfocus)
929                 return;
930
931         focus_win(winfocus);
932         XSync(display, False);
933 }
934
935 void
936 cycle_layout(struct swm_region *r, union arg *args)
937 {
938         struct workspace        *ws = r->ws;
939
940         DNPRINTF(SWM_D_EVENT, "cycle_layout: workspace: %d\n", ws->idx);
941
942         ws->cur_layout++;
943         if (ws->cur_layout->l_stack == NULL)
944                 ws->cur_layout = &layouts[0];
945         ignore_enter = 1;
946
947         stack();
948 }
949
950 void
951 stack_config(struct swm_region *r, union arg *args)
952 {
953         struct workspace        *ws = r->ws;
954
955         DNPRINTF(SWM_D_STACK, "stack_config for workspace %d (id %d\n",
956             args->id, ws->idx);
957
958         if (ws->cur_layout->l_config != NULL)
959                 ws->cur_layout->l_config(ws, args->id);
960
961         if (args->id != SWM_ARG_ID_STACKINIT);
962                 stack();
963 }
964
965 void
966 stack(void) {
967         struct swm_geometry     g;
968         struct swm_region       *r;
969         int                     i, j;
970
971         DNPRINTF(SWM_D_STACK, "stack\n");
972
973         for (i = 0; i < ScreenCount(display); i++) {
974                 j = 0;
975                 TAILQ_FOREACH(r, &screens[i].rl, entry) {
976                         DNPRINTF(SWM_D_STACK, "stacking workspace %d "
977                             "(screen %d, region %d)\n", r->ws->idx, i, j++);
978
979                         /* start with screen geometry, adjust for bar */
980                         g = r->g;
981                         g.w -= 2;
982                         g.h -= 2;
983                         if (bar_enabled) {
984                                 g.y += bar_height;
985                                 g.h -= bar_height;
986                         } 
987
988                         r->ws->restack = 0;
989                         r->ws->cur_layout->l_stack(r->ws, &g);
990                 }
991         }
992         XSync(display, False);
993 }
994
995 void
996 stack_floater(struct ws_win *win, struct swm_region *r)
997 {
998         unsigned int            mask;
999         XWindowChanges          wc;
1000
1001         bzero(&wc, sizeof wc);
1002         mask = CWX | CWY | CWBorderWidth | CWWidth | CWHeight;
1003         wc.border_width = 1;
1004         if (win->transient) {
1005                 win->g.w = (double)WIDTH(r) * dialog_ratio;
1006                 win->g.h = (double)HEIGHT(r) * dialog_ratio;
1007         }
1008         wc.width = win->g.w;
1009         wc.height = win->g.h;
1010         wc.x = (WIDTH(r) - win->g.w) / 2;
1011         wc.y = (HEIGHT(r) - win->g.h) / 2;
1012
1013         DNPRINTF(SWM_D_STACK, "stack_floater: win %lu x %d y %d w %d h %d\n",
1014             win->id, wc.x, wc.y, wc.width, wc.height);
1015
1016         XConfigureWindow(display, win->id, mask, &wc);
1017 }
1018
1019
1020 void
1021 vertical_config(struct workspace *ws, int id)
1022 {
1023         DNPRINTF(SWM_D_STACK, "vertical_resize: workspace: %d\n", ws->idx);
1024
1025         switch (id) {
1026         case SWM_ARG_ID_STACKRESET:
1027         case SWM_ARG_ID_STACKINIT:
1028                 ws->l_state.vertical_msize = SWM_V_SLICE / 2;
1029                 ws->l_state.vertical_mwin = 1;
1030                 break;
1031         case SWM_ARG_ID_MASTERSHRINK:
1032                 if (ws->l_state.vertical_msize > 1)
1033                         ws->l_state.vertical_msize--;
1034                 break;
1035         case SWM_ARG_ID_MASTERGROW:
1036                 if (ws->l_state.vertical_msize < SWM_V_SLICE - 1)
1037                         ws->l_state.vertical_msize++;
1038                 break;
1039         case SWM_ARG_ID_MASTERADD:
1040                 ws->l_state.vertical_mwin++;
1041                 break;
1042         case SWM_ARG_ID_MASTERDEL:
1043                 if (ws->l_state.vertical_mwin > 0)
1044                         ws->l_state.vertical_mwin--;
1045                 break;
1046         default:
1047                 return;
1048         }
1049 }
1050
1051 void
1052 vertical_stack(struct workspace *ws, struct swm_geometry *g) {
1053         XWindowChanges          wc;
1054         struct swm_geometry     gg = *g;
1055         struct ws_win           *win, *winfocus;
1056         int                     i, j, split, colno, hrh, winno, main_width;
1057         unsigned int            mask;
1058
1059         DNPRINTF(SWM_D_STACK, "vertical_stack: workspace: %d\n", ws->idx);
1060
1061         if ((winno = count_win(ws, 0)) == 0)
1062                 return;
1063
1064         if (ws->focus == NULL)
1065                 ws->focus = TAILQ_FIRST(&ws->winlist);
1066         winfocus = cur_focus ? cur_focus : ws->focus;
1067
1068         if (ws->l_state.vertical_mwin &&
1069             winno > ws->l_state.vertical_mwin) {
1070                 split = ws->l_state.vertical_mwin;
1071                 colno = split;
1072                 main_width = (g->w / SWM_V_SLICE) *
1073                    ws->l_state.vertical_msize;
1074                 gg.w = main_width;
1075         } else {
1076                 colno = winno;
1077                 split = 0;
1078         }
1079         hrh = g->h / colno;
1080         gg.h = hrh - 2;
1081
1082         i = j = 0;
1083         TAILQ_FOREACH(win, &ws->winlist, entry) {
1084                 if (split && i == split) {
1085                         colno = winno - split;
1086                         hrh = (g->h / colno);
1087                         gg.x += main_width + 2;
1088                         gg.w = g->w - (main_width + 2);
1089                         gg.h = hrh - 2;
1090                         j = 0;
1091                 }
1092                 if (j == colno - 1)
1093                         gg.h = (hrh + (g->h - (colno * hrh)));
1094                  
1095                 if (j == 0)
1096                         gg.y = g->y;
1097                 else
1098                         gg.y += hrh;
1099
1100
1101                 if (win->transient != 0 || win->floating != 0)
1102                         stack_floater(win, ws->r);
1103                 else {
1104                         bzero(&wc, sizeof wc);
1105                         wc.border_width = 1;
1106                         win->g.x = wc.x = gg.x;
1107                         win->g.y = wc.y = gg.y;
1108                         win->g.w = wc.width = gg.w;
1109                         win->g.h = wc.height = gg.h;
1110                         mask = CWX | CWY | CWWidth | CWHeight | CWBorderWidth;
1111                         XConfigureWindow(display, win->id, mask, &wc);
1112                 }
1113
1114                 XMapRaised(display, win->id);
1115                 i++;
1116                 j++;
1117         }
1118
1119         if (winfocus)
1120                 focus_win(winfocus); /* has to be done outside of the loop */
1121 }
1122
1123
1124 void
1125 horizontal_config(struct workspace *ws, int id)
1126 {
1127         DNPRINTF(SWM_D_STACK, "horizontal_config: workspace: %d\n", ws->idx);
1128
1129         switch (id) {
1130         case SWM_ARG_ID_STACKRESET:
1131         case SWM_ARG_ID_STACKINIT:
1132                 ws->l_state.horizontal_mwin = 1;
1133                 ws->l_state.horizontal_msize = SWM_H_SLICE / 2;
1134                 break;
1135         case SWM_ARG_ID_MASTERSHRINK:
1136                 if (ws->l_state.horizontal_msize > 1)
1137                         ws->l_state.horizontal_msize--;
1138                 break;
1139         case SWM_ARG_ID_MASTERGROW:
1140                 if (ws->l_state.horizontal_msize < SWM_H_SLICE - 1)
1141                         ws->l_state.horizontal_msize++;
1142                 break;
1143         case SWM_ARG_ID_MASTERADD:
1144                 ws->l_state.horizontal_mwin++;
1145                 break;
1146         case SWM_ARG_ID_MASTERDEL:
1147                 if (ws->l_state.horizontal_mwin > 0)
1148                         ws->l_state.horizontal_mwin--;
1149                 break;
1150         default:
1151                 return;
1152         }
1153 }
1154
1155 void
1156 horizontal_stack(struct workspace *ws, struct swm_geometry *g) {
1157         XWindowChanges          wc;
1158         struct swm_geometry     gg = *g;
1159         struct ws_win           *win, *winfocus;
1160         int                     i, j, split, rowno, hrw, winno, main_height;
1161         unsigned int            mask;
1162
1163         DNPRINTF(SWM_D_STACK, "horizontal_stack: workspace: %d\n", ws->idx);
1164
1165         if ((winno = count_win(ws, 0)) == 0)
1166                 return;
1167
1168         if (ws->focus == NULL)
1169                 ws->focus = TAILQ_FIRST(&ws->winlist);
1170         winfocus = cur_focus ? cur_focus : ws->focus;
1171
1172         if (ws->l_state.horizontal_mwin &&
1173             winno > ws->l_state.horizontal_mwin) {
1174                 split = ws->l_state.horizontal_mwin;
1175                 rowno = split;
1176                 main_height = (g->h / SWM_V_SLICE) *
1177                    ws->l_state.horizontal_msize;
1178                 gg.h = main_height;
1179         } else {
1180                 rowno = winno;
1181                 split = 0;
1182         }
1183         hrw = g->w / rowno;
1184         gg.w = hrw - 2;
1185
1186         i = j = 0;
1187         TAILQ_FOREACH(win, &ws->winlist, entry) {
1188                 if (split && i == split) {
1189                         rowno = winno - split;
1190                         hrw = (g->w / rowno);
1191                         gg.y += main_height + 2;
1192                         gg.h = g->h - (main_height + 2);
1193                         gg.w = hrw - 2;
1194                         j = 0;
1195                 }
1196                 if (j == rowno - 1)
1197                         gg.w = (hrw + (g->w - (rowno * hrw)));
1198
1199                 if (j == 0)
1200                         gg.x = g->x;
1201                 else
1202                         gg.x += hrw;
1203
1204                 if (win->transient != 0 || win->floating != 0)
1205                         stack_floater(win, ws->r);
1206                 else {
1207                         bzero(&wc, sizeof wc);
1208                         wc.border_width = 1;
1209                         win->g.x = wc.x = gg.x;
1210                         win->g.y = wc.y = gg.y;
1211                         win->g.w = wc.width = gg.w;
1212                         win->g.h = wc.height = gg.h;
1213                         mask = CWX | CWY | CWWidth | CWHeight | CWBorderWidth;
1214                         XConfigureWindow(display, win->id, mask, &wc);
1215                 }
1216
1217                 XMapRaised(display, win->id);
1218                 j++;
1219                 i++;
1220         }
1221
1222         if (winfocus)
1223                 focus_win(winfocus); /* this has to be done outside of the loop */
1224 }
1225
1226 /* fullscreen view */
1227 void
1228 max_stack(struct workspace *ws, struct swm_geometry *g) {
1229         XWindowChanges          wc;
1230         struct swm_geometry     gg = *g;
1231         struct ws_win           *win, *winfocus;
1232         unsigned int            mask;
1233
1234         DNPRINTF(SWM_D_STACK, "max_stack: workspace: %d\n", ws->idx);
1235
1236         if (count_win(ws, 0) == 0)
1237                 return;
1238
1239         if (ws->focus == NULL)
1240                 ws->focus = TAILQ_FIRST(&ws->winlist);
1241         winfocus = cur_focus ? cur_focus : ws->focus;
1242
1243         TAILQ_FOREACH(win, &ws->winlist, entry) {
1244                 if (win->transient != 0 || win->floating != 0) {
1245                         if (win == ws->focus) {
1246                                 /* XXX maximize? */
1247                                 stack_floater(win, ws->r);
1248                                 XMapRaised(display, win->id);
1249                         } else
1250                                 XUnmapWindow(display, win->id);
1251                 } else {
1252                         bzero(&wc, sizeof wc);
1253                         wc.border_width = 1;
1254                         win->g.x = wc.x = gg.x;
1255                         win->g.y = wc.y = gg.y;
1256                         win->g.w = wc.width = gg.w;
1257                         win->g.h = wc.height = gg.h;
1258                         mask = CWX | CWY | CWWidth | CWHeight | CWBorderWidth;
1259                         XConfigureWindow(display, win->id, mask, &wc);
1260
1261                         if (win == ws->focus) {
1262                                 XMapRaised(display, win->id);
1263                         } else
1264                                 XUnmapWindow(display, win->id);
1265                 }
1266         }
1267
1268         if (winfocus)
1269                 focus_win(winfocus); /* has to be done outside of the loop */
1270 }
1271
1272 void
1273 send_to_ws(struct swm_region *r, union arg *args)
1274 {
1275         int                     wsid = args->id;
1276         struct ws_win           *win = cur_focus;
1277         struct workspace        *ws, *nws;
1278
1279         DNPRINTF(SWM_D_MOVE, "send_to_ws: win: %lu\n", win->id);
1280
1281         ws = win->ws;
1282         nws = &win->s->ws[wsid];
1283
1284         XUnmapWindow(display, win->id);
1285
1286         /* find a window to focus */
1287         ws->focus = TAILQ_PREV(win, ws_win_list, entry);
1288         if (ws->focus == NULL)
1289                 ws->focus = TAILQ_FIRST(&ws->winlist);
1290         if (ws->focus == win)
1291                 ws->focus = NULL;
1292
1293         TAILQ_REMOVE(&ws->winlist, win, entry);
1294
1295         TAILQ_INSERT_TAIL(&nws->winlist, win, entry);
1296         win->ws = nws;
1297
1298         if (count_win(nws, 1) == 1)
1299                 nws->focus = win;
1300         ws->restack = 1;
1301         nws->restack = 1;
1302
1303         stack();
1304 }
1305
1306 /* key definitions */
1307 struct key {
1308         unsigned int            mod;
1309         KeySym                  keysym;
1310         void                    (*func)(struct swm_region *r, union arg *);
1311         union arg               args;
1312 } keys[] = {
1313         /* modifier             key     function                argument */
1314         { MODKEY,               XK_space,       cycle_layout,   {0} }, 
1315         { MODKEY | ShiftMask,   XK_space,       stack_config,   {.id = SWM_ARG_ID_STACKRESET} }, 
1316         { MODKEY,               XK_h,           stack_config,   {.id = SWM_ARG_ID_MASTERSHRINK} },
1317         { MODKEY,               XK_l,           stack_config,   {.id = SWM_ARG_ID_MASTERGROW} },
1318         { MODKEY,               XK_comma,       stack_config,   {.id = SWM_ARG_ID_MASTERADD} },
1319         { MODKEY,               XK_period,      stack_config,   {.id = SWM_ARG_ID_MASTERDEL} },
1320         { MODKEY,               XK_Return,      swapwin,        {.id = SWM_ARG_ID_SWAPMAIN} },
1321         { MODKEY,               XK_j,           focus,          {.id = SWM_ARG_ID_FOCUSNEXT} },
1322         { MODKEY,               XK_k,           focus,          {.id = SWM_ARG_ID_FOCUSPREV} },
1323         { MODKEY | ShiftMask,   XK_j,           swapwin,        {.id = SWM_ARG_ID_SWAPNEXT} },
1324         { MODKEY | ShiftMask,   XK_k,           swapwin,        {.id = SWM_ARG_ID_SWAPPREV} },
1325         { MODKEY | ShiftMask,   XK_Return,      spawn,          {.argv = spawn_term} },
1326         { MODKEY,               XK_p,           spawn,          {.argv = spawn_menu} },
1327         { MODKEY | ShiftMask,   XK_q,           quit,           {0} },
1328         { MODKEY,               XK_q,           restart,        {0} },
1329         { MODKEY,               XK_m,           focus,          {.id = SWM_ARG_ID_FOCUSMAIN} },
1330         { MODKEY,               XK_1,           switchws,       {.id = 0} },
1331         { MODKEY,               XK_2,           switchws,       {.id = 1} },
1332         { MODKEY,               XK_3,           switchws,       {.id = 2} },
1333         { MODKEY,               XK_4,           switchws,       {.id = 3} },
1334         { MODKEY,               XK_5,           switchws,       {.id = 4} },
1335         { MODKEY,               XK_6,           switchws,       {.id = 5} },
1336         { MODKEY,               XK_7,           switchws,       {.id = 6} },
1337         { MODKEY,               XK_8,           switchws,       {.id = 7} },
1338         { MODKEY,               XK_9,           switchws,       {.id = 8} },
1339         { MODKEY,               XK_0,           switchws,       {.id = 9} },
1340         { MODKEY,               XK_Right,       cyclews,        {.id = SWM_ARG_ID_CYCLEWS_UP} }, 
1341         { MODKEY,               XK_Left,        cyclews,        {.id = SWM_ARG_ID_CYCLEWS_DOWN} }, 
1342         { MODKEY | ShiftMask,   XK_1,           send_to_ws,     {.id = 0} },
1343         { MODKEY | ShiftMask,   XK_2,           send_to_ws,     {.id = 1} },
1344         { MODKEY | ShiftMask,   XK_3,           send_to_ws,     {.id = 2} },
1345         { MODKEY | ShiftMask,   XK_4,           send_to_ws,     {.id = 3} },
1346         { MODKEY | ShiftMask,   XK_5,           send_to_ws,     {.id = 4} },
1347         { MODKEY | ShiftMask,   XK_6,           send_to_ws,     {.id = 5} },
1348         { MODKEY | ShiftMask,   XK_7,           send_to_ws,     {.id = 6} },
1349         { MODKEY | ShiftMask,   XK_8,           send_to_ws,     {.id = 7} },
1350         { MODKEY | ShiftMask,   XK_9,           send_to_ws,     {.id = 8} },
1351         { MODKEY | ShiftMask,   XK_0,           send_to_ws,     {.id = 9} },
1352         { MODKEY,               XK_b,           bar_toggle,     {0} },
1353         { MODKEY,               XK_Tab,         focus,          {.id = SWM_ARG_ID_FOCUSNEXT} },
1354         { MODKEY | ShiftMask,   XK_Tab,         focus,          {.id = SWM_ARG_ID_FOCUSPREV} },
1355 };
1356
1357 void
1358 updatenumlockmask(void)
1359 {
1360         unsigned int            i, j;
1361         XModifierKeymap         *modmap;
1362
1363         DNPRINTF(SWM_D_MISC, "updatenumlockmask\n");
1364         numlockmask = 0;
1365         modmap = XGetModifierMapping(display);
1366         for (i = 0; i < 8; i++)
1367                 for (j = 0; j < modmap->max_keypermod; j++)
1368                         if (modmap->modifiermap[i * modmap->max_keypermod + j]
1369                           == XKeysymToKeycode(display, XK_Num_Lock))
1370                                 numlockmask = (1 << i);
1371
1372         XFreeModifiermap(modmap);
1373 }
1374
1375 void
1376 grabkeys(void)
1377 {
1378         unsigned int            i, j, k;
1379         KeyCode                 code;
1380         unsigned int            modifiers[] =
1381             { 0, LockMask, numlockmask, numlockmask | LockMask };
1382
1383         DNPRINTF(SWM_D_MISC, "grabkeys\n");
1384         updatenumlockmask();
1385
1386         for (k = 0; k < ScreenCount(display); k++) {
1387                 if (TAILQ_EMPTY(&screens[k].rl))
1388                         continue;
1389                 XUngrabKey(display, AnyKey, AnyModifier, screens[k].root);
1390                 for (i = 0; i < LENGTH(keys); i++) {
1391                         if ((code = XKeysymToKeycode(display, keys[i].keysym)))
1392                                 for (j = 0; j < LENGTH(modifiers); j++)
1393                                         XGrabKey(display, code,
1394                                             keys[i].mod | modifiers[j],
1395                                             screens[k].root, True,
1396                                             GrabModeAsync, GrabModeAsync);
1397                 }
1398         }
1399 }
1400 void
1401 expose(XEvent *e)
1402 {
1403         DNPRINTF(SWM_D_EVENT, "expose: window: %lu\n", e->xexpose.window);
1404 }
1405
1406 void
1407 keypress(XEvent *e)
1408 {
1409         unsigned int            i;
1410         KeySym                  keysym;
1411         XKeyEvent               *ev = &e->xkey;
1412
1413         DNPRINTF(SWM_D_EVENT, "keypress: window: %lu\n", ev->window);
1414
1415         keysym = XKeycodeToKeysym(display, (KeyCode)ev->keycode, 0);
1416         for (i = 0; i < LENGTH(keys); i++)
1417                 if (keysym == keys[i].keysym
1418                    && CLEANMASK(keys[i].mod) == CLEANMASK(ev->state)
1419                    && keys[i].func)
1420                         keys[i].func(root_to_region(ev->root),
1421                             &(keys[i].args));
1422 }
1423
1424 void
1425 buttonpress(XEvent *e)
1426 {
1427         XButtonPressedEvent     *ev = &e->xbutton;
1428 #ifdef SWM_CLICKTOFOCUS
1429         struct ws_win           *win;
1430         struct workspace        *ws;
1431         struct swm_region       *r;
1432 #endif
1433
1434         DNPRINTF(SWM_D_EVENT, "buttonpress: window: %lu\n", ev->window);
1435
1436         if (ev->window == ev->root) {
1437                 rootclick = ev->root;
1438                 return;
1439         }
1440         if (ev->window == cur_focus->id)
1441                 return;
1442 #ifdef SWM_CLICKTOFOCUS
1443         r = root_to_region(ev->root);
1444         ws = r->ws;
1445         TAILQ_FOREACH(win, &ws->winlist, entry)
1446                 if (win->id == ev->window) {
1447                         /* focus in the clicked window */
1448                         XSetWindowBorder(display, ev->window, 0xff0000);
1449                         XSetWindowBorder(display, ws->focus->id, 0x888888);
1450                         XSetInputFocus(display, ev->window, RevertToPointerRoot,
1451                             CurrentTime);
1452                         ws->focus = win;
1453                         XSync(display, False);
1454                         break;
1455         }
1456 #endif
1457 }
1458
1459 void
1460 set_win_state(struct ws_win *win, long state)
1461 {
1462         long                    data[] = {state, None};
1463
1464         DNPRINTF(SWM_D_EVENT, "set_win_state: window: %lu\n", win->id);
1465
1466         XChangeProperty(display, win->id, astate, astate, 32, PropModeReplace,
1467             (unsigned char *)data, 2);
1468 }
1469
1470 struct ws_win *
1471 manage_window(Window id, struct workspace *ws)
1472 {
1473         Window                  trans;
1474         struct ws_win           *win;
1475         XClassHint              ch;
1476
1477         TAILQ_FOREACH(win, &ws->winlist, entry) {
1478                 if (win->id == id)
1479                         return (win);   /* already being managed */
1480         }
1481
1482         if ((win = calloc(1, sizeof(struct ws_win))) == NULL)
1483                 errx(1, "calloc: failed to allocate memory for new window");
1484
1485         win->id = id;
1486         win->ws = ws;
1487         win->s = ws->r->s;      /* this never changes */
1488         TAILQ_INSERT_TAIL(&ws->winlist, win, entry);
1489
1490         /* make new win focused */
1491         focus_win(win);
1492
1493         XGetTransientForHint(display, win->id, &trans);
1494         if (trans) {
1495                 win->transient = trans;
1496                 DNPRINTF(SWM_D_MISC, "manage_window: win %u transient %u\n",
1497                     (unsigned)win->id, win->transient);
1498         }
1499         XGetWindowAttributes(display, id, &win->wa);
1500         win->g.w = win->wa.width;
1501         win->g.h = win->wa.height;
1502         win->g.x = win->wa.x;
1503         win->g.y = win->wa.y;
1504
1505         /* XXX make this a table */
1506         bzero(&ch, sizeof ch);
1507         if (XGetClassHint(display, win->id, &ch)) {
1508                 /*fprintf(stderr, "class: %s name: %s\n", ch.res_class, ch.res_name); */
1509                 if (!strcmp(ch.res_class, "MPlayer") && !strcmp(ch.res_name, "xv")) {
1510                         win->floating = 1;
1511                 }
1512                 if (ch.res_class)
1513                         XFree(ch.res_class);
1514                 if (ch.res_name)
1515                         XFree(ch.res_name);
1516         }
1517
1518         XSelectInput(display, id, EnterWindowMask | FocusChangeMask |
1519             PropertyChangeMask | StructureNotifyMask);
1520
1521         set_win_state(win, NormalState);
1522
1523         return (win);
1524 }
1525
1526 void
1527 configurerequest(XEvent *e)
1528 {
1529         XConfigureRequestEvent  *ev = &e->xconfigurerequest;
1530         struct ws_win           *win;
1531         int                     new = 1;
1532         XWindowChanges          wc;
1533
1534         if ((win = find_window(ev->window)) == NULL)
1535                 new = 1;
1536
1537         if (new) {
1538                 DNPRINTF(SWM_D_EVENT, "configurerequest: new window: %lu\n",
1539                     ev->window);
1540                 bzero(&wc, sizeof wc);
1541                 wc.x = ev->x;
1542                 wc.y = ev->y;
1543                 wc.width = ev->width;
1544                 wc.height = ev->height;
1545                 wc.border_width = ev->border_width;
1546                 wc.sibling = ev->above;
1547                 wc.stack_mode = ev->detail;
1548                 XConfigureWindow(display, ev->window, ev->value_mask, &wc);
1549         } else {
1550                 DNPRINTF(SWM_D_EVENT, "configurerequest: change window: %lu\n",
1551                     ev->window);
1552                 if (win->floating) {
1553                         if (ev->value_mask & CWX)
1554                                 win->g.x = ev->x;
1555                         if (ev->value_mask & CWY)
1556                                 win->g.y = ev->y;
1557                         if (ev->value_mask & CWWidth)
1558                                 win->g.w = ev->width;
1559                         if (ev->value_mask & CWHeight)
1560                                 win->g.h = ev->height;
1561                         if (win->ws->r != NULL) {
1562                                 /* this seems to be full screen */
1563                                 if (win->g.w > WIDTH(win->ws->r)) {
1564                                         /* kill border */
1565                                         win->g.x -= 1;
1566                                         win->g.w += 1;
1567                                 }
1568                                 if (win->g.h > HEIGHT(win->ws->r)) {
1569                                         /* kill border */
1570                                         win->g.y -= 1;
1571                                         win->g.h += 1;
1572                                 }
1573                         }
1574                         if ((ev->value_mask & (CWX|CWY)) &&
1575                             !(ev->value_mask & (CWWidth|CWHeight)))
1576                                 config_win(win);
1577                         XMoveResizeWindow(display, win->id,
1578                             win->g.x, win->g.y, win->g.w, win->g.h);
1579                 } else
1580                         config_win(win);
1581         }
1582 }
1583
1584 void
1585 configurenotify(XEvent *e)
1586 {
1587         DNPRINTF(SWM_D_EVENT, "configurenotify: window: %lu\n",
1588             e->xconfigure.window);
1589 }
1590
1591 void
1592 destroynotify(XEvent *e)
1593 {
1594         struct ws_win           *win;
1595         XDestroyWindowEvent     *ev = &e->xdestroywindow;
1596
1597         DNPRINTF(SWM_D_EVENT, "destroynotify: window %lu\n", ev->window);
1598
1599         if ((win = find_window(ev->window)) != NULL) {
1600                 struct workspace *ws = win->ws;
1601                 /* find a window to focus */
1602                 if (ws->focus == win)
1603                         ws->focus = TAILQ_PREV(win, ws_win_list, entry);
1604                 if (ws->focus == NULL)
1605                         ws->focus = TAILQ_FIRST(&ws->winlist);
1606                 if (ws->focus == win)
1607                         ws->focus = NULL;
1608                 if (cur_focus == win) {
1609                         if (ws->focus == NULL) 
1610                                 unfocus_win(win); /* XXX focus another ws? */
1611                         else
1612                                 focus_win(ws->focus);
1613                 }
1614
1615                 TAILQ_REMOVE(&ws->winlist, win, entry);
1616                 set_win_state(win, WithdrawnState);
1617                 free(win);
1618
1619                 if (ws->r == NULL)
1620                         ws->restack = 1;
1621                 else
1622                         stack();
1623         }
1624 }
1625
1626 void
1627 enternotify(XEvent *e)
1628 {
1629         XCrossingEvent          *ev = &e->xcrossing;
1630         struct ws_win           *win;
1631         int                     i, j;
1632
1633         DNPRINTF(SWM_D_EVENT, "enternotify: window: %lu\n", ev->window);
1634
1635         if ((ev->mode != NotifyNormal || ev->detail == NotifyInferior) &&
1636             ev->window != ev->root)
1637                 return;
1638         if (ignore_enter) {
1639                 /* eat event(r) to prevent autofocus */
1640                 ignore_enter--;
1641                 return;
1642         }
1643         /* brute force for now */
1644         for (i = 0; i < ScreenCount(display); i++) {
1645                 for (j = 0; j < SWM_WS_MAX; j++) {
1646                         TAILQ_FOREACH(win, &screens[i].ws[j].winlist , entry) {
1647                                 if (win->id == ev->window)
1648                                         focus_win(win);
1649                         }
1650                 }
1651         }
1652 }
1653
1654 void
1655 focusin(XEvent *e)
1656 {
1657         DNPRINTF(SWM_D_EVENT, "focusin: window: %lu\n", e->xfocus.window);
1658
1659         /* XXX this probably needs better handling now.
1660         if (ev->window == ev->root)
1661                 return;
1662         */
1663         /*
1664          * kill grab for now so that we can cut and paste , this screws up
1665          * click to focus
1666          */
1667         /*
1668         DNPRINTF(SWM_D_EVENT, "focusin: window: %lu grabbing\n", ev->window);
1669         XGrabButton(display, Button1, AnyModifier, ev->window, False,
1670             ButtonPress, GrabModeAsync, GrabModeSync, None, None);
1671         */
1672 }
1673
1674 void
1675 mappingnotify(XEvent *e)
1676 {
1677         XMappingEvent           *ev = &e->xmapping;
1678
1679         DNPRINTF(SWM_D_EVENT, "mappingnotify: window: %lu\n", ev->window);
1680
1681         XRefreshKeyboardMapping(ev);
1682         if (ev->request == MappingKeyboard)
1683                 grabkeys();
1684 }
1685
1686 void
1687 maprequest(XEvent *e)
1688 {
1689         XMapRequestEvent        *ev = &e->xmaprequest;
1690         XWindowAttributes       wa;
1691         struct swm_region       *r;
1692
1693         DNPRINTF(SWM_D_EVENT, "maprequest: window: %lu\n",
1694             e->xmaprequest.window);
1695
1696         if (!XGetWindowAttributes(display, ev->window, &wa))
1697                 return;
1698         if (wa.override_redirect)
1699                 return;
1700         r = root_to_region(wa.root);
1701         manage_window(e->xmaprequest.window, r->ws);
1702         stack();
1703 }
1704
1705 void
1706 propertynotify(XEvent *e)
1707 {
1708         DNPRINTF(SWM_D_EVENT, "propertynotify: window: %lu\n",
1709             e->xproperty.window);
1710 }
1711
1712 void
1713 unmapnotify(XEvent *e)
1714 {
1715         DNPRINTF(SWM_D_EVENT, "unmapnotify: window: %lu\n", e->xunmap.window);
1716 }
1717
1718 void
1719 visibilitynotify(XEvent *e)
1720 {
1721         int                     i;
1722         struct swm_region       *r;
1723
1724         DNPRINTF(SWM_D_EVENT, "visibilitynotify: window: %lu\n",
1725             e->xvisibility.window);
1726         if (e->xvisibility.state == VisibilityUnobscured)
1727                 for (i = 0; i < ScreenCount(display); i++) 
1728                         TAILQ_FOREACH(r, &screens[i].rl, entry)
1729                                 if (e->xvisibility.window == r->bar_window)
1730                                         bar_update();
1731 }
1732
1733 void                    (*handler[LASTEvent])(XEvent *) = {
1734                                 [Expose] = expose,
1735                                 [KeyPress] = keypress,
1736                                 [ButtonPress] = buttonpress,
1737                                 [ConfigureRequest] = configurerequest,
1738                                 [ConfigureNotify] = configurenotify,
1739                                 [DestroyNotify] = destroynotify,
1740                                 [EnterNotify] = enternotify,
1741                                 [FocusIn] = focusin,
1742                                 [MappingNotify] = mappingnotify,
1743                                 [MapRequest] = maprequest,
1744                                 [PropertyNotify] = propertynotify,
1745                                 [UnmapNotify] = unmapnotify,
1746                                 [VisibilityNotify] = visibilitynotify,
1747 };
1748
1749 int
1750 xerror_start(Display *d, XErrorEvent *ee)
1751 {
1752         other_wm = 1;
1753         return (-1);
1754 }
1755
1756 int
1757 xerror(Display *d, XErrorEvent *ee)
1758 {
1759         /* fprintf(stderr, "error: %p %p\n", display, ee); */
1760         return (-1);
1761 }
1762
1763 int
1764 active_wm(void)
1765 {
1766         other_wm = 0;
1767         xerrorxlib = XSetErrorHandler(xerror_start);
1768
1769         /* this causes an error if some other window manager is running */
1770         XSelectInput(display, DefaultRootWindow(display),
1771             SubstructureRedirectMask);
1772         XSync(display, False);
1773         if (other_wm)
1774                 return (1);
1775
1776         XSetErrorHandler(xerror);
1777         XSync(display, False);
1778         return (0);
1779 }
1780
1781 long
1782 getstate(Window w)
1783 {
1784         int                     format, status;
1785         long                    result = -1;
1786         unsigned char           *p = NULL;
1787         unsigned long           n, extra;
1788         Atom                    real;
1789
1790         astate = XInternAtom(display, "WM_STATE", False);
1791         status = XGetWindowProperty(display, w, astate, 0L, 2L, False, astate,
1792             &real, &format, &n, &extra, (unsigned char **)&p);
1793         if (status != Success)
1794                 return (-1);
1795         if (n != 0)
1796                 result = *p;
1797         XFree(p);
1798         return (result);
1799 }
1800
1801 void
1802 new_region(struct swm_screen *s, struct workspace *ws,
1803     int x, int y, int w, int h)
1804 {
1805         struct swm_region       *r;
1806
1807         DNPRINTF(SWM_D_MISC, "new region on screen %d: %dx%d (%d, %d)\n",
1808              s->idx, x, y, w, h);
1809
1810         if ((r = calloc(1, sizeof(struct swm_region))) == NULL)
1811                 errx(1, "calloc: failed to allocate memory for screen");
1812
1813         X(r) = x;
1814         Y(r) = y;
1815         WIDTH(r) = w;
1816         HEIGHT(r) = h;
1817         r->s = s;
1818         r->ws = ws;
1819         ws->r = r;
1820         TAILQ_INSERT_TAIL(&s->rl, r, entry);
1821         bar_setup(r);
1822 }
1823
1824 void
1825 setup_screens(void)
1826 {
1827 #ifdef SWM_XRR_HAS_CRTC
1828         XRRCrtcInfo             *ci;
1829         XRRScreenResources      *sr;
1830         int                     c;
1831 #endif /* SWM_XRR_HAS_CRTC */
1832         Window                  d1, d2, *wins = NULL;
1833         XWindowAttributes       wa;
1834         struct swm_region       *r;
1835         unsigned int            no;
1836         int                     errorbase, major, minor;
1837         int                     ncrtc = 0, w = 0;
1838         int                     i, j, k;
1839         struct workspace        *ws;
1840
1841         if ((screens = calloc(ScreenCount(display),
1842              sizeof(struct swm_screen))) == NULL)
1843                 errx(1, "calloc: screens");
1844
1845         /* map physical screens */
1846         for (i = 0; i < ScreenCount(display); i++) {
1847                 DNPRINTF(SWM_D_WS, "setup_screens: init screen %d\n", i);
1848                 screens[i].idx = i;
1849                 TAILQ_INIT(&screens[i].rl);
1850                 screens[i].root = RootWindow(display, i);
1851                 XGetWindowAttributes(display, screens[i].root, &wa);
1852                 XSelectInput(display, screens[i].root,
1853                     ButtonPressMask | wa.your_event_mask);
1854
1855                 /* set default colors */
1856                 screens[i].color_focus = name_to_color("red");
1857                 screens[i].color_unfocus = name_to_color("rgb:88/88/88");
1858                 screens[i].bar_border = name_to_color("rgb:00/80/80");
1859                 screens[i].bar_color = name_to_color("black");
1860                 screens[i].bar_font_color = name_to_color("rgb:a0/a0/a0");
1861
1862                 /* init all workspaces */
1863                 for (j = 0; j < SWM_WS_MAX; j++) {
1864                         ws = &screens[i].ws[j];
1865                         ws->idx = j;
1866                         ws->restack = 1;
1867                         ws->focus = NULL;
1868                         ws->r = NULL;
1869                         TAILQ_INIT(&ws->winlist);
1870
1871                         for (k = 0; layouts[k].l_stack != NULL; k++)
1872                                 if (layouts[k].l_config != NULL)
1873                                         layouts[k].l_config(ws,
1874                                             SWM_ARG_ID_STACKINIT);
1875                         ws->cur_layout = &layouts[0];
1876                 }
1877
1878                 /* map virtual screens onto physical screens */
1879                 screens[i].xrandr_support = XRRQueryExtension(display,
1880                     &xrandr_eventbase, &errorbase);
1881                 if (screens[i].xrandr_support)
1882                         if (XRRQueryVersion(display, &major, &minor) &&
1883                             major < 1)
1884                                 screens[i].xrandr_support = 0;
1885
1886 #if 0   /* not ready for dynamic screen changes */
1887                 if (screens[i].xrandr_support)
1888                         XRRSelectInput(display,
1889                             screens[r->s].root,
1890                             RRScreenChangeNotifyMask);
1891 #endif
1892
1893                 /* grab existing windows (before we build the bars)*/
1894                 if (!XQueryTree(display, screens[i].root, &d1, &d2, &wins, &no))
1895                         continue;
1896
1897 #ifdef SWM_XRR_HAS_CRTC
1898                 sr = XRRGetScreenResources(display, screens[i].root);
1899                 if (sr == NULL)
1900                         new_region(&screens[i], &screens[i].ws[w],
1901                             0, 0, DisplayWidth(display, i),
1902                             DisplayHeight(display, i)); 
1903                 else 
1904                         ncrtc = sr->ncrtc;
1905
1906                 for (c = 0; c < ncrtc; c++) {
1907                         ci = XRRGetCrtcInfo(display, sr, sr->crtcs[c]);
1908                         if (ci->noutput == 0)
1909                                 continue;
1910
1911                         if (ci != NULL && ci->mode == None)
1912                                 new_region(&screens[i], &screens[i].ws[w], 0, 0,
1913                                     DisplayWidth(display, i),
1914                                     DisplayHeight(display, i)); 
1915                         else
1916                                 new_region(&screens[i], &screens[i].ws[w],
1917                                     ci->x, ci->y, ci->width, ci->height);
1918                         w++;
1919                 }
1920                 XRRFreeCrtcInfo(ci);
1921                 XRRFreeScreenResources(sr);
1922 #else
1923                 new_region(&screens[i], &screens[i].ws[w], 0, 0,
1924                     DisplayWidth(display, i),
1925                     DisplayHeight(display, i)); 
1926 #endif /* SWM_XRR_HAS_CRTC */
1927
1928                 /* attach windows to a region */
1929                 /* normal windows */
1930                 if ((r = TAILQ_FIRST(&screens[i].rl)) == NULL)
1931                         errx(1, "no regions on screen %d", i);
1932
1933                 for (i = 0; i < no; i++) {
1934                         XGetWindowAttributes(display, wins[i], &wa);
1935                         if (!XGetWindowAttributes(display, wins[i], &wa) ||
1936                             wa.override_redirect ||
1937                             XGetTransientForHint(display, wins[i], &d1))
1938                                 continue;
1939
1940                         if (wa.map_state == IsViewable ||
1941                             getstate(wins[i]) == NormalState)
1942                                 manage_window(wins[i], r->ws);
1943                 }
1944                 /* transient windows */
1945                 for (i = 0; i < no; i++) {
1946                         if (!XGetWindowAttributes(display, wins[i], &wa))
1947                                 continue;
1948
1949                         if (XGetTransientForHint(display, wins[i], &d1) &&
1950                             (wa.map_state == IsViewable || getstate(wins[i]) ==
1951                             NormalState))
1952                                 manage_window(wins[i], r->ws);
1953                 }
1954                 if (wins) {
1955                         XFree(wins);
1956                         wins = NULL;
1957                 }
1958         }
1959 }
1960
1961 int
1962 main(int argc, char *argv[])
1963 {
1964         struct passwd           *pwd;
1965         char                    conf[PATH_MAX], *cfile = NULL;
1966         struct stat             sb;
1967         XEvent                  e;
1968         int                     xfd;
1969         fd_set                  rd;
1970
1971         start_argv = argv;
1972         fprintf(stderr, "Welcome to scrotwm V%s\n", SWM_VERSION);
1973         if (!setlocale(LC_CTYPE, "") || !XSupportsLocale())
1974                 warnx("no locale support");
1975
1976         if (!(display = XOpenDisplay(0)))
1977                 errx(1, "can not open display");
1978
1979         if (active_wm())
1980                 errx(1, "other wm running");
1981
1982         astate = XInternAtom(display, "WM_STATE", False);
1983
1984         /* look for local and global conf file */
1985         pwd = getpwuid(getuid());
1986         if (pwd == NULL)
1987                 errx(1, "invalid user %d", getuid());
1988
1989         setup_screens();
1990
1991         snprintf(conf, sizeof conf, "%s/.%s", pwd->pw_dir, SWM_CONF_FILE);
1992         if (stat(conf, &sb) != -1) {
1993                 if (S_ISREG(sb.st_mode))
1994                         cfile = conf;
1995         } else {
1996                 /* try global conf file */
1997                 snprintf(conf, sizeof conf, "/etc/%s", SWM_CONF_FILE);
1998                 if (!stat(conf, &sb))
1999                         if (S_ISREG(sb.st_mode))
2000                                 cfile = conf;
2001         }
2002         if (cfile)
2003                 conf_load(cfile);
2004         bar_refresh();
2005
2006         /* ws[0].focus = TAILQ_FIRST(&ws[0].winlist); */
2007
2008         grabkeys();
2009         stack();
2010
2011         xfd = ConnectionNumber(display);
2012         while (running) {
2013                 FD_SET(xfd, &rd);
2014                 if (select(xfd + 1, &rd, NULL, NULL, NULL) == -1)
2015                         if (errno != EINTR)
2016                                 errx(1, "select failed");
2017                 if (bar_alarm) {
2018                         bar_alarm = 0;
2019                         bar_update();
2020                 }
2021                 while(XPending(display)) {
2022                         XNextEvent(display, &e);
2023                         if (handler[e.type])
2024                                 handler[e.type](&e);
2025                 }
2026         }
2027
2028         XCloseDisplay(display);
2029
2030         return (0);
2031 }