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