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