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