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