JasonWoof Got questions, comments, patches, etc.? Contact Jason Woofenden
one. last. off-by-2.
[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                 }
964                 if (j == colno - 1)
965                         gg.h = (hrh + (g->h - (colno * hrh)));
966                  
967                 if (j == 0)
968                         gg.y = g->y;
969                 else
970                         gg.y += hrh;
971
972
973                 if (win->transient != 0 || win->floating != 0)
974                         stack_floater(win, ws->r);
975                 else {
976                         bzero(&wc, sizeof wc);
977                         wc.border_width = 1;
978                         win->g.x = wc.x = gg.x;
979                         win->g.y = wc.y = gg.y;
980                         win->g.w = wc.width = gg.w;
981                         win->g.h = wc.height = gg.h;
982                         mask = CWX | CWY | CWWidth | CWHeight | CWBorderWidth;
983                         XConfigureWindow(display, win->id, mask, &wc);
984                 }
985
986                 XMapRaised(display, win->id);
987                 i++;
988                 j++;
989         }
990
991         if (winfocus)
992                 focus_win(winfocus); /* has to be done outside of the loop */
993 }
994
995
996 void
997 horizontal_config(struct workspace *ws, int id)
998 {
999         DNPRINTF(SWM_D_STACK, "horizontal_config: workspace: %d\n", ws->idx);
1000
1001         switch (id) {
1002         case SWM_ARG_ID_STACKRESET:
1003         case SWM_ARG_ID_STACKINIT:
1004                 ws->l_state.horizontal_mwin = 1;
1005                 ws->l_state.horizontal_msize = SWM_H_SLICE / 2;
1006                 break;
1007         case SWM_ARG_ID_MASTERSHRINK:
1008                 if (ws->l_state.horizontal_msize > 1)
1009                         ws->l_state.horizontal_msize--;
1010                 break;
1011         case SWM_ARG_ID_MASTERGROW:
1012                 if (ws->l_state.horizontal_msize < SWM_H_SLICE - 1)
1013                         ws->l_state.horizontal_msize++;
1014                 break;
1015         case SWM_ARG_ID_MASTERADD:
1016                 ws->l_state.horizontal_mwin++;
1017                 break;
1018         case SWM_ARG_ID_MASTERDEL:
1019                 if (ws->l_state.horizontal_mwin > 0)
1020                         ws->l_state.horizontal_mwin--;
1021                 break;
1022         default:
1023                 return;
1024         }
1025 }
1026
1027 void
1028 horizontal_stack(struct workspace *ws, struct swm_geometry *g) {
1029         XWindowChanges          wc;
1030         struct swm_geometry     gg = *g;
1031         struct ws_win           *win, *winfocus;
1032         int                     i, j, split, rowno, hrw, winno, main_height;
1033         unsigned int            mask;
1034
1035         DNPRINTF(SWM_D_STACK, "horizontal_stack: workspace: %d\n", ws->idx);
1036
1037         if ((winno = count_win(ws, 0)) == 0)
1038                 return;
1039
1040         if (ws->focus == NULL)
1041                 ws->focus = TAILQ_FIRST(&ws->winlist);
1042         winfocus = cur_focus ? cur_focus : ws->focus;
1043
1044         if (ws->l_state.horizontal_mwin &&
1045             winno > ws->l_state.horizontal_mwin) {
1046                 split = ws->l_state.horizontal_mwin;
1047                 rowno = split;
1048                 main_height = (g->h / SWM_V_SLICE) *
1049                    ws->l_state.horizontal_msize;
1050                 gg.h = main_height;
1051         } else {
1052                 rowno = winno;
1053                 split = 0;
1054         }
1055         hrw = g->w / rowno;
1056         gg.w = hrw - 2;
1057
1058         i = j = 0;
1059         TAILQ_FOREACH(win, &ws->winlist, entry) {
1060                 if (split && i == split) {
1061                         rowno = winno - split;
1062                         hrw = (g->w / rowno);
1063                         gg.y += main_height + 2;
1064                         gg.h = g->h - (main_height + 2);
1065                         gg.w = hrw - 2;
1066                         j = 0;
1067                 }
1068                 if (j == rowno - 1)
1069                         gg.w = (hrw + (g->w - (rowno * hrw)));
1070
1071                 if (j == 0)
1072                         gg.x = g->x;
1073                 else
1074                         gg.x += hrw;
1075
1076                 if (win->transient != 0 || win->floating != 0)
1077                         stack_floater(win, ws->r);
1078                 else {
1079                         bzero(&wc, sizeof wc);
1080                         wc.border_width = 1;
1081                         win->g.x = wc.x = gg.x;
1082                         win->g.y = wc.y = gg.y;
1083                         win->g.w = wc.width = gg.w;
1084                         win->g.h = wc.height = gg.h;
1085                         mask = CWX | CWY | CWWidth | CWHeight | CWBorderWidth;
1086                         XConfigureWindow(display, win->id, mask, &wc);
1087                 }
1088
1089                 XMapRaised(display, win->id);
1090                 j++;
1091                 i++;
1092         }
1093
1094         if (winfocus)
1095                 focus_win(winfocus); /* this has to be done outside of the loop */
1096 }
1097
1098 /* fullscreen view */
1099 void
1100 max_stack(struct workspace *ws, struct swm_geometry *g) {
1101         XWindowChanges          wc;
1102         struct swm_geometry     gg = *g;
1103         struct ws_win           *win, *winfocus;
1104         unsigned int            mask;
1105
1106         DNPRINTF(SWM_D_STACK, "max_stack: workspace: %d\n", ws->idx);
1107
1108         if (count_win(ws, 0) == 0)
1109                 return;
1110
1111         if (ws->focus == NULL)
1112                 ws->focus = TAILQ_FIRST(&ws->winlist);
1113         winfocus = cur_focus ? cur_focus : ws->focus;
1114
1115         TAILQ_FOREACH(win, &ws->winlist, entry) {
1116                 if (win->transient != 0 || win->floating != 0) {
1117                         if (win == ws->focus) {
1118                                 /* XXX maximize? */
1119                                 stack_floater(win, ws->r);
1120                                 XMapRaised(display, win->id);
1121                         } else
1122                                 XUnmapWindow(display, win->id);
1123                 } else {
1124                         bzero(&wc, sizeof wc);
1125                         wc.border_width = 1;
1126                         win->g.x = wc.x = gg.x;
1127                         win->g.y = wc.y = gg.y;
1128                         win->g.w = wc.width = gg.w;
1129                         win->g.h = wc.height = gg.h;
1130                         mask = CWX | CWY | CWWidth | CWHeight | CWBorderWidth;
1131                         XConfigureWindow(display, win->id, mask, &wc);
1132
1133                         if (win == ws->focus) {
1134                                 XMapRaised(display, win->id);
1135                         } else
1136                                 XUnmapWindow(display, win->id);
1137                 }
1138         }
1139
1140         if (winfocus)
1141                 focus_win(winfocus); /* has to be done outside of the loop */
1142 }
1143
1144 void
1145 send_to_ws(struct swm_region *r, union arg *args)
1146 {
1147         int                     wsid = args->id;
1148         struct ws_win           *win = cur_focus;
1149         struct workspace        *ws, *nws;
1150
1151         DNPRINTF(SWM_D_MOVE, "send_to_ws: win: %lu\n", win->id);
1152
1153         ws = win->ws;
1154         nws = &win->s->ws[wsid];
1155
1156         XUnmapWindow(display, win->id);
1157
1158         /* find a window to focus */
1159         ws->focus = TAILQ_PREV(win, ws_win_list, entry);
1160         if (ws->focus == NULL)
1161                 ws->focus = TAILQ_FIRST(&ws->winlist);
1162         if (ws->focus == win)
1163                 ws->focus = NULL;
1164
1165         TAILQ_REMOVE(&ws->winlist, win, entry);
1166
1167         TAILQ_INSERT_TAIL(&nws->winlist, win, entry);
1168         win->ws = nws;
1169
1170         if (count_win(nws, 1) == 1)
1171                 nws->focus = win;
1172         ws->restack = 1;
1173         nws->restack = 1;
1174
1175         stack();
1176 }
1177
1178 /* key definitions */
1179 struct key {
1180         unsigned int            mod;
1181         KeySym                  keysym;
1182         void                    (*func)(struct swm_region *r, union arg *);
1183         union arg               args;
1184 } keys[] = {
1185         /* modifier             key     function                argument */
1186         { MODKEY,               XK_space,       cycle_layout,   {0} }, 
1187         { MODKEY | ShiftMask,   XK_space,       stack_config,   {.id = SWM_ARG_ID_STACKRESET} }, 
1188         { MODKEY,               XK_h,           stack_config,   {.id = SWM_ARG_ID_MASTERSHRINK} },
1189         { MODKEY,               XK_l,           stack_config,   {.id = SWM_ARG_ID_MASTERGROW} },
1190         { MODKEY,               XK_comma,       stack_config,   {.id = SWM_ARG_ID_MASTERADD} },
1191         { MODKEY,               XK_period,      stack_config,   {.id = SWM_ARG_ID_MASTERDEL} },
1192         { MODKEY,               XK_Return,      swapwin,        {.id = SWM_ARG_ID_SWAPMAIN} },
1193         { MODKEY,               XK_j,           focus,          {.id = SWM_ARG_ID_FOCUSNEXT} },
1194         { MODKEY,               XK_k,           focus,          {.id = SWM_ARG_ID_FOCUSPREV} },
1195         { MODKEY | ShiftMask,   XK_j,           swapwin,        {.id = SWM_ARG_ID_SWAPNEXT} },
1196         { MODKEY | ShiftMask,   XK_k,           swapwin,        {.id = SWM_ARG_ID_SWAPPREV} },
1197         { MODKEY | ShiftMask,   XK_Return,      spawn,          {.argv = spawn_term} },
1198         { MODKEY,               XK_p,           spawn,          {.argv = spawn_menu} },
1199         { MODKEY | ShiftMask,   XK_q,           quit,           {0} },
1200         { MODKEY,               XK_q,           restart,        {0} },
1201         { MODKEY,               XK_m,           focus,          {.id = SWM_ARG_ID_FOCUSMAIN} },
1202         { MODKEY,               XK_1,           switchws,       {.id = 0} },
1203         { MODKEY,               XK_2,           switchws,       {.id = 1} },
1204         { MODKEY,               XK_3,           switchws,       {.id = 2} },
1205         { MODKEY,               XK_4,           switchws,       {.id = 3} },
1206         { MODKEY,               XK_5,           switchws,       {.id = 4} },
1207         { MODKEY,               XK_6,           switchws,       {.id = 5} },
1208         { MODKEY,               XK_7,           switchws,       {.id = 6} },
1209         { MODKEY,               XK_8,           switchws,       {.id = 7} },
1210         { MODKEY,               XK_9,           switchws,       {.id = 8} },
1211         { MODKEY,               XK_0,           switchws,       {.id = 9} },
1212         { MODKEY | ShiftMask,   XK_1,           send_to_ws,     {.id = 0} },
1213         { MODKEY | ShiftMask,   XK_2,           send_to_ws,     {.id = 1} },
1214         { MODKEY | ShiftMask,   XK_3,           send_to_ws,     {.id = 2} },
1215         { MODKEY | ShiftMask,   XK_4,           send_to_ws,     {.id = 3} },
1216         { MODKEY | ShiftMask,   XK_5,           send_to_ws,     {.id = 4} },
1217         { MODKEY | ShiftMask,   XK_6,           send_to_ws,     {.id = 5} },
1218         { MODKEY | ShiftMask,   XK_7,           send_to_ws,     {.id = 6} },
1219         { MODKEY | ShiftMask,   XK_8,           send_to_ws,     {.id = 7} },
1220         { MODKEY | ShiftMask,   XK_9,           send_to_ws,     {.id = 8} },
1221         { MODKEY | ShiftMask,   XK_0,           send_to_ws,     {.id = 9} },
1222         { MODKEY,               XK_b,           bar_toggle,     {0} },
1223         { MODKEY,               XK_Tab,         focus,          {.id = SWM_ARG_ID_FOCUSNEXT} },
1224         { MODKEY | ShiftMask,   XK_Tab,         focus,          {.id = SWM_ARG_ID_FOCUSPREV} },
1225 };
1226
1227 void
1228 updatenumlockmask(void)
1229 {
1230         unsigned int            i, j;
1231         XModifierKeymap         *modmap;
1232
1233         DNPRINTF(SWM_D_MISC, "updatenumlockmask\n");
1234         numlockmask = 0;
1235         modmap = XGetModifierMapping(display);
1236         for (i = 0; i < 8; i++)
1237                 for (j = 0; j < modmap->max_keypermod; j++)
1238                         if (modmap->modifiermap[i * modmap->max_keypermod + j]
1239                           == XKeysymToKeycode(display, XK_Num_Lock))
1240                                 numlockmask = (1 << i);
1241
1242         XFreeModifiermap(modmap);
1243 }
1244
1245 void
1246 grabkeys(void)
1247 {
1248         unsigned int            i, j, k;
1249         KeyCode                 code;
1250         unsigned int            modifiers[] =
1251             { 0, LockMask, numlockmask, numlockmask | LockMask };
1252
1253         DNPRINTF(SWM_D_MISC, "grabkeys\n");
1254         updatenumlockmask();
1255
1256         for (k = 0; k < ScreenCount(display); k++) {
1257                 if (TAILQ_EMPTY(&screens[k].rl))
1258                         continue;
1259                 XUngrabKey(display, AnyKey, AnyModifier, screens[k].root);
1260                 for (i = 0; i < LENGTH(keys); i++) {
1261                         if ((code = XKeysymToKeycode(display, keys[i].keysym)))
1262                                 for (j = 0; j < LENGTH(modifiers); j++)
1263                                         XGrabKey(display, code,
1264                                             keys[i].mod | modifiers[j],
1265                                             screens[k].root, True,
1266                                             GrabModeAsync, GrabModeAsync);
1267                 }
1268         }
1269 }
1270 void
1271 expose(XEvent *e)
1272 {
1273         DNPRINTF(SWM_D_EVENT, "expose: window: %lu\n", e->xexpose.window);
1274 }
1275
1276 void
1277 keypress(XEvent *e)
1278 {
1279         unsigned int            i;
1280         KeySym                  keysym;
1281         XKeyEvent               *ev = &e->xkey;
1282
1283         DNPRINTF(SWM_D_EVENT, "keypress: window: %lu\n", ev->window);
1284
1285         keysym = XKeycodeToKeysym(display, (KeyCode)ev->keycode, 0);
1286         for (i = 0; i < LENGTH(keys); i++)
1287                 if (keysym == keys[i].keysym
1288                    && CLEANMASK(keys[i].mod) == CLEANMASK(ev->state)
1289                    && keys[i].func)
1290                         keys[i].func(root_to_region(ev->root),
1291                             &(keys[i].args));
1292 }
1293
1294 void
1295 buttonpress(XEvent *e)
1296 {
1297         XButtonPressedEvent     *ev = &e->xbutton;
1298 #ifdef SWM_CLICKTOFOCUS
1299         struct ws_win           *win;
1300         struct workspace        *ws;
1301         struct swm_region       *r;
1302 #endif
1303
1304         DNPRINTF(SWM_D_EVENT, "buttonpress: window: %lu\n", ev->window);
1305
1306         if (ev->window == ev->root) {
1307                 rootclick = ev->root;
1308                 return;
1309         }
1310         if (ev->window == cur_focus->id)
1311                 return;
1312 #ifdef SWM_CLICKTOFOCUS
1313         r = root_to_region(ev->root);
1314         ws = r->ws;
1315         TAILQ_FOREACH(win, &ws->winlist, entry)
1316                 if (win->id == ev->window) {
1317                         /* focus in the clicked window */
1318                         XSetWindowBorder(display, ev->window, 0xff0000);
1319                         XSetWindowBorder(display, ws->focus->id, 0x888888);
1320                         XSetInputFocus(display, ev->window, RevertToPointerRoot,
1321                             CurrentTime);
1322                         ws->focus = win;
1323                         XSync(display, False);
1324                         break;
1325         }
1326 #endif
1327 }
1328
1329 void
1330 set_win_state(struct ws_win *win, long state)
1331 {
1332         long                    data[] = {state, None};
1333
1334         DNPRINTF(SWM_D_EVENT, "set_win_state: window: %lu\n", win->id);
1335
1336         XChangeProperty(display, win->id, astate, astate, 32, PropModeReplace,
1337             (unsigned char *)data, 2);
1338 }
1339
1340 struct ws_win *
1341 manage_window(Window id, struct workspace *ws)
1342 {
1343         Window                  trans;
1344         struct ws_win           *win;
1345         XClassHint              ch;
1346
1347         TAILQ_FOREACH(win, &ws->winlist, entry) {
1348                 if (win->id == id)
1349                         return (win);   /* already being managed */
1350         }
1351
1352         if ((win = calloc(1, sizeof(struct ws_win))) == NULL)
1353                 errx(1, "calloc: failed to allocate memory for new window");
1354
1355         win->id = id;
1356         win->ws = ws;
1357         win->s = ws->r->s;      /* this never changes */
1358         TAILQ_INSERT_TAIL(&ws->winlist, win, entry);
1359
1360         /* make new win focused */
1361         focus_win(win);
1362
1363         XGetTransientForHint(display, win->id, &trans);
1364         if (trans) {
1365                 win->transient = trans;
1366                 DNPRINTF(SWM_D_MISC, "manage_window: win %u transient %u\n",
1367                     (unsigned)win->id, win->transient);
1368         }
1369         XGetWindowAttributes(display, id, &win->wa);
1370         win->g.w = win->wa.width;
1371         win->g.h = win->wa.height;
1372         win->g.x = win->wa.x;
1373         win->g.y = win->wa.y;
1374
1375         /* XXX make this a table */
1376         bzero(&ch, sizeof ch);
1377         if (XGetClassHint(display, win->id, &ch)) {
1378                 /*fprintf(stderr, "class: %s name: %s\n", ch.res_class, ch.res_name); */
1379                 if (!strcmp(ch.res_class, "MPlayer") && !strcmp(ch.res_name, "xv")) {
1380                         win->floating = 1;
1381                 }
1382                 if (ch.res_class)
1383                         XFree(ch.res_class);
1384                 if (ch.res_name)
1385                         XFree(ch.res_name);
1386         }
1387
1388         XSelectInput(display, id, EnterWindowMask | FocusChangeMask |
1389             PropertyChangeMask | StructureNotifyMask);
1390
1391         set_win_state(win, NormalState);
1392
1393         return (win);
1394 }
1395
1396 void
1397 configurerequest(XEvent *e)
1398 {
1399         XConfigureRequestEvent  *ev = &e->xconfigurerequest;
1400         struct ws_win           *win;
1401         int                     new = 1;
1402         XWindowChanges          wc;
1403
1404         if ((win = find_window(ev->window)) == NULL)
1405                 new = 1;
1406
1407         if (new) {
1408                 DNPRINTF(SWM_D_EVENT, "configurerequest: new window: %lu\n",
1409                     ev->window);
1410                 bzero(&wc, sizeof wc);
1411                 wc.x = ev->x;
1412                 wc.y = ev->y;
1413                 wc.width = ev->width;
1414                 wc.height = ev->height;
1415                 wc.border_width = ev->border_width;
1416                 wc.sibling = ev->above;
1417                 wc.stack_mode = ev->detail;
1418                 XConfigureWindow(display, ev->window, ev->value_mask, &wc);
1419         } else {
1420                 DNPRINTF(SWM_D_EVENT, "configurerequest: change window: %lu\n",
1421                     ev->window);
1422                 if (win->floating) {
1423                         if (ev->value_mask & CWX)
1424                                 win->g.x = ev->x;
1425                         if (ev->value_mask & CWY)
1426                                 win->g.y = ev->y;
1427                         if (ev->value_mask & CWWidth)
1428                                 win->g.w = ev->width;
1429                         if (ev->value_mask & CWHeight)
1430                                 win->g.h = ev->height;
1431                         if (win->ws->r != NULL) {
1432                                 /* this seems to be full screen */
1433                                 if (win->g.w > WIDTH(win->ws->r)) {
1434                                         /* kill border */
1435                                         win->g.x -= 1;
1436                                         win->g.w += 1;
1437                                 }
1438                                 if (win->g.h > HEIGHT(win->ws->r)) {
1439                                         /* kill border */
1440                                         win->g.y -= 1;
1441                                         win->g.h += 1;
1442                                 }
1443                         }
1444                         if ((ev->value_mask & (CWX|CWY)) &&
1445                             !(ev->value_mask & (CWWidth|CWHeight)))
1446                                 config_win(win);
1447                         XMoveResizeWindow(display, win->id,
1448                             win->g.x, win->g.y, win->g.w, win->g.h);
1449                 } else
1450                         config_win(win);
1451         }
1452 }
1453
1454 void
1455 configurenotify(XEvent *e)
1456 {
1457         DNPRINTF(SWM_D_EVENT, "configurenotify: window: %lu\n",
1458             e->xconfigure.window);
1459 }
1460
1461 void
1462 destroynotify(XEvent *e)
1463 {
1464         struct ws_win           *win;
1465         XDestroyWindowEvent     *ev = &e->xdestroywindow;
1466
1467         DNPRINTF(SWM_D_EVENT, "destroynotify: window %lu\n", ev->window);
1468
1469         if ((win = find_window(ev->window)) != NULL) {
1470                 struct workspace *ws = win->ws;
1471                 /* find a window to focus */
1472                 if (ws->focus == win)
1473                         ws->focus = TAILQ_PREV(win, ws_win_list, entry);
1474                 if (ws->focus == NULL)
1475                         ws->focus = TAILQ_FIRST(&ws->winlist);
1476                 if (ws->focus == win)
1477                         ws->focus = NULL;
1478                 if (cur_focus == win) {
1479                         if (ws->focus == NULL) 
1480                                 unfocus_win(win); /* XXX focus another ws? */
1481                         else
1482                                 focus_win(ws->focus);
1483                 }
1484
1485                 TAILQ_REMOVE(&ws->winlist, win, entry);
1486                 set_win_state(win, WithdrawnState);
1487                 free(win);
1488         }
1489         stack();
1490 }
1491
1492 void
1493 enternotify(XEvent *e)
1494 {
1495         XCrossingEvent          *ev = &e->xcrossing;
1496         struct ws_win           *win;
1497         int                     i, j;
1498
1499         DNPRINTF(SWM_D_EVENT, "enternotify: window: %lu\n", ev->window);
1500
1501         if ((ev->mode != NotifyNormal || ev->detail == NotifyInferior) &&
1502             ev->window != ev->root)
1503                 return;
1504         if (ignore_enter) {
1505                 /* eat event(r) to prevent autofocus */
1506                 ignore_enter--;
1507                 return;
1508         }
1509         /* brute force for now */
1510         for (i = 0; i < ScreenCount(display); i++) {
1511                 for (j = 0; j < SWM_WS_MAX; j++) {
1512                         TAILQ_FOREACH(win, &screens[i].ws[j].winlist , entry) {
1513                                 if (win->id == ev->window)
1514                                         focus_win(win);
1515                         }
1516                 }
1517         }
1518 }
1519
1520 void
1521 focusin(XEvent *e)
1522 {
1523         DNPRINTF(SWM_D_EVENT, "focusin: window: %lu\n", e->xfocus.window);
1524
1525         /* XXX this probably needs better handling now.
1526         if (ev->window == ev->root)
1527                 return;
1528         */
1529         /*
1530          * kill grab for now so that we can cut and paste , this screws up
1531          * click to focus
1532          */
1533         /*
1534         DNPRINTF(SWM_D_EVENT, "focusin: window: %lu grabbing\n", ev->window);
1535         XGrabButton(display, Button1, AnyModifier, ev->window, False,
1536             ButtonPress, GrabModeAsync, GrabModeSync, None, None);
1537         */
1538 }
1539
1540 void
1541 mappingnotify(XEvent *e)
1542 {
1543         XMappingEvent           *ev = &e->xmapping;
1544
1545         DNPRINTF(SWM_D_EVENT, "mappingnotify: window: %lu\n", ev->window);
1546
1547         XRefreshKeyboardMapping(ev);
1548         if (ev->request == MappingKeyboard)
1549                 grabkeys();
1550 }
1551
1552 void
1553 maprequest(XEvent *e)
1554 {
1555         XMapRequestEvent        *ev = &e->xmaprequest;
1556         XWindowAttributes       wa;
1557         struct swm_region       *r;
1558
1559         DNPRINTF(SWM_D_EVENT, "maprequest: window: %lu\n",
1560             e->xmaprequest.window);
1561
1562         if (!XGetWindowAttributes(display, ev->window, &wa))
1563                 return;
1564         if (wa.override_redirect)
1565                 return;
1566         r = root_to_region(wa.root);
1567         manage_window(e->xmaprequest.window, r->ws);
1568         stack();
1569 }
1570
1571 void
1572 propertynotify(XEvent *e)
1573 {
1574         DNPRINTF(SWM_D_EVENT, "propertynotify: window: %lu\n",
1575             e->xproperty.window);
1576 }
1577
1578 void
1579 unmapnotify(XEvent *e)
1580 {
1581         DNPRINTF(SWM_D_EVENT, "unmapnotify: window: %lu\n", e->xunmap.window);
1582 }
1583
1584 void
1585 visibilitynotify(XEvent *e)
1586 {
1587         int                     i;
1588         struct swm_region       *r;
1589
1590         DNPRINTF(SWM_D_EVENT, "visibilitynotify: window: %lu\n",
1591             e->xvisibility.window);
1592         if (e->xvisibility.state == VisibilityUnobscured)
1593                 for (i = 0; i < ScreenCount(display); i++) 
1594                         TAILQ_FOREACH(r, &screens[i].rl, entry)
1595                                 if (e->xvisibility.window == r->bar_window)
1596                                         bar_update();
1597 }
1598
1599 void                    (*handler[LASTEvent])(XEvent *) = {
1600                                 [Expose] = expose,
1601                                 [KeyPress] = keypress,
1602                                 [ButtonPress] = buttonpress,
1603                                 [ConfigureRequest] = configurerequest,
1604                                 [ConfigureNotify] = configurenotify,
1605                                 [DestroyNotify] = destroynotify,
1606                                 [EnterNotify] = enternotify,
1607                                 [FocusIn] = focusin,
1608                                 [MappingNotify] = mappingnotify,
1609                                 [MapRequest] = maprequest,
1610                                 [PropertyNotify] = propertynotify,
1611                                 [UnmapNotify] = unmapnotify,
1612                                 [VisibilityNotify] = visibilitynotify,
1613 };
1614
1615 int
1616 xerror_start(Display *d, XErrorEvent *ee)
1617 {
1618         other_wm = 1;
1619         return (-1);
1620 }
1621
1622 int
1623 xerror(Display *d, XErrorEvent *ee)
1624 {
1625         /* fprintf(stderr, "error: %p %p\n", display, ee); */
1626         return (-1);
1627 }
1628
1629 int
1630 active_wm(void)
1631 {
1632         other_wm = 0;
1633         xerrorxlib = XSetErrorHandler(xerror_start);
1634
1635         /* this causes an error if some other window manager is running */
1636         XSelectInput(display, DefaultRootWindow(display),
1637             SubstructureRedirectMask);
1638         XSync(display, False);
1639         if (other_wm)
1640                 return (1);
1641
1642         XSetErrorHandler(xerror);
1643         XSync(display, False);
1644         return (0);
1645 }
1646
1647 long
1648 getstate(Window w)
1649 {
1650         int                     format, status;
1651         long                    result = -1;
1652         unsigned char           *p = NULL;
1653         unsigned long           n, extra;
1654         Atom                    real;
1655
1656         astate = XInternAtom(display, "WM_STATE", False);
1657         status = XGetWindowProperty(display, w, astate, 0L, 2L, False, astate,
1658             &real, &format, &n, &extra, (unsigned char **)&p);
1659         if (status != Success)
1660                 return (-1);
1661         if (n != 0)
1662                 result = *p;
1663         XFree(p);
1664         return (result);
1665 }
1666
1667 void
1668 new_region(struct swm_screen *s, struct workspace *ws,
1669     int x, int y, int w, int h)
1670 {
1671         struct swm_region       *r;
1672
1673         DNPRINTF(SWM_D_MISC, "new region on screen %d: %dx%d (%d, %d)\n",
1674              s->idx, x, y, w, h);
1675
1676         if ((r = calloc(1, sizeof(struct swm_region))) == NULL)
1677                 errx(1, "calloc: failed to allocate memory for screen");
1678
1679         X(r) = x;
1680         Y(r) = y;
1681         WIDTH(r) = w;
1682         HEIGHT(r) = h;
1683         r->s = s;
1684         r->ws = ws;
1685         ws->r = r;
1686         TAILQ_INSERT_TAIL(&s->rl, r, entry);
1687         bar_setup(r);
1688 }
1689
1690 void
1691 setup_screens(void)
1692 {
1693 #ifdef SWM_XRR_HAS_CRTC
1694         XRRCrtcInfo             *ci;
1695         XRRScreenResources      *sr;
1696         int                     c;
1697 #endif /* SWM_XRR_HAS_CRTC */
1698         Window                  d1, d2, *wins = NULL;
1699         XWindowAttributes       wa;
1700         struct swm_region       *r;
1701         unsigned int            no;
1702         int                     errorbase, major, minor;
1703         int                     ncrtc = 0, w = 0;
1704         int                     i, j, k;
1705         struct workspace        *ws;
1706
1707         if ((screens = calloc(ScreenCount(display),
1708              sizeof(struct swm_screen))) == NULL)
1709                 errx(1, "calloc: screens");
1710
1711         /* map physical screens */
1712         for (i = 0; i < ScreenCount(display); i++) {
1713                 DNPRINTF(SWM_D_WS, "setup_screens: init screen %d\n", i);
1714                 screens[i].idx = i;
1715                 TAILQ_INIT(&screens[i].rl);
1716                 screens[i].root = RootWindow(display, i);
1717                 XGetWindowAttributes(display, screens[i].root, &wa);
1718                 XSelectInput(display, screens[i].root,
1719                     ButtonPressMask | wa.your_event_mask);
1720
1721                 /* set default colors */
1722                 screens[i].color_focus = name_to_color("red");
1723                 screens[i].color_unfocus = name_to_color("rgb:88/88/88");
1724                 screens[i].bar_border = name_to_color("rgb:00/80/80");
1725                 screens[i].bar_color = name_to_color("black");
1726                 screens[i].bar_font_color = name_to_color("rgb:a0/a0/a0");
1727
1728                 /* init all workspaces */
1729                 for (j = 0; j < SWM_WS_MAX; j++) {
1730                         ws = &screens[i].ws[j];
1731                         ws->idx = j;
1732                         ws->restack = 1;
1733                         ws->focus = NULL;
1734                         ws->r = NULL;
1735                         TAILQ_INIT(&ws->winlist);
1736
1737                         for (k = 0; layouts[k].l_stack != NULL; k++)
1738                                 if (layouts[k].l_config != NULL)
1739                                         layouts[k].l_config(ws,
1740                                             SWM_ARG_ID_STACKINIT);
1741                         ws->cur_layout = &layouts[0];
1742                 }
1743
1744                 /* map virtual screens onto physical screens */
1745                 screens[i].xrandr_support = XRRQueryExtension(display,
1746                     &xrandr_eventbase, &errorbase);
1747                 if (screens[i].xrandr_support)
1748                         if (XRRQueryVersion(display, &major, &minor) &&
1749                             major < 1)
1750                                 screens[i].xrandr_support = 0;
1751
1752 #if 0   /* not ready for dynamic screen changes */
1753                 if (screens[i].xrandr_support)
1754                         XRRSelectInput(display,
1755                             screens[r->s].root,
1756                             RRScreenChangeNotifyMask);
1757 #endif
1758
1759                 /* grab existing windows (before we build the bars)*/
1760                 if (!XQueryTree(display, screens[i].root, &d1, &d2, &wins, &no))
1761                         continue;
1762
1763 #ifdef SWM_XRR_HAS_CRTC
1764                 sr = XRRGetScreenResources(display, screens[i].root);
1765                 if (sr == NULL)
1766                         new_region(&screens[i], &screens[i].ws[w],
1767                             0, 0, DisplayWidth(display, i),
1768                             DisplayHeight(display, i)); 
1769                 else 
1770                         ncrtc = sr->ncrtc;
1771
1772                 for (c = 0; c < ncrtc; c++) {
1773                         ci = XRRGetCrtcInfo(display, sr, sr->crtcs[c]);
1774                         if (ci->noutput == 0)
1775                                 continue;
1776
1777                         if (ci != NULL && ci->mode == None)
1778                                 new_region(&screens[i], &screens[i].ws[w], 0, 0,
1779                                     DisplayWidth(display, i),
1780                                     DisplayHeight(display, i)); 
1781                         else
1782                                 new_region(&screens[i], &screens[i].ws[w],
1783                                     ci->x, ci->y, ci->width, ci->height);
1784                         w++;
1785                 }
1786                 XRRFreeCrtcInfo(ci);
1787                 XRRFreeScreenResources(sr);
1788 #else
1789                 new_region(&screens[i], &screens[i].ws[w], 0, 0,
1790                     DisplayWidth(display, i),
1791                     DisplayHeight(display, i)); 
1792 #endif /* SWM_XRR_HAS_CRTC */
1793
1794                 /* attach windows to a region */
1795                 /* normal windows */
1796                 if ((r = TAILQ_FIRST(&screens[i].rl)) == NULL)
1797                         errx(1, "no regions on screen %d", i);
1798
1799                 for (i = 0; i < no; i++) {
1800                         XGetWindowAttributes(display, wins[i], &wa);
1801                         if (!XGetWindowAttributes(display, wins[i], &wa) ||
1802                             wa.override_redirect ||
1803                             XGetTransientForHint(display, wins[i], &d1))
1804                                 continue;
1805
1806                         if (wa.map_state == IsViewable ||
1807                             getstate(wins[i]) == NormalState)
1808                                 manage_window(wins[i], r->ws);
1809                 }
1810                 /* transient windows */
1811                 for (i = 0; i < no; i++) {
1812                         if (!XGetWindowAttributes(display, wins[i], &wa))
1813                                 continue;
1814
1815                         if (XGetTransientForHint(display, wins[i], &d1) &&
1816                             (wa.map_state == IsViewable || getstate(wins[i]) ==
1817                             NormalState))
1818                                 manage_window(wins[i], r->ws);
1819                 }
1820                 if (wins) {
1821                         XFree(wins);
1822                         wins = NULL;
1823                 }
1824         }
1825 }
1826
1827 int
1828 main(int argc, char *argv[])
1829 {
1830         struct passwd           *pwd;
1831         char                    conf[PATH_MAX], *cfile = NULL;
1832         struct stat             sb;
1833         XEvent                  e;
1834         int                     xfd;
1835         fd_set                  rd;
1836
1837         start_argv = argv;
1838         fprintf(stderr, "Welcome to scrotwm V%s\n", SWM_VERSION);
1839         if (!setlocale(LC_CTYPE, "") || !XSupportsLocale())
1840                 warnx("no locale support");
1841
1842         if (!(display = XOpenDisplay(0)))
1843                 errx(1, "can not open display");
1844
1845         if (active_wm())
1846                 errx(1, "other wm running");
1847
1848         astate = XInternAtom(display, "WM_STATE", False);
1849
1850         /* look for local and global conf file */
1851         pwd = getpwuid(getuid());
1852         if (pwd == NULL)
1853                 errx(1, "invalid user %d", getuid());
1854
1855         snprintf(conf, sizeof conf, "%s/.%s", pwd->pw_dir, SWM_CONF_FILE);
1856         if (stat(conf, &sb) != -1) {
1857                 if (S_ISREG(sb.st_mode))
1858                         cfile = conf;
1859         } else {
1860                 /* try global conf file */
1861                 snprintf(conf, sizeof conf, "/etc/%s", SWM_CONF_FILE);
1862                 if (!stat(conf, &sb))
1863                         if (S_ISREG(sb.st_mode))
1864                                 cfile = conf;
1865         }
1866
1867         setup_screens();
1868
1869         if (cfile)
1870                 conf_load(cfile);
1871
1872
1873         /* ws[0].focus = TAILQ_FIRST(&ws[0].winlist); */
1874
1875         grabkeys();
1876         stack();
1877
1878         xfd = ConnectionNumber(display);
1879         while (running) {
1880                 FD_SET(xfd, &rd);
1881                 if (select(xfd + 1, &rd, NULL, NULL, NULL) == -1)
1882                         if (errno != EINTR)
1883                                 errx(1, "select failed");
1884                 if (bar_alarm) {
1885                         bar_alarm = 0;
1886                         bar_update();
1887                 }
1888                 while(XPending(display)) {
1889                         XNextEvent(display, &e);
1890                         if (handler[e.type])
1891                                 handler[e.type](&e);
1892                 }
1893         }
1894
1895         XCloseDisplay(display);
1896
1897         return (0);
1898 }