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