JasonWoof Got questions, comments, patches, etc.? Contact Jason Woofenden
Some X apps work now such as gvim and firefox
[spectrwm.git] / scrotwm.c
1 /* $scrotwm$ */
2 /*
3  * Copyright (c) 2009 Marco Peereboom <marco@peereboom.us>
4  * Copyright (c) 2009 Ryan McBride <mcbride@countersiege.com>
5  *
6  * Permission to use, copy, modify, and distribute this software for any
7  * purpose with or without fee is hereby granted, provided that the above
8  * copyright notice and this permission notice appear in all copies.
9  *
10  * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
11  * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
12  * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
13  * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
14  * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
15  * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
16  * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
17  */
18 /*
19  * Much code and ideas taken from dwm under the following license:
20  * MIT/X Consortium License
21  * 
22  * 2006-2008 Anselm R Garbe <garbeam at gmail dot com>
23  * 2006-2007 Sander van Dijk <a dot h dot vandijk at gmail dot com>
24  * 2006-2007 Jukka Salmi <jukka at salmi dot ch>
25  * 2007 Premysl Hruby <dfenze at gmail dot com>
26  * 2007 Szabolcs Nagy <nszabolcs at gmail dot com>
27  * 2007 Christof Musik <christof at sendfax dot de>
28  * 2007-2008 Enno Gottox Boland <gottox at s01 dot de>
29  * 2007-2008 Peter Hartlich <sgkkr at hartlich dot com>
30  * 2008 Martin Hurton <martin dot hurton at gmail dot com>
31  * 
32  * Permission is hereby granted, free of charge, to any person obtaining a
33  * copy of this software and associated documentation files (the "Software"),
34  * to deal in the Software without restriction, including without limitation
35  * the rights to use, copy, modify, merge, publish, distribute, sublicense,
36  * and/or sell copies of the Software, and to permit persons to whom the
37  * Software is furnished to do so, subject to the following conditions:
38  * 
39  * The above copyright notice and this permission notice shall be included in
40  * all copies or substantial portions of the Software.
41  * 
42  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
43  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
44  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
45  * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
46  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
47  * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
48  * DEALINGS IN THE SOFTWARE.
49  */
50
51 #define SWM_VERSION     "0.5"
52
53 #include <stdio.h>
54 #include <stdlib.h>
55 #include <err.h>
56 #include <locale.h>
57 #include <unistd.h>
58 #include <time.h>
59 #include <signal.h>
60 #include <string.h>
61 #include <util.h>
62 #include <pwd.h>
63
64 #include <sys/types.h>
65 #include <sys/stat.h>
66 #include <sys/wait.h>
67 #include <sys/queue.h>
68 #include <sys/param.h>
69
70 #include <X11/cursorfont.h>
71 #include <X11/keysym.h>
72 #include <X11/Xatom.h>
73 #include <X11/Xlib.h>
74 #include <X11/Xproto.h>
75 #include <X11/Xutil.h>
76
77 /* #define SWM_DEBUG */
78 #ifdef SWM_DEBUG
79 #define DPRINTF(x...)           do { if (swm_debug) fprintf(stderr, x); } while(0)
80 #define DNPRINTF(n,x...)        do { if (swm_debug & n) fprintf(stderr, x); } while(0)
81 #define SWM_D_EVENT             0x0001
82 #define SWM_D_WS                0x0002
83 #define SWM_D_FOCUS             0x0004
84 #define SWM_D_MISC              0x0008
85
86 uint32_t                swm_debug = 0
87                             | SWM_D_EVENT
88                             | SWM_D_WS
89                             | SWM_D_FOCUS
90                             | SWM_D_MISC
91                             ;
92 #else
93 #define DPRINTF(x...)
94 #define DNPRINTF(n,x...)
95 #endif
96
97 #define LENGTH(x)               (sizeof x / sizeof x[0])
98 #define MODKEY                  Mod1Mask
99 #define CLEANMASK(mask)         (mask & ~(numlockmask | LockMask))
100
101 int                     (*xerrorxlib)(Display *, XErrorEvent *);
102 int                     other_wm;
103 int                     screen;
104 int                     width, height;
105 int                     running = 1;
106 int                     ignore_enter = 0;
107 unsigned int            numlockmask = 0;
108 unsigned long           color_focus = 0xff0000; /* XXX should this be per ws? */
109 unsigned long           color_unfocus = 0x888888;
110 Display                 *display;
111 Window                  root;
112
113 /* status bar */
114 int                     bar_enabled = 1;
115 int                     bar_height = 0;
116 unsigned long           bar_border = 0x008080;
117 unsigned long           bar_color = 0x000000;
118 unsigned long           bar_font_color = 0xa0a0a0;
119 Window                  bar_window;
120 GC                      bar_gc;
121 XGCValues               bar_gcv;
122 XFontStruct             *bar_fs;
123 char                    bar_text[128];
124 char                    *bar_fonts[] = {
125                             "-*-terminus-*-*-*-*-*-*-*-*-*-*-*-*",
126                             "-*-times-medium-r-*-*-*-*-*-*-*-*-*-*",
127                             NULL
128 };
129
130 /* terminal + args */
131 char                            *spawn_term[] = { "xterm", NULL };
132
133 struct ws_win {
134         TAILQ_ENTRY(ws_win)     entry;
135         Window                  id;
136         int                     x;
137         int                     y;
138         int                     width;
139         int                     height;
140 };
141
142 TAILQ_HEAD(ws_win_list, ws_win);
143
144 /* define work spaces */
145 #define SWM_WS_MAX              (10)
146 struct workspace {
147         int                     visible;        /* workspace visible */
148         int                     restack;        /* restack on switch */
149         struct ws_win           *focus;         /* which win has focus */
150         int                     winno;          /* total nr of windows */
151         struct ws_win_list      winlist;        /* list of windows in ws */
152 } ws[SWM_WS_MAX];
153 int                     current_ws = 0;
154
155 /* args to functions */
156 union arg {
157         int                     id;
158 #define SWM_ARG_ID_FOCUSNEXT    (0)
159 #define SWM_ARG_ID_FOCUSPREV    (1)
160 #define SWM_ARG_ID_FOCUSMAIN    (2)
161         char                    **argv;
162 };
163
164
165 void    stack(void);
166
167 #define SWM_CONF_WS     "\n= \t"
168 #define SWM_CONF_FILE   "scrotwm.conf"
169 int
170 conf_load(char *filename)
171 {
172         FILE                    *config;
173         char                    *line, *cp, *var, *val;
174         size_t                   len, lineno = 0;
175
176         DNPRINTF(SWM_D_MISC, "conf_load: filename %s\n", filename);
177
178         if (filename == NULL)
179                 return (1);
180
181         if ((config = fopen(filename, "r")) == NULL)
182                 return (1);
183
184         for (;;) {
185                 if ((line = fparseln(config, &len, &lineno, NULL, 0)) == NULL)
186                         if (feof(config))
187                                 break;
188                 cp = line;
189                 cp += (long)strspn(cp, SWM_CONF_WS);
190                 if (cp[0] == '\0') {
191                         /* empty line */
192                         free(line);
193                         continue;
194                 }
195                 if ((var = strsep(&cp, SWM_CONF_WS)) == NULL || cp == NULL)
196                         break;
197                 cp += (long)strspn(cp, SWM_CONF_WS);
198                 if ((val = strsep(&cp, SWM_CONF_WS)) == NULL)
199                         break;
200
201                 DNPRINTF(SWM_D_MISC, "conf_load: %s=%s\n",var ,val);
202                 switch (var[0]) {
203                 case 'b':
204                         if (!strncmp(var, "bar_enabled", strlen("bar_enabled")))
205                                 bar_enabled = atoi(val);
206                         else if (!strncmp(var, "bar_border",
207                             strlen("bar_border")))
208                                 bar_border = strtol(val, NULL, 16);
209                         else if (!strncmp(var, "bar_color",
210                             strlen("bar_color")))
211                                 bar_color = strtol(val, NULL, 16);
212                         else if (!strncmp(var, "bar_font_color",
213                             strlen("bar_font_color")))
214                                 bar_font_color = strtol(val, NULL, 16);
215                         else if (!strncmp(var, "bar_font", strlen("bar_font")))
216                                 asprintf(&bar_fonts[0], "%s", val);
217                         else
218                                 goto bad;
219                         break;
220
221                 case 'c':
222                         if (!strncmp(var, "color_focus", strlen("color_focus")))
223                                 color_focus = strtol(val, NULL, 16);
224                         else if (!strncmp(var, "color_unfocus",
225                             strlen("color_unfocus")))
226                                 color_unfocus = strtol(val, NULL, 16);
227                         else
228                                 goto bad;
229                         break;
230
231                 case 's':
232                         if (!strncmp(var, "spawn_term", strlen("spawn_term")))
233                                 asprintf(&spawn_term[0], "%s", val); /* XXX args? */
234                         break;
235                 default:
236                         goto bad;
237                 }
238                 free(line);
239         }
240
241         fclose(config);
242         return (0);
243 bad:
244         errx(1, "invalid conf file entry: %s=%s", var, val);
245 }
246
247 void
248 bar_print(void)
249 {
250         time_t                  tmt;
251         struct tm               tm;
252
253         if (bar_enabled == 0)
254                 return;
255
256         /* clear old text */
257         XSetForeground(display, bar_gc, bar_color);
258         XDrawString(display, bar_window, bar_gc, 4, bar_fs->ascent, bar_text,
259             strlen(bar_text));
260
261         /* draw new text */
262         time(&tmt);
263         localtime_r(&tmt, &tm);
264         strftime(bar_text, sizeof bar_text, "%a %b %d %R %Z %Y", &tm);
265         XSetForeground(display, bar_gc, bar_font_color);
266         XDrawString(display, bar_window, bar_gc, 4, bar_fs->ascent, bar_text,
267             strlen(bar_text));
268         XSync(display, False);
269
270         alarm(60);
271 }
272
273 void
274 bar_signal(int sig)
275 {
276         /* XXX yeah yeah byte me */
277         bar_print();
278 }
279
280 void
281 bar_toggle(union arg *args)
282 {
283         int i;
284
285         DNPRINTF(SWM_D_MISC, "bar_toggle\n");
286
287         if (bar_enabled) {
288                 bar_enabled = 0;
289                 height += bar_height; /* correct screen height */
290                 XUnmapWindow(display, bar_window);
291         } else {
292                 bar_enabled = 1;
293                 height -= bar_height; /* correct screen height */
294                 XMapWindow(display, bar_window);
295         }
296         XSync(display, False);
297         for (i = 0; i < SWM_WS_MAX; i++)
298                 ws[i].restack = 1;
299
300         stack();
301         bar_print(); /* must be after stack */
302 }
303
304 void
305 bar_setup(void)
306 {
307         int                     i;
308
309         for (i = 0; bar_fonts[i] != NULL; i++) {
310                 bar_fs = XLoadQueryFont(display, bar_fonts[i]);
311                 if (bar_fs)
312                         break;
313         }
314         if (bar_fonts[i] == NULL)
315                         errx(1, "couldn't load font");
316         bar_height = bar_fs->ascent + bar_fs->descent + 3;
317
318         bar_window = XCreateSimpleWindow(display, root, 0, 0, width,
319             bar_height - 2, 1, bar_border, bar_color);
320         bar_gc = XCreateGC(display, bar_window, 0, &bar_gcv);
321         XSetFont(display, bar_gc, bar_fs->fid);
322         if (bar_enabled) {
323                 height -= bar_height; /* correct screen height */
324                 XMapWindow(display, bar_window);
325         }
326
327         if (signal(SIGALRM, bar_signal) == SIG_ERR)
328                 err(1, "could not install bar_signal");
329         bar_print();
330 }
331
332 void
333 quit(union arg *args)
334 {
335         DNPRINTF(SWM_D_MISC, "quit\n");
336         running = 0;
337 }
338
339 void
340 spawn(union arg *args)
341 {
342         DNPRINTF(SWM_D_MISC, "spawn: %s\n", args->argv[0]);
343         /*
344          * The double-fork construct avoids zombie processes and keeps the code
345          * clean from stupid signal handlers.
346          */
347         if(fork() == 0) {
348                 if(fork() == 0) {
349                         if(display)
350                                 close(ConnectionNumber(display));
351                         setsid();
352                         execvp(args->argv[0], args->argv);
353                         fprintf(stderr, "execvp failed\n");
354                         perror(" failed");
355                 }
356                 exit(0);
357         }
358         wait(0);
359 }
360
361 void
362 focus_win(struct ws_win *win)
363 {
364         DNPRINTF(SWM_D_FOCUS, "focus_win: id: %lu\n", win->id);
365         XSetWindowBorder(display, win->id, color_focus);
366         XSetInputFocus(display, win->id, RevertToPointerRoot, CurrentTime);
367         ws[current_ws].focus = win;
368 }
369
370 void
371 unfocus_win(struct ws_win *win)
372 {
373         DNPRINTF(SWM_D_FOCUS, "unfocus_win: id: %lu\n", win->id);
374         XSetWindowBorder(display, win->id, color_unfocus);
375         if (ws[current_ws].focus == win)
376                 ws[current_ws].focus = NULL;
377 }
378
379 void
380 switchws(union arg *args)
381 {
382         int                     wsid = args->id;
383         struct ws_win           *win;
384
385         DNPRINTF(SWM_D_WS, "switchws: %d\n", wsid + 1);
386
387         if (wsid == current_ws)
388                 return;
389
390         /* map new window first to prevent ugly blinking */
391         TAILQ_FOREACH (win, &ws[wsid].winlist, entry)
392                 XMapRaised(display, win->id);
393         ws[wsid].visible = 1;
394
395         TAILQ_FOREACH (win, &ws[current_ws].winlist, entry)
396                 XUnmapWindow(display, win->id);
397         ws[current_ws].visible = 0;
398
399         current_ws = wsid;
400
401         ignore_enter = 1;
402         if (ws[wsid].restack) {
403                 stack();
404                 bar_print();
405         } else {
406                 if (ws[wsid].focus != NULL)
407                         focus_win(ws[wsid].focus);
408                 XSync(display, False);
409         }
410 }
411
412 void
413 focus(union arg *args)
414 {
415         struct ws_win           *winfocus, *winlostfocus;
416
417         DNPRINTF(SWM_D_FOCUS, "focus: id %d\n", args->id);
418         if (ws[current_ws].focus == NULL || ws[current_ws].winno == 0)
419                 return;
420
421         winlostfocus = ws[current_ws].focus;
422
423         switch (args->id) {
424         case SWM_ARG_ID_FOCUSPREV:
425                 ws[current_ws].focus =
426                     TAILQ_PREV(ws[current_ws].focus, ws_win_list, entry);
427                 if (ws[current_ws].focus == NULL)
428                         ws[current_ws].focus =
429                             TAILQ_LAST(&ws[current_ws].winlist, ws_win_list);
430                 break;
431
432         case SWM_ARG_ID_FOCUSNEXT:
433                 ws[current_ws].focus = TAILQ_NEXT(ws[current_ws].focus, entry);
434                 if (ws[current_ws].focus == NULL)
435                         ws[current_ws].focus =
436                             TAILQ_FIRST(&ws[current_ws].winlist);
437                 break;
438
439         case SWM_ARG_ID_FOCUSMAIN:
440                 ws[current_ws].focus = TAILQ_FIRST(&ws[current_ws].winlist);
441                 break;
442
443         default:
444                 return;
445         }
446
447         winfocus = ws[current_ws].focus;
448         unfocus_win(winlostfocus);
449         focus_win(winfocus);
450         XSync(display, False);
451 }
452
453 /* I know this sucks but it works well enough */
454 void
455 stack(void)
456 {
457         XWindowChanges          wc;
458         struct ws_win           wf, *win, *winfocus = &wf;
459         int                     i, h, w, x, y, hrh;
460
461         DNPRINTF(SWM_D_EVENT, "stack: workspace: %d\n", current_ws);
462
463         winfocus->id = root;
464
465         ws[current_ws].restack = 0;
466
467         if (ws[current_ws].winno == 0)
468                 return;
469
470         if (ws[current_ws].winno > 1)
471                 w = width / 2;
472         else
473                 w = width;
474
475         if (ws[current_ws].winno > 2)
476                 hrh = height / (ws[current_ws].winno - 1);
477         else
478                 hrh = 0;
479
480         x = 0;
481         y = bar_enabled ? bar_height : 0;
482         h = height;
483         i = 0;
484         TAILQ_FOREACH (win, &ws[current_ws].winlist, entry) {
485                 if (i == 1) {
486                         x += w + 2;
487                         w -= 2;
488                 }
489                 if (i != 0 && hrh != 0) {
490                         /* correct the last window for lost pixels */
491                         if (win == TAILQ_LAST(&ws[current_ws].winlist,
492                             ws_win_list)) {
493                                 h = height - (i * hrh);
494                                 if (h == 0)
495                                         h = hrh;
496                                 else
497                                         h += hrh;
498                                 y += hrh;
499                         } else {
500                                 h = hrh - 2;
501                                 /* leave first right hand window at y = 0 */
502                                 if (i > 1)
503                                         y += h + 2;
504                         }
505                 }
506
507                 bzero(&wc, sizeof wc);
508                 win->x = wc.x = x;
509                 win->y = wc.y = y;
510                 win->width = wc.width = w;
511                 win->height = wc.height = h;
512                 wc.border_width = 1;
513                 XConfigureWindow(display, win->id, CWX | CWY | CWWidth |
514                     CWHeight | CWBorderWidth, &wc);
515                 if (win == ws[current_ws].focus)
516                         winfocus = win;
517                 else
518                         unfocus_win(win);
519                 XMapRaised(display, win->id);
520                 i++;
521         }
522
523         focus_win(winfocus); /* this has to be done outside of the loop */
524         XSync(display, False);
525 }
526
527 void
528 swap_to_main(union arg *args)
529 {
530         struct ws_win           *tmpwin = TAILQ_FIRST(&ws[current_ws].winlist);
531
532         DNPRINTF(SWM_D_MISC, "swap_to_main: win: %lu\n",
533             ws[current_ws].focus ? ws[current_ws].focus->id : 0);
534
535         if (ws[current_ws].focus == NULL || ws[current_ws].focus == tmpwin)
536                 return;
537
538         TAILQ_REMOVE(&ws[current_ws].winlist, tmpwin, entry);
539         TAILQ_INSERT_AFTER(&ws[current_ws].winlist, ws[current_ws].focus,
540             tmpwin, entry);
541         TAILQ_REMOVE(&ws[current_ws].winlist, ws[current_ws].focus, entry);
542         TAILQ_INSERT_HEAD(&ws[current_ws].winlist, ws[current_ws].focus, entry);
543         ws[current_ws].focus = TAILQ_FIRST(&ws[current_ws].winlist);
544         ignore_enter = 2;
545         stack();
546 }
547
548 void
549 send_to_ws(union arg *args)
550 {
551         int                     wsid = args->id;
552         struct ws_win           *win = ws[current_ws].focus;
553
554         DNPRINTF(SWM_D_WS, "send_to_ws: win: %lu\n", win->id);
555
556         XUnmapWindow(display, win->id);
557
558         /* find a window to focus */
559         ws[current_ws].focus = TAILQ_PREV(win, ws_win_list,entry);
560         if (ws[current_ws].focus == NULL)
561                 ws[current_ws].focus = TAILQ_FIRST(&ws[current_ws].winlist);
562
563         TAILQ_REMOVE(&ws[current_ws].winlist, win, entry);
564         ws[current_ws].winno--;
565
566         TAILQ_INSERT_TAIL(&ws[wsid].winlist, win, entry);
567         if (ws[wsid].winno == 0)
568                 ws[wsid].focus = win;
569         ws[wsid].winno++;
570         ws[wsid].restack = 1;
571
572         stack();
573 }
574
575 /* key definitions */
576 struct key {
577         unsigned int            mod;
578         KeySym                  keysym;
579         void                    (*func)(union arg *);
580         union arg               args;
581 } keys[] = {
582         /* modifier             key     function                argument */
583         { MODKEY,               XK_Return,      swap_to_main,   {0} },
584         { MODKEY | ShiftMask,   XK_Return,      spawn,          {.argv = spawn_term } },
585         { MODKEY | ShiftMask,   XK_q,           quit,           {0} },
586         { MODKEY,               XK_m,           focus,          {.id = SWM_ARG_ID_FOCUSMAIN} },
587         { MODKEY,               XK_1,           switchws,       {.id = 0} },
588         { MODKEY,               XK_2,           switchws,       {.id = 1} },
589         { MODKEY,               XK_3,           switchws,       {.id = 2} },
590         { MODKEY,               XK_4,           switchws,       {.id = 3} },
591         { MODKEY,               XK_5,           switchws,       {.id = 4} },
592         { MODKEY,               XK_6,           switchws,       {.id = 5} },
593         { MODKEY,               XK_7,           switchws,       {.id = 6} },
594         { MODKEY,               XK_8,           switchws,       {.id = 7} },
595         { MODKEY,               XK_9,           switchws,       {.id = 8} },
596         { MODKEY,               XK_0,           switchws,       {.id = 9} },
597         { MODKEY | ShiftMask,   XK_1,           send_to_ws,     {.id = 0} },
598         { MODKEY | ShiftMask,   XK_2,           send_to_ws,     {.id = 1} },
599         { MODKEY | ShiftMask,   XK_3,           send_to_ws,     {.id = 2} },
600         { MODKEY | ShiftMask,   XK_4,           send_to_ws,     {.id = 3} },
601         { MODKEY | ShiftMask,   XK_5,           send_to_ws,     {.id = 4} },
602         { MODKEY | ShiftMask,   XK_6,           send_to_ws,     {.id = 5} },
603         { MODKEY | ShiftMask,   XK_7,           send_to_ws,     {.id = 6} },
604         { MODKEY | ShiftMask,   XK_8,           send_to_ws,     {.id = 7} },
605         { MODKEY | ShiftMask,   XK_9,           send_to_ws,     {.id = 8} },
606         { MODKEY | ShiftMask,   XK_0,           send_to_ws,     {.id = 9} },
607         { MODKEY,               XK_b,           bar_toggle,     {0} },
608         { MODKEY,               XK_Tab,         focus,          {.id = SWM_ARG_ID_FOCUSNEXT} },
609         { MODKEY | ShiftMask,   XK_Tab,         focus,          {.id = SWM_ARG_ID_FOCUSPREV} },
610 };
611
612 void
613 updatenumlockmask(void)
614 {
615         unsigned int            i, j;
616         XModifierKeymap         *modmap;
617
618         DNPRINTF(SWM_D_MISC, "updatenumlockmask\n");
619         numlockmask = 0;
620         modmap = XGetModifierMapping(display);
621         for (i = 0; i < 8; i++)
622                 for (j = 0; j < modmap->max_keypermod; j++)
623                         if (modmap->modifiermap[i * modmap->max_keypermod + j]
624                           == XKeysymToKeycode(display, XK_Num_Lock))
625                                 numlockmask = (1 << i);
626
627         XFreeModifiermap(modmap);
628 }
629
630 void
631 grabkeys(void)
632 {
633         unsigned int            i, j;
634         KeyCode                 code;
635         unsigned int            modifiers[] =
636             { 0, LockMask, numlockmask, numlockmask | LockMask };
637
638         DNPRINTF(SWM_D_MISC, "grabkeys\n");
639         updatenumlockmask();
640
641         XUngrabKey(display, AnyKey, AnyModifier, root);
642         for(i = 0; i < LENGTH(keys); i++) {
643                 if((code = XKeysymToKeycode(display, keys[i].keysym)))
644                         for(j = 0; j < LENGTH(modifiers); j++)
645                                 XGrabKey(display, code,
646                                     keys[i].mod | modifiers[j], root,
647                                     True, GrabModeAsync, GrabModeAsync);
648         }
649 }
650 void
651 expose(XEvent *e)
652 {
653         DNPRINTF(SWM_D_EVENT, "expose: window: %lu\n", e->xexpose.window);
654 }
655
656 void
657 keypress(XEvent *e)
658 {
659         unsigned int            i;
660         KeySym                  keysym;
661         XKeyEvent               *ev = &e->xkey;
662
663         DNPRINTF(SWM_D_EVENT, "keypress: window: %lu\n", ev->window);
664
665         keysym = XKeycodeToKeysym(display, (KeyCode)ev->keycode, 0);
666         for(i = 0; i < LENGTH(keys); i++)
667                 if(keysym == keys[i].keysym
668                    && CLEANMASK(keys[i].mod) == CLEANMASK(ev->state)
669                    && keys[i].func)
670                         keys[i].func(&(keys[i].args));
671 }
672
673 void
674 buttonpress(XEvent *e)
675 {
676         XButtonPressedEvent     *ev = &e->xbutton;
677 #ifdef SWM_CLICKTOFOCUS
678         struct ws_win           *win;
679 #endif
680
681
682         DNPRINTF(SWM_D_EVENT, "buttonpress: window: %lu\n", ev->window);
683
684         if (ev->window == root)
685                 return;
686         if (ev->window == ws[current_ws].focus->id)
687                 return;
688 #ifdef SWM_CLICKTOFOCUS
689         TAILQ_FOREACH(win, &ws[current_ws].winlist, entry)
690                 if (win->id == ev->window) {
691                         /* focus in the clicked window */
692                         XSetWindowBorder(display, ev->window, 0xff0000);
693                         XSetWindowBorder(display,
694                             ws[current_ws].focus->id, 0x888888);
695                         XSetInputFocus(display, ev->window, RevertToPointerRoot,
696                             CurrentTime);
697                         ws[current_ws].focus = win;
698                         XSync(display, False);
699                         break;
700         }
701 #endif
702 }
703
704 void
705 configurerequest(XEvent *e)
706 {
707         XConfigureRequestEvent  *ev = &e->xconfigurerequest;
708         struct ws_win           *win;
709
710         DNPRINTF(SWM_D_EVENT, "configurerequest: window: %lu\n", ev->window);
711
712         TAILQ_FOREACH (win, &ws[current_ws].winlist, entry) {
713                 if (ev->window == win->id)
714                         return;
715         }
716
717         XSelectInput(display, ev->window, ButtonPressMask | EnterWindowMask |
718             FocusChangeMask);
719
720         if ((win = calloc(1, sizeof(struct ws_win))) == NULL)
721                 errx(1, "calloc: failed to allocate memory for new window");
722
723         win->id = ev->window;
724         TAILQ_INSERT_TAIL(&ws[current_ws].winlist, win, entry);
725         ws[current_ws].focus = win; /* make new win focused */
726         ws[current_ws].winno++;
727         stack();
728 }
729
730 void
731 configurenotify(XEvent *e)
732 {
733         DNPRINTF(SWM_D_EVENT, "configurenotify: window: %lu\n",
734             e->xconfigure.window);
735 }
736
737 void
738 destroynotify(XEvent *e)
739 {
740         struct ws_win           *win;
741         XDestroyWindowEvent     *ev = &e->xdestroywindow;
742
743         DNPRINTF(SWM_D_EVENT, "destroynotify: window %lu\n", ev->window);
744
745         TAILQ_FOREACH (win, &ws[current_ws].winlist, entry) {
746                 if (ev->window == win->id) {
747                         /* find a window to focus */
748                         ws[current_ws].focus =
749                             TAILQ_PREV(win, ws_win_list,entry);
750                         if (ws[current_ws].focus == NULL)
751                                 ws[current_ws].focus =
752                                     TAILQ_FIRST(&ws[current_ws].winlist);
753         
754                         TAILQ_REMOVE(&ws[current_ws].winlist, win, entry);
755                         free(win);
756                         ws[current_ws].winno--;
757                         break;
758                 }
759         }
760
761         stack();
762 }
763
764 void
765 enternotify(XEvent *e)
766 {
767         XCrossingEvent          *ev = &e->xcrossing;
768         struct ws_win           *win;
769
770         DNPRINTF(SWM_D_EVENT, "enternotify: window: %lu\n", ev->window);
771
772         if((ev->mode != NotifyNormal || ev->detail == NotifyInferior) &&
773             ev->window != root)
774                 return;
775         if (ignore_enter) {
776                 /* eat event(s) to prevent autofocus */
777                 ignore_enter--;
778                 return;
779         }
780         TAILQ_FOREACH (win, &ws[current_ws].winlist, entry) {
781                 if (win->id == ev->window)
782                         focus_win(win);
783                 else
784                         unfocus_win(win);
785         }
786 }
787
788 void
789 focusin(XEvent *e)
790 {
791         XFocusChangeEvent       *ev = &e->xfocus;
792
793         DNPRINTF(SWM_D_EVENT, "focusin: window: %lu\n", ev->window);
794
795         XSync(display, False); /* not sure this helps redrawing graphic apps */
796
797         if (ev->window == root)
798                 return;
799         /*
800          * kill grab for now so that we can cut and paste , this screws up
801          * click to focus
802          */
803         /*
804         DNPRINTF(SWM_D_EVENT, "focusin: window: %lu grabbing\n", ev->window);
805         XGrabButton(display, Button1, AnyModifier, ev->window, False,
806             ButtonPress, GrabModeAsync, GrabModeSync, None, None);
807         */
808 }
809
810 void
811 mappingnotify(XEvent *e)
812 {
813         XMappingEvent           *ev = &e->xmapping;
814
815         DNPRINTF(SWM_D_EVENT, "mappingnotify: window: %lu\n", ev->window);
816
817         XRefreshKeyboardMapping(ev);
818         if(ev->request == MappingKeyboard)
819                 grabkeys();
820 }
821
822 void
823 maprequest(XEvent *e)
824 {
825         DNPRINTF(SWM_D_EVENT, "maprequest: window: %lu\n",
826             e->xmaprequest.window);
827 }
828
829 void
830 propertynotify(XEvent *e)
831 {
832         DNPRINTF(SWM_D_EVENT, "propertynotify: window: %lu\n",
833             e->xproperty.window);
834 }
835
836 void
837 unmapnotify(XEvent *e)
838 {
839         DNPRINTF(SWM_D_EVENT, "unmapnotify: window: %lu\n", e->xunmap.window);
840 }
841
842 void                    (*handler[LASTEvent])(XEvent *) = {
843                                 [Expose] = expose,
844                                 [KeyPress] = keypress,
845                                 [ButtonPress] = buttonpress,
846                                 [ConfigureRequest] = configurerequest,
847                                 [ConfigureNotify] = configurenotify,
848                                 [DestroyNotify] = destroynotify,
849                                 [EnterNotify] = enternotify,
850                                 [FocusIn] = focusin,
851                                 [MappingNotify] = mappingnotify,
852                                 [MapRequest] = maprequest,
853                                 [PropertyNotify] = propertynotify,
854                                 [UnmapNotify] = unmapnotify,
855 };
856
857 int
858 xerror_start(Display *d, XErrorEvent *ee)
859 {
860         other_wm = 1;
861         return (-1);
862 }
863
864 int
865 xerror(Display *d, XErrorEvent *ee)
866 {
867         fprintf(stderr, "error: %p %p\n", display, ee);
868
869         return (-1);
870 }
871
872 int
873 active_wm(void)
874 {
875         other_wm = 0;
876         xerrorxlib = XSetErrorHandler(xerror_start);
877
878         /* this causes an error if some other window manager is running */
879         XSelectInput(display, DefaultRootWindow(display),
880             SubstructureRedirectMask);
881         XSync(display, False);
882         if(other_wm)
883                 return (1);
884
885         XSetErrorHandler(xerror);
886         XSync(display, False);
887         return (0);
888 }
889
890 int
891 main(int argc, char *argv[])
892 {
893         struct passwd           *pwd;
894         char                    conf[PATH_MAX], *cfile = NULL;
895         struct stat             sb;
896         XEvent                  e;
897         int                     i;
898
899         fprintf(stderr, "Welcome to scrotwm V%s\n", SWM_VERSION);
900         if(!setlocale(LC_CTYPE, "") || !XSupportsLocale())
901                 warnx("no locale support");
902
903         if(!(display = XOpenDisplay(0)))
904                 errx(1, "can not open display");
905
906         if (active_wm())
907                 errx(1, "other wm running");
908
909         screen = DefaultScreen(display);
910         root = RootWindow(display, screen);
911         width = DisplayWidth(display, screen) - 2;
912         height = DisplayHeight(display, screen) - 2;
913
914         /* look for local and global conf file */
915         pwd = getpwuid(getuid());
916         if (pwd == NULL)
917                 errx(1, "invalid user %d", getuid());
918
919         snprintf(conf, sizeof conf, "%s/.%s", pwd->pw_dir, SWM_CONF_FILE);
920         if (stat(conf, &sb) != -1) {
921                 if (S_ISREG(sb.st_mode))
922                         cfile = conf;
923         } else {
924                 /* try global conf file */
925                 snprintf(conf, sizeof conf, "/etc/%s", SWM_CONF_FILE);
926                 if (!stat(conf, &sb))
927                         if (S_ISREG(sb.st_mode))
928                                 cfile = conf;
929         }
930         if (cfile)
931                 conf_load(cfile);
932
933         /* make work space 1 active */
934         ws[0].visible = 1;
935         ws[0].restack = 0;
936         ws[0].focus = NULL;
937         ws[0].winno = 0;
938         TAILQ_INIT(&ws[0].winlist);
939         for (i = 1; i < SWM_WS_MAX; i++) {
940                 ws[i].visible = 0;
941                 ws[i].restack = 0;
942                 ws[i].focus = NULL;
943                 ws[i].winno = 0;
944                 TAILQ_INIT(&ws[i].winlist);
945         }
946
947         /* setup status bar */
948         bar_setup();
949
950         XSelectInput(display, root, SubstructureRedirectMask |
951             SubstructureNotifyMask | ButtonPressMask | KeyPressMask |
952             EnterWindowMask | LeaveWindowMask | StructureNotifyMask |
953             FocusChangeMask | PropertyChangeMask);
954
955         grabkeys();
956
957         while (running) {
958                 XNextEvent(display, &e);
959                 if (handler[e.type])
960                         handler[e.type](&e);
961         }
962
963         XCloseDisplay(display);
964
965         return (0);
966 }