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