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