JasonWoof Got questions, comments, patches, etc.? Contact Jason Woofenden
Collapse focus and unfocus and brute force unfocs. This way we don't lose
[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 /* #define SWM_DEBUG */
94 #ifdef SWM_DEBUG
95 #define DPRINTF(x...)           do { if (swm_debug) fprintf(stderr, x); } while(0)
96 #define DNPRINTF(n,x...)        do { if (swm_debug & n) fprintf(stderr, x); } while(0)
97 #define SWM_D_MISC              0x0001
98 #define SWM_D_EVENT             0x0002
99 #define SWM_D_WS                0x0004
100 #define SWM_D_FOCUS             0x0008
101 #define SWM_D_MOVE              0x0010
102 #define SWM_D_STACK             0x0020
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
121 #define X(r)            (r)->g.x        
122 #define Y(r)            (r)->g.y
123 #define WIDTH(r)        (r)->g.w        
124 #define HEIGHT(r)       (r)->g.h
125
126 char                    **start_argv;
127 Atom                    astate;
128 int                     (*xerrorxlib)(Display *, XErrorEvent *);
129 int                     other_wm;
130 int                     running = 1;
131 int                     xrandr_eventbase;
132 int                     ignore_enter = 0;
133 unsigned int            numlockmask = 0;
134 Display                 *display;
135
136 int                     cycle_empty = 0;
137 int                     cycle_visible = 0;
138
139 /* dialog windows */
140 double                  dialog_ratio = .6;
141 /* status bar */
142 #define SWM_BAR_MAX     (128)
143 sig_atomic_t            bar_alarm = 0;
144 int                     bar_enabled = 1;
145 int                     bar_verbose = 1;
146 int                     bar_height = 0;
147 GC                      bar_gc;
148 XGCValues               bar_gcv;
149 XFontStruct             *bar_fs;
150 char                    *bar_fonts[] = {
151                             "-*-terminus-*-*-*-*-*-*-*-*-*-*-*-*",
152                             "-*-times-medium-r-*-*-*-*-*-*-*-*-*-*",
153                             NULL
154 };
155
156 /* terminal + args */
157 char                            *spawn_term[] = { "xterm", NULL };
158 char                            *spawn_menu[] = { "dmenu_run", NULL };
159
160 /* layout manager data */
161 struct swm_geometry {
162         int                     x;
163         int                     y;
164         int                     w;
165         int                     h;
166 };
167
168 struct swm_screen;
169 struct workspace;
170
171 /* virtual "screens" */
172 struct swm_region {
173         TAILQ_ENTRY(swm_region) entry;
174         struct swm_geometry     g;
175         Window                  bar_window;
176         struct workspace        *ws;    /* current workspace on this region */
177         struct swm_screen       *s;     /* screen idx */
178 }; 
179 TAILQ_HEAD(swm_region_list, swm_region);
180
181
182 struct ws_win {
183         TAILQ_ENTRY(ws_win)     entry;
184         Window                  id;
185         struct swm_geometry     g;
186         int                     got_focus;
187         int                     floating;
188         int                     transient;
189         struct workspace        *ws;    /* always valid */
190         struct swm_screen       *s;     /* always valid, never changes */
191         XWindowAttributes       wa;
192 };
193 TAILQ_HEAD(ws_win_list, ws_win);
194
195 /* layout handlers */
196 void    stack(void);
197 void    vertical_config(struct workspace *, int);
198 void    vertical_stack(struct workspace *, struct swm_geometry *);
199 void    horizontal_config(struct workspace *, int);
200 void    horizontal_stack(struct workspace *, struct swm_geometry *);
201 void    max_stack(struct workspace *, struct swm_geometry *);
202
203 struct layout {
204         void            (*l_stack)(struct workspace *, struct swm_geometry *);
205         void            (*l_config)(struct workspace *, int);
206 } layouts[] =  {
207         /* stack,               configure */
208         { vertical_stack,       vertical_config},
209         { horizontal_stack,     horizontal_config},
210         { max_stack,            NULL},
211         { NULL,                 NULL},
212 };
213
214 #define SWM_H_SLICE             (32)
215 #define SWM_V_SLICE             (32)
216
217 /* define work spaces */
218 struct workspace {
219         int                     idx;            /* workspace index */
220         int                     restack;        /* restack on switch */
221         struct layout           *cur_layout;    /* current layout handlers */
222         struct ws_win           *focus;         /* may be NULL */
223         struct swm_region       *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_all(void)
717 {
718         struct ws_win           *win;
719         int                     i, j;
720
721         DNPRINTF(SWM_D_FOCUS, "unfocus_all:\n");
722
723         for (i = 0; i < ScreenCount(display); i++)
724                 for (j = 0; j < SWM_WS_MAX; j++)
725                         TAILQ_FOREACH(win, &screens[i].ws[j].winlist, entry) {
726                                 if (win->ws->r == NULL)
727                                         continue;
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         rootclick = 0;
745         unfocus_all();
746         win->ws->focus = win;
747         if (win->ws->r != NULL) {
748                 cur_focus = win;
749                 if (!win->got_focus)
750                         XSetWindowBorder(display, win->id,
751                             win->ws->r->s->color_focus);
752                 win->got_focus = 1;
753                 XSetInputFocus(display, win->id,
754                     RevertToPointerRoot, CurrentTime);
755         }
756 }
757
758 void
759 switchws(struct swm_region *r, union arg *args)
760 {
761         int                     wsid = args->id;
762         struct swm_region       *this_r, *other_r;
763         struct ws_win           *win;
764         struct workspace        *new_ws, *old_ws;
765
766         this_r = r;
767         old_ws = this_r->ws;
768         new_ws = &this_r->s->ws[wsid];
769
770         DNPRINTF(SWM_D_WS, "switchws screen %d region %dx%d+%d+%d: "
771             "%d -> %d\n", r->s->idx, WIDTH(r), HEIGHT(r), X(r), Y(r),
772             old_ws->idx, wsid);
773
774         if (new_ws == old_ws)
775                 return;
776
777         other_r = new_ws->r;
778         if (!other_r) {
779                 /* if the other workspace is hidden, switch windows */
780                 /* map new window first to prevent ugly blinking */
781                 TAILQ_FOREACH(win, &new_ws->winlist, entry)
782                         XMapRaised(display, win->id);
783
784                 TAILQ_FOREACH(win, &old_ws->winlist, entry)
785                         XUnmapWindow(display, win->id);
786
787                 old_ws->r = NULL;
788                 old_ws->restack = 1;
789         } else {
790                 other_r->ws = old_ws;
791                 old_ws->r = other_r;
792         }
793         this_r->ws = new_ws;
794         new_ws->r = this_r;
795
796         ignore_enter = 1;
797         /* set focus */
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         struct workspace        *ws;
1597
1598         DNPRINTF(SWM_D_EVENT, "destroynotify: window %lu\n", ev->window);
1599
1600         if ((win = find_window(ev->window)) != NULL) {
1601                 ws = win->ws;
1602                 /* find a window to focus */
1603                 if (ws->focus == win)
1604                         ws->focus = TAILQ_PREV(win, ws_win_list, entry);
1605                 if (ws->focus == NULL)
1606                         ws->focus = TAILQ_FIRST(&ws->winlist);
1607                 if (ws->focus == win)
1608                         ws->focus = NULL;
1609                 if (cur_focus == win)
1610                         focus_win(ws->focus);
1611
1612                 TAILQ_REMOVE(&ws->winlist, win, entry);
1613                 set_win_state(win, WithdrawnState);
1614                 free(win);
1615         }
1616         stack();
1617 }
1618
1619 void
1620 enternotify(XEvent *e)
1621 {
1622         XCrossingEvent          *ev = &e->xcrossing;
1623         struct ws_win           *win;
1624         int                     i, j;
1625
1626         DNPRINTF(SWM_D_EVENT, "enternotify: window: %lu\n", ev->window);
1627
1628         if ((ev->mode != NotifyNormal || ev->detail == NotifyInferior) &&
1629             ev->window != ev->root)
1630                 return;
1631         if (ignore_enter) {
1632                 /* eat event(r) to prevent autofocus */
1633                 ignore_enter--;
1634                 return;
1635         }
1636         /* brute force for now */
1637         for (i = 0; i < ScreenCount(display); i++) {
1638                 for (j = 0; j < SWM_WS_MAX; j++) {
1639                         TAILQ_FOREACH(win, &screens[i].ws[j].winlist , entry) {
1640                                 if (win->id == ev->window)
1641                                         focus_win(win);
1642                         }
1643                 }
1644         }
1645 }
1646
1647 void
1648 focusin(XEvent *e)
1649 {
1650         DNPRINTF(SWM_D_EVENT, "focusin: window: %lu\n", e->xfocus.window);
1651
1652         /* XXX this probably needs better handling now.
1653         if (ev->window == ev->root)
1654                 return;
1655         */
1656         /*
1657          * kill grab for now so that we can cut and paste , this screws up
1658          * click to focus
1659          */
1660         /*
1661         DNPRINTF(SWM_D_EVENT, "focusin: window: %lu grabbing\n", ev->window);
1662         XGrabButton(display, Button1, AnyModifier, ev->window, False,
1663             ButtonPress, GrabModeAsync, GrabModeSync, None, None);
1664         */
1665 }
1666
1667 void
1668 mappingnotify(XEvent *e)
1669 {
1670         XMappingEvent           *ev = &e->xmapping;
1671
1672         DNPRINTF(SWM_D_EVENT, "mappingnotify: window: %lu\n", ev->window);
1673
1674         XRefreshKeyboardMapping(ev);
1675         if (ev->request == MappingKeyboard)
1676                 grabkeys();
1677 }
1678
1679 void
1680 maprequest(XEvent *e)
1681 {
1682         XMapRequestEvent        *ev = &e->xmaprequest;
1683         XWindowAttributes       wa;
1684         struct swm_region       *r;
1685
1686         DNPRINTF(SWM_D_EVENT, "maprequest: window: %lu\n",
1687             e->xmaprequest.window);
1688
1689         if (!XGetWindowAttributes(display, ev->window, &wa))
1690                 return;
1691         if (wa.override_redirect)
1692                 return;
1693         r = root_to_region(wa.root);
1694         manage_window(e->xmaprequest.window, r->ws);
1695         stack();
1696 }
1697
1698 void
1699 propertynotify(XEvent *e)
1700 {
1701         DNPRINTF(SWM_D_EVENT, "propertynotify: window: %lu\n",
1702             e->xproperty.window);
1703 }
1704
1705 void
1706 unmapnotify(XEvent *e)
1707 {
1708         DNPRINTF(SWM_D_EVENT, "unmapnotify: window: %lu\n", e->xunmap.window);
1709 }
1710
1711 void
1712 visibilitynotify(XEvent *e)
1713 {
1714         int                     i;
1715         struct swm_region       *r;
1716
1717         DNPRINTF(SWM_D_EVENT, "visibilitynotify: window: %lu\n",
1718             e->xvisibility.window);
1719         if (e->xvisibility.state == VisibilityUnobscured)
1720                 for (i = 0; i < ScreenCount(display); i++) 
1721                         TAILQ_FOREACH(r, &screens[i].rl, entry)
1722                                 if (e->xvisibility.window == r->bar_window)
1723                                         bar_update();
1724 }
1725
1726 void                    (*handler[LASTEvent])(XEvent *) = {
1727                                 [Expose] = expose,
1728                                 [KeyPress] = keypress,
1729                                 [ButtonPress] = buttonpress,
1730                                 [ConfigureRequest] = configurerequest,
1731                                 [ConfigureNotify] = configurenotify,
1732                                 [DestroyNotify] = destroynotify,
1733                                 [EnterNotify] = enternotify,
1734                                 [FocusIn] = focusin,
1735                                 [MappingNotify] = mappingnotify,
1736                                 [MapRequest] = maprequest,
1737                                 [PropertyNotify] = propertynotify,
1738                                 [UnmapNotify] = unmapnotify,
1739                                 [VisibilityNotify] = visibilitynotify,
1740 };
1741
1742 int
1743 xerror_start(Display *d, XErrorEvent *ee)
1744 {
1745         other_wm = 1;
1746         return (-1);
1747 }
1748
1749 int
1750 xerror(Display *d, XErrorEvent *ee)
1751 {
1752         /* fprintf(stderr, "error: %p %p\n", display, ee); */
1753         return (-1);
1754 }
1755
1756 int
1757 active_wm(void)
1758 {
1759         other_wm = 0;
1760         xerrorxlib = XSetErrorHandler(xerror_start);
1761
1762         /* this causes an error if some other window manager is running */
1763         XSelectInput(display, DefaultRootWindow(display),
1764             SubstructureRedirectMask);
1765         XSync(display, False);
1766         if (other_wm)
1767                 return (1);
1768
1769         XSetErrorHandler(xerror);
1770         XSync(display, False);
1771         return (0);
1772 }
1773
1774 long
1775 getstate(Window w)
1776 {
1777         int                     format, status;
1778         long                    result = -1;
1779         unsigned char           *p = NULL;
1780         unsigned long           n, extra;
1781         Atom                    real;
1782
1783         astate = XInternAtom(display, "WM_STATE", False);
1784         status = XGetWindowProperty(display, w, astate, 0L, 2L, False, astate,
1785             &real, &format, &n, &extra, (unsigned char **)&p);
1786         if (status != Success)
1787                 return (-1);
1788         if (n != 0)
1789                 result = *p;
1790         XFree(p);
1791         return (result);
1792 }
1793
1794 void
1795 new_region(struct swm_screen *s, struct workspace *ws,
1796     int x, int y, int w, int h)
1797 {
1798         struct swm_region       *r;
1799
1800         DNPRINTF(SWM_D_MISC, "new region on screen %d: %dx%d (%d, %d)\n",
1801              s->idx, x, y, w, h);
1802
1803         if ((r = calloc(1, sizeof(struct swm_region))) == NULL)
1804                 errx(1, "calloc: failed to allocate memory for screen");
1805
1806         X(r) = x;
1807         Y(r) = y;
1808         WIDTH(r) = w;
1809         HEIGHT(r) = h;
1810         r->s = s;
1811         r->ws = ws;
1812         ws->r = r;
1813         TAILQ_INSERT_TAIL(&s->rl, r, entry);
1814         bar_setup(r);
1815 }
1816
1817 void
1818 setup_screens(void)
1819 {
1820 #ifdef SWM_XRR_HAS_CRTC
1821         XRRCrtcInfo             *ci;
1822         XRRScreenResources      *sr;
1823         int                     c;
1824 #endif /* SWM_XRR_HAS_CRTC */
1825         Window                  d1, d2, *wins = NULL;
1826         XWindowAttributes       wa;
1827         struct swm_region       *r;
1828         unsigned int            no;
1829         int                     errorbase, major, minor;
1830         int                     ncrtc = 0, w = 0;
1831         int                     i, j, k;
1832         struct workspace        *ws;
1833
1834         if ((screens = calloc(ScreenCount(display),
1835              sizeof(struct swm_screen))) == NULL)
1836                 errx(1, "calloc: screens");
1837
1838         /* map physical screens */
1839         for (i = 0; i < ScreenCount(display); i++) {
1840                 DNPRINTF(SWM_D_WS, "setup_screens: init screen %d\n", i);
1841                 screens[i].idx = i;
1842                 TAILQ_INIT(&screens[i].rl);
1843                 screens[i].root = RootWindow(display, i);
1844                 XGetWindowAttributes(display, screens[i].root, &wa);
1845                 XSelectInput(display, screens[i].root,
1846                     ButtonPressMask | wa.your_event_mask);
1847
1848                 /* set default colors */
1849                 screens[i].color_focus = name_to_color("red");
1850                 screens[i].color_unfocus = name_to_color("rgb:88/88/88");
1851                 screens[i].bar_border = name_to_color("rgb:00/80/80");
1852                 screens[i].bar_color = name_to_color("black");
1853                 screens[i].bar_font_color = name_to_color("rgb:a0/a0/a0");
1854
1855                 /* init all workspaces */
1856                 for (j = 0; j < SWM_WS_MAX; j++) {
1857                         ws = &screens[i].ws[j];
1858                         ws->idx = j;
1859                         ws->restack = 1;
1860                         ws->focus = NULL;
1861                         ws->r = NULL;
1862                         TAILQ_INIT(&ws->winlist);
1863
1864                         for (k = 0; layouts[k].l_stack != NULL; k++)
1865                                 if (layouts[k].l_config != NULL)
1866                                         layouts[k].l_config(ws,
1867                                             SWM_ARG_ID_STACKINIT);
1868                         ws->cur_layout = &layouts[0];
1869                 }
1870
1871                 /* map virtual screens onto physical screens */
1872                 screens[i].xrandr_support = XRRQueryExtension(display,
1873                     &xrandr_eventbase, &errorbase);
1874                 if (screens[i].xrandr_support)
1875                         if (XRRQueryVersion(display, &major, &minor) &&
1876                             major < 1)
1877                                 screens[i].xrandr_support = 0;
1878
1879 #if 0   /* not ready for dynamic screen changes */
1880                 if (screens[i].xrandr_support)
1881                         XRRSelectInput(display,
1882                             screens[r->s].root,
1883                             RRScreenChangeNotifyMask);
1884 #endif
1885
1886                 /* grab existing windows (before we build the bars)*/
1887                 if (!XQueryTree(display, screens[i].root, &d1, &d2, &wins, &no))
1888                         continue;
1889
1890 #ifdef SWM_XRR_HAS_CRTC
1891                 sr = XRRGetScreenResources(display, screens[i].root);
1892                 if (sr == NULL)
1893                         new_region(&screens[i], &screens[i].ws[w],
1894                             0, 0, DisplayWidth(display, i),
1895                             DisplayHeight(display, i)); 
1896                 else 
1897                         ncrtc = sr->ncrtc;
1898
1899                 for (c = 0; c < ncrtc; c++) {
1900                         ci = XRRGetCrtcInfo(display, sr, sr->crtcs[c]);
1901                         if (ci->noutput == 0)
1902                                 continue;
1903
1904                         if (ci != NULL && ci->mode == None)
1905                                 new_region(&screens[i], &screens[i].ws[w], 0, 0,
1906                                     DisplayWidth(display, i),
1907                                     DisplayHeight(display, i)); 
1908                         else
1909                                 new_region(&screens[i], &screens[i].ws[w],
1910                                     ci->x, ci->y, ci->width, ci->height);
1911                         w++;
1912                 }
1913                 XRRFreeCrtcInfo(ci);
1914                 XRRFreeScreenResources(sr);
1915 #else
1916                 new_region(&screens[i], &screens[i].ws[w], 0, 0,
1917                     DisplayWidth(display, i),
1918                     DisplayHeight(display, i)); 
1919 #endif /* SWM_XRR_HAS_CRTC */
1920
1921                 /* attach windows to a region */
1922                 /* normal windows */
1923                 if ((r = TAILQ_FIRST(&screens[i].rl)) == NULL)
1924                         errx(1, "no regions on screen %d", i);
1925
1926                 for (i = 0; i < no; i++) {
1927                         XGetWindowAttributes(display, wins[i], &wa);
1928                         if (!XGetWindowAttributes(display, wins[i], &wa) ||
1929                             wa.override_redirect ||
1930                             XGetTransientForHint(display, wins[i], &d1))
1931                                 continue;
1932
1933                         if (wa.map_state == IsViewable ||
1934                             getstate(wins[i]) == NormalState)
1935                                 manage_window(wins[i], r->ws);
1936                 }
1937                 /* transient windows */
1938                 for (i = 0; i < no; i++) {
1939                         if (!XGetWindowAttributes(display, wins[i], &wa))
1940                                 continue;
1941
1942                         if (XGetTransientForHint(display, wins[i], &d1) &&
1943                             (wa.map_state == IsViewable || getstate(wins[i]) ==
1944                             NormalState))
1945                                 manage_window(wins[i], r->ws);
1946                 }
1947                 if (wins) {
1948                         XFree(wins);
1949                         wins = NULL;
1950                 }
1951         }
1952 }
1953
1954 int
1955 main(int argc, char *argv[])
1956 {
1957         struct passwd           *pwd;
1958         char                    conf[PATH_MAX], *cfile = NULL;
1959         struct stat             sb;
1960         XEvent                  e;
1961         int                     xfd;
1962         fd_set                  rd;
1963
1964         start_argv = argv;
1965         fprintf(stderr, "Welcome to scrotwm V%s\n", SWM_VERSION);
1966         if (!setlocale(LC_CTYPE, "") || !XSupportsLocale())
1967                 warnx("no locale support");
1968
1969         if (!(display = XOpenDisplay(0)))
1970                 errx(1, "can not open display");
1971
1972         if (active_wm())
1973                 errx(1, "other wm running");
1974
1975         astate = XInternAtom(display, "WM_STATE", False);
1976
1977         /* look for local and global conf file */
1978         pwd = getpwuid(getuid());
1979         if (pwd == NULL)
1980                 errx(1, "invalid user %d", getuid());
1981
1982         setup_screens();
1983
1984         snprintf(conf, sizeof conf, "%s/.%s", pwd->pw_dir, SWM_CONF_FILE);
1985         if (stat(conf, &sb) != -1) {
1986                 if (S_ISREG(sb.st_mode))
1987                         cfile = conf;
1988         } else {
1989                 /* try global conf file */
1990                 snprintf(conf, sizeof conf, "/etc/%s", SWM_CONF_FILE);
1991                 if (!stat(conf, &sb))
1992                         if (S_ISREG(sb.st_mode))
1993                                 cfile = conf;
1994         }
1995         if (cfile)
1996                 conf_load(cfile);
1997         bar_refresh();
1998
1999         /* ws[0].focus = TAILQ_FIRST(&ws[0].winlist); */
2000
2001         grabkeys();
2002         stack();
2003
2004         xfd = ConnectionNumber(display);
2005         while (running) {
2006                 FD_SET(xfd, &rd);
2007                 if (select(xfd + 1, &rd, NULL, NULL, NULL) == -1)
2008                         if (errno != EINTR)
2009                                 errx(1, "select failed");
2010                 if (bar_alarm) {
2011                         bar_alarm = 0;
2012                         bar_update();
2013                 }
2014                 while(XPending(display)) {
2015                         XNextEvent(display, &e);
2016                         if (handler[e.type])
2017                                 handler[e.type](&e);
2018                 }
2019         }
2020
2021         XCloseDisplay(display);
2022
2023         return (0);
2024 }