JasonWoof Got questions, comments, patches, etc.? Contact Jason Woofenden
Cleanup; get rid of crufty cur_ws and cur_region and replace with
[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         int i;
542
543         for (i = 0; i < ScreenCount(display); i++)
544                 if (screens[i].root == root)
545                         break;
546
547         if (rootclick != root && /* if root was just clicked in, use cursor */
548             cur_focus && cur_focus->ws->r && cur_focus->s == &screens[i])
549                 r = cur_focus->ws->r;
550         else {
551                 Window                  rr, cr;
552                 int                     x, y, wx, wy;
553                 unsigned int            mask;
554                         
555                 if (XQueryPointer(display, screens[i].root, 
556                     &rr, &cr, &x, &y, &wx, &wy, &mask) == False) {
557                         r = TAILQ_FIRST(&screens[i].rl);
558                 } else {
559                         TAILQ_FOREACH(r, &screens[i].rl, entry) {
560                                 if (x > X(r) && x < X(r) + WIDTH(r) &&
561                                     y > Y(r) && y < Y(r) + HEIGHT(r)) {
562                                         break;
563                                 }
564                         }
565
566                         if (r == NULL)
567                                 r = TAILQ_FIRST(&screens[i].rl);
568                 }
569         }
570         return (r);
571 }
572
573 struct ws_win *
574 find_window(Window id)
575 {
576         struct ws_win *win;
577         int i, j;
578
579         for (i = 0; i < ScreenCount(display); i++)
580                 for (j = 0; j < SWM_WS_MAX; j++)
581                         TAILQ_FOREACH(win, &screens[i].ws[j].winlist, entry)
582                                 if (id == win->id)
583                                         return (win);
584         return (NULL);
585 }
586
587 void
588 spawn(struct swm_region *r, union arg *args)
589 {
590         DNPRINTF(SWM_D_MISC, "spawn: %s\n", args->argv[0]);
591         /*
592          * The double-fork construct avoids zombie processes and keeps the code
593          * clean from stupid signal handlers.
594          */
595         if (fork() == 0) {
596                 if (fork() == 0) {
597                         if (display)
598                                 close(ConnectionNumber(display));
599                         setsid();
600                         execvp(args->argv[0], args->argv);
601                         fprintf(stderr, "execvp failed\n");
602                         perror(" failed");
603                 }
604                 exit(0);
605         }
606         wait(0);
607 }
608
609 void
610 unfocus_win(struct ws_win *win)
611 {
612         DNPRINTF(SWM_D_FOCUS, "unfocus_win: id: %lu\n", win->id);
613         if (win->ws->r && win->focus)
614                 XSetWindowBorder(display, win->id,
615                     win->ws->r->s->color_unfocus);
616         win->focus = 0;
617         if (win->ws->focus == win)
618                 win->ws->focus = NULL;
619         if (cur_focus == win)
620                 cur_focus = NULL;
621 }
622
623
624 void
625 focus_win(struct ws_win *win)
626 {
627         DNPRINTF(SWM_D_FOCUS, "focus_win: id: %lu\n", win->id);
628
629         rootclick = 0;
630
631         win->ws->focus = win;
632         if (win->ws->r != NULL) {
633                 if (cur_focus && cur_focus != win)
634                         unfocus_win(cur_focus);
635                 cur_focus = win;
636                 if (!win->focus)
637                         XSetWindowBorder(display, win->id,
638                             win->ws->r->s->color_focus);
639                 win->focus = 1;
640                 XSetInputFocus(display, win->id,
641                     RevertToPointerRoot, CurrentTime);
642         }
643 }
644
645 void
646 switchws(struct swm_region *r, union arg *args)
647 {
648         int                     wsid = args->id;
649         struct swm_region       *this_r, *other_r;
650         struct ws_win           *win;
651         struct workspace        *new_ws, *old_ws;
652
653         this_r = r;
654         old_ws = this_r->ws;
655         new_ws = &this_r->s->ws[wsid];
656
657         DNPRINTF(SWM_D_WS, "switchws screen %d region %dx%d+%d+%d: "
658             "%d -> %d\n", r->s->idx, WIDTH(r), HEIGHT(r), X(r), Y(r),
659             old_ws->idx, wsid);
660
661         if (new_ws == old_ws)
662                 return;
663
664         other_r = new_ws->r;
665         if (!other_r) {
666                 /* if the other region is hidden, switch windows */
667         
668                 /* map new window first to prevent ugly blinking */
669                 TAILQ_FOREACH(win, &new_ws->winlist, entry)
670                         XMapRaised(display, win->id);
671
672                 TAILQ_FOREACH(win, &old_ws->winlist, entry)
673                         XUnmapWindow(display, win->id);
674
675                 old_ws->r = NULL;
676                 old_ws->restack = 1;
677         } else {
678                 other_r->ws = old_ws;
679                 old_ws->r = other_r;
680         }
681         this_r->ws = new_ws;
682         new_ws->r = this_r;
683
684         ignore_enter = 1;
685         /* set focus */
686         if (new_ws->focus)
687                 focus_win(new_ws->focus);
688         stack();
689 }
690
691 void
692 swapwin(struct swm_region *r, union arg *args)
693 {
694         struct ws_win           *target;
695         struct ws_win_list      *wl;
696
697
698         DNPRINTF(SWM_D_WS, "swapwin id %d "
699             "in screen %d region %dx%d+%d+%d ws %d\n", args->id,
700             r->s->idx, WIDTH(r), HEIGHT(r), X(r), Y(r), r->ws->idx);
701         if (cur_focus == NULL)
702                 return;
703
704         wl = &cur_focus->ws->winlist;
705
706         switch (args->id) {
707         case SWM_ARG_ID_SWAPPREV:
708                 target = TAILQ_PREV(cur_focus, ws_win_list, entry);
709                 TAILQ_REMOVE(wl, cur_focus, entry);
710                 if (target == NULL)
711                         TAILQ_INSERT_TAIL(wl, cur_focus, entry);
712                 else
713                         TAILQ_INSERT_BEFORE(target, cur_focus, entry);
714                 break;
715         case SWM_ARG_ID_SWAPNEXT: 
716                 target = TAILQ_NEXT(cur_focus, entry);
717                 TAILQ_REMOVE(wl, cur_focus, entry);
718                 if (target == NULL)
719                         TAILQ_INSERT_HEAD(wl, cur_focus, entry);
720                 else
721                         TAILQ_INSERT_AFTER(wl, target, cur_focus, entry);
722                 break;
723         case SWM_ARG_ID_SWAPMAIN:
724                 target = TAILQ_FIRST(wl);
725                 if (target == cur_focus)
726                         return;
727                 TAILQ_REMOVE(wl, target, entry);
728                 TAILQ_INSERT_BEFORE(cur_focus, target, entry);
729                 TAILQ_REMOVE(wl, cur_focus, entry);
730                 TAILQ_INSERT_HEAD(wl, cur_focus, entry);
731                 break;
732         default:
733                 DNPRINTF(SWM_D_MOVE, "invalid id: %d\n", args->id);
734                 return;
735         }
736
737         ignore_enter = 2;
738         stack();
739 }
740
741 void
742 focus(struct swm_region *r, union arg *args)
743 {
744         struct ws_win           *winfocus, *winlostfocus;
745         struct ws_win_list      *wl;
746
747         DNPRINTF(SWM_D_FOCUS, "focus: id %d\n", args->id);
748         if (cur_focus == NULL)
749                 return;
750
751         wl = &cur_focus->ws->winlist;
752
753         winlostfocus = cur_focus;
754
755         switch (args->id) {
756         case SWM_ARG_ID_FOCUSPREV:
757                 winfocus = TAILQ_PREV(cur_focus, ws_win_list, entry);
758                 if (winfocus == NULL)
759                         winfocus = TAILQ_LAST(wl, ws_win_list);
760                 break;
761
762         case SWM_ARG_ID_FOCUSNEXT:
763                 winfocus = TAILQ_NEXT(cur_focus, entry);
764                 if (winfocus == NULL)
765                         winfocus = TAILQ_FIRST(wl);
766                 break;
767
768         case SWM_ARG_ID_FOCUSMAIN:
769                 winfocus = TAILQ_FIRST(wl);
770                 break;
771
772         default:
773                 return;
774         }
775
776         if (winfocus == winlostfocus)
777                 return;
778
779         focus_win(winfocus);
780         XSync(display, False);
781 }
782
783 void
784 cycle_layout(struct swm_region *r, union arg *args)
785 {
786         struct workspace *ws = r->ws;
787
788         DNPRINTF(SWM_D_EVENT, "cycle_layout: workspace: %d\n", ws->idx);
789
790         ws->cur_layout++;
791         if (ws->cur_layout->l_stack == NULL)
792                 ws->cur_layout = &layouts[0];
793         ignore_enter = 1;
794
795         stack();
796 }
797
798 void
799 resize_master(struct swm_region *r, union arg *args)
800 {
801         struct workspace        *ws = r->ws;
802
803         DNPRINTF(SWM_D_STACK, "resize_master for workspace %d (id %d\n",
804             args->id, ws->idx);
805
806         if (ws->cur_layout->l_resize != NULL)
807                 ws->cur_layout->l_resize(ws, args->id);
808 }
809
810 void
811 stack_reset(struct swm_region *r, union arg *args)
812 {
813         struct workspace        *ws = r->ws;
814
815         DNPRINTF(SWM_D_STACK, "stack_reset: ws %d\n", ws->idx);
816
817         if (ws->cur_layout->l_init != NULL) {
818                 ws->cur_layout->l_init(ws);
819                 stack();
820         }
821 }
822
823 void
824 stack(void) {
825         struct swm_geometry g;
826         struct swm_region *r;
827         int i, j;
828
829         DNPRINTF(SWM_D_STACK, "stack\n");
830
831         for (i = 0; i < ScreenCount(display); i++) {
832                 j = 0;
833                 TAILQ_FOREACH(r, &screens[i].rl, entry) {
834                         DNPRINTF(SWM_D_STACK, "stacking workspace %d "
835                             "(screen %d, region %d)\n", r->ws->idx, i, j++);
836
837                         /* start with screen geometry, adjust for bar */
838                         g = r->g;
839                         g.w -= 2;
840                         g.h -= 2;
841                         if (bar_enabled) {
842                                 g.y += bar_height;
843                                 g.h -= bar_height;
844                         } 
845
846                         r->ws->restack = 0;
847                         r->ws->cur_layout->l_stack(r->ws, &g);
848                 }
849         }
850         XSync(display, False);
851 }
852
853 void
854 stack_floater(struct ws_win *win, struct swm_region *r)
855 {
856         unsigned int            mask;
857         XWindowChanges          wc;
858
859         bzero(&wc, sizeof wc);
860         mask = CWX | CWY | CWBorderWidth | CWWidth | CWHeight;
861         wc.border_width = 1;
862         if (win->transient) {
863                 win->g.w = (double)WIDTH(r) * dialog_ratio;
864                 win->g.h = (double)HEIGHT(r) * dialog_ratio;
865         }
866         wc.width = win->g.w;
867         wc.height = win->g.h;
868         wc.x = (WIDTH(r) - win->g.w) / 2;
869         wc.y = (HEIGHT(r) - win->g.h) / 2;
870
871         DNPRINTF(SWM_D_STACK, "stack_floater: win %lu x %d y %d w %d h %d\n",
872             win->id, wc.x, wc.y, wc.width, wc.height);
873
874         XConfigureWindow(display, win->id, mask, &wc);
875 }
876
877 int vertical_msize[SWM_WS_MAX];
878
879 void
880 vertical_init(struct workspace *ws)
881 {
882         DNPRINTF(SWM_D_MISC, "vertical_init: workspace: %d\n", ws->idx);
883
884         ws->l_state.vertical_msize = SWM_V_SLICE / 2;
885 }
886
887 void
888 vertical_resize(struct workspace *ws, int id)
889 {
890         DNPRINTF(SWM_D_STACK, "vertical_resize: workspace: %d\n", ws->idx);
891
892         switch (id) {
893         case SWM_ARG_ID_MASTERSHRINK:
894                 ws->l_state.vertical_msize--;
895                 if (ws->l_state.vertical_msize < 1)
896                         ws->l_state.vertical_msize = 1;
897                 break;
898         case SWM_ARG_ID_MASTERGROW:
899                 ws->l_state.vertical_msize++;
900                 if (ws->l_state.vertical_msize > SWM_V_SLICE - 1)
901                         ws->l_state.vertical_msize = SWM_V_SLICE - 1;
902                 break;
903         default:
904                 return;
905         }
906         stack();
907 }
908
909 void
910 vertical_stack(struct workspace *ws, struct swm_geometry *g) {
911         XWindowChanges          wc;
912         struct swm_geometry     gg = *g;
913         struct ws_win           *win, *winfocus;
914         int                     i, hrh, winno, main_width;
915         unsigned int            mask;
916
917         DNPRINTF(SWM_D_STACK, "vertical_stack: workspace: %d\n", ws->idx);
918
919         if ((winno = count_win(ws, 0)) == 0)
920                 return;
921
922         if (ws->focus == NULL)
923                 ws->focus = TAILQ_FIRST(&ws->winlist);
924         winfocus = cur_focus ? cur_focus : ws->focus;
925
926         if (winno > 1) {
927                 main_width = (g->w / SWM_V_SLICE) *
928                    ws->l_state.vertical_msize;
929                 gg.w = main_width;
930         }
931
932         if (winno > 2)
933                 hrh = g->h / (winno - 1);
934         else
935                 hrh = 0;
936
937         i = 0;
938         TAILQ_FOREACH(win, &ws->winlist, entry) {
939                 if (i == 1) {
940                         gg.x += main_width + 2;
941                         gg.w = g->w - (main_width + 2);
942                 }
943                 if (i != 0 && hrh != 0) {
944                         /* correct the last window for lost pixels */
945                         if (win == TAILQ_LAST(&ws->winlist, ws_win_list)) {
946                                 gg.h = hrh + (g->h - (i * hrh));
947                                 gg.y += hrh;
948                         } else {
949                                 gg.h = hrh - 2;
950                                 /* leave first right hand window at y = 0 */
951                                 if (i > 1)
952                                         gg.y += gg.h + 2;
953                         }
954                 }
955
956                 if (win->transient != 0 || win->floating != 0)
957                         stack_floater(win, ws->r);
958                 else {
959                         bzero(&wc, sizeof wc);
960                         wc.border_width = 1;
961                         win->g.x = wc.x = gg.x;
962                         win->g.y = wc.y = gg.y;
963                         win->g.w = wc.width = gg.w;
964                         win->g.h = wc.height = gg.h;
965                         mask = CWX | CWY | CWWidth | CWHeight | CWBorderWidth;
966                         XConfigureWindow(display, win->id, mask, &wc);
967                 }
968
969                 XMapRaised(display, win->id);
970                 i++;
971         }
972
973         if (winfocus)
974                 focus_win(winfocus); /* has to be done outside of the loop */
975 }
976
977
978 void
979 horizontal_init(struct workspace *ws)
980 {
981         DNPRINTF(SWM_D_STACK, "horizontal_init: workspace: %d\n", ws->idx);
982
983         ws->l_state.horizontal_msize = SWM_H_SLICE / 2;
984 }
985
986 void
987 horizontal_resize(struct workspace *ws, int id)
988 {
989         DNPRINTF(SWM_D_STACK, "horizontal_resize: workspace: %d\n", ws->idx);
990
991         switch (id) {
992         case SWM_ARG_ID_MASTERSHRINK:
993                 ws->l_state.horizontal_msize--;
994                 if (ws->l_state.horizontal_msize < 1)
995                         ws->l_state.horizontal_msize = 1;
996                 break;
997         case SWM_ARG_ID_MASTERGROW:
998                 ws->l_state.horizontal_msize++;
999                 if (ws->l_state.horizontal_msize > SWM_H_SLICE - 1)
1000                         ws->l_state.horizontal_msize = SWM_H_SLICE - 1;
1001                 break;
1002         default:
1003                 return;
1004         }
1005         stack();
1006 }
1007
1008 void
1009 horizontal_stack(struct workspace *ws, struct swm_geometry *g) {
1010         XWindowChanges          wc;
1011         struct swm_geometry     gg = *g;
1012         struct ws_win           *win, *winfocus;
1013         int                     i, hrw, winno, main_height;
1014         unsigned int            mask;
1015
1016         DNPRINTF(SWM_D_STACK, "horizontal_stack: workspace: %d\n", ws->idx);
1017
1018         if ((winno = count_win(ws, 0)) == 0)
1019                 return;
1020
1021         if (ws->focus == NULL)
1022                 ws->focus = TAILQ_FIRST(&ws->winlist);
1023         winfocus = cur_focus ? cur_focus : ws->focus;
1024
1025         if (winno > 1) {
1026                 main_height = (g->h / SWM_H_SLICE) *
1027                     ws->l_state.horizontal_msize;
1028                 gg.h = main_height;
1029         }
1030
1031         if (winno > 2)
1032                 hrw = g->w / (winno - 1);
1033         else
1034                 hrw = 0;
1035
1036         i = 0;
1037         TAILQ_FOREACH(win, &ws->winlist, entry) {
1038                 if (i == 1) {
1039                         gg.y += main_height + 2;
1040                         gg.h = g->h - (main_height + 2);
1041                 }
1042                 if (i != 0 && hrw != 0) {
1043                         /* correct the last window for lost pixels */
1044                         if (win == TAILQ_LAST(&ws->winlist, ws_win_list)) {
1045                                 gg.w = hrw + (g->w - (i * hrw));
1046                                 gg.x += hrw;
1047                         } else {
1048                                 gg.w = hrw - 2;
1049                                 /* leave first bottom window at x = 0 */
1050                                 if (i > 1)
1051                                         gg.x += gg.w + 2;
1052                         }
1053                 }
1054
1055                 if (win->transient != 0 || win->floating != 0)
1056                         stack_floater(win, ws->r);
1057                 else {
1058                         bzero(&wc, sizeof wc);
1059                         wc.border_width = 1;
1060                         win->g.x = wc.x = gg.x;
1061                         win->g.y = wc.y = gg.y;
1062                         win->g.w = wc.width = gg.w;
1063                         win->g.h = wc.height = gg.h;
1064                         mask = CWX | CWY | CWWidth | CWHeight | CWBorderWidth;
1065                         XConfigureWindow(display, win->id, mask, &wc);
1066                 }
1067
1068                 XMapRaised(display, win->id);
1069                 i++;
1070         }
1071
1072         if (winfocus)
1073                 focus_win(winfocus); /* this has to be done outside of the loop */
1074 }
1075
1076 /* fullscreen view */
1077 void
1078 max_stack(struct workspace *ws, struct swm_geometry *g) {
1079         XWindowChanges          wc;
1080         struct swm_geometry     gg = *g;
1081         struct ws_win           *win, *winfocus;
1082         unsigned int            mask;
1083
1084         DNPRINTF(SWM_D_STACK, "max_stack: workspace: %d\n", ws->idx);
1085
1086         if (count_win(ws, 0) == 0)
1087                 return;
1088
1089         if (ws->focus == NULL)
1090                 ws->focus = TAILQ_FIRST(&ws->winlist);
1091         winfocus = cur_focus ? cur_focus : ws->focus;
1092
1093         TAILQ_FOREACH(win, &ws->winlist, entry) {
1094                 if (win->transient != 0 || win->floating != 0) {
1095                         if (win == ws->focus) {
1096                                 /* XXX maximize? */
1097                                 stack_floater(win, ws->r);
1098                                 XMapRaised(display, win->id);
1099                         } else
1100                                 XUnmapWindow(display, win->id);
1101                 } else {
1102                         bzero(&wc, sizeof wc);
1103                         wc.border_width = 1;
1104                         win->g.x = wc.x = gg.x;
1105                         win->g.y = wc.y = gg.y;
1106                         win->g.w = wc.width = gg.w;
1107                         win->g.h = wc.height = gg.h;
1108                         mask = CWX | CWY | CWWidth | CWHeight | CWBorderWidth;
1109                         XConfigureWindow(display, win->id, mask, &wc);
1110
1111                         if (win == ws->focus) {
1112                                 XMapRaised(display, win->id);
1113                         } else
1114                                 XUnmapWindow(display, win->id);
1115                 }
1116         }
1117
1118         if (winfocus)
1119                 focus_win(winfocus); /* has to be done outside of the loop */
1120 }
1121
1122 void
1123 send_to_ws(struct swm_region *r, union arg *args)
1124 {
1125         int                     wsid = args->id;
1126         struct ws_win           *win = cur_focus;
1127         struct workspace        *ws, *nws;
1128
1129         DNPRINTF(SWM_D_MOVE, "send_to_ws: win: %lu\n", win->id);
1130
1131         ws = win->ws;
1132         nws = &win->s->ws[wsid];
1133
1134         XUnmapWindow(display, win->id);
1135
1136         /* find a window to focus */
1137         ws->focus = TAILQ_PREV(win, ws_win_list, entry);
1138         if (ws->focus == NULL)
1139                 ws->focus = TAILQ_FIRST(&ws->winlist);
1140         if (ws->focus == win)
1141                 ws->focus = NULL;
1142
1143         TAILQ_REMOVE(&ws->winlist, win, entry);
1144
1145         TAILQ_INSERT_TAIL(&nws->winlist, win, entry);
1146         win->ws = nws;
1147
1148         if (count_win(nws, 1) == 1)
1149                 nws->focus = win;
1150         ws->restack = 1;
1151         nws->restack = 1;
1152
1153         stack();
1154 }
1155
1156 /* key definitions */
1157 struct key {
1158         unsigned int            mod;
1159         KeySym                  keysym;
1160         void                    (*func)(struct swm_region *r, union arg *);
1161         union arg               args;
1162 } keys[] = {
1163         /* modifier             key     function                argument */
1164         { MODKEY,               XK_space,       cycle_layout,   {0} }, 
1165         { MODKEY | ShiftMask,   XK_space,       stack_reset,    {0} }, 
1166         { MODKEY,               XK_h,           resize_master,  {.id = SWM_ARG_ID_MASTERSHRINK} },
1167         { MODKEY,               XK_l,           resize_master,  {.id = SWM_ARG_ID_MASTERGROW} },
1168         { MODKEY,               XK_Return,      swapwin,        {.id = SWM_ARG_ID_SWAPMAIN} },
1169         { MODKEY,               XK_j,           focus,          {.id = SWM_ARG_ID_FOCUSNEXT} },
1170         { MODKEY,               XK_k,           focus,          {.id = SWM_ARG_ID_FOCUSPREV} },
1171         { MODKEY | ShiftMask,   XK_j,           swapwin,        {.id = SWM_ARG_ID_SWAPNEXT} },
1172         { MODKEY | ShiftMask,   XK_k,           swapwin,        {.id = SWM_ARG_ID_SWAPPREV} },
1173         { MODKEY | ShiftMask,   XK_Return,      spawn,          {.argv = spawn_term} },
1174         { MODKEY,               XK_p,           spawn,          {.argv = spawn_menu} },
1175         { MODKEY | ShiftMask,   XK_q,           quit,           {0} },
1176         { MODKEY,               XK_q,           restart,        {0} },
1177         { MODKEY,               XK_m,           focus,          {.id = SWM_ARG_ID_FOCUSMAIN} },
1178         { MODKEY,               XK_1,           switchws,       {.id = 0} },
1179         { MODKEY,               XK_2,           switchws,       {.id = 1} },
1180         { MODKEY,               XK_3,           switchws,       {.id = 2} },
1181         { MODKEY,               XK_4,           switchws,       {.id = 3} },
1182         { MODKEY,               XK_5,           switchws,       {.id = 4} },
1183         { MODKEY,               XK_6,           switchws,       {.id = 5} },
1184         { MODKEY,               XK_7,           switchws,       {.id = 6} },
1185         { MODKEY,               XK_8,           switchws,       {.id = 7} },
1186         { MODKEY,               XK_9,           switchws,       {.id = 8} },
1187         { MODKEY,               XK_0,           switchws,       {.id = 9} },
1188         { MODKEY | ShiftMask,   XK_1,           send_to_ws,     {.id = 0} },
1189         { MODKEY | ShiftMask,   XK_2,           send_to_ws,     {.id = 1} },
1190         { MODKEY | ShiftMask,   XK_3,           send_to_ws,     {.id = 2} },
1191         { MODKEY | ShiftMask,   XK_4,           send_to_ws,     {.id = 3} },
1192         { MODKEY | ShiftMask,   XK_5,           send_to_ws,     {.id = 4} },
1193         { MODKEY | ShiftMask,   XK_6,           send_to_ws,     {.id = 5} },
1194         { MODKEY | ShiftMask,   XK_7,           send_to_ws,     {.id = 6} },
1195         { MODKEY | ShiftMask,   XK_8,           send_to_ws,     {.id = 7} },
1196         { MODKEY | ShiftMask,   XK_9,           send_to_ws,     {.id = 8} },
1197         { MODKEY | ShiftMask,   XK_0,           send_to_ws,     {.id = 9} },
1198         { MODKEY,               XK_b,           bar_toggle,     {0} },
1199         { MODKEY,               XK_Tab,         focus,          {.id = SWM_ARG_ID_FOCUSNEXT} },
1200         { MODKEY | ShiftMask,   XK_Tab,         focus,          {.id = SWM_ARG_ID_FOCUSPREV} },
1201 };
1202
1203 void
1204 updatenumlockmask(void)
1205 {
1206         unsigned int            i, j;
1207         XModifierKeymap         *modmap;
1208
1209         DNPRINTF(SWM_D_MISC, "updatenumlockmask\n");
1210         numlockmask = 0;
1211         modmap = XGetModifierMapping(display);
1212         for (i = 0; i < 8; i++)
1213                 for (j = 0; j < modmap->max_keypermod; j++)
1214                         if (modmap->modifiermap[i * modmap->max_keypermod + j]
1215                           == XKeysymToKeycode(display, XK_Num_Lock))
1216                                 numlockmask = (1 << i);
1217
1218         XFreeModifiermap(modmap);
1219 }
1220
1221 void
1222 grabkeys(void)
1223 {
1224         unsigned int            i, j, k;
1225         KeyCode                 code;
1226         unsigned int            modifiers[] =
1227             { 0, LockMask, numlockmask, numlockmask | LockMask };
1228
1229         DNPRINTF(SWM_D_MISC, "grabkeys\n");
1230         updatenumlockmask();
1231
1232         for (k = 0; k < ScreenCount(display); k++) {
1233                 if (TAILQ_EMPTY(&screens[k].rl))
1234                         continue;
1235                 XUngrabKey(display, AnyKey, AnyModifier, screens[k].root);
1236                 for(i = 0; i < LENGTH(keys); i++) {
1237                         if((code = XKeysymToKeycode(display, keys[i].keysym)))
1238                                 for(j = 0; j < LENGTH(modifiers); j++)
1239                                         XGrabKey(display, code,
1240                                             keys[i].mod | modifiers[j],
1241                                             screens[k].root, True,
1242                                             GrabModeAsync, GrabModeAsync);
1243                 }
1244         }
1245 }
1246 void
1247 expose(XEvent *e)
1248 {
1249         DNPRINTF(SWM_D_EVENT, "expose: window: %lu\n", e->xexpose.window);
1250 }
1251
1252 void
1253 keypress(XEvent *e)
1254 {
1255         unsigned int            i;
1256         KeySym                  keysym;
1257         XKeyEvent               *ev = &e->xkey;
1258
1259         DNPRINTF(SWM_D_EVENT, "keypress: window: %lu\n", ev->window);
1260
1261         keysym = XKeycodeToKeysym(display, (KeyCode)ev->keycode, 0);
1262         for (i = 0; i < LENGTH(keys); i++)
1263                 if (keysym == keys[i].keysym
1264                    && CLEANMASK(keys[i].mod) == CLEANMASK(ev->state)
1265                    && keys[i].func)
1266                         keys[i].func(root_to_region(ev->root),
1267                             &(keys[i].args));
1268 }
1269
1270 void
1271 buttonpress(XEvent *e)
1272 {
1273         XButtonPressedEvent     *ev = &e->xbutton;
1274 #ifdef SWM_CLICKTOFOCUS
1275         struct ws_win           *win;
1276         struct workspace        *ws;
1277         struct swm_region       *r;
1278 #endif
1279
1280         DNPRINTF(SWM_D_EVENT, "buttonpress: window: %lu\n", ev->window);
1281
1282         if (ev->window == ev->root) {
1283                 rootclick = ev->root;
1284                 return;
1285         }
1286         if (ev->window == cur_focus->id)
1287                 return;
1288 #ifdef SWM_CLICKTOFOCUS
1289         r = root_to_region(ev->root);
1290         ws = r->ws;
1291         TAILQ_FOREACH(win, &ws->winlist, entry)
1292                 if (win->id == ev->window) {
1293                         /* focus in the clicked window */
1294                         XSetWindowBorder(display, ev->window, 0xff0000);
1295                         XSetWindowBorder(display, ws->focus->id, 0x888888);
1296                         XSetInputFocus(display, ev->window, RevertToPointerRoot,
1297                             CurrentTime);
1298                         ws->focus = win;
1299                         XSync(display, False);
1300                         break;
1301         }
1302 #endif
1303 }
1304
1305 void
1306 set_win_state(struct ws_win *win, long state)
1307 {
1308         long                    data[] = {state, None};
1309
1310         DNPRINTF(SWM_D_EVENT, "set_win_state: window: %lu\n", win->id);
1311
1312         XChangeProperty(display, win->id, astate, astate, 32, PropModeReplace,
1313             (unsigned char *)data, 2);
1314 }
1315
1316 struct ws_win *
1317 manage_window(Window id, struct workspace *ws)
1318 {
1319         Window                  trans;
1320         struct ws_win           *win;
1321         XClassHint              ch;
1322
1323         TAILQ_FOREACH(win, &ws->winlist, entry) {
1324                 if (win->id == id)
1325                         return (win);   /* already being managed */
1326         }
1327
1328         if ((win = calloc(1, sizeof(struct ws_win))) == NULL)
1329                 errx(1, "calloc: failed to allocate memory for new window");
1330
1331         win->id = id;
1332         win->ws = ws;
1333         win->s = ws->r->s;      /* this never changes */
1334         TAILQ_INSERT_TAIL(&ws->winlist, win, entry);
1335
1336         /* make new win focused */
1337         focus_win(win);
1338
1339         XGetTransientForHint(display, win->id, &trans);
1340         if (trans) {
1341                 win->transient = trans;
1342                 DNPRINTF(SWM_D_MISC, "manage_window: win %u transient %u\n",
1343                     (unsigned)win->id, win->transient);
1344         }
1345         XGetWindowAttributes(display, id, &win->wa);
1346         win->g.w = win->wa.width;
1347         win->g.h = win->wa.height;
1348         win->g.x = win->wa.x;
1349         win->g.y = win->wa.y;
1350
1351         /* XXX make this a table */
1352         bzero(&ch, sizeof ch);
1353         if (XGetClassHint(display, win->id, &ch)) {
1354                 /*fprintf(stderr, "class: %s name: %s\n", ch.res_class, ch.res_name); */
1355                 if (!strcmp(ch.res_class, "MPlayer") && !strcmp(ch.res_name, "xv")) {
1356                         win->floating = 1;
1357                 }
1358                 if (ch.res_class)
1359                         XFree(ch.res_class);
1360                 if (ch.res_name)
1361                         XFree(ch.res_name);
1362         }
1363
1364         XSelectInput(display, id, EnterWindowMask | FocusChangeMask |
1365             PropertyChangeMask | StructureNotifyMask);
1366
1367         set_win_state(win, NormalState);
1368
1369         return (win);
1370 }
1371
1372 void
1373 configurerequest(XEvent *e)
1374 {
1375         XConfigureRequestEvent  *ev = &e->xconfigurerequest;
1376         struct ws_win           *win;
1377         int                     new = 1;
1378         XWindowChanges          wc;
1379
1380         if ((win = find_window(ev->window)) == NULL)
1381                 new = 1;
1382
1383         if (new) {
1384                 DNPRINTF(SWM_D_EVENT, "configurerequest: new window: %lu\n",
1385                     ev->window);
1386                 bzero(&wc, sizeof wc);
1387                 wc.x = ev->x;
1388                 wc.y = ev->y;
1389                 wc.width = ev->width;
1390                 wc.height = ev->height;
1391                 wc.border_width = ev->border_width;
1392                 wc.sibling = ev->above;
1393                 wc.stack_mode = ev->detail;
1394                 XConfigureWindow(display, ev->window, ev->value_mask, &wc);
1395         } else {
1396                 DNPRINTF(SWM_D_EVENT, "configurerequest: change window: %lu\n",
1397                     ev->window);
1398                 if (win->floating) {
1399                         if (ev->value_mask & CWX)
1400                                 win->g.x = ev->x;
1401                         if (ev->value_mask & CWY)
1402                                 win->g.y = ev->y;
1403                         if (ev->value_mask & CWWidth)
1404                                 win->g.w = ev->width;
1405                         if (ev->value_mask & CWHeight)
1406                                 win->g.h = ev->height;
1407                         if (win->ws->r != NULL) {
1408                                 /* this seems to be full screen */
1409                                 if (win->g.w > WIDTH(win->ws->r)) {
1410                                         /* kill border */
1411                                         win->g.x -= 1;
1412                                         win->g.w += 1;
1413                                 }
1414                                 if (win->g.h > HEIGHT(win->ws->r)) {
1415                                         /* kill border */
1416                                         win->g.y -= 1;
1417                                         win->g.h += 1;
1418                                 }
1419                         }
1420                         if ((ev->value_mask & (CWX|CWY)) &&
1421                             !(ev->value_mask & (CWWidth|CWHeight)))
1422                                 config_win(win);
1423                         XMoveResizeWindow(display, win->id,
1424                             win->g.x, win->g.y, win->g.w, win->g.h);
1425                 } else
1426                         config_win(win);
1427         }
1428 }
1429
1430 void
1431 configurenotify(XEvent *e)
1432 {
1433         DNPRINTF(SWM_D_EVENT, "configurenotify: window: %lu\n",
1434             e->xconfigure.window);
1435 }
1436
1437 void
1438 destroynotify(XEvent *e)
1439 {
1440         struct ws_win           *win;
1441         XDestroyWindowEvent     *ev = &e->xdestroywindow;
1442
1443         DNPRINTF(SWM_D_EVENT, "destroynotify: window %lu\n", ev->window);
1444
1445         if ((win = find_window(ev->window)) != NULL) {
1446                 struct workspace *ws = win->ws;
1447                 /* find a window to focus */
1448                 if (ws->focus == win)
1449                         ws->focus = TAILQ_PREV(win, ws_win_list, entry);
1450                 if (ws->focus == NULL)
1451                         ws->focus = TAILQ_FIRST(&ws->winlist);
1452                 if (ws->focus == win)
1453                         ws->focus = NULL;
1454                 if (cur_focus == win) {
1455                         if (ws->focus == NULL) 
1456                                 unfocus_win(win); /* XXX focus another ws? */
1457                         else
1458                                 focus_win(ws->focus);
1459                 }
1460
1461                 TAILQ_REMOVE(&ws->winlist, win, entry);
1462                 set_win_state(win, WithdrawnState);
1463                 free(win);
1464         }
1465
1466         stack();
1467 }
1468
1469 void
1470 enternotify(XEvent *e)
1471 {
1472         XCrossingEvent          *ev = &e->xcrossing;
1473         struct ws_win           *win;
1474         int                     i, j;
1475
1476         DNPRINTF(SWM_D_EVENT, "enternotify: window: %lu\n", ev->window);
1477
1478         if((ev->mode != NotifyNormal || ev->detail == NotifyInferior) &&
1479             ev->window != ev->root)
1480                 return;
1481         if (ignore_enter) {
1482                 /* eat event(r) to prevent autofocus */
1483                 ignore_enter--;
1484                 return;
1485         }
1486         /* brute force for now */
1487         for (i = 0; i < ScreenCount(display); i++) {
1488                 for (j = 0; j < SWM_WS_MAX; j++) {
1489                         TAILQ_FOREACH(win, &screens[i].ws[j].winlist , entry) {
1490                                 if (win->id == ev->window)
1491                                         focus_win(win);
1492                         }
1493                 }
1494         }
1495 }
1496
1497 void
1498 focusin(XEvent *e)
1499 {
1500         DNPRINTF(SWM_D_EVENT, "focusin: window: %lu\n", e->xfocus.window);
1501
1502         /* XXX this probably needs better handling now.
1503         if (ev->window == ev->root)
1504                 return;
1505         */
1506         /*
1507          * kill grab for now so that we can cut and paste , this screws up
1508          * click to focus
1509          */
1510         /*
1511         DNPRINTF(SWM_D_EVENT, "focusin: window: %lu grabbing\n", ev->window);
1512         XGrabButton(display, Button1, AnyModifier, ev->window, False,
1513             ButtonPress, GrabModeAsync, GrabModeSync, None, None);
1514         */
1515 }
1516
1517 void
1518 mappingnotify(XEvent *e)
1519 {
1520         XMappingEvent           *ev = &e->xmapping;
1521
1522         DNPRINTF(SWM_D_EVENT, "mappingnotify: window: %lu\n", ev->window);
1523
1524         XRefreshKeyboardMapping(ev);
1525         if (ev->request == MappingKeyboard)
1526                 grabkeys();
1527 }
1528
1529 void
1530 maprequest(XEvent *e)
1531 {
1532         XMapRequestEvent        *ev = &e->xmaprequest;
1533         XWindowAttributes       wa;
1534         struct swm_region       *r;
1535
1536         DNPRINTF(SWM_D_EVENT, "maprequest: window: %lu\n",
1537             e->xmaprequest.window);
1538
1539         if (!XGetWindowAttributes(display, ev->window, &wa))
1540                 return;
1541         if (wa.override_redirect)
1542                 return;
1543         r = root_to_region(wa.root);
1544         manage_window(e->xmaprequest.window, r->ws);
1545         stack();
1546 }
1547
1548 void
1549 propertynotify(XEvent *e)
1550 {
1551         DNPRINTF(SWM_D_EVENT, "propertynotify: window: %lu\n",
1552             e->xproperty.window);
1553 }
1554
1555 void
1556 unmapnotify(XEvent *e)
1557 {
1558         DNPRINTF(SWM_D_EVENT, "unmapnotify: window: %lu\n", e->xunmap.window);
1559 }
1560
1561 void
1562 visibilitynotify(XEvent *e)
1563 {
1564         int i;
1565         struct swm_region *r;
1566         DNPRINTF(SWM_D_EVENT, "visibilitynotify: window: %lu\n", 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         int i;
1669
1670
1671         if ((screens = calloc(ScreenCount(display),
1672              sizeof(struct swm_screen))) == NULL)
1673                 errx(1, "calloc: screens");
1674
1675         /* map physical screens */
1676         for (i = 0; i < ScreenCount(display); i++) {
1677 #ifdef SWM_XRR_HAS_CRTC
1678                 XRRCrtcInfo             *crtc_info;
1679                 XRRScreenResources      *res;
1680                 int                     c;
1681 #endif /* SWM_XRR_HAS_CRTC */
1682                 Window                  d1, d2, *wins = NULL;
1683                 XWindowAttributes       wa;
1684                 struct swm_region       *r;
1685                 int                     errorbase, major, minor;
1686                 int                     j, ncrtc, w = 0;
1687                 unsigned int            num;
1688
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                         int                     k;
1706                         struct workspace        *ws = &screens[i].ws[j];
1707
1708                         ws->idx = j;
1709                         ws->restack = 1;
1710                         ws->focus = NULL;
1711                         ws->r = NULL;
1712                         TAILQ_INIT(&ws->winlist);
1713
1714                         for (k = 0; layouts[k].l_stack != NULL; k++) {
1715                                 if (layouts[k].l_init != NULL)
1716                                         layouts[k].l_init(ws);
1717                         }
1718                         ws->cur_layout = &layouts[0];
1719                 }
1720
1721                 /* map virtual screens onto physical screens */
1722                 screens[i].xrandr_support = XRRQueryExtension(display,
1723                     &xrandr_eventbase, &errorbase);
1724                 if (screens[i].xrandr_support)
1725                         if (XRRQueryVersion(display, &major, &minor) &&
1726                             major < 1)
1727                                 screens[i].xrandr_support = 0;
1728
1729 #if 0   /* not ready for dynamic screen changes */
1730                 if (screens[i].xrandr_support)
1731                         XRRSelectInput(display,
1732                             screens[r->s].root,
1733                             RRScreenChangeNotifyMask);
1734 #endif
1735
1736                 /* grab existing windows (before we build the bars)*/
1737                 if (!XQueryTree(display, screens[i].root,
1738                     &d1, &d2, &wins, &num)) {
1739                         if (wins)       /* not sure if this is necessary */
1740                                 XFree(wins);
1741                         continue;
1742                 }
1743
1744
1745 #ifdef SWM_XRR_HAS_CRTC
1746                 res = XRRGetScreenResources (display, screens[i].root);
1747                 if (res == NULL) {
1748                         ncrtc = 0;
1749                         new_region(&screens[i], &screens[i].ws[w],
1750                             0, 0, DisplayWidth(display, i),
1751                             DisplayHeight(display, i)); 
1752                 } else 
1753                         ncrtc = res->ncrtc;
1754
1755                 for (c = 0; c < ncrtc; c++) {
1756                         crtc_info = XRRGetCrtcInfo(display, res, res->crtcs[c]);
1757                         if (crtc_info != NULL && crtc_info->mode == None)
1758                                 new_region(&screens[i], &screens[i].ws[w],
1759                                     0, 0, DisplayWidth(display, i),
1760                                     DisplayHeight(display, i)); 
1761                         else
1762                                 new_region(&screens[i], &screens[i].ws[w],
1763                                     crtc_info->x, crtc_info->y,
1764                                     crtc_info->width, crtc_info->height);
1765                         w++;
1766                 }
1767 #else
1768                 new_region(&screens[i], &screens[i].ws[w],
1769                     0, 0, DisplayWidth(display, i),
1770                     DisplayHeight(display, i)); 
1771 #endif /* SWM_XRR_HAS_CRTC */
1772
1773                 /* attach windows to a region */
1774                 /* normal windows */
1775                 if ((r = TAILQ_FIRST(&screens[i].rl)) == NULL)
1776                         errx(1, "no regions on screen %d", i);
1777
1778                 for (i = 0; i < num; i++) {
1779                         XGetWindowAttributes(display, wins[i], &wa);
1780                         if (!XGetWindowAttributes(display, wins[i], &wa) ||
1781                             wa.override_redirect ||
1782                             XGetTransientForHint(display, wins[i], &d1))
1783                                 continue;
1784                         if (wa.map_state == IsViewable ||
1785                             getstate(wins[i]) == NormalState)
1786                                 manage_window(wins[i], r->ws);
1787                 }
1788                 /* transient windows */
1789                 for (i = 0; i < num; i++) {
1790                         if (!XGetWindowAttributes(display, wins[i], &wa))
1791                                 continue;
1792                         if (XGetTransientForHint(display, wins[i], &d1) &&
1793                             (wa.map_state == IsViewable || getstate(wins[i]) ==
1794                             NormalState))
1795                                 manage_window(wins[i], r->ws);
1796                 }
1797                 if (wins)
1798                         XFree(wins);
1799         }
1800 }
1801
1802 int
1803 main(int argc, char *argv[])
1804 {
1805         struct passwd           *pwd;
1806         char                    conf[PATH_MAX], *cfile = NULL;
1807         struct stat             sb;
1808         XEvent                  e;
1809
1810         start_argv = argv;
1811         fprintf(stderr, "Welcome to scrotwm V%s\n", SWM_VERSION);
1812         if (!setlocale(LC_CTYPE, "") || !XSupportsLocale())
1813                 warnx("no locale support");
1814
1815         if (!(display = XOpenDisplay(0)))
1816                 errx(1, "can not open display");
1817
1818         if (active_wm())
1819                 errx(1, "other wm running");
1820
1821         astate = XInternAtom(display, "WM_STATE", False);
1822
1823         /* look for local and global conf file */
1824         pwd = getpwuid(getuid());
1825         if (pwd == NULL)
1826                 errx(1, "invalid user %d", getuid());
1827
1828         snprintf(conf, sizeof conf, "%s/.%s", pwd->pw_dir, SWM_CONF_FILE);
1829         if (stat(conf, &sb) != -1) {
1830                 if (S_ISREG(sb.st_mode))
1831                         cfile = conf;
1832         } else {
1833                 /* try global conf file */
1834                 snprintf(conf, sizeof conf, "/etc/%s", SWM_CONF_FILE);
1835                 if (!stat(conf, &sb))
1836                         if (S_ISREG(sb.st_mode))
1837                                 cfile = conf;
1838         }
1839         if (cfile)
1840                 conf_load(cfile);
1841
1842         setup_screens();
1843
1844         //ws[0].focus = TAILQ_FIRST(&ws[0].winlist);
1845
1846         grabkeys();
1847         stack();
1848
1849         while (running) {
1850                 XNextEvent(display, &e);
1851                 if (handler[e.type])
1852                         handler[e.type](&e);
1853         }
1854
1855         XCloseDisplay(display);
1856
1857         return (0);
1858 }