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