JasonWoof Got questions, comments, patches, etc.? Contact Jason Woofenden
simplify and shrink code in setup some more
[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 #define SWM_VERSION     "0.5"
52
53 #include <stdio.h>
54 #include <stdlib.h>
55 #include <err.h>
56 #include <locale.h>
57 #include <unistd.h>
58 #include <time.h>
59 #include <signal.h>
60 #include <string.h>
61 #include <util.h>
62 #include <pwd.h>
63
64 #include <sys/types.h>
65 #include <sys/stat.h>
66 #include <sys/wait.h>
67 #include <sys/queue.h>
68 #include <sys/param.h>
69
70 #include <X11/cursorfont.h>
71 #include <X11/keysym.h>
72 #include <X11/Xatom.h>
73 #include <X11/Xlib.h>
74 #include <X11/Xproto.h>
75 #include <X11/Xutil.h>
76 #include <X11/extensions/Xrandr.h>
77
78 #if RANDR_MAJOR < 1
79 #  error XRandR versions less than 1.0 are not supported
80 #endif
81
82 #if RANDR_MAJOR >= 1
83 #if RANDR_MINOR >= 2
84 #define SWM_XRR_HAS_CRTC
85 #endif
86 #endif
87
88 /* #define SWM_DEBUG */
89 #ifdef SWM_DEBUG
90 #define DPRINTF(x...)           do { if (swm_debug) fprintf(stderr, x); } while(0)
91 #define DNPRINTF(n,x...)        do { if (swm_debug & n) fprintf(stderr, x); } while(0)
92 #define SWM_D_MISC              0x0001
93 #define SWM_D_EVENT             0x0002
94 #define SWM_D_WS                0x0004
95 #define SWM_D_FOCUS             0x0008
96 #define SWM_D_MOVE              0x0010
97 #define SWM_D_STACK             0x0020
98
99 u_int32_t               swm_debug = 0
100                             | SWM_D_MISC
101                             | SWM_D_EVENT
102                             | SWM_D_WS
103                             | SWM_D_FOCUS
104                             | SWM_D_MOVE
105                             | SWM_D_STACK
106                             ;
107 #else
108 #define DPRINTF(x...)
109 #define DNPRINTF(n,x...)
110 #endif
111
112 #define LENGTH(x)               (sizeof x / sizeof x[0])
113 #define MODKEY                  Mod1Mask
114 #define CLEANMASK(mask)         (mask & ~(numlockmask | LockMask))
115
116 #define X(r)            (r)->g.x        
117 #define Y(r)            (r)->g.y
118 #define WIDTH(r)        (r)->g.w        
119 #define HEIGHT(r)       (r)->g.h
120
121 char                    **start_argv;
122 Atom                    astate;
123 int                     (*xerrorxlib)(Display *, XErrorEvent *);
124 int                     other_wm;
125 int                     running = 1;
126 int                     xrandr_eventbase;
127 int                     ignore_enter = 0;
128 unsigned int            numlockmask = 0;
129 Display                 *display;
130
131 /* dialog windows */
132 double                  dialog_ratio = .6;
133 /* status bar */
134 int                     bar_enabled = 1;
135 int                     bar_height = 0;
136 GC                      bar_gc;
137 XGCValues               bar_gcv;
138 XFontStruct             *bar_fs;
139 char                    bar_text[128];
140 char                    *bar_fonts[] = {
141                             "-*-terminus-*-*-*-*-*-*-*-*-*-*-*-*",
142                             "-*-times-medium-r-*-*-*-*-*-*-*-*-*-*",
143                             NULL
144 };
145
146 /* terminal + args */
147 char                            *spawn_term[] = { "xterm", NULL };
148 char                            *spawn_menu[] = { "dmenu_run", NULL };
149
150 /* layout manager data */
151 struct swm_geometry {
152         int                     x;
153         int                     y;
154         int                     w;
155         int                     h;
156 };
157
158 struct swm_screen;
159 struct workspace;
160
161 /* virtual "screens" */
162 struct swm_region {
163         TAILQ_ENTRY(swm_region) entry;
164         struct swm_geometry     g;
165         Window                  bar_window;
166         struct workspace        *ws;    /* current workspace on this region */
167         struct swm_screen       *s;     /* screen idx */
168 }; 
169 TAILQ_HEAD(swm_region_list, swm_region);
170
171
172 struct ws_win {
173         TAILQ_ENTRY(ws_win)     entry;
174         Window                  id;
175         struct swm_geometry     g;
176         int                     focus;
177         int                     floating;
178         int                     transient;
179         struct workspace        *ws;    /* always valid */
180         struct swm_screen       *s;     /* always valid, never changes */
181         XWindowAttributes       wa;
182 };
183 TAILQ_HEAD(ws_win_list, ws_win);
184
185 /* layout handlers */
186 void    stack(void);
187 void    vertical_init(struct workspace *);
188 void    vertical_resize(struct workspace *, int);
189 void    vertical_stack(struct workspace *, struct swm_geometry *);
190 void    horizontal_init(struct workspace *);
191 void    horizontal_resize(struct workspace *, int);
192 void    horizontal_stack(struct workspace *, struct swm_geometry *);
193 void    max_init(struct workspace *);
194 void    max_stack(struct workspace *, struct swm_geometry *);
195
196 struct layout {
197         void            (*l_init)(struct workspace *);  /* init/reset */
198         void            (*l_stack)(struct workspace *, struct swm_geometry *);
199         void            (*l_resize)(struct workspace *, int);
200 } layouts[] =  {
201         /* init                 stack,                  resize */
202         { vertical_init,        vertical_stack,         vertical_resize},
203         { horizontal_init,      horizontal_stack,       horizontal_resize},
204         { NULL,                 max_stack,              NULL},
205         { NULL,                 NULL,                   NULL},
206 };
207
208 #define SWM_H_SLICE             (32)
209 #define SWM_V_SLICE             (32)
210
211
212 /* define work spaces */
213 struct workspace {
214         int                     idx;            /* workspace index */
215         int                     restack;        /* restack on switch */
216         struct layout           *cur_layout;    /* current layout handlers */
217         struct ws_win           *focus;         /* may be NULL */
218         struct swm_region       *r;             /* may be NULL */
219         struct ws_win_list      winlist;        /* list of windows in ws */
220
221         /* stacker state */
222         struct {
223                                 int horizontal_msize;
224                                 int vertical_msize;
225         } l_state;
226 };
227
228 /* physical screen mapping */
229 #define SWM_WS_MAX              (10)            /* XXX Too small? */
230 struct swm_screen {
231         int                     idx;            /* screen index */
232         struct swm_region_list  rl;     /* list of regions on this screen */
233         Window                  root;
234         int                     xrandr_support;
235         struct workspace        ws[SWM_WS_MAX];
236
237         /* colors */
238         unsigned long           bar_border;
239         unsigned long           bar_color;
240         unsigned long           bar_font_color;
241         unsigned long           color_focus;            /* XXX should this be per ws? */
242         unsigned long           color_unfocus;
243 };
244 struct swm_screen       *screens;
245 int                     num_screens;
246 Window rootclick = 0;
247
248 struct ws_win           *cur_focus = NULL;
249
250 /* args to functions */
251 union arg {
252         int                     id;
253 #define SWM_ARG_ID_FOCUSNEXT    (0)
254 #define SWM_ARG_ID_FOCUSPREV    (1)
255 #define SWM_ARG_ID_FOCUSMAIN    (2)
256 #define SWM_ARG_ID_SWAPNEXT     (3)
257 #define SWM_ARG_ID_SWAPPREV     (4)
258 #define SWM_ARG_ID_SWAPMAIN     (5)
259 #define SWM_ARG_ID_MASTERSHRINK (6)
260 #define SWM_ARG_ID_MASTERGROW   (7)
261         char                    **argv;
262 };
263
264 unsigned long
265 name_to_color(char *colorname)
266 {
267         Colormap                cmap;
268         Status                  status;
269         XColor                  screen_def, exact_def;
270         unsigned long           result = 0;
271         char                    cname[32] = "#";
272
273         cmap = DefaultColormap(display, screens[0].idx);
274         status = XAllocNamedColor(display, cmap, colorname,
275             &screen_def, &exact_def);
276         if (!status) {
277                 strlcat(cname, colorname + 2, sizeof cname - 1);
278                 status = XAllocNamedColor(display, cmap, cname, &screen_def,
279                     &exact_def);
280         }
281         if (status)
282                 result = screen_def.pixel;
283         else
284                 fprintf(stderr, "color '%s' not found.\n", colorname);
285
286         return (result);
287 }
288
289 /* conf file stuff */
290 #define SWM_CONF_WS     "\n= \t"
291 #define SWM_CONF_FILE   "scrotwm.conf"
292 int
293 conf_load(char *filename)
294 {
295         FILE                    *config;
296         char                    *line, *cp, *var, *val;
297         size_t                  len, lineno = 0;
298         int                     i;
299
300         DNPRINTF(SWM_D_MISC, "conf_load: filename %s\n", filename);
301
302         if (filename == NULL)
303                 return (1);
304
305         if ((config = fopen(filename, "r")) == NULL)
306                 return (1);
307
308         for (;;) {
309                 if ((line = fparseln(config, &len, &lineno, NULL, 0)) == NULL)
310                         if (feof(config))
311                                 break;
312                 cp = line;
313                 cp += (long)strspn(cp, SWM_CONF_WS);
314                 if (cp[0] == '\0') {
315                         /* empty line */
316                         free(line);
317                         continue;
318                 }
319                 if ((var = strsep(&cp, SWM_CONF_WS)) == NULL || cp == NULL)
320                         break;
321                 cp += (long)strspn(cp, SWM_CONF_WS);
322                 if ((val = strsep(&cp, SWM_CONF_WS)) == NULL)
323                         break;
324
325                 DNPRINTF(SWM_D_MISC, "conf_load: %s=%s\n",var ,val);
326                 switch (var[0]) {
327                 case 'b':
328                         if (!strncmp(var, "bar_enabled", strlen("bar_enabled")))
329                                 bar_enabled = atoi(val);
330                         else if (!strncmp(var, "bar_border",
331                             strlen("bar_border")))
332                                 for (i = 0; i < ScreenCount(display); i++)
333                                         screens[i].bar_border = name_to_color(val);
334                         else if (!strncmp(var, "bar_color",
335                             strlen("bar_color")))
336                                 for (i = 0; i < ScreenCount(display); i++)
337                                         screens[i].bar_color = name_to_color(val);
338                         else if (!strncmp(var, "bar_font_color",
339                             strlen("bar_font_color")))
340                                 for (i = 0; i < ScreenCount(display); i++)
341                                         screens[i].bar_font_color = name_to_color(val);
342                         else if (!strncmp(var, "bar_font", strlen("bar_font")))
343                                 asprintf(&bar_fonts[0], "%s", val);
344                         else
345                                 goto bad;
346                         break;
347
348                 case 'c':
349                         if (!strncmp(var, "color_focus", strlen("color_focus")))
350                                 for (i = 0; i < ScreenCount(display); i++)
351                                         screens[i].color_focus = name_to_color(val);
352                         else if (!strncmp(var, "color_unfocus",
353                             strlen("color_unfocus")))
354                                 for (i = 0; i < ScreenCount(display); i++)
355                                         screens[i].color_unfocus = name_to_color(val);
356                         else
357                                 goto bad;
358                         break;
359
360                 case 'd':
361                         if (!strncmp(var, "dialog_ratio",
362                             strlen("dialog_ratio"))) {
363                                 dialog_ratio = atof(val);
364                                 if (dialog_ratio > 1.0 || dialog_ratio <= .3)
365                                         dialog_ratio = .6;
366                         } else
367                                 goto bad;
368                         break;
369
370                 case 's':
371                         if (!strncmp(var, "spawn_term", strlen("spawn_term")))
372                                 asprintf(&spawn_term[0], "%s", val); /* XXX args? */
373                         break;
374                 default:
375                         goto bad;
376                 }
377                 free(line);
378         }
379
380         fclose(config);
381         return (0);
382 bad:
383         errx(1, "invalid conf file entry: %s=%s", var, val);
384 }
385
386 void
387 bar_print(struct swm_region *r)
388 {
389         time_t                  tmt;
390         struct tm               tm;
391
392         if (bar_enabled == 0)
393                 return;
394
395         /* clear old text */
396         XSetForeground(display, bar_gc, r->s->bar_color);
397         XDrawString(display, r->bar_window,
398             bar_gc, 4, bar_fs->ascent, bar_text, strlen(bar_text));
399
400         /* draw new text */
401         time(&tmt);
402         localtime_r(&tmt, &tm);
403         strftime(bar_text, sizeof bar_text, "%a %b %d %R %Z %Y", &tm);
404         XSetForeground(display, bar_gc, r->s->bar_font_color);
405         XDrawString(display, r->bar_window, bar_gc, 4,
406             bar_fs->ascent, bar_text, strlen(bar_text));
407         XSync(display, False);
408
409         alarm(60);
410 }
411
412 void
413 bar_signal(int sig)
414 {
415         /* XXX yeah yeah byte me */
416         if (cur_focus)
417                 bar_print(cur_focus->ws->r);
418 }
419
420 void
421 bar_toggle(struct swm_region *r, union arg *args)
422 {
423         struct swm_region *tmpr;
424         int i, j;       
425
426         DNPRINTF(SWM_D_MISC, "bar_toggle\n");
427
428         if (bar_enabled) {
429                 for (i = 0; i < ScreenCount(display); i++)
430                         TAILQ_FOREACH(tmpr, &screens[i].rl, entry)
431                                 XUnmapWindow(display, tmpr->bar_window);
432         } else {
433                 for (i = 0; i < ScreenCount(display); i++)
434                         TAILQ_FOREACH(tmpr, &screens[i].rl, entry)
435                                 XMapRaised(display, tmpr->bar_window);
436         }
437         bar_enabled = !bar_enabled;
438         XSync(display, False);
439         for (i = 0; i < ScreenCount(display); i++)
440                 for (j = 0; j < SWM_WS_MAX; j++)
441                         screens[i].ws[j].restack = 1;
442
443         stack();
444         /* must be after stack */
445         for (i = 0; i < ScreenCount(display); i++)
446                 TAILQ_FOREACH(tmpr, &screens[i].rl, entry)
447                         bar_print(tmpr);
448 }
449
450 void
451 bar_setup(struct swm_region *r)
452 {
453         int                     i;
454
455         for (i = 0; bar_fonts[i] != NULL; i++) {
456                 bar_fs = XLoadQueryFont(display, bar_fonts[i]);
457                 if (bar_fs)
458                         break;
459         }
460         if (bar_fonts[i] == NULL)
461                         errx(1, "couldn't load font");
462         bar_height = bar_fs->ascent + bar_fs->descent + 3;
463
464         r->bar_window = XCreateSimpleWindow(display, 
465             r->s->root, X(r), Y(r), WIDTH(r), bar_height - 2,
466             1, r->s->bar_border, r->s->bar_color);
467         bar_gc = XCreateGC(display, r->bar_window, 0, &bar_gcv);
468         XSetFont(display, bar_gc, bar_fs->fid);
469         XSelectInput(display, r->bar_window, VisibilityChangeMask);
470         if (bar_enabled)
471                 XMapRaised(display, r->bar_window);
472         DNPRINTF(SWM_D_MISC, "bar_setup: bar_window %lu\n", r->bar_window);
473
474         if (signal(SIGALRM, bar_signal) == SIG_ERR)
475                 err(1, "could not install bar_signal");
476         bar_print(r);
477 }
478
479 void
480 config_win(struct ws_win *win)
481 {
482         XConfigureEvent         ce;
483
484         DNPRINTF(SWM_D_MISC, "config_win: win %lu x %d y %d w %d h %d\n",
485             win->id, win->g.x, win->g.y, win->g.w, win->g.h);
486         ce.type = ConfigureNotify;
487         ce.display = display;
488         ce.event = win->id;
489         ce.window = win->id;
490         ce.x = win->g.x;
491         ce.y = win->g.y;
492         ce.width = win->g.w;
493         ce.height = win->g.h;
494         ce.border_width = 1; /* XXX store this! */
495         ce.above = None;
496         ce.override_redirect = False;
497         XSendEvent(display, win->id, False, StructureNotifyMask, (XEvent *)&ce);
498 }
499
500 int
501 count_win(struct workspace *ws, int count_transient)
502 {
503         struct ws_win           *win;
504         int                     count = 0;
505
506         TAILQ_FOREACH(win, &ws->winlist, entry) {
507                 if (count_transient == 0 && win->floating)
508                         continue;
509                 if (count_transient == 0 && win->transient)
510                         continue;
511                 count++;
512         }
513         DNPRINTF(SWM_D_MISC, "count_win: %d\n", count);
514
515         return (count);
516 }
517
518 void
519 quit(struct swm_region *r, union arg *args)
520 {
521         DNPRINTF(SWM_D_MISC, "quit\n");
522         running = 0;
523 }
524
525 void
526 restart(struct swm_region *r, union arg *args)
527 {
528         DNPRINTF(SWM_D_MISC, "restart: %s\n", start_argv[0]);
529
530         XCloseDisplay(display);
531         execvp(start_argv[0], start_argv);
532         fprintf(stderr, "execvp failed\n");
533         perror(" failed");
534         quit(NULL, NULL);
535 }
536
537 struct swm_region *
538 root_to_region(Window root)
539 {
540         struct swm_region       *r;
541         Window                  rr, cr;
542         int                     i, x, y, wx, wy;
543         unsigned int            mask;
544
545         for (i = 0; i < ScreenCount(display); i++)
546                 if (screens[i].root == root)
547                         break;
548
549         if (rootclick != root && /* if root was just clicked in, use cursor */
550             cur_focus && cur_focus->ws->r && cur_focus->s == &screens[i])
551                 r = cur_focus->ws->r;
552         else {
553                 if (XQueryPointer(display, screens[i].root, 
554                     &rr, &cr, &x, &y, &wx, &wy, &mask) == False) {
555                         r = TAILQ_FIRST(&screens[i].rl);
556                 } else {
557                         TAILQ_FOREACH(r, &screens[i].rl, entry) {
558                                 if (x > X(r) && x < X(r) + WIDTH(r) &&
559                                     y > Y(r) && y < Y(r) + HEIGHT(r))
560                                         break;
561                         }
562
563                         if (r == NULL)
564                                 r = TAILQ_FIRST(&screens[i].rl);
565                 }
566         }
567         return (r);
568 }
569
570 struct ws_win *
571 find_window(Window id)
572 {
573         struct ws_win           *win;
574         int                     i, j;
575
576         for (i = 0; i < ScreenCount(display); i++)
577                 for (j = 0; j < SWM_WS_MAX; j++)
578                         TAILQ_FOREACH(win, &screens[i].ws[j].winlist, entry)
579                                 if (id == win->id)
580                                         return (win);
581         return (NULL);
582 }
583
584 void
585 spawn(struct swm_region *r, union arg *args)
586 {
587         DNPRINTF(SWM_D_MISC, "spawn: %s\n", args->argv[0]);
588         /*
589          * The double-fork construct avoids zombie processes and keeps the code
590          * clean from stupid signal handlers.
591          */
592         if (fork() == 0) {
593                 if (fork() == 0) {
594                         if (display)
595                                 close(ConnectionNumber(display));
596                         setsid();
597                         execvp(args->argv[0], args->argv);
598                         fprintf(stderr, "execvp failed\n");
599                         perror(" failed");
600                 }
601                 exit(0);
602         }
603         wait(0);
604 }
605
606 void
607 unfocus_win(struct ws_win *win)
608 {
609         DNPRINTF(SWM_D_FOCUS, "unfocus_win: id: %lu\n", win->id);
610         if (win->ws->r && win->focus)
611                 XSetWindowBorder(display, win->id,
612                     win->ws->r->s->color_unfocus);
613         win->focus = 0;
614         if (win->ws->focus == win)
615                 win->ws->focus = NULL;
616         if (cur_focus == win)
617                 cur_focus = NULL;
618 }
619
620
621 void
622 focus_win(struct ws_win *win)
623 {
624         DNPRINTF(SWM_D_FOCUS, "focus_win: id: %lu\n", win->id);
625
626         rootclick = 0;
627
628         win->ws->focus = win;
629         if (win->ws->r != NULL) {
630                 if (cur_focus && cur_focus != win)
631                         unfocus_win(cur_focus);
632                 cur_focus = win;
633                 if (!win->focus)
634                         XSetWindowBorder(display, win->id,
635                             win->ws->r->s->color_focus);
636                 win->focus = 1;
637                 XSetInputFocus(display, win->id,
638                     RevertToPointerRoot, CurrentTime);
639         }
640 }
641
642 void
643 switchws(struct swm_region *r, union arg *args)
644 {
645         int                     wsid = args->id;
646         struct swm_region       *this_r, *other_r;
647         struct ws_win           *win;
648         struct workspace        *new_ws, *old_ws;
649
650         this_r = r;
651         old_ws = this_r->ws;
652         new_ws = &this_r->s->ws[wsid];
653
654         DNPRINTF(SWM_D_WS, "switchws screen %d region %dx%d+%d+%d: "
655             "%d -> %d\n", r->s->idx, WIDTH(r), HEIGHT(r), X(r), Y(r),
656             old_ws->idx, wsid);
657
658         if (new_ws == old_ws)
659                 return;
660
661         other_r = new_ws->r;
662         fprintf(stderr, "switchws: other_r %p\n", other_r);
663         if (!other_r) {
664                 /* if the other workspace is hidden, switch windows */
665         
666                 /* map new window first to prevent ugly blinking */
667                 TAILQ_FOREACH(win, &new_ws->winlist, entry)
668                         XMapRaised(display, win->id);
669
670                 TAILQ_FOREACH(win, &old_ws->winlist, entry)
671                         XUnmapWindow(display, win->id);
672
673                 old_ws->r = NULL;
674                 old_ws->restack = 1;
675         } else {
676                 other_r->ws = old_ws;
677                 old_ws->r = other_r;
678         }
679         this_r->ws = new_ws;
680         new_ws->r = this_r;
681
682         ignore_enter = 1;
683         /* set focus */
684         if (new_ws->focus)
685                 focus_win(new_ws->focus);
686         stack();
687 }
688
689 void
690 swapwin(struct swm_region *r, union arg *args)
691 {
692         struct ws_win           *target;
693         struct ws_win_list      *wl;
694
695
696         DNPRINTF(SWM_D_WS, "swapwin id %d "
697             "in screen %d region %dx%d+%d+%d ws %d\n", args->id,
698             r->s->idx, WIDTH(r), HEIGHT(r), X(r), Y(r), r->ws->idx);
699         if (cur_focus == NULL)
700                 return;
701
702         wl = &cur_focus->ws->winlist;
703
704         switch (args->id) {
705         case SWM_ARG_ID_SWAPPREV:
706                 target = TAILQ_PREV(cur_focus, ws_win_list, entry);
707                 TAILQ_REMOVE(wl, cur_focus, entry);
708                 if (target == NULL)
709                         TAILQ_INSERT_TAIL(wl, cur_focus, entry);
710                 else
711                         TAILQ_INSERT_BEFORE(target, cur_focus, entry);
712                 break;
713         case SWM_ARG_ID_SWAPNEXT: 
714                 target = TAILQ_NEXT(cur_focus, entry);
715                 TAILQ_REMOVE(wl, cur_focus, entry);
716                 if (target == NULL)
717                         TAILQ_INSERT_HEAD(wl, cur_focus, entry);
718                 else
719                         TAILQ_INSERT_AFTER(wl, target, cur_focus, entry);
720                 break;
721         case SWM_ARG_ID_SWAPMAIN:
722                 target = TAILQ_FIRST(wl);
723                 if (target == cur_focus)
724                         return;
725                 TAILQ_REMOVE(wl, target, entry);
726                 TAILQ_INSERT_BEFORE(cur_focus, target, entry);
727                 TAILQ_REMOVE(wl, cur_focus, entry);
728                 TAILQ_INSERT_HEAD(wl, cur_focus, entry);
729                 break;
730         default:
731                 DNPRINTF(SWM_D_MOVE, "invalid id: %d\n", args->id);
732                 return;
733         }
734
735         ignore_enter = 2;
736         stack();
737 }
738
739 void
740 focus(struct swm_region *r, union arg *args)
741 {
742         struct ws_win           *winfocus, *winlostfocus;
743         struct ws_win_list      *wl;
744
745         DNPRINTF(SWM_D_FOCUS, "focus: id %d\n", args->id);
746         if (cur_focus == NULL)
747                 return;
748
749         wl = &cur_focus->ws->winlist;
750
751         winlostfocus = cur_focus;
752
753         switch (args->id) {
754         case SWM_ARG_ID_FOCUSPREV:
755                 winfocus = TAILQ_PREV(cur_focus, ws_win_list, entry);
756                 if (winfocus == NULL)
757                         winfocus = TAILQ_LAST(wl, ws_win_list);
758                 break;
759
760         case SWM_ARG_ID_FOCUSNEXT:
761                 winfocus = TAILQ_NEXT(cur_focus, entry);
762                 if (winfocus == NULL)
763                         winfocus = TAILQ_FIRST(wl);
764                 break;
765
766         case SWM_ARG_ID_FOCUSMAIN:
767                 winfocus = TAILQ_FIRST(wl);
768                 break;
769
770         default:
771                 return;
772         }
773
774         if (winfocus == winlostfocus)
775                 return;
776
777         focus_win(winfocus);
778         XSync(display, False);
779 }
780
781 void
782 cycle_layout(struct swm_region *r, union arg *args)
783 {
784         struct workspace        *ws = r->ws;
785
786         DNPRINTF(SWM_D_EVENT, "cycle_layout: workspace: %d\n", ws->idx);
787
788         ws->cur_layout++;
789         if (ws->cur_layout->l_stack == NULL)
790                 ws->cur_layout = &layouts[0];
791         ignore_enter = 1;
792
793         stack();
794 }
795
796 void
797 resize_master(struct swm_region *r, union arg *args)
798 {
799         struct workspace        *ws = r->ws;
800
801         DNPRINTF(SWM_D_STACK, "resize_master for workspace %d (id %d\n",
802             args->id, ws->idx);
803
804         if (ws->cur_layout->l_resize != NULL)
805                 ws->cur_layout->l_resize(ws, args->id);
806 }
807
808 void
809 stack_reset(struct swm_region *r, union arg *args)
810 {
811         struct workspace        *ws = r->ws;
812
813         DNPRINTF(SWM_D_STACK, "stack_reset: ws %d\n", ws->idx);
814
815         if (ws->cur_layout->l_init != NULL) {
816                 ws->cur_layout->l_init(ws);
817                 stack();
818         }
819 }
820
821 void
822 stack(void) {
823         struct swm_geometry     g;
824         struct swm_region       *r;
825         int                     i, j;
826
827         DNPRINTF(SWM_D_STACK, "stack\n");
828
829         for (i = 0; i < ScreenCount(display); i++) {
830                 j = 0;
831                 TAILQ_FOREACH(r, &screens[i].rl, entry) {
832                         DNPRINTF(SWM_D_STACK, "stacking workspace %d "
833                             "(screen %d, region %d)\n", r->ws->idx, i, j++);
834
835                         /* start with screen geometry, adjust for bar */
836                         g = r->g;
837                         g.w -= 2;
838                         g.h -= 2;
839                         if (bar_enabled) {
840                                 g.y += bar_height;
841                                 g.h -= bar_height;
842                         } 
843
844                         r->ws->restack = 0;
845                         r->ws->cur_layout->l_stack(r->ws, &g);
846                 }
847         }
848         XSync(display, False);
849 }
850
851 void
852 stack_floater(struct ws_win *win, struct swm_region *r)
853 {
854         unsigned int            mask;
855         XWindowChanges          wc;
856
857         bzero(&wc, sizeof wc);
858         mask = CWX | CWY | CWBorderWidth | CWWidth | CWHeight;
859         wc.border_width = 1;
860         if (win->transient) {
861                 win->g.w = (double)WIDTH(r) * dialog_ratio;
862                 win->g.h = (double)HEIGHT(r) * dialog_ratio;
863         }
864         wc.width = win->g.w;
865         wc.height = win->g.h;
866         wc.x = (WIDTH(r) - win->g.w) / 2;
867         wc.y = (HEIGHT(r) - win->g.h) / 2;
868
869         DNPRINTF(SWM_D_STACK, "stack_floater: win %lu x %d y %d w %d h %d\n",
870             win->id, wc.x, wc.y, wc.width, wc.height);
871
872         XConfigureWindow(display, win->id, mask, &wc);
873 }
874
875 int vertical_msize[SWM_WS_MAX];
876
877 void
878 vertical_init(struct workspace *ws)
879 {
880         DNPRINTF(SWM_D_MISC, "vertical_init: workspace: %d\n", ws->idx);
881
882         ws->l_state.vertical_msize = SWM_V_SLICE / 2;
883 }
884
885 void
886 vertical_resize(struct workspace *ws, int id)
887 {
888         DNPRINTF(SWM_D_STACK, "vertical_resize: workspace: %d\n", ws->idx);
889
890         switch (id) {
891         case SWM_ARG_ID_MASTERSHRINK:
892                 ws->l_state.vertical_msize--;
893                 if (ws->l_state.vertical_msize < 1)
894                         ws->l_state.vertical_msize = 1;
895                 break;
896         case SWM_ARG_ID_MASTERGROW:
897                 ws->l_state.vertical_msize++;
898                 if (ws->l_state.vertical_msize > SWM_V_SLICE - 1)
899                         ws->l_state.vertical_msize = SWM_V_SLICE - 1;
900                 break;
901         default:
902                 return;
903         }
904         stack();
905 }
906
907 void
908 vertical_stack(struct workspace *ws, struct swm_geometry *g) {
909         XWindowChanges          wc;
910         struct swm_geometry     gg = *g;
911         struct ws_win           *win, *winfocus;
912         int                     i, hrh, winno, main_width;
913         unsigned int            mask;
914
915         DNPRINTF(SWM_D_STACK, "vertical_stack: workspace: %d\n", ws->idx);
916
917         if ((winno = count_win(ws, 0)) == 0)
918                 return;
919
920         if (ws->focus == NULL)
921                 ws->focus = TAILQ_FIRST(&ws->winlist);
922         winfocus = cur_focus ? cur_focus : ws->focus;
923
924         if (winno > 1) {
925                 main_width = (g->w / SWM_V_SLICE) *
926                    ws->l_state.vertical_msize;
927                 gg.w = main_width;
928         }
929
930         if (winno > 2)
931                 hrh = g->h / (winno - 1);
932         else
933                 hrh = 0;
934
935         i = 0;
936         TAILQ_FOREACH(win, &ws->winlist, entry) {
937                 if (i == 1) {
938                         gg.x += main_width + 2;
939                         gg.w = g->w - (main_width + 2);
940                 }
941                 if (i != 0 && hrh != 0) {
942                         /* correct the last window for lost pixels */
943                         if (win == TAILQ_LAST(&ws->winlist, ws_win_list)) {
944                                 gg.h = hrh + (g->h - (i * hrh));
945                                 gg.y += hrh;
946                         } else {
947                                 gg.h = hrh - 2;
948                                 /* leave first right hand window at y = 0 */
949                                 if (i > 1)
950                                         gg.y += gg.h + 2;
951                         }
952                 }
953
954                 if (win->transient != 0 || win->floating != 0)
955                         stack_floater(win, ws->r);
956                 else {
957                         bzero(&wc, sizeof wc);
958                         wc.border_width = 1;
959                         win->g.x = wc.x = gg.x;
960                         win->g.y = wc.y = gg.y;
961                         win->g.w = wc.width = gg.w;
962                         win->g.h = wc.height = gg.h;
963                         mask = CWX | CWY | CWWidth | CWHeight | CWBorderWidth;
964                         XConfigureWindow(display, win->id, mask, &wc);
965                 }
966
967                 XMapRaised(display, win->id);
968                 i++;
969         }
970
971         if (winfocus)
972                 focus_win(winfocus); /* has to be done outside of the loop */
973 }
974
975
976 void
977 horizontal_init(struct workspace *ws)
978 {
979         DNPRINTF(SWM_D_STACK, "horizontal_init: workspace: %d\n", ws->idx);
980
981         ws->l_state.horizontal_msize = SWM_H_SLICE / 2;
982 }
983
984 void
985 horizontal_resize(struct workspace *ws, int id)
986 {
987         DNPRINTF(SWM_D_STACK, "horizontal_resize: workspace: %d\n", ws->idx);
988
989         switch (id) {
990         case SWM_ARG_ID_MASTERSHRINK:
991                 ws->l_state.horizontal_msize--;
992                 if (ws->l_state.horizontal_msize < 1)
993                         ws->l_state.horizontal_msize = 1;
994                 break;
995         case SWM_ARG_ID_MASTERGROW:
996                 ws->l_state.horizontal_msize++;
997                 if (ws->l_state.horizontal_msize > SWM_H_SLICE - 1)
998                         ws->l_state.horizontal_msize = SWM_H_SLICE - 1;
999                 break;
1000         default:
1001                 return;
1002         }
1003         stack();
1004 }
1005
1006 void
1007 horizontal_stack(struct workspace *ws, struct swm_geometry *g) {
1008         XWindowChanges          wc;
1009         struct swm_geometry     gg = *g;
1010         struct ws_win           *win, *winfocus;
1011         int                     i, hrw, winno, main_height;
1012         unsigned int            mask;
1013
1014         DNPRINTF(SWM_D_STACK, "horizontal_stack: workspace: %d\n", ws->idx);
1015
1016         if ((winno = count_win(ws, 0)) == 0)
1017                 return;
1018
1019         if (ws->focus == NULL)
1020                 ws->focus = TAILQ_FIRST(&ws->winlist);
1021         winfocus = cur_focus ? cur_focus : ws->focus;
1022
1023         if (winno > 1) {
1024                 main_height = (g->h / SWM_H_SLICE) *
1025                     ws->l_state.horizontal_msize;
1026                 gg.h = main_height;
1027         }
1028
1029         if (winno > 2)
1030                 hrw = g->w / (winno - 1);
1031         else
1032                 hrw = 0;
1033
1034         i = 0;
1035         TAILQ_FOREACH(win, &ws->winlist, entry) {
1036                 if (i == 1) {
1037                         gg.y += main_height + 2;
1038                         gg.h = g->h - (main_height + 2);
1039                 }
1040                 if (i != 0 && hrw != 0) {
1041                         /* correct the last window for lost pixels */
1042                         if (win == TAILQ_LAST(&ws->winlist, ws_win_list)) {
1043                                 gg.w = hrw + (g->w - (i * hrw));
1044                                 gg.x += hrw;
1045                         } else {
1046                                 gg.w = hrw - 2;
1047                                 /* leave first bottom window at x = 0 */
1048                                 if (i > 1)
1049                                         gg.x += gg.w + 2;
1050                         }
1051                 }
1052
1053                 if (win->transient != 0 || win->floating != 0)
1054                         stack_floater(win, ws->r);
1055                 else {
1056                         bzero(&wc, sizeof wc);
1057                         wc.border_width = 1;
1058                         win->g.x = wc.x = gg.x;
1059                         win->g.y = wc.y = gg.y;
1060                         win->g.w = wc.width = gg.w;
1061                         win->g.h = wc.height = gg.h;
1062                         mask = CWX | CWY | CWWidth | CWHeight | CWBorderWidth;
1063                         XConfigureWindow(display, win->id, mask, &wc);
1064                 }
1065
1066                 XMapRaised(display, win->id);
1067                 i++;
1068         }
1069
1070         if (winfocus)
1071                 focus_win(winfocus); /* this has to be done outside of the loop */
1072 }
1073
1074 /* fullscreen view */
1075 void
1076 max_stack(struct workspace *ws, struct swm_geometry *g) {
1077         XWindowChanges          wc;
1078         struct swm_geometry     gg = *g;
1079         struct ws_win           *win, *winfocus;
1080         unsigned int            mask;
1081
1082         DNPRINTF(SWM_D_STACK, "max_stack: workspace: %d\n", ws->idx);
1083
1084         if (count_win(ws, 0) == 0)
1085                 return;
1086
1087         if (ws->focus == NULL)
1088                 ws->focus = TAILQ_FIRST(&ws->winlist);
1089         winfocus = cur_focus ? cur_focus : ws->focus;
1090
1091         TAILQ_FOREACH(win, &ws->winlist, entry) {
1092                 if (win->transient != 0 || win->floating != 0) {
1093                         if (win == ws->focus) {
1094                                 /* XXX maximize? */
1095                                 stack_floater(win, ws->r);
1096                                 XMapRaised(display, win->id);
1097                         } else
1098                                 XUnmapWindow(display, win->id);
1099                 } else {
1100                         bzero(&wc, sizeof wc);
1101                         wc.border_width = 1;
1102                         win->g.x = wc.x = gg.x;
1103                         win->g.y = wc.y = gg.y;
1104                         win->g.w = wc.width = gg.w;
1105                         win->g.h = wc.height = gg.h;
1106                         mask = CWX | CWY | CWWidth | CWHeight | CWBorderWidth;
1107                         XConfigureWindow(display, win->id, mask, &wc);
1108
1109                         if (win == ws->focus) {
1110                                 XMapRaised(display, win->id);
1111                         } else
1112                                 XUnmapWindow(display, win->id);
1113                 }
1114         }
1115
1116         if (winfocus)
1117                 focus_win(winfocus); /* has to be done outside of the loop */
1118 }
1119
1120 void
1121 send_to_ws(struct swm_region *r, union arg *args)
1122 {
1123         int                     wsid = args->id;
1124         struct ws_win           *win = cur_focus;
1125         struct workspace        *ws, *nws;
1126
1127         DNPRINTF(SWM_D_MOVE, "send_to_ws: win: %lu\n", win->id);
1128
1129         ws = win->ws;
1130         nws = &win->s->ws[wsid];
1131
1132         XUnmapWindow(display, win->id);
1133
1134         /* find a window to focus */
1135         ws->focus = TAILQ_PREV(win, ws_win_list, entry);
1136         if (ws->focus == NULL)
1137                 ws->focus = TAILQ_FIRST(&ws->winlist);
1138         if (ws->focus == win)
1139                 ws->focus = NULL;
1140
1141         TAILQ_REMOVE(&ws->winlist, win, entry);
1142
1143         TAILQ_INSERT_TAIL(&nws->winlist, win, entry);
1144         win->ws = nws;
1145
1146         if (count_win(nws, 1) == 1)
1147                 nws->focus = win;
1148         ws->restack = 1;
1149         nws->restack = 1;
1150
1151         stack();
1152 }
1153
1154 /* key definitions */
1155 struct key {
1156         unsigned int            mod;
1157         KeySym                  keysym;
1158         void                    (*func)(struct swm_region *r, union arg *);
1159         union arg               args;
1160 } keys[] = {
1161         /* modifier             key     function                argument */
1162         { MODKEY,               XK_space,       cycle_layout,   {0} }, 
1163         { MODKEY | ShiftMask,   XK_space,       stack_reset,    {0} }, 
1164         { MODKEY,               XK_h,           resize_master,  {.id = SWM_ARG_ID_MASTERSHRINK} },
1165         { MODKEY,               XK_l,           resize_master,  {.id = SWM_ARG_ID_MASTERGROW} },
1166         { MODKEY,               XK_Return,      swapwin,        {.id = SWM_ARG_ID_SWAPMAIN} },
1167         { MODKEY,               XK_j,           focus,          {.id = SWM_ARG_ID_FOCUSNEXT} },
1168         { MODKEY,               XK_k,           focus,          {.id = SWM_ARG_ID_FOCUSPREV} },
1169         { MODKEY | ShiftMask,   XK_j,           swapwin,        {.id = SWM_ARG_ID_SWAPNEXT} },
1170         { MODKEY | ShiftMask,   XK_k,           swapwin,        {.id = SWM_ARG_ID_SWAPPREV} },
1171         { MODKEY | ShiftMask,   XK_Return,      spawn,          {.argv = spawn_term} },
1172         { MODKEY,               XK_p,           spawn,          {.argv = spawn_menu} },
1173         { MODKEY | ShiftMask,   XK_q,           quit,           {0} },
1174         { MODKEY,               XK_q,           restart,        {0} },
1175         { MODKEY,               XK_m,           focus,          {.id = SWM_ARG_ID_FOCUSMAIN} },
1176         { MODKEY,               XK_1,           switchws,       {.id = 0} },
1177         { MODKEY,               XK_2,           switchws,       {.id = 1} },
1178         { MODKEY,               XK_3,           switchws,       {.id = 2} },
1179         { MODKEY,               XK_4,           switchws,       {.id = 3} },
1180         { MODKEY,               XK_5,           switchws,       {.id = 4} },
1181         { MODKEY,               XK_6,           switchws,       {.id = 5} },
1182         { MODKEY,               XK_7,           switchws,       {.id = 6} },
1183         { MODKEY,               XK_8,           switchws,       {.id = 7} },
1184         { MODKEY,               XK_9,           switchws,       {.id = 8} },
1185         { MODKEY,               XK_0,           switchws,       {.id = 9} },
1186         { MODKEY | ShiftMask,   XK_1,           send_to_ws,     {.id = 0} },
1187         { MODKEY | ShiftMask,   XK_2,           send_to_ws,     {.id = 1} },
1188         { MODKEY | ShiftMask,   XK_3,           send_to_ws,     {.id = 2} },
1189         { MODKEY | ShiftMask,   XK_4,           send_to_ws,     {.id = 3} },
1190         { MODKEY | ShiftMask,   XK_5,           send_to_ws,     {.id = 4} },
1191         { MODKEY | ShiftMask,   XK_6,           send_to_ws,     {.id = 5} },
1192         { MODKEY | ShiftMask,   XK_7,           send_to_ws,     {.id = 6} },
1193         { MODKEY | ShiftMask,   XK_8,           send_to_ws,     {.id = 7} },
1194         { MODKEY | ShiftMask,   XK_9,           send_to_ws,     {.id = 8} },
1195         { MODKEY | ShiftMask,   XK_0,           send_to_ws,     {.id = 9} },
1196         { MODKEY,               XK_b,           bar_toggle,     {0} },
1197         { MODKEY,               XK_Tab,         focus,          {.id = SWM_ARG_ID_FOCUSNEXT} },
1198         { MODKEY | ShiftMask,   XK_Tab,         focus,          {.id = SWM_ARG_ID_FOCUSPREV} },
1199 };
1200
1201 void
1202 updatenumlockmask(void)
1203 {
1204         unsigned int            i, j;
1205         XModifierKeymap         *modmap;
1206
1207         DNPRINTF(SWM_D_MISC, "updatenumlockmask\n");
1208         numlockmask = 0;
1209         modmap = XGetModifierMapping(display);
1210         for (i = 0; i < 8; i++)
1211                 for (j = 0; j < modmap->max_keypermod; j++)
1212                         if (modmap->modifiermap[i * modmap->max_keypermod + j]
1213                           == XKeysymToKeycode(display, XK_Num_Lock))
1214                                 numlockmask = (1 << i);
1215
1216         XFreeModifiermap(modmap);
1217 }
1218
1219 void
1220 grabkeys(void)
1221 {
1222         unsigned int            i, j, k;
1223         KeyCode                 code;
1224         unsigned int            modifiers[] =
1225             { 0, LockMask, numlockmask, numlockmask | LockMask };
1226
1227         DNPRINTF(SWM_D_MISC, "grabkeys\n");
1228         updatenumlockmask();
1229
1230         for (k = 0; k < ScreenCount(display); k++) {
1231                 if (TAILQ_EMPTY(&screens[k].rl))
1232                         continue;
1233                 XUngrabKey(display, AnyKey, AnyModifier, screens[k].root);
1234                 for(i = 0; i < LENGTH(keys); i++) {
1235                         if((code = XKeysymToKeycode(display, keys[i].keysym)))
1236                                 for(j = 0; j < LENGTH(modifiers); j++)
1237                                         XGrabKey(display, code,
1238                                             keys[i].mod | modifiers[j],
1239                                             screens[k].root, True,
1240                                             GrabModeAsync, GrabModeAsync);
1241                 }
1242         }
1243 }
1244 void
1245 expose(XEvent *e)
1246 {
1247         DNPRINTF(SWM_D_EVENT, "expose: window: %lu\n", e->xexpose.window);
1248 }
1249
1250 void
1251 keypress(XEvent *e)
1252 {
1253         unsigned int            i;
1254         KeySym                  keysym;
1255         XKeyEvent               *ev = &e->xkey;
1256
1257         DNPRINTF(SWM_D_EVENT, "keypress: window: %lu\n", ev->window);
1258
1259         keysym = XKeycodeToKeysym(display, (KeyCode)ev->keycode, 0);
1260         for (i = 0; i < LENGTH(keys); i++)
1261                 if (keysym == keys[i].keysym
1262                    && CLEANMASK(keys[i].mod) == CLEANMASK(ev->state)
1263                    && keys[i].func)
1264                         keys[i].func(root_to_region(ev->root),
1265                             &(keys[i].args));
1266 }
1267
1268 void
1269 buttonpress(XEvent *e)
1270 {
1271         XButtonPressedEvent     *ev = &e->xbutton;
1272 #ifdef SWM_CLICKTOFOCUS
1273         struct ws_win           *win;
1274         struct workspace        *ws;
1275         struct swm_region       *r;
1276 #endif
1277
1278         DNPRINTF(SWM_D_EVENT, "buttonpress: window: %lu\n", ev->window);
1279
1280         if (ev->window == ev->root) {
1281                 rootclick = ev->root;
1282                 return;
1283         }
1284         if (ev->window == cur_focus->id)
1285                 return;
1286 #ifdef SWM_CLICKTOFOCUS
1287         r = root_to_region(ev->root);
1288         ws = r->ws;
1289         TAILQ_FOREACH(win, &ws->winlist, entry)
1290                 if (win->id == ev->window) {
1291                         /* focus in the clicked window */
1292                         XSetWindowBorder(display, ev->window, 0xff0000);
1293                         XSetWindowBorder(display, ws->focus->id, 0x888888);
1294                         XSetInputFocus(display, ev->window, RevertToPointerRoot,
1295                             CurrentTime);
1296                         ws->focus = win;
1297                         XSync(display, False);
1298                         break;
1299         }
1300 #endif
1301 }
1302
1303 void
1304 set_win_state(struct ws_win *win, long state)
1305 {
1306         long                    data[] = {state, None};
1307
1308         DNPRINTF(SWM_D_EVENT, "set_win_state: window: %lu\n", win->id);
1309
1310         XChangeProperty(display, win->id, astate, astate, 32, PropModeReplace,
1311             (unsigned char *)data, 2);
1312 }
1313
1314 struct ws_win *
1315 manage_window(Window id, struct workspace *ws)
1316 {
1317         Window                  trans;
1318         struct ws_win           *win;
1319         XClassHint              ch;
1320
1321         TAILQ_FOREACH(win, &ws->winlist, entry) {
1322                 if (win->id == id)
1323                         return (win);   /* already being managed */
1324         }
1325
1326         if ((win = calloc(1, sizeof(struct ws_win))) == NULL)
1327                 errx(1, "calloc: failed to allocate memory for new window");
1328
1329         win->id = id;
1330         win->ws = ws;
1331         win->s = ws->r->s;      /* this never changes */
1332         TAILQ_INSERT_TAIL(&ws->winlist, win, entry);
1333
1334         /* make new win focused */
1335         focus_win(win);
1336
1337         XGetTransientForHint(display, win->id, &trans);
1338         if (trans) {
1339                 win->transient = trans;
1340                 DNPRINTF(SWM_D_MISC, "manage_window: win %u transient %u\n",
1341                     (unsigned)win->id, win->transient);
1342         }
1343         XGetWindowAttributes(display, id, &win->wa);
1344         win->g.w = win->wa.width;
1345         win->g.h = win->wa.height;
1346         win->g.x = win->wa.x;
1347         win->g.y = win->wa.y;
1348
1349         /* XXX make this a table */
1350         bzero(&ch, sizeof ch);
1351         if (XGetClassHint(display, win->id, &ch)) {
1352                 /*fprintf(stderr, "class: %s name: %s\n", ch.res_class, ch.res_name); */
1353                 if (!strcmp(ch.res_class, "MPlayer") && !strcmp(ch.res_name, "xv")) {
1354                         win->floating = 1;
1355                 }
1356                 if (ch.res_class)
1357                         XFree(ch.res_class);
1358                 if (ch.res_name)
1359                         XFree(ch.res_name);
1360         }
1361
1362         XSelectInput(display, id, EnterWindowMask | FocusChangeMask |
1363             PropertyChangeMask | StructureNotifyMask);
1364
1365         set_win_state(win, NormalState);
1366
1367         return (win);
1368 }
1369
1370 void
1371 configurerequest(XEvent *e)
1372 {
1373         XConfigureRequestEvent  *ev = &e->xconfigurerequest;
1374         struct ws_win           *win;
1375         int                     new = 1;
1376         XWindowChanges          wc;
1377
1378         if ((win = find_window(ev->window)) == NULL)
1379                 new = 1;
1380
1381         if (new) {
1382                 DNPRINTF(SWM_D_EVENT, "configurerequest: new window: %lu\n",
1383                     ev->window);
1384                 bzero(&wc, sizeof wc);
1385                 wc.x = ev->x;
1386                 wc.y = ev->y;
1387                 wc.width = ev->width;
1388                 wc.height = ev->height;
1389                 wc.border_width = ev->border_width;
1390                 wc.sibling = ev->above;
1391                 wc.stack_mode = ev->detail;
1392                 XConfigureWindow(display, ev->window, ev->value_mask, &wc);
1393         } else {
1394                 DNPRINTF(SWM_D_EVENT, "configurerequest: change window: %lu\n",
1395                     ev->window);
1396                 if (win->floating) {
1397                         if (ev->value_mask & CWX)
1398                                 win->g.x = ev->x;
1399                         if (ev->value_mask & CWY)
1400                                 win->g.y = ev->y;
1401                         if (ev->value_mask & CWWidth)
1402                                 win->g.w = ev->width;
1403                         if (ev->value_mask & CWHeight)
1404                                 win->g.h = ev->height;
1405                         if (win->ws->r != NULL) {
1406                                 /* this seems to be full screen */
1407                                 if (win->g.w > WIDTH(win->ws->r)) {
1408                                         /* kill border */
1409                                         win->g.x -= 1;
1410                                         win->g.w += 1;
1411                                 }
1412                                 if (win->g.h > HEIGHT(win->ws->r)) {
1413                                         /* kill border */
1414                                         win->g.y -= 1;
1415                                         win->g.h += 1;
1416                                 }
1417                         }
1418                         if ((ev->value_mask & (CWX|CWY)) &&
1419                             !(ev->value_mask & (CWWidth|CWHeight)))
1420                                 config_win(win);
1421                         XMoveResizeWindow(display, win->id,
1422                             win->g.x, win->g.y, win->g.w, win->g.h);
1423                 } else
1424                         config_win(win);
1425         }
1426 }
1427
1428 void
1429 configurenotify(XEvent *e)
1430 {
1431         DNPRINTF(SWM_D_EVENT, "configurenotify: window: %lu\n",
1432             e->xconfigure.window);
1433 }
1434
1435 void
1436 destroynotify(XEvent *e)
1437 {
1438         struct ws_win           *win;
1439         XDestroyWindowEvent     *ev = &e->xdestroywindow;
1440
1441         DNPRINTF(SWM_D_EVENT, "destroynotify: window %lu\n", ev->window);
1442
1443         if ((win = find_window(ev->window)) != NULL) {
1444                 struct workspace *ws = win->ws;
1445                 /* find a window to focus */
1446                 if (ws->focus == win)
1447                         ws->focus = TAILQ_PREV(win, ws_win_list, entry);
1448                 if (ws->focus == NULL)
1449                         ws->focus = TAILQ_FIRST(&ws->winlist);
1450                 if (ws->focus == win)
1451                         ws->focus = NULL;
1452                 if (cur_focus == win) {
1453                         if (ws->focus == NULL) 
1454                                 unfocus_win(win); /* XXX focus another ws? */
1455                         else
1456                                 focus_win(ws->focus);
1457                 }
1458
1459                 TAILQ_REMOVE(&ws->winlist, win, entry);
1460                 set_win_state(win, WithdrawnState);
1461                 free(win);
1462         }
1463
1464         stack();
1465 }
1466
1467 void
1468 enternotify(XEvent *e)
1469 {
1470         XCrossingEvent          *ev = &e->xcrossing;
1471         struct ws_win           *win;
1472         int                     i, j;
1473
1474         DNPRINTF(SWM_D_EVENT, "enternotify: window: %lu\n", ev->window);
1475
1476         if((ev->mode != NotifyNormal || ev->detail == NotifyInferior) &&
1477             ev->window != ev->root)
1478                 return;
1479         if (ignore_enter) {
1480                 /* eat event(r) to prevent autofocus */
1481                 ignore_enter--;
1482                 return;
1483         }
1484         /* brute force for now */
1485         for (i = 0; i < ScreenCount(display); i++) {
1486                 for (j = 0; j < SWM_WS_MAX; j++) {
1487                         TAILQ_FOREACH(win, &screens[i].ws[j].winlist , entry) {
1488                                 if (win->id == ev->window)
1489                                         focus_win(win);
1490                         }
1491                 }
1492         }
1493 }
1494
1495 void
1496 focusin(XEvent *e)
1497 {
1498         DNPRINTF(SWM_D_EVENT, "focusin: window: %lu\n", e->xfocus.window);
1499
1500         /* XXX this probably needs better handling now.
1501         if (ev->window == ev->root)
1502                 return;
1503         */
1504         /*
1505          * kill grab for now so that we can cut and paste , this screws up
1506          * click to focus
1507          */
1508         /*
1509         DNPRINTF(SWM_D_EVENT, "focusin: window: %lu grabbing\n", ev->window);
1510         XGrabButton(display, Button1, AnyModifier, ev->window, False,
1511             ButtonPress, GrabModeAsync, GrabModeSync, None, None);
1512         */
1513 }
1514
1515 void
1516 mappingnotify(XEvent *e)
1517 {
1518         XMappingEvent           *ev = &e->xmapping;
1519
1520         DNPRINTF(SWM_D_EVENT, "mappingnotify: window: %lu\n", ev->window);
1521
1522         XRefreshKeyboardMapping(ev);
1523         if (ev->request == MappingKeyboard)
1524                 grabkeys();
1525 }
1526
1527 void
1528 maprequest(XEvent *e)
1529 {
1530         XMapRequestEvent        *ev = &e->xmaprequest;
1531         XWindowAttributes       wa;
1532         struct swm_region       *r;
1533
1534         DNPRINTF(SWM_D_EVENT, "maprequest: window: %lu\n",
1535             e->xmaprequest.window);
1536
1537         if (!XGetWindowAttributes(display, ev->window, &wa))
1538                 return;
1539         if (wa.override_redirect)
1540                 return;
1541         r = root_to_region(wa.root);
1542         manage_window(e->xmaprequest.window, r->ws);
1543         stack();
1544 }
1545
1546 void
1547 propertynotify(XEvent *e)
1548 {
1549         DNPRINTF(SWM_D_EVENT, "propertynotify: window: %lu\n",
1550             e->xproperty.window);
1551 }
1552
1553 void
1554 unmapnotify(XEvent *e)
1555 {
1556         DNPRINTF(SWM_D_EVENT, "unmapnotify: window: %lu\n", e->xunmap.window);
1557 }
1558
1559 void
1560 visibilitynotify(XEvent *e)
1561 {
1562         int                     i;
1563         struct swm_region       *r;
1564
1565         DNPRINTF(SWM_D_EVENT, "visibilitynotify: window: %lu\n",
1566             e->xvisibility.window);
1567         if (e->xvisibility.state == VisibilityUnobscured)
1568                 for (i = 0; i < ScreenCount(display); i++) 
1569                         TAILQ_FOREACH(r, &screens[i].rl, entry)
1570                                 if (e->xvisibility.window == r->bar_window)
1571                                         bar_print(r);
1572 }
1573
1574 void                    (*handler[LASTEvent])(XEvent *) = {
1575                                 [Expose] = expose,
1576                                 [KeyPress] = keypress,
1577                                 [ButtonPress] = buttonpress,
1578                                 [ConfigureRequest] = configurerequest,
1579                                 [ConfigureNotify] = configurenotify,
1580                                 [DestroyNotify] = destroynotify,
1581                                 [EnterNotify] = enternotify,
1582                                 [FocusIn] = focusin,
1583                                 [MappingNotify] = mappingnotify,
1584                                 [MapRequest] = maprequest,
1585                                 [PropertyNotify] = propertynotify,
1586                                 [UnmapNotify] = unmapnotify,
1587                                 [VisibilityNotify] = visibilitynotify,
1588 };
1589
1590 int
1591 xerror_start(Display *d, XErrorEvent *ee)
1592 {
1593         other_wm = 1;
1594         return (-1);
1595 }
1596
1597 int
1598 xerror(Display *d, XErrorEvent *ee)
1599 {
1600         /* fprintf(stderr, "error: %p %p\n", display, ee); */
1601         return (-1);
1602 }
1603
1604 int
1605 active_wm(void)
1606 {
1607         other_wm = 0;
1608         xerrorxlib = XSetErrorHandler(xerror_start);
1609
1610         /* this causes an error if some other window manager is running */
1611         XSelectInput(display, DefaultRootWindow(display),
1612             SubstructureRedirectMask);
1613         XSync(display, False);
1614         if (other_wm)
1615                 return (1);
1616
1617         XSetErrorHandler(xerror);
1618         XSync(display, False);
1619         return (0);
1620 }
1621
1622 long
1623 getstate(Window w)
1624 {
1625         int                     format, status;
1626         long                    result = -1;
1627         unsigned char           *p = NULL;
1628         unsigned long           n, extra;
1629         Atom                    real;
1630
1631         astate = XInternAtom(display, "WM_STATE", False);
1632         status = XGetWindowProperty(display, w, astate, 0L, 2L, False, astate,
1633             &real, &format, &n, &extra, (unsigned char **)&p);
1634         if (status != Success)
1635                 return (-1);
1636         if (n != 0)
1637                 result = *p;
1638         XFree(p);
1639         return (result);
1640 }
1641
1642 void
1643 new_region(struct swm_screen *s, struct workspace *ws,
1644     int x, int y, int w, int h)
1645 {
1646         struct swm_region       *r;
1647
1648         DNPRINTF(SWM_D_MISC, "new region on screen %d: %dx%d (%d, %d)\n",
1649              s->idx, x, y, w, h);
1650
1651         if ((r = calloc(1, sizeof(struct swm_region))) == NULL)
1652                 errx(1, "calloc: failed to allocate memory for screen");
1653
1654         X(r) = x;
1655         Y(r) = y;
1656         WIDTH(r) = w;
1657         HEIGHT(r) = h;
1658         r->s = s;
1659         r->ws = ws;
1660         ws->r = r;
1661         TAILQ_INSERT_TAIL(&s->rl, r, entry);
1662         bar_setup(r);
1663 }
1664
1665 void
1666 setup_screens(void)
1667 {
1668 #ifdef SWM_XRR_HAS_CRTC
1669         XRRCrtcInfo             *ci;
1670         XRRScreenResources      *sr;
1671         int                     c;
1672 #endif /* SWM_XRR_HAS_CRTC */
1673         Window                  d1, d2, *wins = NULL;
1674         XWindowAttributes       wa;
1675         struct swm_region       *r;
1676         unsigned int            no;
1677         int                     errorbase, major, minor;
1678         int                     ncrtc = 0, w = 0;
1679         int                     i, j, k;
1680         struct workspace        *ws;
1681
1682         if ((screens = calloc(ScreenCount(display),
1683              sizeof(struct swm_screen))) == NULL)
1684                 errx(1, "calloc: screens");
1685
1686         /* map physical screens */
1687         for (i = 0; i < ScreenCount(display); i++) {
1688                 DNPRINTF(SWM_D_WS, "setup_screens: init screen %d\n", i);
1689                 screens[i].idx = i;
1690                 TAILQ_INIT(&screens[i].rl);
1691                 screens[i].root = RootWindow(display, i);
1692                 XGetWindowAttributes(display, screens[i].root, &wa);
1693                 XSelectInput(display, screens[i].root,
1694                     ButtonPressMask | wa.your_event_mask);
1695
1696                 /* set default colors */
1697                 screens[i].color_focus = name_to_color("red");
1698                 screens[i].color_unfocus = name_to_color("rgb:88/88/88");
1699                 screens[i].bar_border = name_to_color("rgb:00/80/80");
1700                 screens[i].bar_color = name_to_color("black");
1701                 screens[i].bar_font_color = name_to_color("rgb:a0/a0/a0");
1702
1703                 /* init all workspaces */
1704                 for (j = 0; j < SWM_WS_MAX; j++) {
1705                         ws = &screens[i].ws[j];
1706                         ws->idx = j;
1707                         ws->restack = 1;
1708                         ws->focus = NULL;
1709                         ws->r = NULL;
1710                         TAILQ_INIT(&ws->winlist);
1711
1712                         for (k = 0; layouts[k].l_stack != NULL; k++)
1713                                 if (layouts[k].l_init != NULL)
1714                                         layouts[k].l_init(ws);
1715                         ws->cur_layout = &layouts[0];
1716                 }
1717
1718                 /* map virtual screens onto physical screens */
1719                 screens[i].xrandr_support = XRRQueryExtension(display,
1720                     &xrandr_eventbase, &errorbase);
1721                 if (screens[i].xrandr_support)
1722                         if (XRRQueryVersion(display, &major, &minor) &&
1723                             major < 1)
1724                                 screens[i].xrandr_support = 0;
1725
1726 #if 0   /* not ready for dynamic screen changes */
1727                 if (screens[i].xrandr_support)
1728                         XRRSelectInput(display,
1729                             screens[r->s].root,
1730                             RRScreenChangeNotifyMask);
1731 #endif
1732
1733                 /* grab existing windows (before we build the bars)*/
1734                 if (!XQueryTree(display, screens[i].root, &d1, &d2, &wins, &no))
1735                         continue;
1736
1737 #ifdef SWM_XRR_HAS_CRTC
1738                 sr = XRRGetScreenResources(display, screens[i].root);
1739                 if (sr == NULL)
1740                         new_region(&screens[i], &screens[i].ws[w],
1741                             0, 0, DisplayWidth(display, i),
1742                             DisplayHeight(display, i)); 
1743                 else 
1744                         ncrtc = sr->ncrtc;
1745
1746                 for (c = 0; c < ncrtc; c++) {
1747                         ci = XRRGetCrtcInfo(display, sr, sr->crtcs[c]);
1748                         if (ci->noutput == 0)
1749                                 continue;
1750
1751                         if (ci != NULL && ci->mode == None)
1752                                 new_region(&screens[i], &screens[i].ws[w], 0, 0,
1753                                     DisplayWidth(display, i),
1754                                     DisplayHeight(display, i)); 
1755                         else
1756                                 new_region(&screens[i], &screens[i].ws[w],
1757                                     ci->x, ci->y, ci->width, ci->height);
1758                         w++;
1759                 }
1760                 XRRFreeCrtcInfo(ci);
1761                 XRRFreeScreenResources(sr);
1762 #else
1763                 new_region(&screens[i], &screens[i].ws[w], 0, 0,
1764                     DisplayWidth(display, i),
1765                     DisplayHeight(display, i)); 
1766 #endif /* SWM_XRR_HAS_CRTC */
1767
1768                 /* attach windows to a region */
1769                 /* normal windows */
1770                 if ((r = TAILQ_FIRST(&screens[i].rl)) == NULL)
1771                         errx(1, "no regions on screen %d", i);
1772
1773                 for (i = 0; i < no; i++) {
1774                         XGetWindowAttributes(display, wins[i], &wa);
1775                         if (!XGetWindowAttributes(display, wins[i], &wa) ||
1776                             wa.override_redirect ||
1777                             XGetTransientForHint(display, wins[i], &d1))
1778                                 continue;
1779
1780                         if (wa.map_state == IsViewable ||
1781                             getstate(wins[i]) == NormalState)
1782                                 manage_window(wins[i], r->ws);
1783                 }
1784                 /* transient windows */
1785                 for (i = 0; i < no; i++) {
1786                         if (!XGetWindowAttributes(display, wins[i], &wa))
1787                                 continue;
1788
1789                         if (XGetTransientForHint(display, wins[i], &d1) &&
1790                             (wa.map_state == IsViewable || getstate(wins[i]) ==
1791                             NormalState))
1792                                 manage_window(wins[i], r->ws);
1793                 }
1794                 if (wins) {
1795                         XFree(wins);
1796                         wins = NULL;
1797                 }
1798         }
1799 }
1800
1801 int
1802 main(int argc, char *argv[])
1803 {
1804         struct passwd           *pwd;
1805         char                    conf[PATH_MAX], *cfile = NULL;
1806         struct stat             sb;
1807         XEvent                  e;
1808
1809         start_argv = argv;
1810         fprintf(stderr, "Welcome to scrotwm V%s\n", SWM_VERSION);
1811         if (!setlocale(LC_CTYPE, "") || !XSupportsLocale())
1812                 warnx("no locale support");
1813
1814         if (!(display = XOpenDisplay(0)))
1815                 errx(1, "can not open display");
1816
1817         if (active_wm())
1818                 errx(1, "other wm running");
1819
1820         astate = XInternAtom(display, "WM_STATE", False);
1821
1822         /* look for local and global conf file */
1823         pwd = getpwuid(getuid());
1824         if (pwd == NULL)
1825                 errx(1, "invalid user %d", getuid());
1826
1827         snprintf(conf, sizeof conf, "%s/.%s", pwd->pw_dir, SWM_CONF_FILE);
1828         if (stat(conf, &sb) != -1) {
1829                 if (S_ISREG(sb.st_mode))
1830                         cfile = conf;
1831         } else {
1832                 /* try global conf file */
1833                 snprintf(conf, sizeof conf, "/etc/%s", SWM_CONF_FILE);
1834                 if (!stat(conf, &sb))
1835                         if (S_ISREG(sb.st_mode))
1836                                 cfile = conf;
1837         }
1838         if (cfile)
1839                 conf_load(cfile);
1840
1841         setup_screens();
1842
1843         /* ws[0].focus = TAILQ_FIRST(&ws[0].winlist); */
1844
1845         grabkeys();
1846         stack();
1847
1848         while (running) {
1849                 XNextEvent(display, &e);
1850                 if (handler[e.type])
1851                         handler[e.type](&e);
1852         }
1853
1854         XCloseDisplay(display);
1855
1856         return (0);
1857 }