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