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