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