JasonWoof Got questions, comments, patches, etc.? Contact Jason Woofenden
Bump version for snap
[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 static const char       *cvstag = "$scrotwm$";
52
53 #define SWM_VERSION     "0.7"
54
55 #include <stdio.h>
56 #include <stdlib.h>
57 #include <err.h>
58 #include <errno.h>
59 #include <fcntl.h>
60 #include <locale.h>
61 #include <unistd.h>
62 #include <time.h>
63 #include <signal.h>
64 #include <string.h>
65 #include <util.h>
66 #include <pwd.h>
67 #include <ctype.h>
68
69 #include <sys/types.h>
70 #include <sys/time.h>
71 #include <sys/stat.h>
72 #include <sys/wait.h>
73 #include <sys/queue.h>
74 #include <sys/param.h>
75 #include <sys/select.h>
76
77 #include <X11/cursorfont.h>
78 #include <X11/keysym.h>
79 #include <X11/Xatom.h>
80 #include <X11/Xlib.h>
81 #include <X11/Xproto.h>
82 #include <X11/Xutil.h>
83 #include <X11/extensions/Xrandr.h>
84
85 #if RANDR_MAJOR < 1
86 #  error XRandR versions less than 1.0 are not supported
87 #endif
88
89 #if RANDR_MAJOR >= 1
90 #if RANDR_MINOR >= 2
91 #define SWM_XRR_HAS_CRTC
92 #endif
93 #endif
94
95 /* #define SWM_DEBUG */
96 #ifdef SWM_DEBUG
97 #define DPRINTF(x...)           do { if (swm_debug) fprintf(stderr, x); } while(0)
98 #define DNPRINTF(n,x...)        do { if (swm_debug & n) fprintf(stderr, x); } while(0)
99 #define SWM_D_MISC              0x0001
100 #define SWM_D_EVENT             0x0002
101 #define SWM_D_WS                0x0004
102 #define SWM_D_FOCUS             0x0008
103 #define SWM_D_MOVE              0x0010
104 #define SWM_D_STACK             0x0020
105 #define SWM_D_MOUSE             0x0040
106 #define SWM_D_PROP              0x0080
107 #define SWM_D_CLASS             0x0100
108
109 u_int32_t               swm_debug = 0
110                             | SWM_D_MISC
111                             | SWM_D_EVENT
112                             | SWM_D_WS
113                             | SWM_D_FOCUS
114                             | SWM_D_MOVE
115                             | SWM_D_STACK
116                             | SWM_D_MOUSE
117                             | SWM_D_PROP
118                             | SWM_D_CLASS
119                             ;
120 #else
121 #define DPRINTF(x...)
122 #define DNPRINTF(n,x...)
123 #endif
124
125 #define LENGTH(x)               (sizeof x / sizeof x[0])
126 #define MODKEY                  Mod1Mask
127 #define CLEANMASK(mask)         (mask & ~(numlockmask | LockMask))
128 #define BUTTONMASK              (ButtonPressMask|ButtonReleaseMask)
129 #define MOUSEMASK               (BUTTONMASK|PointerMotionMask)
130 #define SWM_PROPLEN             (16)
131 #define X(r)                    (r)->g.x        
132 #define Y(r)                    (r)->g.y
133 #define WIDTH(r)                (r)->g.w        
134 #define HEIGHT(r)               (r)->g.h
135
136 #ifndef SWM_LIB
137 #define SWM_LIB                 "/usr/X11R6/lib/swmhack.so"
138 #endif
139
140 char                    **start_argv;
141 Atom                    astate;
142 int                     (*xerrorxlib)(Display *, XErrorEvent *);
143 int                     other_wm;
144 int                     running = 1;
145 int                     ss_enabled = 0;
146 int                     xrandr_eventbase;
147 int                     ignore_enter = 0;
148 unsigned int            numlockmask = 0;
149 Display                 *display;
150
151 int                     cycle_empty = 0;
152 int                     cycle_visible = 0;
153
154 /* dialog windows */
155 double                  dialog_ratio = .6;
156 /* status bar */
157 #define SWM_BAR_MAX     (128)
158 char                    *bar_argv[] = { NULL, NULL };
159 int                     bar_pipe[2];
160 char                    bar_ext[SWM_BAR_MAX];
161 char                    bar_vertext[SWM_BAR_MAX];
162 int                     bar_version = 0;
163 sig_atomic_t            bar_alarm = 0;
164 int                     bar_delay = 30;
165 int                     bar_enabled = 1;
166 int                     bar_extra = 1;
167 int                     bar_extra_running = 0;
168 int                     bar_verbose = 1;
169 int                     bar_height = 0;
170 pid_t                   bar_pid;
171 GC                      bar_gc;
172 XGCValues               bar_gcv;
173 int                     bar_fidx = 0;
174 XFontStruct             *bar_fs;
175 char                    *bar_fonts[] = {
176                             "-*-terminus-*-*-*-*-*-*-*-*-*-*-*-*",
177                             "-*-times-medium-r-*-*-*-*-*-*-*-*-*-*",
178                             NULL
179 };
180
181 /* terminal + args */
182 char                    *spawn_term[] = { "xterm", NULL };
183 char                    *spawn_screenshot[] = { "screenshot.sh", NULL, NULL };
184 char                    *spawn_menu[] = { "dmenu_run", "-fn", NULL, "-nb", NULL,
185                             "-nf", NULL, "-sb", NULL, "-sf", NULL, NULL };
186
187 #define SWM_MENU_FN     (2)
188 #define SWM_MENU_NB     (4)
189 #define SWM_MENU_NF     (6)
190 #define SWM_MENU_SB     (8)
191 #define SWM_MENU_SF     (10)
192
193 /* layout manager data */
194 struct swm_geometry {
195         int                     x;
196         int                     y;
197         int                     w;
198         int                     h;
199 };
200
201 struct swm_screen;
202 struct workspace;
203
204 /* virtual "screens" */
205 struct swm_region {
206         TAILQ_ENTRY(swm_region) entry;
207         struct swm_geometry     g;
208         Window                  bar_window;
209         struct workspace        *ws;    /* current workspace on this region */
210         struct swm_screen       *s;     /* screen idx */
211 }; 
212 TAILQ_HEAD(swm_region_list, swm_region);
213
214 struct ws_win {
215         TAILQ_ENTRY(ws_win)     entry;
216         Window                  id;
217         struct swm_geometry     g;
218         int                     got_focus;
219         int                     floating;
220         int                     transient;
221         int                     manual;
222         struct workspace        *ws;    /* always valid */
223         struct swm_screen       *s;     /* always valid, never changes */
224         XWindowAttributes       wa;
225         XSizeHints              sh;
226         XClassHint              ch;
227 };
228 TAILQ_HEAD(ws_win_list, ws_win);
229
230 /* layout handlers */
231 void    stack(void);
232 void    vertical_config(struct workspace *, int);
233 void    vertical_stack(struct workspace *, struct swm_geometry *);
234 void    horizontal_config(struct workspace *, int);
235 void    horizontal_stack(struct workspace *, struct swm_geometry *);
236 void    max_stack(struct workspace *, struct swm_geometry *);
237
238 void    grabbuttons(struct ws_win *, int);
239
240 struct layout {
241         void            (*l_stack)(struct workspace *, struct swm_geometry *);
242         void            (*l_config)(struct workspace *, int);
243 } layouts[] =  {
244         /* stack,               configure */
245         { vertical_stack,       vertical_config},
246         { horizontal_stack,     horizontal_config},
247         { max_stack,            NULL},
248         { NULL,                 NULL},
249 };
250
251 #define SWM_H_SLICE             (32)
252 #define SWM_V_SLICE             (32)
253
254 /* define work spaces */
255 struct workspace {
256         int                     idx;            /* workspace index */
257         int                     restack;        /* restack on switch */
258         struct layout           *cur_layout;    /* current layout handlers */
259         struct ws_win           *focus;         /* may be NULL */
260         struct swm_region       *r;             /* may be NULL */
261         struct ws_win_list      winlist;        /* list of windows in ws */
262
263         /* stacker state */
264         struct {
265                                 int horizontal_msize;
266                                 int horizontal_mwin;
267                                 int vertical_msize;
268                                 int vertical_mwin;
269         } l_state;
270 };
271
272 enum    { SWM_S_COLOR_BAR, SWM_S_COLOR_BAR_BORDER, SWM_S_COLOR_BAR_FONT,
273           SWM_S_COLOR_FOCUS, SWM_S_COLOR_UNFOCUS, SWM_S_COLOR_MAX };
274
275 /* physical screen mapping */
276 #define SWM_WS_MAX              (10)            /* XXX Too small? */
277 struct swm_screen {
278         int                     idx;            /* screen index */
279         struct swm_region_list  rl;     /* list of regions on this screen */
280         Window                  root;
281         int                     xrandr_support;
282         struct workspace        ws[SWM_WS_MAX];
283
284         /* colors */
285         struct {
286                 unsigned long   color;
287                 char            *name;
288         } c[SWM_S_COLOR_MAX];
289 };
290 struct swm_screen       *screens;
291 int                     num_screens;
292
293 struct ws_win           *cur_focus = NULL;
294
295 /* args to functions */
296 union arg {
297         int                     id;
298 #define SWM_ARG_ID_FOCUSNEXT    (0)
299 #define SWM_ARG_ID_FOCUSPREV    (1)
300 #define SWM_ARG_ID_FOCUSMAIN    (2)
301 #define SWM_ARG_ID_SWAPNEXT     (3)
302 #define SWM_ARG_ID_SWAPPREV     (4)
303 #define SWM_ARG_ID_SWAPMAIN     (5)
304 #define SWM_ARG_ID_MASTERSHRINK (6)
305 #define SWM_ARG_ID_MASTERGROW   (7)
306 #define SWM_ARG_ID_MASTERADD    (8)
307 #define SWM_ARG_ID_MASTERDEL    (9)
308 #define SWM_ARG_ID_STACKRESET   (10)
309 #define SWM_ARG_ID_STACKINIT    (11)
310 #define SWM_ARG_ID_CYCLEWS_UP   (12)
311 #define SWM_ARG_ID_CYCLEWS_DOWN (13)
312 #define SWM_ARG_ID_CYCLESC_UP   (14)
313 #define SWM_ARG_ID_CYCLESC_DOWN (15)
314 #define SWM_ARG_ID_SS_ALL       (0)
315 #define SWM_ARG_ID_SS_WINDOW    (1)
316 #define SWM_ARG_ID_DONTCENTER   (0)
317 #define SWM_ARG_ID_CENTER       (1)
318         char                    **argv;
319 };
320
321 /* quirks */
322 struct quirk {
323         char                    *class;
324         char                    *name;
325         unsigned long           quirk;
326 #define SWM_Q_FLOAT             (1<<0)
327 } quirks[] = {
328         { "MPlayer",            "xv",           SWM_Q_FLOAT },
329         { "OpenOffice.org 2.4", "VCLSalFrame",  SWM_Q_FLOAT },
330         { NULL,         NULL,           0},
331 };
332
333 /* events */
334 void                    expose(XEvent *);
335 void                    keypress(XEvent *);
336 void                    buttonpress(XEvent *);
337 void                    configurerequest(XEvent *);
338 void                    configurenotify(XEvent *);
339 void                    destroynotify(XEvent *);
340 void                    enternotify(XEvent *);
341 void                    focusin(XEvent *);
342 void                    mappingnotify(XEvent *);
343 void                    maprequest(XEvent *);
344 void                    propertynotify(XEvent *);
345 void                    unmapnotify(XEvent *);
346 void                    visibilitynotify(XEvent *);
347
348 void                    (*handler[LASTEvent])(XEvent *) = {
349                                 [Expose] = expose,
350                                 [KeyPress] = keypress,
351                                 [ButtonPress] = buttonpress,
352                                 [ConfigureRequest] = configurerequest,
353                                 [ConfigureNotify] = configurenotify,
354                                 [DestroyNotify] = destroynotify,
355                                 [EnterNotify] = enternotify,
356                                 [FocusIn] = focusin,
357                                 [MappingNotify] = mappingnotify,
358                                 [MapRequest] = maprequest,
359                                 [PropertyNotify] = propertynotify,
360                                 [UnmapNotify] = unmapnotify,
361                                 [VisibilityNotify] = visibilitynotify,
362 };
363
364 unsigned long
365 name_to_color(char *colorname)
366 {
367         Colormap                cmap;
368         Status                  status;
369         XColor                  screen_def, exact_def;
370         unsigned long           result = 0;
371         char                    cname[32] = "#";
372
373         cmap = DefaultColormap(display, screens[0].idx);
374         status = XAllocNamedColor(display, cmap, colorname,
375             &screen_def, &exact_def);
376         if (!status) {
377                 strlcat(cname, colorname + 2, sizeof cname - 1);
378                 status = XAllocNamedColor(display, cmap, cname, &screen_def,
379                     &exact_def);
380         }
381         if (status)
382                 result = screen_def.pixel;
383         else
384                 fprintf(stderr, "color '%s' not found.\n", colorname);
385
386         return (result);
387 }
388
389 void
390 setscreencolor(char *val, int i, int c)
391 {
392         if (i > 0 && i <= ScreenCount(display)) {
393                 screens[i - 1].c[c].color = name_to_color(val);
394                 if ((screens[i - 1].c[c].name = strdup(val)) == NULL)
395                         errx(1, "strdup");
396         } else if (i == -1) {
397                 for (i = 0; i < ScreenCount(display); i++)
398                         screens[i].c[c].color = name_to_color(val);
399                         if ((screens[i - 1].c[c].name = strdup(val)) == NULL)
400                                 errx(1, "strdup");
401         } else
402                 errx(1, "invalid screen index: %d out of bounds (maximum %d)\n",
403                     i, ScreenCount(display));
404 }
405
406 int
407 varmatch(char *var, char *name, int *index)
408 {
409         char                    *p, buf[5];
410         int                     i;
411
412         i = strncmp(var, name, 255);
413         if (index == NULL)
414                 return (i);
415
416         *index = -1;
417         if (i <= 0)
418                 return (i);
419         p = var + strlen(name);
420         if (*p++ != '[')
421                 return (i);
422         bzero(buf, sizeof buf);
423         i = 0;
424         while (isdigit(*p) && i < sizeof buf)
425                 buf[i++] = *p++;
426         if (i == 0 || i >= sizeof buf || *p != ']')
427                 return (1);
428         *index = strtonum(buf, 0, 99, NULL);
429         return (0);
430 }
431
432 /* conf file stuff */
433 #define SWM_CONF_WS     "\n= \t"
434 #define SWM_CONF_FILE   "scrotwm.conf"
435 int
436 conf_load(char *filename)
437 {
438         FILE                    *config;
439         char                    *line, *cp, *var, *val;
440         size_t                  len, lineno = 0;
441         int                     i, sc;
442
443         DNPRINTF(SWM_D_MISC, "conf_load: filename %s\n", filename);
444
445         if (filename == NULL)
446                 return (1);
447
448         if ((config = fopen(filename, "r")) == NULL)
449                 return (1);
450
451         for (sc = ScreenCount(display);;) {
452                 if ((line = fparseln(config, &len, &lineno, NULL, 0)) == NULL)
453                         if (feof(config))
454                                 break;
455                 cp = line;
456                 cp += (long)strspn(cp, SWM_CONF_WS);
457                 if (cp[0] == '\0') {
458                         /* empty line */
459                         free(line);
460                         continue;
461                 }
462                 if ((var = strsep(&cp, SWM_CONF_WS)) == NULL || cp == NULL)
463                         break;
464                 cp += (long)strspn(cp, SWM_CONF_WS);
465                 if ((val = strsep(&cp, SWM_CONF_WS)) == NULL)
466                         break;
467
468                 DNPRINTF(SWM_D_MISC, "conf_load: %s=%s\n",var ,val);
469                 switch (var[0]) {
470                 case 'b':
471                         if (!strncmp(var, "bar_enabled", strlen("bar_enabled")))
472                                 bar_enabled = atoi(val);
473                         else if (!varmatch(var, "bar_border", &i))
474                                 setscreencolor(val, i, SWM_S_COLOR_BAR_BORDER);
475                         else if (!varmatch(var, "bar_color", &i))
476                                 setscreencolor(val, i, SWM_S_COLOR_BAR);
477                         else if (!varmatch(var, "bar_font_color", &i))
478                                 setscreencolor(val, i, SWM_S_COLOR_BAR_FONT);
479                         else if (!strncmp(var, "bar_font", strlen("bar_font")))
480                                 asprintf(&bar_fonts[0], "%s", val);
481                         else if (!strncmp(var, "bar_action", strlen("bar_action")))
482                                 asprintf(&bar_argv[0], "%s", val);
483                         else if (!strncmp(var, "bar_delay", strlen("bar_delay")))
484                                 bar_delay = atoi(val);
485                         else
486                                 goto bad;
487                         break;
488
489                 case 'c':
490                         if (!varmatch(var, "color_focus", &i))
491                                 setscreencolor(val, i, SWM_S_COLOR_FOCUS);
492                         else if (!varmatch(var, "color_unfocus", &i))
493                                 setscreencolor(val, i, SWM_S_COLOR_UNFOCUS);
494                         else if (!strncmp(var, "cycle_empty", strlen("cycle_empty")))
495                                 cycle_visible = atoi(val);
496                         else if (!strncmp(var, "cycle_visible", strlen("cycle_visible")))
497                                 cycle_visible = atoi(val);
498                         else
499                                 goto bad;
500                         break;
501
502                 case 'd':
503                         if (!strncmp(var, "dialog_ratio",
504                             strlen("dialog_ratio"))) {
505                                 dialog_ratio = atof(val);
506                                 if (dialog_ratio > 1.0 || dialog_ratio <= .3)
507                                         dialog_ratio = .6;
508                         } else
509                                 goto bad;
510                         break;
511
512                 case 's':
513                         if (!strncmp(var, "spawn_term", strlen("spawn_term")))
514                                 asprintf(&spawn_term[0], "%s", val);
515                         if (!strncmp(var, "screenshot_enabled",
516                             strlen("screenshot_enabled")))
517                                 ss_enabled = atoi(val);
518                         if (!strncmp(var, "screenshot_app",
519                             strlen("screenshot_app")))
520                                 asprintf(&spawn_screenshot[0], "%s", val);
521                         break;
522                 default:
523                         goto bad;
524                 }
525                 free(line);
526         }
527
528         fclose(config);
529         return (0);
530
531 bad:
532         errx(1, "invalid conf file entry: %s=%s", var, val);
533 }
534
535 void
536 socket_setnonblock(int fd)
537 {
538         int                     flags;
539
540         if ((flags = fcntl(fd, F_GETFL, 0)) == -1)
541                 err(1, "fcntl F_GETFL");
542         flags |= O_NONBLOCK;
543         if ((flags = fcntl(fd, F_SETFL, flags)) == -1)
544                 err(1, "fcntl F_SETFL");
545 }
546
547 void
548 bar_print(struct swm_region *r, char *s)
549 {
550         XClearWindow(display, r->bar_window);
551         XSetForeground(display, bar_gc, r->s->c[SWM_S_COLOR_BAR_FONT].color);
552         XDrawString(display, r->bar_window, bar_gc, 4, bar_fs->ascent, s,
553             strlen(s));
554 }
555
556 void
557 bar_extra_stop(void)
558 {
559         if (bar_pipe[0]) {
560                 close(bar_pipe[0]);
561                 bzero(bar_pipe, sizeof bar_pipe);
562         }
563         if (bar_pid) {
564                 kill(bar_pid, SIGTERM);
565                 bar_pid = 0;
566         }
567         strlcpy(bar_ext, "", sizeof bar_ext);
568         bar_extra = 0;
569 }
570
571 void
572 bar_update(void)
573 {
574         time_t                  tmt;
575         struct tm               tm;
576         struct swm_region       *r;
577         int                     i, x;
578         size_t                  len;
579         char                    s[SWM_BAR_MAX];
580         char                    loc[SWM_BAR_MAX];
581         char                    *b;
582
583         if (bar_enabled == 0)
584                 return;
585
586         if (bar_extra && bar_extra_running) {
587                 /* ignore short reads; it'll correct itself */
588                 while ((b = fgetln(stdin, &len)) != NULL)
589                         if (b && b[len - 1] == '\n') {
590                                 b[len - 1] = '\0';
591                                 strlcpy(bar_ext, b, sizeof bar_ext);
592                         }
593                 if (b == NULL && errno != EAGAIN) {
594                         fprintf(stderr, "bar_extra failed: errno: %d %s\n",
595                             errno, strerror(errno));
596                         bar_extra_stop();
597                 }
598         } else
599                 strlcpy(bar_ext, "", sizeof bar_ext);
600
601         time(&tmt);
602         localtime_r(&tmt, &tm);
603         strftime(s, sizeof s, "%a %b %d %R %Z %Y", &tm);
604         for (i = 0; i < ScreenCount(display); i++) {
605                 x = 1;
606                 TAILQ_FOREACH(r, &screens[i].rl, entry) {
607                         snprintf(loc, sizeof loc, "%s     %d:%d    %s    %s",
608                             s, x++, r->ws->idx + 1, bar_ext, bar_vertext);
609                         bar_print(r, loc);
610                 }
611         }
612         XSync(display, False);
613         alarm(bar_delay);
614 }
615
616 void
617 bar_signal(int sig)
618 {
619         bar_alarm = 1;
620 }
621
622 void
623 bar_toggle(struct swm_region *r, union arg *args)
624 {
625         struct swm_region       *tmpr;
626         int                     i, j, sc = ScreenCount(display);
627
628         DNPRINTF(SWM_D_MISC, "bar_toggle\n");
629
630         if (bar_enabled) {
631                 for (i = 0; i < sc; i++)
632                         TAILQ_FOREACH(tmpr, &screens[i].rl, entry)
633                                 XUnmapWindow(display, tmpr->bar_window);
634         } else {
635                 for (i = 0; i < sc; i++)
636                         TAILQ_FOREACH(tmpr, &screens[i].rl, entry)
637                                 XMapRaised(display, tmpr->bar_window);
638         }
639         bar_enabled = !bar_enabled;
640         XSync(display, False);
641         for (i = 0; i < sc; i++)
642                 for (j = 0; j < SWM_WS_MAX; j++)
643                         screens[i].ws[j].restack = 1;
644
645         stack();
646         /* must be after stack */
647         for (i = 0; i < sc; i++)
648                 TAILQ_FOREACH(tmpr, &screens[i].rl, entry)
649                         bar_update();
650 }
651
652 void
653 bar_refresh(void)
654 {
655         XSetWindowAttributes    wa;
656         struct swm_region       *r;
657         int                     i;
658
659         /* do this here because the conf file is in memory */
660         if (bar_extra && bar_extra_running == 0 && bar_argv[0]) {
661                 /* launch external status app */
662                 bar_extra_running = 1;
663                 if (pipe(bar_pipe) == -1)
664                         err(1, "pipe error");
665                 socket_setnonblock(bar_pipe[0]);
666                 socket_setnonblock(bar_pipe[1]); /* XXX hmmm, really? */
667                 if (dup2(bar_pipe[0], 0) == -1)
668                         errx(1, "dup2");
669                 if (dup2(bar_pipe[1], 1) == -1)
670                         errx(1, "dup2");
671                 if (signal(SIGPIPE, SIG_IGN) == SIG_ERR)
672                         err(1, "could not disable SIGPIPE");
673                 switch (bar_pid = fork()) {
674                 case -1:
675                         err(1, "cannot fork");
676                         break;
677                 case 0: /* child */
678                         close(bar_pipe[0]);
679                         execvp(bar_argv[0], bar_argv);
680                         err(1, "%s external app failed", bar_argv[0]);
681                         break;
682                 default: /* parent */
683                         close(bar_pipe[1]);
684                         break;
685                 }
686         }
687
688         bzero(&wa, sizeof wa);
689         for (i = 0; i < ScreenCount(display); i++)
690                 TAILQ_FOREACH(r, &screens[i].rl, entry) {
691                         wa.border_pixel =
692                             screens[i].c[SWM_S_COLOR_BAR_BORDER].color;
693                         wa.background_pixel =
694                             screens[i].c[SWM_S_COLOR_BAR].color;
695                         XChangeWindowAttributes(display, r->bar_window,
696                             CWBackPixel | CWBorderPixel, &wa);
697                 }
698         bar_update();
699 }
700
701 void
702 bar_setup(struct swm_region *r)
703 {
704         int                     i;
705
706         for (i = 0; bar_fonts[i] != NULL; i++) {
707                 bar_fs = XLoadQueryFont(display, bar_fonts[i]);
708                 if (bar_fs) {
709                         bar_fidx = i;
710                         break;
711                 }
712         }
713         if (bar_fonts[i] == NULL)
714                         errx(1, "couldn't load font");
715         bar_height = bar_fs->ascent + bar_fs->descent + 3;
716
717         r->bar_window = XCreateSimpleWindow(display, 
718             r->s->root, X(r), Y(r), WIDTH(r) - 2, bar_height - 2,
719             1, r->s->c[SWM_S_COLOR_BAR_BORDER].color,
720             r->s->c[SWM_S_COLOR_BAR].color);
721         bar_gc = XCreateGC(display, r->bar_window, 0, &bar_gcv);
722         XSetFont(display, bar_gc, bar_fs->fid);
723         XSelectInput(display, r->bar_window, VisibilityChangeMask);
724         if (bar_enabled)
725                 XMapRaised(display, r->bar_window);
726         DNPRINTF(SWM_D_MISC, "bar_setup: bar_window %lu\n", r->bar_window);
727
728         if (signal(SIGALRM, bar_signal) == SIG_ERR)
729                 err(1, "could not install bar_signal");
730         bar_refresh();
731 }
732
733 void
734 version(struct swm_region *r, union arg *args)
735 {
736         bar_version = !bar_version;
737         if (bar_version)
738                 strlcpy(bar_vertext, cvstag, sizeof bar_vertext);
739         else
740                 strlcpy(bar_vertext, "", sizeof bar_vertext);
741         bar_update();
742 }
743
744 void
745 config_win(struct ws_win *win)
746 {
747         XConfigureEvent         ce;
748
749         DNPRINTF(SWM_D_MISC, "config_win: win %lu x %d y %d w %d h %d\n",
750             win->id, win->g.x, win->g.y, win->g.w, win->g.h);
751         ce.type = ConfigureNotify;
752         ce.display = display;
753         ce.event = win->id;
754         ce.window = win->id;
755         ce.x = win->g.x;
756         ce.y = win->g.y;
757         ce.width = win->g.w;
758         ce.height = win->g.h;
759         ce.border_width = 1; /* XXX store this! */
760         ce.above = None;
761         ce.override_redirect = False;
762         XSendEvent(display, win->id, False, StructureNotifyMask, (XEvent *)&ce);
763 }
764
765 int
766 count_win(struct workspace *ws, int count_transient)
767 {
768         struct ws_win           *win;
769         int                     count = 0;
770
771         TAILQ_FOREACH(win, &ws->winlist, entry) {
772                 if (count_transient == 0 && win->floating)
773                         continue;
774                 if (count_transient == 0 && win->transient)
775                         continue;
776                 count++;
777         }
778         DNPRINTF(SWM_D_MISC, "count_win: %d\n", count);
779
780         return (count);
781 }
782
783 void
784 quit(struct swm_region *r, union arg *args)
785 {
786         DNPRINTF(SWM_D_MISC, "quit\n");
787         running = 0;
788 }
789
790 void
791 unmap_all(void)
792 {
793         struct ws_win           *win;
794         int                     i, j;
795
796         for (i = 0; i < ScreenCount(display); i++)
797                 for (j = 0; j < SWM_WS_MAX; j++)
798                         TAILQ_FOREACH(win, &screens[i].ws[j].winlist, entry)
799                                 XUnmapWindow(display, win->id);
800 }
801
802 void
803 restart(struct swm_region *r, union arg *args)
804 {
805         DNPRINTF(SWM_D_MISC, "restart: %s\n", start_argv[0]);
806
807         /* disable alarm because the following code may not be interrupted */
808         alarm(0);
809         if (signal(SIGALRM, SIG_IGN) == SIG_ERR)
810                 errx(1, "can't disable alarm");
811
812         bar_extra_stop();
813         bar_extra = 1;
814         unmap_all();
815         XCloseDisplay(display);
816         execvp(start_argv[0], start_argv);
817         fprintf(stderr, "execvp failed\n");
818         perror(" failed");
819         quit(NULL, NULL);
820 }
821
822 struct swm_region *
823 root_to_region(Window root)
824 {
825         struct swm_region       *r;
826         Window                  rr, cr;
827         int                     i, x, y, wx, wy;
828         unsigned int            mask;
829
830         for (i = 0; i < ScreenCount(display); i++)
831                 if (screens[i].root == root)
832                         break;
833
834         if (XQueryPointer(display, screens[i].root, 
835             &rr, &cr, &x, &y, &wx, &wy, &mask) == False) {
836                 /* if we can't query the pointer, grab the first region */
837                 r = TAILQ_FIRST(&screens[i].rl);
838         } else {
839                 /* otherwise, choose a region based on pointer location */
840                 TAILQ_FOREACH(r, &screens[i].rl, entry) {
841                         if (x >= X(r) && x <= X(r) + WIDTH(r) &&
842                             y >= Y(r) && y <= Y(r) + HEIGHT(r))
843                                 break;
844                 }
845
846                 if (r == NULL)
847                         r = TAILQ_FIRST(&screens[i].rl);
848         }
849         return (r);
850 }
851
852 struct ws_win *
853 find_window(Window id)
854 {
855         struct ws_win           *win;
856         int                     i, j;
857
858         for (i = 0; i < ScreenCount(display); i++)
859                 for (j = 0; j < SWM_WS_MAX; j++)
860                         TAILQ_FOREACH(win, &screens[i].ws[j].winlist, entry)
861                                 if (id == win->id)
862                                         return (win);
863         return (NULL);
864 }
865
866 void
867 spawn(struct swm_region *r, union arg *args)
868 {
869         char                    *ret;
870         int                     si;
871
872         DNPRINTF(SWM_D_MISC, "spawn: %s\n", args->argv[0]);
873         /*
874          * The double-fork construct avoids zombie processes and keeps the code
875          * clean from stupid signal handlers.
876          */
877         if (fork() == 0) {
878                 if (fork() == 0) {
879                         if (display)
880                                 close(ConnectionNumber(display));
881                         setenv("LD_PRELOAD", SWM_LIB, 1);
882                         if (asprintf(&ret, "%d", r->ws->idx)) {
883                                 setenv("_SWM_WS", ret, 1);
884                                 free(ret);
885                         }
886                         if (asprintf(&ret, "%d", getpid())) {
887                                 setenv("_SWM_PID", ret, 1);
888                                 free(ret);
889                         }
890                         setsid();
891                         /* kill stdin, mplayer, ssh-add etc. need that */
892                         si = open("/dev/null", O_RDONLY, 0);
893                         if (si == -1)
894                                 err(1, "open /dev/null");
895                         if (dup2(si, 0) == -1)
896                                 err(1, "dup2 /dev/null");
897                         execvp(args->argv[0], args->argv);
898                         fprintf(stderr, "execvp failed\n");
899                         perror(" failed");
900                 }
901                 exit(0);
902         }
903         wait(0);
904 }
905
906 void
907 spawnmenu(struct swm_region *r, union arg *args)
908 {
909         DNPRINTF(SWM_D_MISC, "spawnmenu\n");
910
911         spawn_menu[SWM_MENU_FN] = bar_fonts[bar_fidx];
912         spawn_menu[SWM_MENU_NB] = r->s->c[SWM_S_COLOR_BAR].name;
913         spawn_menu[SWM_MENU_NF] = r->s->c[SWM_S_COLOR_BAR_FONT].name;
914         spawn_menu[SWM_MENU_SB] = r->s->c[SWM_S_COLOR_BAR_BORDER].name;
915         spawn_menu[SWM_MENU_SF] = r->s->c[SWM_S_COLOR_BAR].name;
916
917         spawn(r, args);
918 }
919
920 void
921 unfocus_all(void)
922 {
923         struct ws_win           *win;
924         int                     i, j;
925
926         DNPRINTF(SWM_D_FOCUS, "unfocus_all:\n");
927
928         for (i = 0; i < ScreenCount(display); i++)
929                 for (j = 0; j < SWM_WS_MAX; j++)
930                         TAILQ_FOREACH(win, &screens[i].ws[j].winlist, entry) {
931                                 if (win->ws->r == NULL)
932                                         continue;
933                                 grabbuttons(win, 0);
934                                 XSetWindowBorder(display, win->id,
935                                     win->ws->r->s->c[SWM_S_COLOR_UNFOCUS].color);
936                                 win->got_focus = 0;
937                                 win->ws->focus = NULL;
938                                 cur_focus = NULL;
939                         }
940 }
941
942 void
943 focus_win(struct ws_win *win)
944 {
945         DNPRINTF(SWM_D_FOCUS, "focus_win: id: %lu\n", win ? win->id : 0);
946
947         if (win == NULL)
948                 return;
949
950         unfocus_all();
951         win->ws->focus = win;
952         if (win->ws->r != NULL) {
953                 cur_focus = win;
954                 if (!win->got_focus) {
955                         XSetWindowBorder(display, win->id,
956                             win->ws->r->s->c[SWM_S_COLOR_FOCUS].color);
957                         grabbuttons(win, 1);
958                 }
959                 win->got_focus = 1;
960                 XSetInputFocus(display, win->id,
961                     RevertToPointerRoot, CurrentTime);
962         }
963 }
964
965 void
966 switchws(struct swm_region *r, union arg *args)
967 {
968         int                     wsid = args->id;
969         struct swm_region       *this_r, *other_r;
970         struct ws_win           *win;
971         struct workspace        *new_ws, *old_ws;
972
973         this_r = r;
974         old_ws = this_r->ws;
975         new_ws = &this_r->s->ws[wsid];
976
977         DNPRINTF(SWM_D_WS, "switchws screen %d region %dx%d+%d+%d: "
978             "%d -> %d\n", r->s->idx, WIDTH(r), HEIGHT(r), X(r), Y(r),
979             old_ws->idx, wsid);
980
981         if (new_ws == old_ws)
982                 return;
983
984         other_r = new_ws->r;
985         if (!other_r) {
986                 /* if the other workspace is hidden, switch windows */
987                 /* map new window first to prevent ugly blinking */
988                 TAILQ_FOREACH(win, &new_ws->winlist, entry)
989                         XMapRaised(display, win->id);
990
991                 TAILQ_FOREACH(win, &old_ws->winlist, entry)
992                         XUnmapWindow(display, win->id);
993                 old_ws->r = NULL;
994                 old_ws->restack = 1;
995         } else {
996                 other_r->ws = old_ws;
997                 old_ws->r = other_r;
998         }
999         this_r->ws = new_ws;
1000         new_ws->r = this_r;
1001
1002         ignore_enter = 1;
1003         /* set focus */
1004         if (new_ws->focus)
1005                 focus_win(new_ws->focus);
1006         stack();
1007         bar_update();
1008 }
1009
1010 void
1011 cyclews(struct swm_region *r, union arg *args)
1012 {
1013         union                   arg a;
1014         struct swm_screen       *s = r->s;
1015
1016         DNPRINTF(SWM_D_WS, "cyclews id %d "
1017             "in screen %d region %dx%d+%d+%d ws %d\n", args->id,
1018             r->s->idx, WIDTH(r), HEIGHT(r), X(r), Y(r), r->ws->idx);
1019
1020         a.id = r->ws->idx;
1021         do {
1022                 switch (args->id) {
1023                 case SWM_ARG_ID_CYCLEWS_UP:
1024                         if (a.id < SWM_WS_MAX - 1)
1025                                 a.id++;
1026                         else
1027                                 a.id = 0;
1028                         break;
1029                 case SWM_ARG_ID_CYCLEWS_DOWN:
1030                         if (a.id > 0)
1031                                 a.id--;
1032                         else
1033                                 a.id = SWM_WS_MAX - 1;
1034                         break;
1035                 default:
1036                         return;
1037                 };
1038
1039                 if (cycle_empty == 0 && TAILQ_EMPTY(&s->ws[a.id].winlist))
1040                         continue;
1041                 if (cycle_visible == 0 && s->ws[a.id].r != NULL)
1042                         continue;
1043
1044                 switchws(r, &a);
1045         } while (a.id != r->ws->idx);
1046 }
1047
1048 void
1049 cyclescr(struct swm_region *r, union arg *args)
1050 {
1051         struct swm_region       *rr;
1052         int                     i;
1053
1054         i = r->s->idx;
1055         switch (args->id) {
1056         case SWM_ARG_ID_CYCLESC_UP:
1057                 rr = TAILQ_NEXT(r, entry);
1058                 if (rr == NULL)
1059                         rr = TAILQ_FIRST(&screens[i].rl);
1060                 break;
1061         case SWM_ARG_ID_CYCLESC_DOWN:
1062                 rr = TAILQ_PREV(r, swm_region_list, entry);
1063                 if (rr == NULL)
1064                         rr = TAILQ_LAST(&screens[i].rl, swm_region_list);
1065                 break;
1066         default:
1067                 return;
1068         };
1069         unfocus_all();
1070         XSetInputFocus(display, PointerRoot, RevertToPointerRoot, CurrentTime);
1071         XWarpPointer(display, None, rr->s[i].root, 0, 0, 0, 0, rr->g.x,
1072             rr->g.y + bar_enabled ? bar_height : 0);
1073 }
1074
1075 void
1076 swapwin(struct swm_region *r, union arg *args)
1077 {
1078         struct ws_win           *target;
1079         struct ws_win_list      *wl;
1080
1081
1082         DNPRINTF(SWM_D_WS, "swapwin id %d "
1083             "in screen %d region %dx%d+%d+%d ws %d\n", args->id,
1084             r->s->idx, WIDTH(r), HEIGHT(r), X(r), Y(r), r->ws->idx);
1085         if (cur_focus == NULL)
1086                 return;
1087
1088         wl = &cur_focus->ws->winlist;
1089
1090         switch (args->id) {
1091         case SWM_ARG_ID_SWAPPREV:
1092                 target = TAILQ_PREV(cur_focus, ws_win_list, entry);
1093                 TAILQ_REMOVE(wl, cur_focus, entry);
1094                 if (target == NULL)
1095                         TAILQ_INSERT_TAIL(wl, cur_focus, entry);
1096                 else
1097                         TAILQ_INSERT_BEFORE(target, cur_focus, entry);
1098                 break;
1099         case SWM_ARG_ID_SWAPNEXT: 
1100                 target = TAILQ_NEXT(cur_focus, entry);
1101                 TAILQ_REMOVE(wl, cur_focus, entry);
1102                 if (target == NULL)
1103                         TAILQ_INSERT_HEAD(wl, cur_focus, entry);
1104                 else
1105                         TAILQ_INSERT_AFTER(wl, target, cur_focus, entry);
1106                 break;
1107         case SWM_ARG_ID_SWAPMAIN:
1108                 target = TAILQ_FIRST(wl);
1109                 if (target == cur_focus)
1110                         return;
1111                 TAILQ_REMOVE(wl, target, entry);
1112                 TAILQ_INSERT_BEFORE(cur_focus, target, entry);
1113                 TAILQ_REMOVE(wl, cur_focus, entry);
1114                 TAILQ_INSERT_HEAD(wl, cur_focus, entry);
1115                 break;
1116         default:
1117                 DNPRINTF(SWM_D_MOVE, "invalid id: %d\n", args->id);
1118                 return;
1119         }
1120
1121         ignore_enter = 2;
1122         stack();
1123 }
1124
1125 void
1126 focus(struct swm_region *r, union arg *args)
1127 {
1128         struct ws_win           *winfocus, *winlostfocus;
1129         struct ws_win_list      *wl;
1130
1131         DNPRINTF(SWM_D_FOCUS, "focus: id %d\n", args->id);
1132         if (cur_focus == NULL)
1133                 return;
1134
1135         wl = &cur_focus->ws->winlist;
1136
1137         winlostfocus = cur_focus;
1138
1139         switch (args->id) {
1140         case SWM_ARG_ID_FOCUSPREV:
1141                 winfocus = TAILQ_PREV(cur_focus, ws_win_list, entry);
1142                 if (winfocus == NULL)
1143                         winfocus = TAILQ_LAST(wl, ws_win_list);
1144                 break;
1145
1146         case SWM_ARG_ID_FOCUSNEXT:
1147                 winfocus = TAILQ_NEXT(cur_focus, entry);
1148                 if (winfocus == NULL)
1149                         winfocus = TAILQ_FIRST(wl);
1150                 break;
1151
1152         case SWM_ARG_ID_FOCUSMAIN:
1153                 winfocus = TAILQ_FIRST(wl);
1154                 break;
1155
1156         default:
1157                 return;
1158         }
1159
1160         if (winfocus == winlostfocus || winfocus == NULL)
1161                 return;
1162
1163         XMapRaised(display, winfocus->id);
1164         focus_win(winfocus);
1165         XSync(display, False);
1166 }
1167
1168 void
1169 cycle_layout(struct swm_region *r, union arg *args)
1170 {
1171         struct workspace        *ws = r->ws;
1172
1173         DNPRINTF(SWM_D_EVENT, "cycle_layout: workspace: %d\n", ws->idx);
1174
1175         ws->cur_layout++;
1176         if (ws->cur_layout->l_stack == NULL)
1177                 ws->cur_layout = &layouts[0];
1178         ignore_enter = 1;
1179         stack();
1180 }
1181
1182 void
1183 stack_config(struct swm_region *r, union arg *args)
1184 {
1185         struct workspace        *ws = r->ws;
1186
1187         DNPRINTF(SWM_D_STACK, "stack_config for workspace %d (id %d\n",
1188             args->id, ws->idx);
1189
1190         if (ws->cur_layout->l_config != NULL)
1191                 ws->cur_layout->l_config(ws, args->id);
1192
1193         if (args->id != SWM_ARG_ID_STACKINIT);
1194                 stack();
1195 }
1196
1197 void
1198 stack(void) {
1199         struct swm_geometry     g;
1200         struct swm_region       *r;
1201         int                     i, j;
1202
1203         DNPRINTF(SWM_D_STACK, "stack\n");
1204
1205         for (i = 0; i < ScreenCount(display); i++) {
1206                 j = 0;
1207                 TAILQ_FOREACH(r, &screens[i].rl, entry) {
1208                         DNPRINTF(SWM_D_STACK, "stacking workspace %d "
1209                             "(screen %d, region %d)\n", r->ws->idx, i, j++);
1210
1211                         /* start with screen geometry, adjust for bar */
1212                         g = r->g;
1213                         g.w -= 2;
1214                         g.h -= 2;
1215                         if (bar_enabled) {
1216                                 g.y += bar_height;
1217                                 g.h -= bar_height;
1218                         } 
1219
1220                         r->ws->restack = 0;
1221                         r->ws->cur_layout->l_stack(r->ws, &g);
1222                 }
1223         }
1224         XSync(display, False);
1225 }
1226
1227 void
1228 stack_floater(struct ws_win *win, struct swm_region *r)
1229 {
1230         unsigned int            mask;
1231         XWindowChanges          wc;
1232
1233         bzero(&wc, sizeof wc);
1234         mask = CWX | CWY | CWBorderWidth | CWWidth | CWHeight;
1235         wc.border_width = 1;
1236         if (win->transient) {
1237                 win->g.w = (double)WIDTH(r) * dialog_ratio;
1238                 win->g.h = (double)HEIGHT(r) * dialog_ratio;
1239         }
1240         wc.width = win->g.w;
1241         wc.height = win->g.h;
1242         if (win->manual) {
1243                 wc.x = win->g.x;
1244                 wc.y = win->g.y;
1245         } else {
1246                 wc.x = (WIDTH(r) - win->g.w) / 2;
1247                 wc.y = (HEIGHT(r) - win->g.h) / 2;
1248         }
1249
1250         DNPRINTF(SWM_D_STACK, "stack_floater: win %lu x %d y %d w %d h %d\n",
1251             win->id, wc.x, wc.y, wc.width, wc.height);
1252
1253         XConfigureWindow(display, win->id, mask, &wc);
1254 }
1255
1256 #define SWAPXY(g)       do {                            \
1257         int tmp;                                        \
1258         tmp = (g)->y; (g)->y = (g)->x; (g)->x = tmp;    \
1259         tmp = (g)->h; (g)->h = (g)->w; (g)->w = tmp;    \
1260 } while (0)
1261 void
1262 stack_master(struct workspace *ws, struct swm_geometry *g, int rot, int flip)
1263 {
1264         XWindowChanges          wc;
1265         struct swm_geometry     win_g, r_g = *g;
1266         struct ws_win           *win, *winfocus;
1267         int                     i, j, w_inc, h_inc, w_base, h_base;
1268         int                     hrh, extra, h_slice, last_h = 0;
1269         int                     split, colno, winno, mwin, msize, mscale;
1270         int                     remain, missing, v_slice;;
1271         unsigned int            mask;
1272
1273         DNPRINTF(SWM_D_STACK, "stack_master: workspace: %d\n rot=%s flip=%s",
1274             ws->idx, rot ? "yes" : "no", flip ? "yes" : "no");
1275
1276         if ((winno = count_win(ws, 0)) == 0)
1277                 return;
1278
1279         if (ws->focus == NULL)
1280                 ws->focus = TAILQ_FIRST(&ws->winlist);
1281         winfocus = cur_focus ? cur_focus : ws->focus;
1282
1283         win = TAILQ_FIRST(&ws->winlist);
1284         if (rot) {
1285                 w_inc = win->sh.width_inc;
1286                 w_base = win->sh.base_width;
1287                 mwin = ws->l_state.horizontal_mwin;
1288                 mscale = ws->l_state.horizontal_msize;
1289                 SWAPXY(&r_g);
1290         } else {
1291                 w_inc = win->sh.height_inc;
1292                 w_base = win->sh.base_height;
1293                 mwin = ws->l_state.vertical_mwin;
1294                 mscale = ws->l_state.vertical_msize;
1295         }
1296         win_g = r_g;
1297
1298         h_slice = r_g.h / SWM_H_SLICE;
1299         if (mwin && winno > mwin) {
1300                 v_slice = r_g.w / SWM_V_SLICE;
1301
1302                 split = mwin;
1303                 colno = split;
1304                 msize = v_slice * mscale;
1305
1306                 if (w_inc > 1 && w_inc < v_slice) {
1307                         /* adjust for window's requested size increment */
1308                         remain = (win_g.w - w_base) % w_inc;
1309                         missing = w_inc - remain;
1310
1311                         if (missing <= extra || j == 0) {
1312                                 extra -= missing;
1313                                 win_g.w += missing;
1314                         } else {
1315                                 win_g.w -= remain;
1316                                 extra += remain;
1317                         }
1318                 }
1319
1320                 win_g.w = msize;
1321                 if (flip) 
1322                         win_g.x += r_g.w - msize;
1323         } else {
1324                 colno = winno;
1325                 split = 0;
1326         }
1327         hrh = r_g.h / colno;
1328         extra = r_g.h - (colno * hrh);
1329         win_g.h = hrh - 2;
1330
1331         /*  stack all the tiled windows */
1332         i = j = 0;
1333         TAILQ_FOREACH(win, &ws->winlist, entry) {
1334                 if (win->transient != 0 || win->floating != 0)
1335                         continue;
1336
1337                 if (split && i == split) {
1338                         colno = winno - split;
1339                         hrh = (r_g.h / colno);
1340                         extra = r_g.h - (colno * hrh);
1341                         if (flip)
1342                                 win_g.x = r_g.x;
1343                         else
1344                                 win_g.x += msize + 2;
1345                         win_g.w = r_g.w - (msize + 2);
1346                         j = 0;
1347                 }
1348                 win_g.h = hrh - 2;
1349                 if (rot) {
1350                         h_inc = win->sh.width_inc;
1351                         h_base = win->sh.base_width;
1352                 } else {
1353                         h_inc = win->sh.height_inc;     
1354                         h_base = win->sh.base_height;
1355                 }
1356                 if (j == colno - 1) {
1357                         win_g.h = hrh + extra;
1358                 } else if (h_inc > 1 && h_inc < h_slice) {
1359                         /* adjust for window's requested size increment */
1360                         remain = (win_g.h - h_base) % h_inc;
1361                         missing = h_inc - remain;
1362
1363                         if (missing <= extra || j == 0) {
1364                                 extra -= missing;
1365                                 win_g.h += missing;
1366                         } else {
1367                                 win_g.h -= remain;
1368                                 extra += remain;
1369                         }
1370                 }
1371                  
1372                 if (j == 0)
1373                         win_g.y = r_g.y;
1374                 else
1375                         win_g.y += last_h + 2;
1376
1377                 bzero(&wc, sizeof wc);
1378                 wc.border_width = 1;
1379                 if (rot) {
1380                         win->g.x = wc.x = win_g.y;
1381                         win->g.y = wc.y = win_g.x;
1382                         win->g.w = wc.width = win_g.h;
1383                         win->g.h = wc.height = win_g.w;
1384                 } else {
1385                         win->g.x = wc.x = win_g.x;
1386                         win->g.y = wc.y = win_g.y;
1387                         win->g.w = wc.width = win_g.w;
1388                         win->g.h = wc.height = win_g.h;
1389                 }
1390                 mask = CWX | CWY | CWWidth | CWHeight | CWBorderWidth;
1391                 XConfigureWindow(display, win->id, mask, &wc);
1392                 XMapRaised(display, win->id);
1393                 /*
1394                 fprintf(stderr, "vertical_stack: win %d x %d y %d w %d h %d bw %d\n", win->id, win->g.x, win->g.y, win->g.w , win->g.h, wc.border_width);
1395                 */
1396
1397                 last_h = win_g.h;
1398                 i++;
1399                 j++;
1400         }
1401
1402         /* now, stack all the floaters and transients */
1403         TAILQ_FOREACH(win, &ws->winlist, entry) {
1404                 if (win->transient == 0 && win->floating == 0)
1405                         continue;
1406
1407                 stack_floater(win, ws->r);
1408                 XMapRaised(display, win->id);
1409         }
1410
1411         if (winfocus)
1412                 focus_win(winfocus); /* has to be done outside of the loop */
1413 }
1414
1415 void
1416 vertical_config(struct workspace *ws, int id)
1417 {
1418         DNPRINTF(SWM_D_STACK, "vertical_resize: workspace: %d\n", ws->idx);
1419
1420         switch (id) {
1421         case SWM_ARG_ID_STACKRESET:
1422         case SWM_ARG_ID_STACKINIT:
1423                 ws->l_state.vertical_msize = SWM_V_SLICE / 2;
1424                 ws->l_state.vertical_mwin = 1;
1425                 break;
1426         case SWM_ARG_ID_MASTERSHRINK:
1427                 if (ws->l_state.vertical_msize > 1)
1428                         ws->l_state.vertical_msize--;
1429                 break;
1430         case SWM_ARG_ID_MASTERGROW:
1431                 if (ws->l_state.vertical_msize < SWM_V_SLICE - 1)
1432                         ws->l_state.vertical_msize++;
1433                 break;
1434         case SWM_ARG_ID_MASTERADD:
1435                 ws->l_state.vertical_mwin++;
1436                 break;
1437         case SWM_ARG_ID_MASTERDEL:
1438                 if (ws->l_state.vertical_mwin > 0)
1439                         ws->l_state.vertical_mwin--;
1440                 break;
1441         default:
1442                 return;
1443         }
1444 }
1445
1446 void
1447 vertical_stack(struct workspace *ws, struct swm_geometry *g)
1448 {
1449         DNPRINTF(SWM_D_STACK, "vertical_stack: workspace: %d\n", ws->idx);
1450
1451         stack_master(ws, g, 0, 0);
1452 }
1453
1454 void
1455 horizontal_config(struct workspace *ws, int id)
1456 {
1457         DNPRINTF(SWM_D_STACK, "horizontal_config: workspace: %d\n", ws->idx);
1458
1459         switch (id) {
1460         case SWM_ARG_ID_STACKRESET:
1461         case SWM_ARG_ID_STACKINIT:
1462                 ws->l_state.horizontal_mwin = 1;
1463                 ws->l_state.horizontal_msize = SWM_H_SLICE / 2;
1464                 break;
1465         case SWM_ARG_ID_MASTERSHRINK:
1466                 if (ws->l_state.horizontal_msize > 1)
1467                         ws->l_state.horizontal_msize--;
1468                 break;
1469         case SWM_ARG_ID_MASTERGROW:
1470                 if (ws->l_state.horizontal_msize < SWM_H_SLICE - 1)
1471                         ws->l_state.horizontal_msize++;
1472                 break;
1473         case SWM_ARG_ID_MASTERADD:
1474                 ws->l_state.horizontal_mwin++;
1475                 break;
1476         case SWM_ARG_ID_MASTERDEL:
1477                 if (ws->l_state.horizontal_mwin > 0)
1478                         ws->l_state.horizontal_mwin--;
1479                 break;
1480         default:
1481                 return;
1482         }
1483 }
1484
1485 void
1486 horizontal_stack(struct workspace *ws, struct swm_geometry *g)
1487 {
1488         DNPRINTF(SWM_D_STACK, "vertical_stack: workspace: %d\n", ws->idx);
1489
1490         stack_master(ws, g, 1, 0);
1491 }
1492
1493 /* fullscreen view */
1494 void
1495 max_stack(struct workspace *ws, struct swm_geometry *g) {
1496         XWindowChanges          wc;
1497         struct swm_geometry     gg = *g;
1498         struct ws_win           *win, *winfocus;
1499         unsigned int            mask;
1500
1501         DNPRINTF(SWM_D_STACK, "max_stack: workspace: %d\n", ws->idx);
1502
1503         if (count_win(ws, 0) == 0)
1504                 return;
1505
1506         if (ws->focus == NULL)
1507                 ws->focus = TAILQ_FIRST(&ws->winlist);
1508         winfocus = cur_focus ? cur_focus : ws->focus;
1509
1510         TAILQ_FOREACH(win, &ws->winlist, entry) {
1511                 if (win->transient != 0 || win->floating != 0) {
1512                         if (win == ws->focus) {
1513                                 /* XXX maximize? */
1514                                 stack_floater(win, ws->r);
1515                                 XMapRaised(display, win->id);
1516                         } else
1517                                 XUnmapWindow(display, win->id);
1518                 } else {
1519                         bzero(&wc, sizeof wc);
1520                         wc.border_width = 1;
1521                         win->g.x = wc.x = gg.x;
1522                         win->g.y = wc.y = gg.y;
1523                         win->g.w = wc.width = gg.w;
1524                         win->g.h = wc.height = gg.h;
1525                         mask = CWX | CWY | CWWidth | CWHeight | CWBorderWidth;
1526                         XConfigureWindow(display, win->id, mask, &wc);
1527
1528                         if (win == ws->focus) {
1529                                 XMapRaised(display, win->id);
1530                         } else
1531                                 XUnmapWindow(display, win->id);
1532                 }
1533         }
1534
1535         if (winfocus)
1536                 focus_win(winfocus); /* has to be done outside of the loop */
1537 }
1538
1539 void
1540 send_to_ws(struct swm_region *r, union arg *args)
1541 {
1542         int                     wsid = args->id;
1543         struct ws_win           *win = cur_focus;
1544         struct workspace        *ws, *nws;
1545         Atom                    ws_idx_atom = 0;
1546         unsigned char           ws_idx_str[SWM_PROPLEN];
1547
1548         if (win == NULL)
1549                 return;
1550
1551         DNPRINTF(SWM_D_MOVE, "send_to_ws: win: %lu\n", win->id);
1552
1553         ws = win->ws;
1554         nws = &win->s->ws[wsid];
1555
1556         XUnmapWindow(display, win->id);
1557
1558         /* find a window to focus */
1559         ws->focus = TAILQ_PREV(win, ws_win_list, entry);
1560         if (ws->focus == NULL)
1561                 ws->focus = TAILQ_FIRST(&ws->winlist);
1562         if (ws->focus == win)
1563                 ws->focus = NULL;
1564
1565         TAILQ_REMOVE(&ws->winlist, win, entry);
1566
1567         TAILQ_INSERT_TAIL(&nws->winlist, win, entry);
1568         win->ws = nws;
1569
1570         /* Try to update the window's workspace property */
1571         ws_idx_atom = XInternAtom(display, "_SWM_WS", False);
1572         if (ws_idx_atom &&
1573             snprintf(ws_idx_str, SWM_PROPLEN, "%d", nws->idx) < SWM_PROPLEN) {
1574                 DNPRINTF(SWM_D_PROP, "setting property _SWM_WS to %s\n",
1575                     ws_idx_str);
1576                 XChangeProperty(display, win->id, ws_idx_atom, XA_STRING, 8,
1577                     PropModeReplace, ws_idx_str, SWM_PROPLEN);
1578         }
1579
1580         if (count_win(nws, 1) == 1)
1581                 nws->focus = win;
1582         ws->restack = 1;
1583         nws->restack = 1;
1584
1585         stack();
1586 }
1587
1588 void
1589 wkill(struct swm_region *r, union arg *args)
1590 {
1591         DNPRINTF(SWM_D_MISC, "wkill\n");
1592         if(r->ws->focus != NULL)
1593                 XKillClient(display, r->ws->focus->id);
1594 }
1595
1596 void
1597 screenshot(struct swm_region *r, union arg *args)
1598 {
1599         union arg                       a;
1600
1601         DNPRINTF(SWM_D_MISC, "screenshot\n");
1602
1603         if (ss_enabled == 0)
1604                 return;
1605
1606         switch (args->id) {
1607         case SWM_ARG_ID_SS_ALL:
1608                 spawn_screenshot[1] = "full";
1609                 break;
1610         case SWM_ARG_ID_SS_WINDOW:
1611                 spawn_screenshot[1] = "window";
1612                 break;
1613         default:
1614                 return;
1615         }
1616         a.argv = spawn_screenshot;
1617         spawn(r, &a);
1618 }
1619
1620 void
1621 floating_toggle(struct swm_region *r, union arg *args)
1622 {
1623         struct ws_win   *win = cur_focus;
1624
1625         if (win == NULL)
1626                 return;
1627
1628         win->floating = !win->floating;
1629         win->manual = 0;
1630         stack();
1631         focus_win(win);
1632 }
1633
1634 /* key definitions */
1635 struct key {
1636         unsigned int            mod;
1637         KeySym                  keysym;
1638         void                    (*func)(struct swm_region *r, union arg *);
1639         union arg               args;
1640 } keys[] = {
1641         /* modifier             key     function                argument */
1642         { MODKEY,               XK_space,       cycle_layout,   {0} }, 
1643         { MODKEY | ShiftMask,   XK_space,       stack_config,   {.id = SWM_ARG_ID_STACKRESET} }, 
1644         { MODKEY,               XK_h,           stack_config,   {.id = SWM_ARG_ID_MASTERSHRINK} },
1645         { MODKEY,               XK_l,           stack_config,   {.id = SWM_ARG_ID_MASTERGROW} },
1646         { MODKEY,               XK_comma,       stack_config,   {.id = SWM_ARG_ID_MASTERADD} },
1647         { MODKEY,               XK_period,      stack_config,   {.id = SWM_ARG_ID_MASTERDEL} },
1648         { MODKEY,               XK_Return,      swapwin,        {.id = SWM_ARG_ID_SWAPMAIN} },
1649         { MODKEY,               XK_j,           focus,          {.id = SWM_ARG_ID_FOCUSNEXT} },
1650         { MODKEY,               XK_k,           focus,          {.id = SWM_ARG_ID_FOCUSPREV} },
1651         { MODKEY | ShiftMask,   XK_j,           swapwin,        {.id = SWM_ARG_ID_SWAPNEXT} },
1652         { MODKEY | ShiftMask,   XK_k,           swapwin,        {.id = SWM_ARG_ID_SWAPPREV} },
1653         { MODKEY | ShiftMask,   XK_Return,      spawn,          {.argv = spawn_term} },
1654         { MODKEY,               XK_p,           spawnmenu,      {.argv = spawn_menu} },
1655         { MODKEY | ShiftMask,   XK_q,           quit,           {0} },
1656         { MODKEY,               XK_q,           restart,        {0} },
1657         { MODKEY,               XK_m,           focus,          {.id = SWM_ARG_ID_FOCUSMAIN} },
1658         { MODKEY,               XK_1,           switchws,       {.id = 0} },
1659         { MODKEY,               XK_2,           switchws,       {.id = 1} },
1660         { MODKEY,               XK_3,           switchws,       {.id = 2} },
1661         { MODKEY,               XK_4,           switchws,       {.id = 3} },
1662         { MODKEY,               XK_5,           switchws,       {.id = 4} },
1663         { MODKEY,               XK_6,           switchws,       {.id = 5} },
1664         { MODKEY,               XK_7,           switchws,       {.id = 6} },
1665         { MODKEY,               XK_8,           switchws,       {.id = 7} },
1666         { MODKEY,               XK_9,           switchws,       {.id = 8} },
1667         { MODKEY,               XK_0,           switchws,       {.id = 9} },
1668         { MODKEY,               XK_Right,       cyclews,        {.id = SWM_ARG_ID_CYCLEWS_UP} }, 
1669         { MODKEY,               XK_Left,        cyclews,        {.id = SWM_ARG_ID_CYCLEWS_DOWN} }, 
1670         { MODKEY | ShiftMask,   XK_Right,       cyclescr,       {.id = SWM_ARG_ID_CYCLESC_UP} }, 
1671         { MODKEY | ShiftMask,   XK_Left,        cyclescr,       {.id = SWM_ARG_ID_CYCLESC_DOWN} }, 
1672         { MODKEY | ShiftMask,   XK_1,           send_to_ws,     {.id = 0} },
1673         { MODKEY | ShiftMask,   XK_2,           send_to_ws,     {.id = 1} },
1674         { MODKEY | ShiftMask,   XK_3,           send_to_ws,     {.id = 2} },
1675         { MODKEY | ShiftMask,   XK_4,           send_to_ws,     {.id = 3} },
1676         { MODKEY | ShiftMask,   XK_5,           send_to_ws,     {.id = 4} },
1677         { MODKEY | ShiftMask,   XK_6,           send_to_ws,     {.id = 5} },
1678         { MODKEY | ShiftMask,   XK_7,           send_to_ws,     {.id = 6} },
1679         { MODKEY | ShiftMask,   XK_8,           send_to_ws,     {.id = 7} },
1680         { MODKEY | ShiftMask,   XK_9,           send_to_ws,     {.id = 8} },
1681         { MODKEY | ShiftMask,   XK_0,           send_to_ws,     {.id = 9} },
1682         { MODKEY,               XK_b,           bar_toggle,     {0} },
1683         { MODKEY,               XK_Tab,         focus,          {.id = SWM_ARG_ID_FOCUSNEXT} },
1684         { MODKEY | ShiftMask,   XK_Tab,         focus,          {.id = SWM_ARG_ID_FOCUSPREV} },
1685         { MODKEY | ShiftMask,   XK_x,           wkill,          {0} },
1686         { MODKEY,               XK_s,           screenshot,     {.id = SWM_ARG_ID_SS_ALL} },
1687         { MODKEY | ShiftMask,   XK_s,           screenshot,     {.id = SWM_ARG_ID_SS_WINDOW} },
1688         { MODKEY,               XK_t,           floating_toggle,{0} },
1689         { MODKEY | ShiftMask,   XK_v,           version,        {0} },
1690 };
1691
1692 void
1693 resize_window(struct ws_win *win, int center)
1694 {
1695         unsigned int            mask;
1696         XWindowChanges          wc;
1697         struct swm_region       *r;
1698
1699         r = root_to_region(win->wa.root);
1700         bzero(&wc, sizeof wc);
1701         mask = CWBorderWidth | CWWidth | CWHeight;
1702         wc.border_width = 1;
1703         wc.width = win->g.w;
1704         wc.height = win->g.h;
1705         if (center == SWM_ARG_ID_CENTER) {
1706                 wc.x = (WIDTH(r) - win->g.w) / 2;
1707                 wc.y = (HEIGHT(r) - win->g.h) / 2;
1708                 mask |= CWX | CWY;
1709         }
1710
1711         DNPRINTF(SWM_D_STACK, "resize_window: win %lu x %d y %d w %d h %d\n",
1712             win->id, wc.x, wc.y, wc.width, wc.height);
1713
1714         XConfigureWindow(display, win->id, mask, &wc);
1715         config_win(win);
1716 }
1717
1718 void
1719 resize(struct ws_win *win, union arg *args)
1720 {
1721         XEvent                  ev;
1722         Time                    time = 0;
1723
1724         DNPRINTF(SWM_D_MOUSE, "resize: win %d floating %d trans %d\n",
1725             win->id, win->floating, win->transient);
1726
1727         if (!(win->transient != 0 || win->floating != 0))
1728                 return;
1729
1730         if (XGrabPointer(display, win->id, False, MOUSEMASK, GrabModeAsync,
1731             GrabModeAsync, None, None /* cursor */, CurrentTime) != GrabSuccess)
1732                 return;
1733         XWarpPointer(display, None, win->id, 0, 0, 0, 0, win->g.w, win->g.h);
1734         do {
1735                 XMaskEvent(display, MOUSEMASK | ExposureMask |
1736                     SubstructureRedirectMask, &ev);
1737                 switch(ev.type) {
1738                 case ConfigureRequest:
1739                 case Expose:
1740                 case MapRequest:
1741                         handler[ev.type](&ev);
1742                         break;
1743                 case MotionNotify:
1744                         if (ev.xmotion.x < 0)
1745                                 ev.xmotion.x = 0;
1746                         if (ev.xmotion.y < 0)
1747                                 ev.xmotion.y = 0;
1748                         win->g.w = ev.xmotion.x;
1749                         win->g.h = ev.xmotion.y;
1750
1751                         /* not free, don't sync more than 60 times / second */
1752                         if ((ev.xmotion.time - time) > (1000 / 60) ) {
1753                                 time = ev.xmotion.time;
1754                                 XSync(display, False);
1755                                 resize_window(win, args->id);
1756                         }
1757                         break;
1758                 }
1759         } while (ev.type != ButtonRelease);
1760         if (time) {
1761                 XSync(display, False);
1762                 resize_window(win, args->id);
1763         }
1764         XWarpPointer(display, None, win->id, 0, 0, 0, 0, win->g.w - 1,
1765             win->g.h - 1);
1766         XUngrabPointer(display, CurrentTime);
1767
1768         /* drain events */
1769         while (XCheckMaskEvent(display, EnterWindowMask, &ev));
1770 }
1771
1772 void
1773 move_window(struct ws_win *win)
1774 {
1775         unsigned int            mask;
1776         XWindowChanges          wc;
1777         struct swm_region       *r;
1778
1779         r = root_to_region(win->wa.root);
1780         bzero(&wc, sizeof wc);
1781         mask = CWX | CWY;
1782         wc.x = win->g.x;
1783         wc.y = win->g.y;
1784
1785         DNPRINTF(SWM_D_STACK, "move_window: win %lu x %d y %d w %d h %d\n",
1786             win->id, wc.x, wc.y, wc.width, wc.height);
1787
1788         XConfigureWindow(display, win->id, mask, &wc);
1789         config_win(win);
1790 }
1791
1792 void
1793 move(struct ws_win *win, union arg *args)
1794 {
1795         XEvent                  ev;
1796         Time                    time = 0;
1797         int                     restack = 0;
1798
1799         DNPRINTF(SWM_D_MOUSE, "move: win %d floating %d trans %d\n",
1800             win->id, win->floating, win->transient);
1801
1802         if (win->floating == 0) {
1803                 win->floating = 1;
1804                 win->manual = 1;
1805                 restack = 1;
1806         }
1807
1808         if (XGrabPointer(display, win->id, False, MOUSEMASK, GrabModeAsync,
1809             GrabModeAsync, None, None /* cursor */, CurrentTime) != GrabSuccess)
1810                 return;
1811         XWarpPointer(display, None, win->id, 0, 0, 0, 0, 0, 0);
1812         do {
1813                 XMaskEvent(display, MOUSEMASK | ExposureMask |
1814                     SubstructureRedirectMask, &ev);
1815                 switch(ev.type) {
1816                 case ConfigureRequest:
1817                 case Expose:
1818                 case MapRequest:
1819                         handler[ev.type](&ev);
1820                         break;
1821                 case MotionNotify:
1822                         win->g.x = ev.xmotion.x_root;
1823                         win->g.y = ev.xmotion.y_root;
1824
1825                         /* not free, don't sync more than 60 times / second */
1826                         if ((ev.xmotion.time - time) > (1000 / 60) ) {
1827                                 time = ev.xmotion.time;
1828                                 XSync(display, False);
1829                                 move_window(win);
1830                         }
1831                         break;
1832                 }
1833         } while (ev.type != ButtonRelease);
1834         if (time) {
1835                 XSync(display, False);
1836                 move_window(win);
1837         }
1838         XWarpPointer(display, None, win->id, 0, 0, 0, 0, 0, 0);
1839         XUngrabPointer(display, CurrentTime);
1840         if (restack)
1841                 stack();
1842
1843         /* drain events */
1844         while (XCheckMaskEvent(display, EnterWindowMask, &ev));
1845 }
1846
1847 /* mouse */
1848 enum { client_click, root_click };
1849 struct button {
1850         unsigned int            action;
1851         unsigned int            mask;
1852         unsigned int            button;
1853         void                    (*func)(struct ws_win *, union arg *);
1854         union arg               args;
1855 } buttons[] = {
1856           /* action             key             mouse button    func            args */
1857         { client_click,         MODKEY,         Button3,        resize,         {.id = SWM_ARG_ID_DONTCENTER} },
1858         { client_click,         MODKEY | ShiftMask, Button3,    resize,         {.id = SWM_ARG_ID_CENTER} },
1859         { client_click,         MODKEY,         Button1,        move,           {0} },
1860 };
1861
1862 void
1863 updatenumlockmask(void)
1864 {
1865         unsigned int            i, j;
1866         XModifierKeymap         *modmap;
1867
1868         DNPRINTF(SWM_D_MISC, "updatenumlockmask\n");
1869         numlockmask = 0;
1870         modmap = XGetModifierMapping(display);
1871         for (i = 0; i < 8; i++)
1872                 for (j = 0; j < modmap->max_keypermod; j++)
1873                         if (modmap->modifiermap[i * modmap->max_keypermod + j]
1874                           == XKeysymToKeycode(display, XK_Num_Lock))
1875                                 numlockmask = (1 << i);
1876
1877         XFreeModifiermap(modmap);
1878 }
1879
1880 void
1881 grabkeys(void)
1882 {
1883         unsigned int            i, j, k;
1884         KeyCode                 code;
1885         unsigned int            modifiers[] =
1886             { 0, LockMask, numlockmask, numlockmask | LockMask };
1887
1888         DNPRINTF(SWM_D_MISC, "grabkeys\n");
1889         updatenumlockmask();
1890
1891         for (k = 0; k < ScreenCount(display); k++) {
1892                 if (TAILQ_EMPTY(&screens[k].rl))
1893                         continue;
1894                 XUngrabKey(display, AnyKey, AnyModifier, screens[k].root);
1895                 for (i = 0; i < LENGTH(keys); i++) {
1896                         if ((code = XKeysymToKeycode(display, keys[i].keysym)))
1897                                 for (j = 0; j < LENGTH(modifiers); j++)
1898                                         XGrabKey(display, code,
1899                                             keys[i].mod | modifiers[j],
1900                                             screens[k].root, True,
1901                                             GrabModeAsync, GrabModeAsync);
1902                 }
1903         }
1904 }
1905
1906 void
1907 grabbuttons(struct ws_win *win, int focused)
1908 {
1909         unsigned int            i, j;
1910         unsigned int            modifiers[] =
1911             { 0, LockMask, numlockmask, numlockmask|LockMask };
1912
1913         updatenumlockmask();
1914         XUngrabButton(display, AnyButton, AnyModifier, win->id);
1915         if(focused) {
1916                 for (i = 0; i < LENGTH(buttons); i++)
1917                         if (buttons[i].action == client_click)
1918                                 for (j = 0; j < LENGTH(modifiers); j++)
1919                                         XGrabButton(display, buttons[i].button,
1920                                             buttons[i].mask | modifiers[j],
1921                                             win->id, False, BUTTONMASK,
1922                                             GrabModeAsync, GrabModeSync, None,
1923                                             None);
1924         } else
1925                 XGrabButton(display, AnyButton, AnyModifier, win->id, False,
1926                     BUTTONMASK, GrabModeAsync, GrabModeSync, None, None);
1927 }
1928
1929 void
1930 expose(XEvent *e)
1931 {
1932         DNPRINTF(SWM_D_EVENT, "expose: window: %lu\n", e->xexpose.window);
1933 }
1934
1935 void
1936 keypress(XEvent *e)
1937 {
1938         unsigned int            i;
1939         KeySym                  keysym;
1940         XKeyEvent               *ev = &e->xkey;
1941
1942         DNPRINTF(SWM_D_EVENT, "keypress: window: %lu\n", ev->window);
1943
1944         keysym = XKeycodeToKeysym(display, (KeyCode)ev->keycode, 0);
1945         for (i = 0; i < LENGTH(keys); i++)
1946                 if (keysym == keys[i].keysym
1947                    && CLEANMASK(keys[i].mod) == CLEANMASK(ev->state)
1948                    && keys[i].func)
1949                         keys[i].func(root_to_region(ev->root),
1950                             &(keys[i].args));
1951 }
1952
1953 void
1954 buttonpress(XEvent *e)
1955 {
1956         XButtonPressedEvent     *ev = &e->xbutton;
1957
1958         struct ws_win           *win;
1959         int                     i, action;
1960
1961         DNPRINTF(SWM_D_EVENT, "buttonpress: window: %lu\n", ev->window);
1962
1963         action = root_click;
1964         if ((win = find_window(ev->window)) == NULL)
1965                 return;
1966         else {
1967                 focus_win(win);
1968                 action = client_click;
1969         }
1970
1971         for (i = 0; i < LENGTH(buttons); i++)
1972                 if (action == buttons[i].action && buttons[i].func &&
1973                     buttons[i].button == ev->button &&
1974                     CLEANMASK(buttons[i].mask) == CLEANMASK(ev->state))
1975                         buttons[i].func(win, &buttons[i].args);
1976 }
1977
1978 void
1979 set_win_state(struct ws_win *win, long state)
1980 {
1981         long                    data[] = {state, None};
1982
1983         DNPRINTF(SWM_D_EVENT, "set_win_state: window: %lu\n", win->id);
1984
1985         XChangeProperty(display, win->id, astate, astate, 32, PropModeReplace,
1986             (unsigned char *)data, 2);
1987 }
1988
1989 struct ws_win *
1990 manage_window(Window id)
1991 {
1992         Window                  trans;
1993         struct workspace        *ws;
1994         struct ws_win           *win;
1995         int                     format, i, ws_idx;
1996         unsigned long           nitems, bytes;
1997         Atom                    ws_idx_atom = 0, type;
1998         unsigned char           ws_idx_str[SWM_PROPLEN], *prop = NULL;
1999         struct swm_region       *r;
2000         long                    mask;
2001         const char              *errstr;
2002
2003         if ((win = find_window(id)) != NULL)
2004                         return (win);   /* already being managed */
2005
2006         if ((win = calloc(1, sizeof(struct ws_win))) == NULL)
2007                 errx(1, "calloc: failed to allocate memory for new window");
2008
2009         /* Get all the window data in one shot */
2010         ws_idx_atom = XInternAtom(display, "_SWM_WS", False);
2011         if (ws_idx_atom)
2012                 XGetWindowProperty(display, id, ws_idx_atom, 0, SWM_PROPLEN,
2013                     False, XA_STRING, &type, &format, &nitems, &bytes, &prop);
2014         XGetWindowAttributes(display, id, &win->wa);
2015         XGetTransientForHint(display, id, &trans);
2016         XGetWMNormalHints(display, id, &win->sh, &mask); /* XXX function? */
2017         if (trans) {
2018                 win->transient = trans;
2019                 DNPRINTF(SWM_D_MISC, "manage_window: win %u transient %u\n",
2020                     (unsigned)win->id, win->transient);
2021         }
2022         
2023         /*
2024          * Figure out where to put the window. If it was previously assigned to
2025          * a workspace (either by spawn() or manually moving), and isn't
2026          * transient, * put it in the same workspace
2027          */
2028         r = root_to_region(win->wa.root);
2029         if (prop && win->transient == 0) {
2030                 DNPRINTF(SWM_D_PROP, "got property _SWM_WS=%s\n", prop);
2031                 ws_idx = strtonum(prop, 0, 9, &errstr);
2032                 if (errstr) {
2033                         DNPRINTF(SWM_D_EVENT, "window idx is %s: %s",
2034                             errstr, prop);
2035                 }
2036                 ws = &r->s->ws[ws_idx];
2037         } else
2038                 ws = r->ws;
2039
2040         /* set up the window layout */
2041         win->id = id;
2042         win->ws = ws;
2043         win->s = r->s;  /* this never changes */
2044         TAILQ_INSERT_TAIL(&ws->winlist, win, entry);
2045
2046         win->g.w = win->wa.width;
2047         win->g.h = win->wa.height;
2048         win->g.x = win->wa.x;
2049         win->g.y = win->wa.y;
2050
2051         /* Set window properties so we can remember this after reincarnation */
2052         if (ws_idx_atom && prop == NULL &&
2053             snprintf(ws_idx_str, SWM_PROPLEN, "%d", ws->idx) < SWM_PROPLEN) {
2054                 DNPRINTF(SWM_D_PROP, "setting property _SWM_WS to %s\n",
2055                     ws_idx_str);
2056                 XChangeProperty(display, win->id, ws_idx_atom, XA_STRING, 8,
2057                     PropModeReplace, ws_idx_str, SWM_PROPLEN);
2058         }
2059         XFree(prop);
2060
2061         /*
2062         fprintf(stderr, "manage window: %d x %d y %d w %d h %d\n", win->id, win->g.x, win->g.y, win->g.w, win->g.h);
2063         */
2064
2065         if (XGetClassHint(display, win->id, &win->ch)) {
2066                 DNPRINTF(SWM_D_CLASS, "class: %s name: %s\n",
2067                     win->ch.res_class, win->ch.res_name);
2068                 for (i = 0; quirks[i].class != NULL && quirks[i].name != NULL &&
2069                     quirks[i].quirk != 0; i++){
2070                         if (!strcmp(win->ch.res_class, quirks[i].class) &&
2071                             !strcmp(win->ch.res_name, quirks[i].name)) {
2072                                 DNPRINTF(SWM_D_CLASS, "found: %s name: %s\n",
2073                                     win->ch.res_class, win->ch.res_name);
2074                                 if (quirks[i].quirk & SWM_Q_FLOAT)
2075                                         win->floating = 1;
2076                         }
2077                 }
2078         }
2079
2080         XSelectInput(display, id, EnterWindowMask | FocusChangeMask |
2081             PropertyChangeMask | StructureNotifyMask);
2082
2083         set_win_state(win, NormalState);
2084
2085         /* make new win focused */
2086         focus_win(win);
2087
2088         return (win);
2089 }
2090
2091 void
2092 configurerequest(XEvent *e)
2093 {
2094         XConfigureRequestEvent  *ev = &e->xconfigurerequest;
2095         struct ws_win           *win;
2096         int                     new = 0;
2097         XWindowChanges          wc;
2098
2099         if ((win = find_window(ev->window)) == NULL)
2100                 new = 1;
2101
2102         if (new) {
2103                 DNPRINTF(SWM_D_EVENT, "configurerequest: new window: %lu\n",
2104                     ev->window);
2105                 /*
2106                 fprintf(stderr, "configurerequest: new window: %lu x %d y %d w %d h %d bw %d s %d sm %d\n",
2107                     ev->window, ev->x, ev->y, ev->width, ev->height, ev->border_width, ev->above, ev->detail);
2108                 */
2109                 bzero(&wc, sizeof wc);
2110                 wc.x = ev->x;
2111                 wc.y = ev->y;
2112                 wc.width = ev->width;
2113                 wc.height = ev->height;
2114                 wc.border_width = ev->border_width;
2115                 wc.sibling = ev->above;
2116                 wc.stack_mode = ev->detail;
2117                 XConfigureWindow(display, ev->window, ev->value_mask, &wc);
2118         } else {
2119                 /*
2120                 fprintf(stderr, "configurerequest: change window: %lu\n",
2121                     ev->window);
2122                 */
2123                 DNPRINTF(SWM_D_EVENT, "configurerequest: change window: %lu\n",
2124                     ev->window);
2125                 if (win->floating) {
2126                         if (ev->value_mask & CWX)
2127                                 win->g.x = ev->x;
2128                         if (ev->value_mask & CWY)
2129                                 win->g.y = ev->y;
2130                         if (ev->value_mask & CWWidth)
2131                                 win->g.w = ev->width;
2132                         if (ev->value_mask & CWHeight)
2133                                 win->g.h = ev->height;
2134                         if (win->ws->r != NULL) {
2135                                 /* this seems to be full screen */
2136                                 if (win->g.w >= WIDTH(win->ws->r)) {
2137                                         win->g.x = -1;
2138                                         win->g.w = WIDTH(win->ws->r);
2139                                         ev->value_mask |= CWX | CWWidth;
2140                                 }
2141                                 if (win->g.h >= HEIGHT(win->ws->r)) {
2142                                         /* kill border */
2143                                         win->g.y = -1;
2144                                         win->g.h = HEIGHT(win->ws->r);
2145                                         ev->value_mask |= CWY | CWHeight;
2146                                 }
2147                         }
2148                         if ((ev->value_mask & (CWX|CWY)) &&
2149                             !(ev->value_mask & (CWWidth|CWHeight)))
2150                                 config_win(win);
2151                         XMoveResizeWindow(display, win->id,
2152                             win->g.x, win->g.y, win->g.w, win->g.h);
2153                 } else
2154                         config_win(win);
2155         }
2156 }
2157
2158 void
2159 configurenotify(XEvent *e)
2160 {
2161         DNPRINTF(SWM_D_EVENT, "configurenotify: window: %lu\n",
2162             e->xconfigure.window);
2163 }
2164
2165 void
2166 destroynotify(XEvent *e)
2167 {
2168         struct ws_win           *win;
2169         XDestroyWindowEvent     *ev = &e->xdestroywindow;
2170         struct workspace        *ws;
2171
2172         DNPRINTF(SWM_D_EVENT, "destroynotify: window %lu\n", ev->window);
2173
2174         if ((win = find_window(ev->window)) != NULL) {
2175                 ws = win->ws;
2176                 /* find a window to focus */
2177                 if (ws->focus == win)
2178                         ws->focus = TAILQ_PREV(win, ws_win_list, entry);
2179                 if (ws->focus == NULL)
2180                         ws->focus = TAILQ_FIRST(&ws->winlist);
2181                 if (ws->focus == NULL || ws->focus == win) {
2182                         ws->focus = NULL;
2183                         unfocus_all();
2184                 } else
2185                         focus_win(ws->focus);
2186                 TAILQ_REMOVE(&ws->winlist, win, entry);
2187                 set_win_state(win, WithdrawnState);
2188                 if (win->ch.res_class)
2189                         XFree(win->ch.res_class);
2190                 if (win->ch.res_name)
2191                         XFree(win->ch.res_name);
2192                 free(win);
2193                 stack();
2194         }
2195 }
2196
2197 void
2198 enternotify(XEvent *e)
2199 {
2200         XCrossingEvent          *ev = &e->xcrossing;
2201         struct ws_win           *win;
2202
2203         DNPRINTF(SWM_D_EVENT, "enternotify: window: %lu\n", ev->window);
2204
2205         if (ignore_enter) {
2206                 /* eat event(r) to prevent autofocus */
2207                 ignore_enter--;
2208                 return;
2209         }
2210
2211         if ((win = find_window(ev->window)) != NULL)
2212                 focus_win(win);
2213 }
2214
2215 void
2216 focusin(XEvent *e)
2217 {
2218         DNPRINTF(SWM_D_EVENT, "focusin: window: %lu\n", e->xfocus.window);
2219 }
2220
2221 void
2222 mappingnotify(XEvent *e)
2223 {
2224         XMappingEvent           *ev = &e->xmapping;
2225
2226         DNPRINTF(SWM_D_EVENT, "mappingnotify: window: %lu\n", ev->window);
2227
2228         XRefreshKeyboardMapping(ev);
2229         if (ev->request == MappingKeyboard)
2230                 grabkeys();
2231 }
2232
2233 void
2234 maprequest(XEvent *e)
2235 {
2236         XMapRequestEvent        *ev = &e->xmaprequest;
2237         XWindowAttributes       wa;
2238
2239         DNPRINTF(SWM_D_EVENT, "maprequest: window: %lu\n",
2240             e->xmaprequest.window);
2241
2242         if (!XGetWindowAttributes(display, ev->window, &wa))
2243                 return;
2244         if (wa.override_redirect)
2245                 return;
2246         manage_window(e->xmaprequest.window);
2247         stack();
2248 }
2249
2250 void
2251 propertynotify(XEvent *e)
2252 {
2253         struct ws_win           *win;
2254         XPropertyEvent          *ev = &e->xproperty;
2255
2256         DNPRINTF(SWM_D_EVENT, "propertynotify: window: %lu\n",
2257             ev->window);
2258
2259         if (ev->state == PropertyDelete)
2260                 return; /* ignore */
2261         win = find_window(ev->window);
2262         if (win == NULL)
2263                 return;
2264
2265         switch (ev->atom) {
2266         case XA_WM_NORMAL_HINTS:
2267 #if 0
2268                 long            mask;
2269                 XGetWMNormalHints(display, win->id, &win->sh, &mask);
2270                 fprintf(stderr, "normal hints: flag 0x%x\n", win->sh.flags);
2271                 if (win->sh.flags & PMinSize) {
2272                         win->g.w = win->sh.min_width;
2273                         win->g.h = win->sh.min_height;
2274                         fprintf(stderr, "min %d %d\n", win->g.w, win->g.h);
2275                 }
2276                 XMoveResizeWindow(display, win->id,
2277                     win->g.x, win->g.y, win->g.w, win->g.h);
2278 #endif
2279                 break;
2280         default:
2281                 break;
2282         }
2283 }
2284
2285 void
2286 unmapnotify(XEvent *e)
2287 {
2288         DNPRINTF(SWM_D_EVENT, "unmapnotify: window: %lu\n", e->xunmap.window);
2289 }
2290
2291 void
2292 visibilitynotify(XEvent *e)
2293 {
2294         int                     i;
2295         struct swm_region       *r;
2296
2297         DNPRINTF(SWM_D_EVENT, "visibilitynotify: window: %lu\n",
2298             e->xvisibility.window);
2299         if (e->xvisibility.state == VisibilityUnobscured)
2300                 for (i = 0; i < ScreenCount(display); i++) 
2301                         TAILQ_FOREACH(r, &screens[i].rl, entry)
2302                                 if (e->xvisibility.window == r->bar_window)
2303                                         bar_update();
2304 }
2305
2306 int
2307 xerror_start(Display *d, XErrorEvent *ee)
2308 {
2309         other_wm = 1;
2310         return (-1);
2311 }
2312
2313 int
2314 xerror(Display *d, XErrorEvent *ee)
2315 {
2316         /* fprintf(stderr, "error: %p %p\n", display, ee); */
2317         return (-1);
2318 }
2319
2320 int
2321 active_wm(void)
2322 {
2323         other_wm = 0;
2324         xerrorxlib = XSetErrorHandler(xerror_start);
2325
2326         /* this causes an error if some other window manager is running */
2327         XSelectInput(display, DefaultRootWindow(display),
2328             SubstructureRedirectMask);
2329         XSync(display, False);
2330         if (other_wm)
2331                 return (1);
2332
2333         XSetErrorHandler(xerror);
2334         XSync(display, False);
2335         return (0);
2336 }
2337
2338 long
2339 getstate(Window w)
2340 {
2341         int                     format, status;
2342         long                    result = -1;
2343         unsigned char           *p = NULL;
2344         unsigned long           n, extra;
2345         Atom                    real;
2346
2347         astate = XInternAtom(display, "WM_STATE", False);
2348         status = XGetWindowProperty(display, w, astate, 0L, 2L, False, astate,
2349             &real, &format, &n, &extra, (unsigned char **)&p);
2350         if (status != Success)
2351                 return (-1);
2352         if (n != 0)
2353                 result = *p;
2354         XFree(p);
2355         return (result);
2356 }
2357
2358 void
2359 new_region(struct swm_screen *s, struct workspace *ws,
2360     int x, int y, int w, int h)
2361 {
2362         struct swm_region       *r;
2363
2364         DNPRINTF(SWM_D_MISC, "new region on screen %d: %dx%d (%d, %d)\n",
2365              s->idx, x, y, w, h);
2366
2367         if ((r = calloc(1, sizeof(struct swm_region))) == NULL)
2368                 errx(1, "calloc: failed to allocate memory for screen");
2369
2370         X(r) = x;
2371         Y(r) = y;
2372         WIDTH(r) = w;
2373         HEIGHT(r) = h;
2374         r->s = s;
2375         r->ws = ws;
2376         ws->r = r;
2377         TAILQ_INSERT_TAIL(&s->rl, r, entry);
2378         bar_setup(r);
2379 }
2380
2381 void
2382 setup_screens(void)
2383 {
2384 #ifdef SWM_XRR_HAS_CRTC
2385         XRRCrtcInfo             *ci;
2386         XRRScreenResources      *sr;
2387         int                     c;
2388 #endif /* SWM_XRR_HAS_CRTC */
2389         Window                  d1, d2, *wins = NULL;
2390         XWindowAttributes       wa;
2391         struct swm_region       *r;
2392         unsigned int            no;
2393         int                     errorbase, major, minor;
2394         int                     ncrtc = 0, w = 0;
2395         int                     i, j, k;
2396         struct workspace        *ws;
2397         int                     ws_idx_atom;
2398
2399
2400         if ((screens = calloc(ScreenCount(display),
2401              sizeof(struct swm_screen))) == NULL)
2402                 errx(1, "calloc: screens");
2403
2404         ws_idx_atom = XInternAtom(display, "_SWM_WS", False);
2405         
2406
2407         /* map physical screens */
2408         for (i = 0; i < ScreenCount(display); i++) {
2409                 DNPRINTF(SWM_D_WS, "setup_screens: init screen %d\n", i);
2410                 screens[i].idx = i;
2411                 TAILQ_INIT(&screens[i].rl);
2412                 screens[i].root = RootWindow(display, i);
2413
2414                 /* set default colors */
2415                 setscreencolor("red", i + 1, SWM_S_COLOR_FOCUS);
2416                 setscreencolor("rgb:88/88/88", i + 1, SWM_S_COLOR_UNFOCUS);
2417                 setscreencolor("rgb:00/80/80", i + 1, SWM_S_COLOR_BAR_BORDER);
2418                 setscreencolor("black", i + 1, SWM_S_COLOR_BAR);
2419                 setscreencolor("rgb:a0/a0/a0", i + 1, SWM_S_COLOR_BAR_FONT);
2420
2421                 /* init all workspaces */
2422                 for (j = 0; j < SWM_WS_MAX; j++) {
2423                         ws = &screens[i].ws[j];
2424                         ws->idx = j;
2425                         ws->restack = 1;
2426                         ws->focus = NULL;
2427                         ws->r = NULL;
2428                         TAILQ_INIT(&ws->winlist);
2429
2430                         for (k = 0; layouts[k].l_stack != NULL; k++)
2431                                 if (layouts[k].l_config != NULL)
2432                                         layouts[k].l_config(ws,
2433                                             SWM_ARG_ID_STACKINIT);
2434                         ws->cur_layout = &layouts[0];
2435                 }
2436
2437                 /* map virtual screens onto physical screens */
2438                 screens[i].xrandr_support = XRRQueryExtension(display,
2439                     &xrandr_eventbase, &errorbase);
2440                 if (screens[i].xrandr_support)
2441                         if (XRRQueryVersion(display, &major, &minor) &&
2442                             major < 1)
2443                                 screens[i].xrandr_support = 0;
2444
2445 #if 0   /* not ready for dynamic screen changes */
2446                 if (screens[i].xrandr_support)
2447                         XRRSelectInput(display,
2448                             screens[r->s].root,
2449                             RRScreenChangeNotifyMask);
2450 #endif
2451
2452                 /* grab existing windows (before we build the bars)*/
2453                 if (!XQueryTree(display, screens[i].root, &d1, &d2, &wins, &no))
2454                         continue;
2455
2456 #ifdef SWM_XRR_HAS_CRTC
2457                 sr = XRRGetScreenResources(display, screens[i].root);
2458                 if (sr == NULL)
2459                         new_region(&screens[i], &screens[i].ws[w],
2460                             0, 0, DisplayWidth(display, i),
2461                             DisplayHeight(display, i)); 
2462                 else 
2463                         ncrtc = sr->ncrtc;
2464
2465                 for (c = 0, ci = NULL; c < ncrtc; c++) {
2466                         ci = XRRGetCrtcInfo(display, sr, sr->crtcs[c]);
2467                         if (ci->noutput == 0)
2468                                 continue;
2469
2470                         if (ci != NULL && ci->mode == None)
2471                                 new_region(&screens[i], &screens[i].ws[w], 0, 0,
2472                                     DisplayWidth(display, i),
2473                                     DisplayHeight(display, i)); 
2474                         else
2475                                 new_region(&screens[i], &screens[i].ws[w],
2476                                     ci->x, ci->y, ci->width, ci->height);
2477                         w++;
2478                 }
2479                 if (ci)
2480                         XRRFreeCrtcInfo(ci);
2481                 XRRFreeScreenResources(sr);
2482 #else
2483                 new_region(&screens[i], &screens[i].ws[w], 0, 0,
2484                     DisplayWidth(display, i),
2485                     DisplayHeight(display, i)); 
2486 #endif /* SWM_XRR_HAS_CRTC */
2487
2488                 /* attach windows to a region */
2489                 /* normal windows */
2490                 if ((r = TAILQ_FIRST(&screens[i].rl)) == NULL)
2491                         errx(1, "no regions on screen %d", i);
2492
2493                 for (i = 0; i < no; i++) {
2494                         XGetWindowAttributes(display, wins[i], &wa);
2495                         if (!XGetWindowAttributes(display, wins[i], &wa) ||
2496                             wa.override_redirect ||
2497                             XGetTransientForHint(display, wins[i], &d1))
2498                                 continue;
2499
2500                         if (wa.map_state == IsViewable ||
2501                             getstate(wins[i]) == NormalState)
2502                                 manage_window(wins[i]);
2503                 }
2504                 /* transient windows */
2505                 for (i = 0; i < no; i++) {
2506                         if (!XGetWindowAttributes(display, wins[i], &wa))
2507                                 continue;
2508
2509                         if (XGetTransientForHint(display, wins[i], &d1) &&
2510                             (wa.map_state == IsViewable || getstate(wins[i]) ==
2511                             NormalState))
2512                                 manage_window(wins[i]);
2513                 }
2514                 if (wins) {
2515                         XFree(wins);
2516                         wins = NULL;
2517                 }
2518         }
2519 }
2520
2521 int
2522 main(int argc, char *argv[])
2523 {
2524         struct passwd           *pwd;
2525         char                    conf[PATH_MAX], *cfile = NULL;
2526         struct stat             sb;
2527         XEvent                  e;
2528         int                     xfd;
2529         fd_set                  rd;
2530
2531         start_argv = argv;
2532         fprintf(stderr, "Welcome to scrotwm V%s cvs tag: %s\n",
2533             SWM_VERSION, cvstag);
2534         if (!setlocale(LC_CTYPE, "") || !XSupportsLocale())
2535                 warnx("no locale support");
2536
2537         if (!(display = XOpenDisplay(0)))
2538                 errx(1, "can not open display");
2539
2540         if (active_wm())
2541                 errx(1, "other wm running");
2542
2543         astate = XInternAtom(display, "WM_STATE", False);
2544
2545         /* look for local and global conf file */
2546         pwd = getpwuid(getuid());
2547         if (pwd == NULL)
2548                 errx(1, "invalid user %d", getuid());
2549
2550         setup_screens();
2551
2552         snprintf(conf, sizeof conf, "%s/.%s", pwd->pw_dir, SWM_CONF_FILE);
2553         if (stat(conf, &sb) != -1) {
2554                 if (S_ISREG(sb.st_mode))
2555                         cfile = conf;
2556         } else {
2557                 /* try global conf file */
2558                 snprintf(conf, sizeof conf, "/etc/%s", SWM_CONF_FILE);
2559                 if (!stat(conf, &sb))
2560                         if (S_ISREG(sb.st_mode))
2561                                 cfile = conf;
2562         }
2563         if (cfile)
2564                 conf_load(cfile);
2565         bar_refresh();
2566
2567         /* ws[0].focus = TAILQ_FIRST(&ws[0].winlist); */
2568
2569         grabkeys();
2570         stack();
2571
2572         xfd = ConnectionNumber(display);
2573         while (running) {
2574                 FD_ZERO(&rd);
2575                 FD_SET(xfd, &rd);
2576                 if (select(xfd + 1, &rd, NULL, NULL, NULL) == -1)
2577                         if (errno != EINTR)
2578                                 errx(1, "select failed");
2579                 if (bar_alarm) {
2580                         bar_alarm = 0;
2581                         bar_update();
2582                 }
2583                 while(XPending(display)) {
2584                         XNextEvent(display, &e);
2585                         if (handler[e.type])
2586                                 handler[e.type](&e);
2587                 }
2588         }
2589
2590         XCloseDisplay(display);
2591
2592         return (0);
2593 }