JasonWoof Got questions, comments, patches, etc.? Contact Jason Woofenden
557f59e6bfca0cfce85138f8b51429fef6afdf01
[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_init(struct workspace *);
193 void    vertical_resize(struct workspace *, int);
194 void    vertical_stack(struct workspace *, struct swm_geometry *);
195 void    horizontal_init(struct workspace *);
196 void    horizontal_resize(struct workspace *, int);
197 void    horizontal_stack(struct workspace *, struct swm_geometry *);
198 void    max_init(struct workspace *);
199 void    max_stack(struct workspace *, struct swm_geometry *);
200
201 struct layout {
202         void            (*l_init)(struct workspace *);  /* init/reset */
203         void            (*l_stack)(struct workspace *, struct swm_geometry *);
204         void            (*l_resize)(struct workspace *, int);
205 } layouts[] =  {
206         /* init                 stack,                  resize */
207         { vertical_init,        vertical_stack,         vertical_resize},
208         { horizontal_init,      horizontal_stack,       horizontal_resize},
209         { NULL,                 max_stack,              NULL},
210         { NULL,                 NULL,                   NULL},
211 };
212
213 #define SWM_H_SLICE             (32)
214 #define SWM_V_SLICE             (32)
215
216
217 /* define work spaces */
218 struct workspace {
219         int                     idx;            /* workspace index */
220         int                     restack;        /* restack on switch */
221         struct layout           *cur_layout;    /* current layout handlers */
222         struct ws_win           *focus;         /* may be NULL */
223         struct swm_region       *r;             /* may be NULL */
224         struct ws_win_list      winlist;        /* list of windows in ws */
225
226         /* stacker state */
227         struct {
228                                 int horizontal_msize;
229                                 int vertical_msize;
230         } l_state;
231 };
232
233 /* physical screen mapping */
234 #define SWM_WS_MAX              (10)            /* XXX Too small? */
235 struct swm_screen {
236         int                     idx;            /* screen index */
237         struct swm_region_list  rl;     /* list of regions on this screen */
238         Window                  root;
239         int                     xrandr_support;
240         struct workspace        ws[SWM_WS_MAX];
241
242         /* colors */
243         unsigned long           bar_border;
244         unsigned long           bar_color;
245         unsigned long           bar_font_color;
246         unsigned long           color_focus;            /* XXX should this be per ws? */
247         unsigned long           color_unfocus;
248         char                    bar_text[SWM_BAR_MAX];
249 };
250 struct swm_screen       *screens;
251 int                     num_screens;
252 Window rootclick = 0;
253
254 struct ws_win           *cur_focus = NULL;
255
256 /* args to functions */
257 union arg {
258         int                     id;
259 #define SWM_ARG_ID_FOCUSNEXT    (0)
260 #define SWM_ARG_ID_FOCUSPREV    (1)
261 #define SWM_ARG_ID_FOCUSMAIN    (2)
262 #define SWM_ARG_ID_SWAPNEXT     (3)
263 #define SWM_ARG_ID_SWAPPREV     (4)
264 #define SWM_ARG_ID_SWAPMAIN     (5)
265 #define SWM_ARG_ID_MASTERSHRINK (6)
266 #define SWM_ARG_ID_MASTERGROW   (7)
267         char                    **argv;
268 };
269
270 unsigned long
271 name_to_color(char *colorname)
272 {
273         Colormap                cmap;
274         Status                  status;
275         XColor                  screen_def, exact_def;
276         unsigned long           result = 0;
277         char                    cname[32] = "#";
278
279         cmap = DefaultColormap(display, screens[0].idx);
280         status = XAllocNamedColor(display, cmap, colorname,
281             &screen_def, &exact_def);
282         if (!status) {
283                 strlcat(cname, colorname + 2, sizeof cname - 1);
284                 status = XAllocNamedColor(display, cmap, cname, &screen_def,
285                     &exact_def);
286         }
287         if (status)
288                 result = screen_def.pixel;
289         else
290                 fprintf(stderr, "color '%s' not found.\n", colorname);
291
292         return (result);
293 }
294
295 /* conf file stuff */
296 #define SWM_CONF_WS     "\n= \t"
297 #define SWM_CONF_FILE   "scrotwm.conf"
298 int
299 conf_load(char *filename)
300 {
301         FILE                    *config;
302         char                    *line, *cp, *var, *val;
303         size_t                  len, lineno = 0;
304         int                     i;
305
306         DNPRINTF(SWM_D_MISC, "conf_load: filename %s\n", filename);
307
308         if (filename == NULL)
309                 return (1);
310
311         if ((config = fopen(filename, "r")) == NULL)
312                 return (1);
313
314         for (;;) {
315                 if ((line = fparseln(config, &len, &lineno, NULL, 0)) == NULL)
316                         if (feof(config))
317                                 break;
318                 cp = line;
319                 cp += (long)strspn(cp, SWM_CONF_WS);
320                 if (cp[0] == '\0') {
321                         /* empty line */
322                         free(line);
323                         continue;
324                 }
325                 if ((var = strsep(&cp, SWM_CONF_WS)) == NULL || cp == NULL)
326                         break;
327                 cp += (long)strspn(cp, SWM_CONF_WS);
328                 if ((val = strsep(&cp, SWM_CONF_WS)) == NULL)
329                         break;
330
331                 DNPRINTF(SWM_D_MISC, "conf_load: %s=%s\n",var ,val);
332                 switch (var[0]) {
333                 case 'b':
334                         if (!strncmp(var, "bar_enabled", strlen("bar_enabled")))
335                                 bar_enabled = atoi(val);
336                         else if (!strncmp(var, "bar_border",
337                             strlen("bar_border")))
338                                 for (i = 0; i < ScreenCount(display); i++)
339                                         screens[i].bar_border = name_to_color(val);
340                         else if (!strncmp(var, "bar_color",
341                             strlen("bar_color")))
342                                 for (i = 0; i < ScreenCount(display); i++)
343                                         screens[i].bar_color = name_to_color(val);
344                         else if (!strncmp(var, "bar_font_color",
345                             strlen("bar_font_color")))
346                                 for (i = 0; i < ScreenCount(display); i++)
347                                         screens[i].bar_font_color = name_to_color(val);
348                         else if (!strncmp(var, "bar_font", strlen("bar_font")))
349                                 asprintf(&bar_fonts[0], "%s", val);
350                         else
351                                 goto bad;
352                         break;
353
354                 case 'c':
355                         if (!strncmp(var, "color_focus", strlen("color_focus")))
356                                 for (i = 0; i < ScreenCount(display); i++)
357                                         screens[i].color_focus = name_to_color(val);
358                         else if (!strncmp(var, "color_unfocus",
359                             strlen("color_unfocus")))
360                                 for (i = 0; i < ScreenCount(display); i++)
361                                         screens[i].color_unfocus = name_to_color(val);
362                         else
363                                 goto bad;
364                         break;
365
366                 case 'd':
367                         if (!strncmp(var, "dialog_ratio",
368                             strlen("dialog_ratio"))) {
369                                 dialog_ratio = atof(val);
370                                 if (dialog_ratio > 1.0 || dialog_ratio <= .3)
371                                         dialog_ratio = .6;
372                         } else
373                                 goto bad;
374                         break;
375
376                 case 's':
377                         if (!strncmp(var, "spawn_term", strlen("spawn_term")))
378                                 asprintf(&spawn_term[0], "%s", val); /* XXX args? */
379                         break;
380                 default:
381                         goto bad;
382                 }
383                 free(line);
384         }
385
386         fclose(config);
387         return (0);
388 bad:
389         errx(1, "invalid conf file entry: %s=%s", var, val);
390 }
391
392 void
393 bar_print(struct swm_region *r, char *s, int erase)
394 {
395         if (erase) {
396                 XSetForeground(display, bar_gc, r->s->bar_color);
397                 XDrawString(display, r->bar_window, bar_gc, 4, bar_fs->ascent,
398                     r->s->bar_text, strlen(r->s->bar_text));
399         }
400
401         strlcpy(r->s->bar_text, s, sizeof r->s->bar_text);
402         XSetForeground(display, bar_gc, r->s->bar_font_color);
403         XDrawString(display, r->bar_window, bar_gc, 4, bar_fs->ascent,
404             r->s->bar_text, strlen(r->s->bar_text));
405 }
406
407 void
408 bar_update(void)
409 {
410         time_t                  tmt;
411         struct tm               tm;
412         struct swm_region       *r;
413         int                     i, x;
414         char                    s[SWM_BAR_MAX];
415         char                    e[SWM_BAR_MAX];
416  
417         if (bar_enabled == 0)
418                 return;
419
420         /* draw new text */
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", s, x++);
428                         bar_print(r, e, 1);
429                 }
430         }
431         XSync(display, False);
432         alarm(60);
433 }
434
435 void
436 bar_signal(int sig)
437 {
438         bar_alarm = 1;
439 }
440
441 void
442 bar_toggle(struct swm_region *r, union arg *args)
443 {
444         struct swm_region       *tmpr;
445         int                     i, j;   
446
447         DNPRINTF(SWM_D_MISC, "bar_toggle\n");
448
449         if (bar_enabled) {
450                 for (i = 0; i < ScreenCount(display); i++)
451                         TAILQ_FOREACH(tmpr, &screens[i].rl, entry)
452                                 XUnmapWindow(display, tmpr->bar_window);
453         } else {
454                 for (i = 0; i < ScreenCount(display); i++)
455                         TAILQ_FOREACH(tmpr, &screens[i].rl, entry)
456                                 XMapRaised(display, tmpr->bar_window);
457         }
458         bar_enabled = !bar_enabled;
459         XSync(display, False);
460         for (i = 0; i < ScreenCount(display); i++)
461                 for (j = 0; j < SWM_WS_MAX; j++)
462                         screens[i].ws[j].restack = 1;
463
464         stack();
465         /* must be after stack */
466         for (i = 0; i < ScreenCount(display); i++)
467                 TAILQ_FOREACH(tmpr, &screens[i].rl, entry)
468                         bar_update();
469 }
470
471 void
472 bar_setup(struct swm_region *r)
473 {
474         int                     i;
475
476         for (i = 0; bar_fonts[i] != NULL; i++) {
477                 bar_fs = XLoadQueryFont(display, bar_fonts[i]);
478                 if (bar_fs)
479                         break;
480         }
481         if (bar_fonts[i] == NULL)
482                         errx(1, "couldn't load font");
483         bar_height = bar_fs->ascent + bar_fs->descent + 3;
484
485         r->bar_window = XCreateSimpleWindow(display, 
486             r->s->root, X(r), Y(r), WIDTH(r) - 2, bar_height - 2,
487             1, r->s->bar_border, r->s->bar_color);
488         bar_gc = XCreateGC(display, r->bar_window, 0, &bar_gcv);
489         XSetFont(display, bar_gc, bar_fs->fid);
490         XSelectInput(display, r->bar_window, VisibilityChangeMask);
491         if (bar_enabled)
492                 XMapRaised(display, r->bar_window);
493         DNPRINTF(SWM_D_MISC, "bar_setup: bar_window %lu\n", r->bar_window);
494
495         if (signal(SIGALRM, bar_signal) == SIG_ERR)
496                 err(1, "could not install bar_signal");
497         bar_update();
498 }
499
500 void
501 config_win(struct ws_win *win)
502 {
503         XConfigureEvent         ce;
504
505         DNPRINTF(SWM_D_MISC, "config_win: win %lu x %d y %d w %d h %d\n",
506             win->id, win->g.x, win->g.y, win->g.w, win->g.h);
507         ce.type = ConfigureNotify;
508         ce.display = display;
509         ce.event = win->id;
510         ce.window = win->id;
511         ce.x = win->g.x;
512         ce.y = win->g.y;
513         ce.width = win->g.w;
514         ce.height = win->g.h;
515         ce.border_width = 1; /* XXX store this! */
516         ce.above = None;
517         ce.override_redirect = False;
518         XSendEvent(display, win->id, False, StructureNotifyMask, (XEvent *)&ce);
519 }
520
521 int
522 count_win(struct workspace *ws, int count_transient)
523 {
524         struct ws_win           *win;
525         int                     count = 0;
526
527         TAILQ_FOREACH(win, &ws->winlist, entry) {
528                 if (count_transient == 0 && win->floating)
529                         continue;
530                 if (count_transient == 0 && win->transient)
531                         continue;
532                 count++;
533         }
534         DNPRINTF(SWM_D_MISC, "count_win: %d\n", count);
535
536         return (count);
537 }
538
539 void
540 quit(struct swm_region *r, union arg *args)
541 {
542         DNPRINTF(SWM_D_MISC, "quit\n");
543         running = 0;
544 }
545
546 void
547 restart(struct swm_region *r, union arg *args)
548 {
549         DNPRINTF(SWM_D_MISC, "restart: %s\n", start_argv[0]);
550
551         /* disable alarm because the following code may not be interrupted */
552         alarm(0);
553         if (signal(SIGALRM, SIG_IGN) == SIG_ERR)
554                 errx(1, "can't disable alarm");
555
556         XCloseDisplay(display);
557         execvp(start_argv[0], start_argv);
558         fprintf(stderr, "execvp failed\n");
559         perror(" failed");
560         quit(NULL, NULL);
561 }
562
563 struct swm_region *
564 root_to_region(Window root)
565 {
566         struct swm_region       *r;
567         Window                  rr, cr;
568         int                     i, x, y, wx, wy;
569         unsigned int            mask;
570
571         for (i = 0; i < ScreenCount(display); i++)
572                 if (screens[i].root == root)
573                         break;
574
575         if (rootclick != root && /* if root was just clicked in, use cursor */
576             cur_focus && cur_focus->ws->r && cur_focus->s == &screens[i])
577                 r = cur_focus->ws->r;
578         else {
579                 if (XQueryPointer(display, screens[i].root, 
580                     &rr, &cr, &x, &y, &wx, &wy, &mask) == False) {
581                         r = TAILQ_FIRST(&screens[i].rl);
582                 } else {
583                         TAILQ_FOREACH(r, &screens[i].rl, entry) {
584                                 if (x > X(r) && x < X(r) + WIDTH(r) &&
585                                     y > Y(r) && y < Y(r) + HEIGHT(r))
586                                         break;
587                         }
588
589                         if (r == NULL)
590                                 r = TAILQ_FIRST(&screens[i].rl);
591                 }
592         }
593         return (r);
594 }
595
596 struct ws_win *
597 find_window(Window id)
598 {
599         struct ws_win           *win;
600         int                     i, j;
601
602         for (i = 0; i < ScreenCount(display); i++)
603                 for (j = 0; j < SWM_WS_MAX; j++)
604                         TAILQ_FOREACH(win, &screens[i].ws[j].winlist, entry)
605                                 if (id == win->id)
606                                         return (win);
607         return (NULL);
608 }
609
610 void
611 spawn(struct swm_region *r, union arg *args)
612 {
613         DNPRINTF(SWM_D_MISC, "spawn: %s\n", args->argv[0]);
614         /*
615          * The double-fork construct avoids zombie processes and keeps the code
616          * clean from stupid signal handlers.
617          */
618         if (fork() == 0) {
619                 if (fork() == 0) {
620                         if (display)
621                                 close(ConnectionNumber(display));
622                         setsid();
623                         execvp(args->argv[0], args->argv);
624                         fprintf(stderr, "execvp failed\n");
625                         perror(" failed");
626                 }
627                 exit(0);
628         }
629         wait(0);
630 }
631
632 void
633 unfocus_win(struct ws_win *win)
634 {
635         DNPRINTF(SWM_D_FOCUS, "unfocus_win: id: %lu\n", win->id);
636         if (win->ws->r && win->focus)
637                 XSetWindowBorder(display, win->id,
638                     win->ws->r->s->color_unfocus);
639         win->focus = 0;
640         if (win->ws->focus == win)
641                 win->ws->focus = NULL;
642         if (cur_focus == win)
643                 cur_focus = NULL;
644 }
645
646
647 void
648 focus_win(struct ws_win *win)
649 {
650         DNPRINTF(SWM_D_FOCUS, "focus_win: id: %lu\n", win->id);
651
652         rootclick = 0;
653
654         win->ws->focus = win;
655         if (win->ws->r != NULL) {
656                 if (cur_focus && cur_focus != win)
657                         unfocus_win(cur_focus);
658                 cur_focus = win;
659                 if (!win->focus)
660                         XSetWindowBorder(display, win->id,
661                             win->ws->r->s->color_focus);
662                 win->focus = 1;
663                 XSetInputFocus(display, win->id,
664                     RevertToPointerRoot, CurrentTime);
665         }
666 }
667
668 void
669 switchws(struct swm_region *r, union arg *args)
670 {
671         int                     wsid = args->id;
672         struct swm_region       *this_r, *other_r;
673         struct ws_win           *win;
674         struct workspace        *new_ws, *old_ws;
675
676         this_r = r;
677         old_ws = this_r->ws;
678         new_ws = &this_r->s->ws[wsid];
679
680         DNPRINTF(SWM_D_WS, "switchws screen %d region %dx%d+%d+%d: "
681             "%d -> %d\n", r->s->idx, WIDTH(r), HEIGHT(r), X(r), Y(r),
682             old_ws->idx, wsid);
683
684         if (new_ws == old_ws)
685                 return;
686
687         other_r = new_ws->r;
688         if (!other_r) {
689                 /* if the other workspace is hidden, switch windows */
690                 /* map new window first to prevent ugly blinking */
691                 TAILQ_FOREACH(win, &new_ws->winlist, entry)
692                         XMapRaised(display, win->id);
693
694                 TAILQ_FOREACH(win, &old_ws->winlist, entry)
695                         XUnmapWindow(display, win->id);
696
697                 old_ws->r = NULL;
698                 old_ws->restack = 1;
699         } else {
700                 other_r->ws = old_ws;
701                 old_ws->r = other_r;
702         }
703         this_r->ws = new_ws;
704         new_ws->r = this_r;
705
706         ignore_enter = 1;
707         /* set focus */
708         if (new_ws->focus)
709                 focus_win(new_ws->focus);
710         stack();
711 }
712
713 void
714 swapwin(struct swm_region *r, union arg *args)
715 {
716         struct ws_win           *target;
717         struct ws_win_list      *wl;
718
719
720         DNPRINTF(SWM_D_WS, "swapwin id %d "
721             "in screen %d region %dx%d+%d+%d ws %d\n", args->id,
722             r->s->idx, WIDTH(r), HEIGHT(r), X(r), Y(r), r->ws->idx);
723         if (cur_focus == NULL)
724                 return;
725
726         wl = &cur_focus->ws->winlist;
727
728         switch (args->id) {
729         case SWM_ARG_ID_SWAPPREV:
730                 target = TAILQ_PREV(cur_focus, ws_win_list, entry);
731                 TAILQ_REMOVE(wl, cur_focus, entry);
732                 if (target == NULL)
733                         TAILQ_INSERT_TAIL(wl, cur_focus, entry);
734                 else
735                         TAILQ_INSERT_BEFORE(target, cur_focus, entry);
736                 break;
737         case SWM_ARG_ID_SWAPNEXT: 
738                 target = TAILQ_NEXT(cur_focus, entry);
739                 TAILQ_REMOVE(wl, cur_focus, entry);
740                 if (target == NULL)
741                         TAILQ_INSERT_HEAD(wl, cur_focus, entry);
742                 else
743                         TAILQ_INSERT_AFTER(wl, target, cur_focus, entry);
744                 break;
745         case SWM_ARG_ID_SWAPMAIN:
746                 target = TAILQ_FIRST(wl);
747                 if (target == cur_focus)
748                         return;
749                 TAILQ_REMOVE(wl, target, entry);
750                 TAILQ_INSERT_BEFORE(cur_focus, target, entry);
751                 TAILQ_REMOVE(wl, cur_focus, entry);
752                 TAILQ_INSERT_HEAD(wl, cur_focus, entry);
753                 break;
754         default:
755                 DNPRINTF(SWM_D_MOVE, "invalid id: %d\n", args->id);
756                 return;
757         }
758
759         ignore_enter = 2;
760         stack();
761 }
762
763 void
764 focus(struct swm_region *r, union arg *args)
765 {
766         struct ws_win           *winfocus, *winlostfocus;
767         struct ws_win_list      *wl;
768
769         DNPRINTF(SWM_D_FOCUS, "focus: id %d\n", args->id);
770         if (cur_focus == NULL)
771                 return;
772
773         wl = &cur_focus->ws->winlist;
774
775         winlostfocus = cur_focus;
776
777         switch (args->id) {
778         case SWM_ARG_ID_FOCUSPREV:
779                 winfocus = TAILQ_PREV(cur_focus, ws_win_list, entry);
780                 if (winfocus == NULL)
781                         winfocus = TAILQ_LAST(wl, ws_win_list);
782                 break;
783
784         case SWM_ARG_ID_FOCUSNEXT:
785                 winfocus = TAILQ_NEXT(cur_focus, entry);
786                 if (winfocus == NULL)
787                         winfocus = TAILQ_FIRST(wl);
788                 break;
789
790         case SWM_ARG_ID_FOCUSMAIN:
791                 winfocus = TAILQ_FIRST(wl);
792                 break;
793
794         default:
795                 return;
796         }
797
798         if (winfocus == winlostfocus)
799                 return;
800
801         focus_win(winfocus);
802         XSync(display, False);
803 }
804
805 void
806 cycle_layout(struct swm_region *r, union arg *args)
807 {
808         struct workspace        *ws = r->ws;
809
810         DNPRINTF(SWM_D_EVENT, "cycle_layout: workspace: %d\n", ws->idx);
811
812         ws->cur_layout++;
813         if (ws->cur_layout->l_stack == NULL)
814                 ws->cur_layout = &layouts[0];
815         ignore_enter = 1;
816
817         stack();
818 }
819
820 void
821 resize_master(struct swm_region *r, union arg *args)
822 {
823         struct workspace        *ws = r->ws;
824
825         DNPRINTF(SWM_D_STACK, "resize_master for workspace %d (id %d\n",
826             args->id, ws->idx);
827
828         if (ws->cur_layout->l_resize != NULL)
829                 ws->cur_layout->l_resize(ws, args->id);
830 }
831
832 void
833 stack_reset(struct swm_region *r, union arg *args)
834 {
835         struct workspace        *ws = r->ws;
836
837         DNPRINTF(SWM_D_STACK, "stack_reset: ws %d\n", ws->idx);
838
839         if (ws->cur_layout->l_init != NULL) {
840                 ws->cur_layout->l_init(ws);
841                 stack();
842         }
843 }
844
845 void
846 stack(void) {
847         struct swm_geometry     g;
848         struct swm_region       *r;
849         int                     i, j;
850
851         DNPRINTF(SWM_D_STACK, "stack\n");
852
853         for (i = 0; i < ScreenCount(display); i++) {
854                 j = 0;
855                 TAILQ_FOREACH(r, &screens[i].rl, entry) {
856                         DNPRINTF(SWM_D_STACK, "stacking workspace %d "
857                             "(screen %d, region %d)\n", r->ws->idx, i, j++);
858
859                         /* start with screen geometry, adjust for bar */
860                         g = r->g;
861                         g.w -= 2;
862                         g.h -= 2;
863                         if (bar_enabled) {
864                                 g.y += bar_height;
865                                 g.h -= bar_height;
866                         } 
867
868                         r->ws->restack = 0;
869                         r->ws->cur_layout->l_stack(r->ws, &g);
870                 }
871         }
872         XSync(display, False);
873 }
874
875 void
876 stack_floater(struct ws_win *win, struct swm_region *r)
877 {
878         unsigned int            mask;
879         XWindowChanges          wc;
880
881         bzero(&wc, sizeof wc);
882         mask = CWX | CWY | CWBorderWidth | CWWidth | CWHeight;
883         wc.border_width = 1;
884         if (win->transient) {
885                 win->g.w = (double)WIDTH(r) * dialog_ratio;
886                 win->g.h = (double)HEIGHT(r) * dialog_ratio;
887         }
888         wc.width = win->g.w;
889         wc.height = win->g.h;
890         wc.x = (WIDTH(r) - win->g.w) / 2;
891         wc.y = (HEIGHT(r) - win->g.h) / 2;
892
893         DNPRINTF(SWM_D_STACK, "stack_floater: win %lu x %d y %d w %d h %d\n",
894             win->id, wc.x, wc.y, wc.width, wc.height);
895
896         XConfigureWindow(display, win->id, mask, &wc);
897 }
898
899 int vertical_msize[SWM_WS_MAX];
900
901 void
902 vertical_init(struct workspace *ws)
903 {
904         DNPRINTF(SWM_D_MISC, "vertical_init: workspace: %d\n", ws->idx);
905
906         ws->l_state.vertical_msize = SWM_V_SLICE / 2;
907 }
908
909 void
910 vertical_resize(struct workspace *ws, int id)
911 {
912         DNPRINTF(SWM_D_STACK, "vertical_resize: workspace: %d\n", ws->idx);
913
914         switch (id) {
915         case SWM_ARG_ID_MASTERSHRINK:
916                 ws->l_state.vertical_msize--;
917                 if (ws->l_state.vertical_msize < 1)
918                         ws->l_state.vertical_msize = 1;
919                 break;
920         case SWM_ARG_ID_MASTERGROW:
921                 ws->l_state.vertical_msize++;
922                 if (ws->l_state.vertical_msize > SWM_V_SLICE - 1)
923                         ws->l_state.vertical_msize = SWM_V_SLICE - 1;
924                 break;
925         default:
926                 return;
927         }
928         stack();
929 }
930
931 void
932 vertical_stack(struct workspace *ws, struct swm_geometry *g) {
933         XWindowChanges          wc;
934         struct swm_geometry     gg = *g;
935         struct ws_win           *win, *winfocus;
936         int                     i, hrh, winno, main_width;
937         unsigned int            mask;
938
939         DNPRINTF(SWM_D_STACK, "vertical_stack: workspace: %d\n", ws->idx);
940
941         if ((winno = count_win(ws, 0)) == 0)
942                 return;
943
944         if (ws->focus == NULL)
945                 ws->focus = TAILQ_FIRST(&ws->winlist);
946         winfocus = cur_focus ? cur_focus : ws->focus;
947
948         if (winno > 1) {
949                 main_width = (g->w / SWM_V_SLICE) *
950                    ws->l_state.vertical_msize;
951                 gg.w = main_width;
952         }
953
954         if (winno > 2)
955                 hrh = g->h / (winno - 1);
956         else
957                 hrh = 0;
958
959         i = 0;
960         TAILQ_FOREACH(win, &ws->winlist, entry) {
961                 if (i == 1) {
962                         gg.x += main_width + 2;
963                         gg.w = g->w - (main_width + 2);
964                 }
965                 if (i != 0 && hrh != 0) {
966                         /* correct the last window for lost pixels */
967                         if (win == TAILQ_LAST(&ws->winlist, ws_win_list)) {
968                                 gg.h = hrh + (g->h - (i * hrh));
969                                 gg.y += hrh;
970                         } else {
971                                 gg.h = hrh - 2;
972                                 /* leave first right hand window at y = 0 */
973                                 if (i > 1)
974                                         gg.y += gg.h + 2;
975                         }
976                 }
977
978                 if (win->transient != 0 || win->floating != 0)
979                         stack_floater(win, ws->r);
980                 else {
981                         bzero(&wc, sizeof wc);
982                         wc.border_width = 1;
983                         win->g.x = wc.x = gg.x;
984                         win->g.y = wc.y = gg.y;
985                         win->g.w = wc.width = gg.w;
986                         win->g.h = wc.height = gg.h;
987                         mask = CWX | CWY | CWWidth | CWHeight | CWBorderWidth;
988                         XConfigureWindow(display, win->id, mask, &wc);
989                 }
990
991                 XMapRaised(display, win->id);
992                 i++;
993         }
994
995         if (winfocus)
996                 focus_win(winfocus); /* has to be done outside of the loop */
997 }
998
999
1000 void
1001 horizontal_init(struct workspace *ws)
1002 {
1003         DNPRINTF(SWM_D_STACK, "horizontal_init: workspace: %d\n", ws->idx);
1004
1005         ws->l_state.horizontal_msize = SWM_H_SLICE / 2;
1006 }
1007
1008 void
1009 horizontal_resize(struct workspace *ws, int id)
1010 {
1011         DNPRINTF(SWM_D_STACK, "horizontal_resize: workspace: %d\n", ws->idx);
1012
1013         switch (id) {
1014         case SWM_ARG_ID_MASTERSHRINK:
1015                 ws->l_state.horizontal_msize--;
1016                 if (ws->l_state.horizontal_msize < 1)
1017                         ws->l_state.horizontal_msize = 1;
1018                 break;
1019         case SWM_ARG_ID_MASTERGROW:
1020                 ws->l_state.horizontal_msize++;
1021                 if (ws->l_state.horizontal_msize > SWM_H_SLICE - 1)
1022                         ws->l_state.horizontal_msize = SWM_H_SLICE - 1;
1023                 break;
1024         default:
1025                 return;
1026         }
1027         stack();
1028 }
1029
1030 void
1031 horizontal_stack(struct workspace *ws, struct swm_geometry *g) {
1032         XWindowChanges          wc;
1033         struct swm_geometry     gg = *g;
1034         struct ws_win           *win, *winfocus;
1035         int                     i, hrw, winno, main_height;
1036         unsigned int            mask;
1037
1038         DNPRINTF(SWM_D_STACK, "horizontal_stack: workspace: %d\n", ws->idx);
1039
1040         if ((winno = count_win(ws, 0)) == 0)
1041                 return;
1042
1043         if (ws->focus == NULL)
1044                 ws->focus = TAILQ_FIRST(&ws->winlist);
1045         winfocus = cur_focus ? cur_focus : ws->focus;
1046
1047         if (winno > 1) {
1048                 main_height = (g->h / SWM_H_SLICE) *
1049                     ws->l_state.horizontal_msize;
1050                 gg.h = main_height;
1051         }
1052
1053         if (winno > 2)
1054                 hrw = g->w / (winno - 1);
1055         else
1056                 hrw = 0;
1057
1058         i = 0;
1059         TAILQ_FOREACH(win, &ws->winlist, entry) {
1060                 if (i == 1) {
1061                         gg.y += main_height + 2;
1062                         gg.h = g->h - (main_height + 2);
1063                 }
1064                 if (i != 0 && hrw != 0) {
1065                         /* correct the last window for lost pixels */
1066                         if (win == TAILQ_LAST(&ws->winlist, ws_win_list)) {
1067                                 gg.w = hrw + (g->w - (i * hrw));
1068                                 gg.x += hrw;
1069                         } else {
1070                                 gg.w = hrw - 2;
1071                                 /* leave first bottom window at x = 0 */
1072                                 if (i > 1)
1073                                         gg.x += gg.w + 2;
1074                         }
1075                 }
1076
1077                 if (win->transient != 0 || win->floating != 0)
1078                         stack_floater(win, ws->r);
1079                 else {
1080                         bzero(&wc, sizeof wc);
1081                         wc.border_width = 1;
1082                         win->g.x = wc.x = gg.x;
1083                         win->g.y = wc.y = gg.y;
1084                         win->g.w = wc.width = gg.w;
1085                         win->g.h = wc.height = gg.h;
1086                         mask = CWX | CWY | CWWidth | CWHeight | CWBorderWidth;
1087                         XConfigureWindow(display, win->id, mask, &wc);
1088                 }
1089
1090                 XMapRaised(display, win->id);
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_reset,    {0} }, 
1188         { MODKEY,               XK_h,           resize_master,  {.id = SWM_ARG_ID_MASTERSHRINK} },
1189         { MODKEY,               XK_l,           resize_master,  {.id = SWM_ARG_ID_MASTERGROW} },
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_init != NULL)
1737                                         layouts[k].l_init(ws);
1738                         ws->cur_layout = &layouts[0];
1739                 }
1740
1741                 /* map virtual screens onto physical screens */
1742                 screens[i].xrandr_support = XRRQueryExtension(display,
1743                     &xrandr_eventbase, &errorbase);
1744                 if (screens[i].xrandr_support)
1745                         if (XRRQueryVersion(display, &major, &minor) &&
1746                             major < 1)
1747                                 screens[i].xrandr_support = 0;
1748
1749 #if 0   /* not ready for dynamic screen changes */
1750                 if (screens[i].xrandr_support)
1751                         XRRSelectInput(display,
1752                             screens[r->s].root,
1753                             RRScreenChangeNotifyMask);
1754 #endif
1755
1756                 /* grab existing windows (before we build the bars)*/
1757                 if (!XQueryTree(display, screens[i].root, &d1, &d2, &wins, &no))
1758                         continue;
1759
1760 #ifdef SWM_XRR_HAS_CRTC
1761                 sr = XRRGetScreenResources(display, screens[i].root);
1762                 if (sr == NULL)
1763                         new_region(&screens[i], &screens[i].ws[w],
1764                             0, 0, DisplayWidth(display, i),
1765                             DisplayHeight(display, i)); 
1766                 else 
1767                         ncrtc = sr->ncrtc;
1768
1769                 for (c = 0; c < ncrtc; c++) {
1770                         ci = XRRGetCrtcInfo(display, sr, sr->crtcs[c]);
1771                         if (ci->noutput == 0)
1772                                 continue;
1773
1774                         if (ci != NULL && ci->mode == None)
1775                                 new_region(&screens[i], &screens[i].ws[w], 0, 0,
1776                                     DisplayWidth(display, i),
1777                                     DisplayHeight(display, i)); 
1778                         else
1779                                 new_region(&screens[i], &screens[i].ws[w],
1780                                     ci->x, ci->y, ci->width, ci->height);
1781                         w++;
1782                 }
1783                 XRRFreeCrtcInfo(ci);
1784                 XRRFreeScreenResources(sr);
1785 #else
1786                 new_region(&screens[i], &screens[i].ws[w], 0, 0,
1787                     DisplayWidth(display, i),
1788                     DisplayHeight(display, i)); 
1789 #endif /* SWM_XRR_HAS_CRTC */
1790
1791                 /* attach windows to a region */
1792                 /* normal windows */
1793                 if ((r = TAILQ_FIRST(&screens[i].rl)) == NULL)
1794                         errx(1, "no regions on screen %d", i);
1795
1796                 for (i = 0; i < no; i++) {
1797                         XGetWindowAttributes(display, wins[i], &wa);
1798                         if (!XGetWindowAttributes(display, wins[i], &wa) ||
1799                             wa.override_redirect ||
1800                             XGetTransientForHint(display, wins[i], &d1))
1801                                 continue;
1802
1803                         if (wa.map_state == IsViewable ||
1804                             getstate(wins[i]) == NormalState)
1805                                 manage_window(wins[i], r->ws);
1806                 }
1807                 /* transient windows */
1808                 for (i = 0; i < no; i++) {
1809                         if (!XGetWindowAttributes(display, wins[i], &wa))
1810                                 continue;
1811
1812                         if (XGetTransientForHint(display, wins[i], &d1) &&
1813                             (wa.map_state == IsViewable || getstate(wins[i]) ==
1814                             NormalState))
1815                                 manage_window(wins[i], r->ws);
1816                 }
1817                 if (wins) {
1818                         XFree(wins);
1819                         wins = NULL;
1820                 }
1821         }
1822 }
1823
1824 int
1825 main(int argc, char *argv[])
1826 {
1827         struct passwd           *pwd;
1828         char                    conf[PATH_MAX], *cfile = NULL;
1829         struct stat             sb;
1830         XEvent                  e;
1831         int                     xfd;
1832         fd_set                  rd;
1833
1834         start_argv = argv;
1835         fprintf(stderr, "Welcome to scrotwm V%s\n", SWM_VERSION);
1836         if (!setlocale(LC_CTYPE, "") || !XSupportsLocale())
1837                 warnx("no locale support");
1838
1839         if (!(display = XOpenDisplay(0)))
1840                 errx(1, "can not open display");
1841
1842         if (active_wm())
1843                 errx(1, "other wm running");
1844
1845         astate = XInternAtom(display, "WM_STATE", False);
1846
1847         /* look for local and global conf file */
1848         pwd = getpwuid(getuid());
1849         if (pwd == NULL)
1850                 errx(1, "invalid user %d", getuid());
1851
1852         snprintf(conf, sizeof conf, "%s/.%s", pwd->pw_dir, SWM_CONF_FILE);
1853         if (stat(conf, &sb) != -1) {
1854                 if (S_ISREG(sb.st_mode))
1855                         cfile = conf;
1856         } else {
1857                 /* try global conf file */
1858                 snprintf(conf, sizeof conf, "/etc/%s", SWM_CONF_FILE);
1859                 if (!stat(conf, &sb))
1860                         if (S_ISREG(sb.st_mode))
1861                                 cfile = conf;
1862         }
1863
1864         setup_screens();
1865
1866         if (cfile)
1867                 conf_load(cfile);
1868
1869
1870         /* ws[0].focus = TAILQ_FIRST(&ws[0].winlist); */
1871
1872         grabkeys();
1873         stack();
1874
1875         xfd = ConnectionNumber(display);
1876         while (running) {
1877                 FD_SET(xfd, &rd);
1878                 if (select(xfd + 1, &rd, NULL, NULL, NULL) == -1)
1879                         if (errno != EINTR)
1880                                 errx(1, "select failed");
1881                 if (bar_alarm) {
1882                         bar_alarm = 0;
1883                         bar_update();
1884                 }
1885                 while(XPending(display)) {
1886                         XNextEvent(display, &e);
1887                         if (handler[e.type])
1888                                 handler[e.type](&e);
1889                 }
1890         }
1891
1892         XCloseDisplay(display);
1893
1894         return (0);
1895 }