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