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