JasonWoof Got questions, comments, patches, etc.? Contact Jason Woofenden
Add initial dmenu support with alt-p
[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 char                            *spawn_menu[] = { "dmenu_run", NULL };
133
134 struct ws_win {
135         TAILQ_ENTRY(ws_win)     entry;
136         Window                  id;
137         int                     x;
138         int                     y;
139         int                     width;
140         int                     height;
141 };
142
143 TAILQ_HEAD(ws_win_list, ws_win);
144
145 /* define work spaces */
146 #define SWM_WS_MAX              (10)
147 struct workspace {
148         int                     visible;        /* workspace visible */
149         int                     restack;        /* restack on switch */
150         struct ws_win           *focus;         /* which win has focus */
151         int                     winno;          /* total nr of windows */
152         struct ws_win_list      winlist;        /* list of windows in ws */
153 } ws[SWM_WS_MAX];
154 int                     current_ws = 0;
155
156 /* args to functions */
157 union arg {
158         int                     id;
159 #define SWM_ARG_ID_FOCUSNEXT    (0)
160 #define SWM_ARG_ID_FOCUSPREV    (1)
161 #define SWM_ARG_ID_FOCUSMAIN    (2)
162         char                    **argv;
163 };
164
165
166 void    stack(void);
167
168 #define SWM_CONF_WS     "\n= \t"
169 #define SWM_CONF_FILE   "scrotwm.conf"
170 int
171 conf_load(char *filename)
172 {
173         FILE                    *config;
174         char                    *line, *cp, *var, *val;
175         size_t                   len, lineno = 0;
176
177         DNPRINTF(SWM_D_MISC, "conf_load: filename %s\n", filename);
178
179         if (filename == NULL)
180                 return (1);
181
182         if ((config = fopen(filename, "r")) == NULL)
183                 return (1);
184
185         for (;;) {
186                 if ((line = fparseln(config, &len, &lineno, NULL, 0)) == NULL)
187                         if (feof(config))
188                                 break;
189                 cp = line;
190                 cp += (long)strspn(cp, SWM_CONF_WS);
191                 if (cp[0] == '\0') {
192                         /* empty line */
193                         free(line);
194                         continue;
195                 }
196                 if ((var = strsep(&cp, SWM_CONF_WS)) == NULL || cp == NULL)
197                         break;
198                 cp += (long)strspn(cp, SWM_CONF_WS);
199                 if ((val = strsep(&cp, SWM_CONF_WS)) == NULL)
200                         break;
201
202                 DNPRINTF(SWM_D_MISC, "conf_load: %s=%s\n",var ,val);
203                 switch (var[0]) {
204                 case 'b':
205                         if (!strncmp(var, "bar_enabled", strlen("bar_enabled")))
206                                 bar_enabled = atoi(val);
207                         else if (!strncmp(var, "bar_border",
208                             strlen("bar_border")))
209                                 bar_border = strtol(val, NULL, 16);
210                         else if (!strncmp(var, "bar_color",
211                             strlen("bar_color")))
212                                 bar_color = strtol(val, NULL, 16);
213                         else if (!strncmp(var, "bar_font_color",
214                             strlen("bar_font_color")))
215                                 bar_font_color = strtol(val, NULL, 16);
216                         else if (!strncmp(var, "bar_font", strlen("bar_font")))
217                                 asprintf(&bar_fonts[0], "%s", val);
218                         else
219                                 goto bad;
220                         break;
221
222                 case 'c':
223                         if (!strncmp(var, "color_focus", strlen("color_focus")))
224                                 color_focus = strtol(val, NULL, 16);
225                         else if (!strncmp(var, "color_unfocus",
226                             strlen("color_unfocus")))
227                                 color_unfocus = strtol(val, NULL, 16);
228                         else
229                                 goto bad;
230                         break;
231
232                 case 's':
233                         if (!strncmp(var, "spawn_term", strlen("spawn_term")))
234                                 asprintf(&spawn_term[0], "%s", val); /* XXX args? */
235                         break;
236                 default:
237                         goto bad;
238                 }
239                 free(line);
240         }
241
242         fclose(config);
243         return (0);
244 bad:
245         errx(1, "invalid conf file entry: %s=%s", var, val);
246 }
247
248 void
249 bar_print(void)
250 {
251         time_t                  tmt;
252         struct tm               tm;
253
254         if (bar_enabled == 0)
255                 return;
256
257         /* clear old text */
258         XSetForeground(display, bar_gc, bar_color);
259         XDrawString(display, bar_window, bar_gc, 4, bar_fs->ascent, bar_text,
260             strlen(bar_text));
261
262         /* draw new text */
263         time(&tmt);
264         localtime_r(&tmt, &tm);
265         strftime(bar_text, sizeof bar_text, "%a %b %d %R %Z %Y", &tm);
266         XSetForeground(display, bar_gc, bar_font_color);
267         XDrawString(display, bar_window, bar_gc, 4, bar_fs->ascent, bar_text,
268             strlen(bar_text));
269         XSync(display, False);
270
271         alarm(60);
272 }
273
274 void
275 bar_signal(int sig)
276 {
277         /* XXX yeah yeah byte me */
278         bar_print();
279 }
280
281 void
282 bar_toggle(union arg *args)
283 {
284         int i;
285
286         DNPRINTF(SWM_D_MISC, "bar_toggle\n");
287
288         if (bar_enabled) {
289                 bar_enabled = 0;
290                 height += bar_height; /* correct screen height */
291                 XUnmapWindow(display, bar_window);
292         } else {
293                 bar_enabled = 1;
294                 height -= bar_height; /* correct screen height */
295                 XMapWindow(display, bar_window);
296         }
297         XSync(display, False);
298         for (i = 0; i < SWM_WS_MAX; i++)
299                 ws[i].restack = 1;
300
301         stack();
302         bar_print(); /* must be after stack */
303 }
304
305 void
306 bar_setup(void)
307 {
308         int                     i;
309
310         for (i = 0; bar_fonts[i] != NULL; i++) {
311                 bar_fs = XLoadQueryFont(display, bar_fonts[i]);
312                 if (bar_fs)
313                         break;
314         }
315         if (bar_fonts[i] == NULL)
316                         errx(1, "couldn't load font");
317         bar_height = bar_fs->ascent + bar_fs->descent + 3;
318
319         bar_window = XCreateSimpleWindow(display, root, 0, 0, width,
320             bar_height - 2, 1, bar_border, bar_color);
321         bar_gc = XCreateGC(display, bar_window, 0, &bar_gcv);
322         XSetFont(display, bar_gc, bar_fs->fid);
323         if (bar_enabled) {
324                 height -= bar_height; /* correct screen height */
325                 XMapWindow(display, bar_window);
326         }
327
328         if (signal(SIGALRM, bar_signal) == SIG_ERR)
329                 err(1, "could not install bar_signal");
330         bar_print();
331 }
332
333 void
334 quit(union arg *args)
335 {
336         DNPRINTF(SWM_D_MISC, "quit\n");
337         running = 0;
338 }
339
340 void
341 spawn(union arg *args)
342 {
343         DNPRINTF(SWM_D_MISC, "spawn: %s\n", args->argv[0]);
344         /*
345          * The double-fork construct avoids zombie processes and keeps the code
346          * clean from stupid signal handlers.
347          */
348         if(fork() == 0) {
349                 if(fork() == 0) {
350                         if(display)
351                                 close(ConnectionNumber(display));
352                         setsid();
353                         execvp(args->argv[0], args->argv);
354                         fprintf(stderr, "execvp failed\n");
355                         perror(" failed");
356                 }
357                 exit(0);
358         }
359         wait(0);
360 }
361
362 void
363 focus_win(struct ws_win *win)
364 {
365         DNPRINTF(SWM_D_FOCUS, "focus_win: id: %lu\n", win->id);
366         XSetWindowBorder(display, win->id, color_focus);
367         XSetInputFocus(display, win->id, RevertToPointerRoot, CurrentTime);
368         ws[current_ws].focus = win;
369 }
370
371 void
372 unfocus_win(struct ws_win *win)
373 {
374         DNPRINTF(SWM_D_FOCUS, "unfocus_win: id: %lu\n", win->id);
375         XSetWindowBorder(display, win->id, color_unfocus);
376         if (ws[current_ws].focus == win)
377                 ws[current_ws].focus = NULL;
378 }
379
380 void
381 switchws(union arg *args)
382 {
383         int                     wsid = args->id;
384         struct ws_win           *win;
385
386         DNPRINTF(SWM_D_WS, "switchws: %d\n", wsid + 1);
387
388         if (wsid == current_ws)
389                 return;
390
391         /* map new window first to prevent ugly blinking */
392         TAILQ_FOREACH (win, &ws[wsid].winlist, entry)
393                 XMapRaised(display, win->id);
394         ws[wsid].visible = 1;
395
396         TAILQ_FOREACH (win, &ws[current_ws].winlist, entry)
397                 XUnmapWindow(display, win->id);
398         ws[current_ws].visible = 0;
399
400         current_ws = wsid;
401
402         ignore_enter = 1;
403         if (ws[wsid].restack) {
404                 stack();
405                 bar_print();
406         } else {
407                 if (ws[wsid].focus != NULL)
408                         focus_win(ws[wsid].focus);
409                 XSync(display, False);
410         }
411 }
412
413 void
414 focus(union arg *args)
415 {
416         struct ws_win           *winfocus, *winlostfocus;
417
418         DNPRINTF(SWM_D_FOCUS, "focus: id %d\n", args->id);
419         if (ws[current_ws].focus == NULL || ws[current_ws].winno == 0)
420                 return;
421
422         winlostfocus = ws[current_ws].focus;
423
424         switch (args->id) {
425         case SWM_ARG_ID_FOCUSPREV:
426                 ws[current_ws].focus =
427                     TAILQ_PREV(ws[current_ws].focus, ws_win_list, entry);
428                 if (ws[current_ws].focus == NULL)
429                         ws[current_ws].focus =
430                             TAILQ_LAST(&ws[current_ws].winlist, ws_win_list);
431                 break;
432
433         case SWM_ARG_ID_FOCUSNEXT:
434                 ws[current_ws].focus = TAILQ_NEXT(ws[current_ws].focus, entry);
435                 if (ws[current_ws].focus == NULL)
436                         ws[current_ws].focus =
437                             TAILQ_FIRST(&ws[current_ws].winlist);
438                 break;
439
440         case SWM_ARG_ID_FOCUSMAIN:
441                 ws[current_ws].focus = TAILQ_FIRST(&ws[current_ws].winlist);
442                 break;
443
444         default:
445                 return;
446         }
447
448         winfocus = ws[current_ws].focus;
449         unfocus_win(winlostfocus);
450         focus_win(winfocus);
451         XSync(display, False);
452 }
453
454 /* I know this sucks but it works well enough */
455 void
456 stack(void)
457 {
458         XWindowChanges          wc;
459         struct ws_win           wf, *win, *winfocus = &wf;
460         int                     i, h, w, x, y, hrh;
461
462         DNPRINTF(SWM_D_EVENT, "stack: workspace: %d\n", current_ws);
463
464         winfocus->id = root;
465
466         ws[current_ws].restack = 0;
467
468         if (ws[current_ws].winno == 0)
469                 return;
470
471         if (ws[current_ws].winno > 1)
472                 w = width / 2;
473         else
474                 w = width;
475
476         if (ws[current_ws].winno > 2)
477                 hrh = height / (ws[current_ws].winno - 1);
478         else
479                 hrh = 0;
480
481         x = 0;
482         y = bar_enabled ? bar_height : 0;
483         h = height;
484         i = 0;
485         TAILQ_FOREACH (win, &ws[current_ws].winlist, entry) {
486                 if (i == 1) {
487                         x += w + 2;
488                         w -= 2;
489                 }
490                 if (i != 0 && hrh != 0) {
491                         /* correct the last window for lost pixels */
492                         if (win == TAILQ_LAST(&ws[current_ws].winlist,
493                             ws_win_list)) {
494                                 h = height - (i * hrh);
495                                 if (h == 0)
496                                         h = hrh;
497                                 else
498                                         h += hrh;
499                                 y += hrh;
500                         } else {
501                                 h = hrh - 2;
502                                 /* leave first right hand window at y = 0 */
503                                 if (i > 1)
504                                         y += h + 2;
505                         }
506                 }
507
508                 bzero(&wc, sizeof wc);
509                 win->x = wc.x = x;
510                 win->y = wc.y = y;
511                 win->width = wc.width = w;
512                 win->height = wc.height = h;
513                 wc.border_width = 1;
514                 XConfigureWindow(display, win->id, CWX | CWY | CWWidth |
515                     CWHeight | CWBorderWidth, &wc);
516                 if (win == ws[current_ws].focus)
517                         winfocus = win;
518                 else
519                         unfocus_win(win);
520                 XMapRaised(display, win->id);
521                 i++;
522         }
523
524         focus_win(winfocus); /* this has to be done outside of the loop */
525         XSync(display, False);
526 }
527
528 void
529 swap_to_main(union arg *args)
530 {
531         struct ws_win           *tmpwin = TAILQ_FIRST(&ws[current_ws].winlist);
532
533         DNPRINTF(SWM_D_MISC, "swap_to_main: win: %lu\n",
534             ws[current_ws].focus ? ws[current_ws].focus->id : 0);
535
536         if (ws[current_ws].focus == NULL || ws[current_ws].focus == tmpwin)
537                 return;
538
539         TAILQ_REMOVE(&ws[current_ws].winlist, tmpwin, entry);
540         TAILQ_INSERT_AFTER(&ws[current_ws].winlist, ws[current_ws].focus,
541             tmpwin, entry);
542         TAILQ_REMOVE(&ws[current_ws].winlist, ws[current_ws].focus, entry);
543         TAILQ_INSERT_HEAD(&ws[current_ws].winlist, ws[current_ws].focus, entry);
544         ws[current_ws].focus = TAILQ_FIRST(&ws[current_ws].winlist);
545         ignore_enter = 2;
546         stack();
547 }
548
549 void
550 send_to_ws(union arg *args)
551 {
552         int                     wsid = args->id;
553         struct ws_win           *win = ws[current_ws].focus;
554
555         DNPRINTF(SWM_D_WS, "send_to_ws: win: %lu\n", win->id);
556
557         XUnmapWindow(display, win->id);
558
559         /* find a window to focus */
560         ws[current_ws].focus = TAILQ_PREV(win, ws_win_list,entry);
561         if (ws[current_ws].focus == NULL)
562                 ws[current_ws].focus = TAILQ_FIRST(&ws[current_ws].winlist);
563
564         TAILQ_REMOVE(&ws[current_ws].winlist, win, entry);
565         ws[current_ws].winno--;
566
567         TAILQ_INSERT_TAIL(&ws[wsid].winlist, win, entry);
568         if (ws[wsid].winno == 0)
569                 ws[wsid].focus = win;
570         ws[wsid].winno++;
571         ws[wsid].restack = 1;
572
573         stack();
574 }
575
576 /* key definitions */
577 struct key {
578         unsigned int            mod;
579         KeySym                  keysym;
580         void                    (*func)(union arg *);
581         union arg               args;
582 } keys[] = {
583         /* modifier             key     function                argument */
584         { MODKEY,               XK_Return,      swap_to_main,   {0} },
585         { MODKEY | ShiftMask,   XK_Return,      spawn,          {.argv = spawn_term} },
586         { MODKEY,               XK_p,           spawn,          {.argv = spawn_menu} },
587         { MODKEY | ShiftMask,   XK_q,           quit,           {0} },
588         { MODKEY,               XK_m,           focus,          {.id = SWM_ARG_ID_FOCUSMAIN} },
589         { MODKEY,               XK_1,           switchws,       {.id = 0} },
590         { MODKEY,               XK_2,           switchws,       {.id = 1} },
591         { MODKEY,               XK_3,           switchws,       {.id = 2} },
592         { MODKEY,               XK_4,           switchws,       {.id = 3} },
593         { MODKEY,               XK_5,           switchws,       {.id = 4} },
594         { MODKEY,               XK_6,           switchws,       {.id = 5} },
595         { MODKEY,               XK_7,           switchws,       {.id = 6} },
596         { MODKEY,               XK_8,           switchws,       {.id = 7} },
597         { MODKEY,               XK_9,           switchws,       {.id = 8} },
598         { MODKEY,               XK_0,           switchws,       {.id = 9} },
599         { MODKEY | ShiftMask,   XK_1,           send_to_ws,     {.id = 0} },
600         { MODKEY | ShiftMask,   XK_2,           send_to_ws,     {.id = 1} },
601         { MODKEY | ShiftMask,   XK_3,           send_to_ws,     {.id = 2} },
602         { MODKEY | ShiftMask,   XK_4,           send_to_ws,     {.id = 3} },
603         { MODKEY | ShiftMask,   XK_5,           send_to_ws,     {.id = 4} },
604         { MODKEY | ShiftMask,   XK_6,           send_to_ws,     {.id = 5} },
605         { MODKEY | ShiftMask,   XK_7,           send_to_ws,     {.id = 6} },
606         { MODKEY | ShiftMask,   XK_8,           send_to_ws,     {.id = 7} },
607         { MODKEY | ShiftMask,   XK_9,           send_to_ws,     {.id = 8} },
608         { MODKEY | ShiftMask,   XK_0,           send_to_ws,     {.id = 9} },
609         { MODKEY,               XK_b,           bar_toggle,     {0} },
610         { MODKEY,               XK_Tab,         focus,          {.id = SWM_ARG_ID_FOCUSNEXT} },
611         { MODKEY | ShiftMask,   XK_Tab,         focus,          {.id = SWM_ARG_ID_FOCUSPREV} },
612 };
613
614 void
615 updatenumlockmask(void)
616 {
617         unsigned int            i, j;
618         XModifierKeymap         *modmap;
619
620         DNPRINTF(SWM_D_MISC, "updatenumlockmask\n");
621         numlockmask = 0;
622         modmap = XGetModifierMapping(display);
623         for (i = 0; i < 8; i++)
624                 for (j = 0; j < modmap->max_keypermod; j++)
625                         if (modmap->modifiermap[i * modmap->max_keypermod + j]
626                           == XKeysymToKeycode(display, XK_Num_Lock))
627                                 numlockmask = (1 << i);
628
629         XFreeModifiermap(modmap);
630 }
631
632 void
633 grabkeys(void)
634 {
635         unsigned int            i, j;
636         KeyCode                 code;
637         unsigned int            modifiers[] =
638             { 0, LockMask, numlockmask, numlockmask | LockMask };
639
640         DNPRINTF(SWM_D_MISC, "grabkeys\n");
641         updatenumlockmask();
642
643         XUngrabKey(display, AnyKey, AnyModifier, root);
644         for(i = 0; i < LENGTH(keys); i++) {
645                 if((code = XKeysymToKeycode(display, keys[i].keysym)))
646                         for(j = 0; j < LENGTH(modifiers); j++)
647                                 XGrabKey(display, code,
648                                     keys[i].mod | modifiers[j], root,
649                                     True, GrabModeAsync, GrabModeAsync);
650         }
651 }
652 void
653 expose(XEvent *e)
654 {
655         DNPRINTF(SWM_D_EVENT, "expose: window: %lu\n", e->xexpose.window);
656 }
657
658 void
659 keypress(XEvent *e)
660 {
661         unsigned int            i;
662         KeySym                  keysym;
663         XKeyEvent               *ev = &e->xkey;
664
665         DNPRINTF(SWM_D_EVENT, "keypress: window: %lu\n", ev->window);
666
667         keysym = XKeycodeToKeysym(display, (KeyCode)ev->keycode, 0);
668         for(i = 0; i < LENGTH(keys); i++)
669                 if(keysym == keys[i].keysym
670                    && CLEANMASK(keys[i].mod) == CLEANMASK(ev->state)
671                    && keys[i].func)
672                         keys[i].func(&(keys[i].args));
673 }
674
675 void
676 buttonpress(XEvent *e)
677 {
678         XButtonPressedEvent     *ev = &e->xbutton;
679 #ifdef SWM_CLICKTOFOCUS
680         struct ws_win           *win;
681 #endif
682
683
684         DNPRINTF(SWM_D_EVENT, "buttonpress: window: %lu\n", ev->window);
685
686         if (ev->window == root)
687                 return;
688         if (ev->window == ws[current_ws].focus->id)
689                 return;
690 #ifdef SWM_CLICKTOFOCUS
691         TAILQ_FOREACH(win, &ws[current_ws].winlist, entry)
692                 if (win->id == ev->window) {
693                         /* focus in the clicked window */
694                         XSetWindowBorder(display, ev->window, 0xff0000);
695                         XSetWindowBorder(display,
696                             ws[current_ws].focus->id, 0x888888);
697                         XSetInputFocus(display, ev->window, RevertToPointerRoot,
698                             CurrentTime);
699                         ws[current_ws].focus = win;
700                         XSync(display, False);
701                         break;
702         }
703 #endif
704 }
705
706 void
707 configurerequest(XEvent *e)
708 {
709         XConfigureRequestEvent  *ev = &e->xconfigurerequest;
710         struct ws_win           *win;
711
712         DNPRINTF(SWM_D_EVENT, "configurerequest: window: %lu\n", ev->window);
713
714         TAILQ_FOREACH (win, &ws[current_ws].winlist, entry) {
715                 if (ev->window == win->id)
716                         return;
717         }
718
719         XSelectInput(display, ev->window, ButtonPressMask | EnterWindowMask |
720             FocusChangeMask);
721
722         if ((win = calloc(1, sizeof(struct ws_win))) == NULL)
723                 errx(1, "calloc: failed to allocate memory for new window");
724
725         win->id = ev->window;
726         TAILQ_INSERT_TAIL(&ws[current_ws].winlist, win, entry);
727         ws[current_ws].focus = win; /* make new win focused */
728         ws[current_ws].winno++;
729         stack();
730 }
731
732 void
733 configurenotify(XEvent *e)
734 {
735         DNPRINTF(SWM_D_EVENT, "configurenotify: window: %lu\n",
736             e->xconfigure.window);
737 }
738
739 void
740 destroynotify(XEvent *e)
741 {
742         struct ws_win           *win;
743         XDestroyWindowEvent     *ev = &e->xdestroywindow;
744
745         DNPRINTF(SWM_D_EVENT, "destroynotify: window %lu\n", ev->window);
746
747         TAILQ_FOREACH (win, &ws[current_ws].winlist, entry) {
748                 if (ev->window == win->id) {
749                         /* find a window to focus */
750                         ws[current_ws].focus =
751                             TAILQ_PREV(win, ws_win_list,entry);
752                         if (ws[current_ws].focus == NULL)
753                                 ws[current_ws].focus =
754                                     TAILQ_FIRST(&ws[current_ws].winlist);
755         
756                         TAILQ_REMOVE(&ws[current_ws].winlist, win, entry);
757                         free(win);
758                         ws[current_ws].winno--;
759                         break;
760                 }
761         }
762
763         stack();
764 }
765
766 void
767 enternotify(XEvent *e)
768 {
769         XCrossingEvent          *ev = &e->xcrossing;
770         struct ws_win           *win;
771
772         DNPRINTF(SWM_D_EVENT, "enternotify: window: %lu\n", ev->window);
773
774         if((ev->mode != NotifyNormal || ev->detail == NotifyInferior) &&
775             ev->window != root)
776                 return;
777         if (ignore_enter) {
778                 /* eat event(s) to prevent autofocus */
779                 ignore_enter--;
780                 return;
781         }
782         TAILQ_FOREACH (win, &ws[current_ws].winlist, entry) {
783                 if (win->id == ev->window)
784                         focus_win(win);
785                 else
786                         unfocus_win(win);
787         }
788 }
789
790 void
791 focusin(XEvent *e)
792 {
793         XFocusChangeEvent       *ev = &e->xfocus;
794
795         DNPRINTF(SWM_D_EVENT, "focusin: window: %lu\n", ev->window);
796
797         XSync(display, False); /* not sure this helps redrawing graphic apps */
798
799         if (ev->window == root)
800                 return;
801         /*
802          * kill grab for now so that we can cut and paste , this screws up
803          * click to focus
804          */
805         /*
806         DNPRINTF(SWM_D_EVENT, "focusin: window: %lu grabbing\n", ev->window);
807         XGrabButton(display, Button1, AnyModifier, ev->window, False,
808             ButtonPress, GrabModeAsync, GrabModeSync, None, None);
809         */
810 }
811
812 void
813 mappingnotify(XEvent *e)
814 {
815         XMappingEvent           *ev = &e->xmapping;
816
817         DNPRINTF(SWM_D_EVENT, "mappingnotify: window: %lu\n", ev->window);
818
819         XRefreshKeyboardMapping(ev);
820         if(ev->request == MappingKeyboard)
821                 grabkeys();
822 }
823
824 void
825 maprequest(XEvent *e)
826 {
827         DNPRINTF(SWM_D_EVENT, "maprequest: window: %lu\n",
828             e->xmaprequest.window);
829 }
830
831 void
832 propertynotify(XEvent *e)
833 {
834         DNPRINTF(SWM_D_EVENT, "propertynotify: window: %lu\n",
835             e->xproperty.window);
836 }
837
838 void
839 unmapnotify(XEvent *e)
840 {
841         DNPRINTF(SWM_D_EVENT, "unmapnotify: window: %lu\n", e->xunmap.window);
842 }
843
844 void                    (*handler[LASTEvent])(XEvent *) = {
845                                 [Expose] = expose,
846                                 [KeyPress] = keypress,
847                                 [ButtonPress] = buttonpress,
848                                 [ConfigureRequest] = configurerequest,
849                                 [ConfigureNotify] = configurenotify,
850                                 [DestroyNotify] = destroynotify,
851                                 [EnterNotify] = enternotify,
852                                 [FocusIn] = focusin,
853                                 [MappingNotify] = mappingnotify,
854                                 [MapRequest] = maprequest,
855                                 [PropertyNotify] = propertynotify,
856                                 [UnmapNotify] = unmapnotify,
857 };
858
859 int
860 xerror_start(Display *d, XErrorEvent *ee)
861 {
862         other_wm = 1;
863         return (-1);
864 }
865
866 int
867 xerror(Display *d, XErrorEvent *ee)
868 {
869         fprintf(stderr, "error: %p %p\n", display, ee);
870
871         return (-1);
872 }
873
874 int
875 active_wm(void)
876 {
877         other_wm = 0;
878         xerrorxlib = XSetErrorHandler(xerror_start);
879
880         /* this causes an error if some other window manager is running */
881         XSelectInput(display, DefaultRootWindow(display),
882             SubstructureRedirectMask);
883         XSync(display, False);
884         if(other_wm)
885                 return (1);
886
887         XSetErrorHandler(xerror);
888         XSync(display, False);
889         return (0);
890 }
891
892 int
893 main(int argc, char *argv[])
894 {
895         struct passwd           *pwd;
896         char                    conf[PATH_MAX], *cfile = NULL;
897         struct stat             sb;
898         XEvent                  e;
899         int                     i;
900
901         fprintf(stderr, "Welcome to scrotwm V%s\n", SWM_VERSION);
902         if(!setlocale(LC_CTYPE, "") || !XSupportsLocale())
903                 warnx("no locale support");
904
905         if(!(display = XOpenDisplay(0)))
906                 errx(1, "can not open display");
907
908         if (active_wm())
909                 errx(1, "other wm running");
910
911         screen = DefaultScreen(display);
912         root = RootWindow(display, screen);
913         width = DisplayWidth(display, screen) - 2;
914         height = DisplayHeight(display, screen) - 2;
915
916         /* look for local and global conf file */
917         pwd = getpwuid(getuid());
918         if (pwd == NULL)
919                 errx(1, "invalid user %d", getuid());
920
921         snprintf(conf, sizeof conf, "%s/.%s", pwd->pw_dir, SWM_CONF_FILE);
922         if (stat(conf, &sb) != -1) {
923                 if (S_ISREG(sb.st_mode))
924                         cfile = conf;
925         } else {
926                 /* try global conf file */
927                 snprintf(conf, sizeof conf, "/etc/%s", SWM_CONF_FILE);
928                 if (!stat(conf, &sb))
929                         if (S_ISREG(sb.st_mode))
930                                 cfile = conf;
931         }
932         if (cfile)
933                 conf_load(cfile);
934
935         /* make work space 1 active */
936         ws[0].visible = 1;
937         ws[0].restack = 0;
938         ws[0].focus = NULL;
939         ws[0].winno = 0;
940         TAILQ_INIT(&ws[0].winlist);
941         for (i = 1; i < SWM_WS_MAX; i++) {
942                 ws[i].visible = 0;
943                 ws[i].restack = 0;
944                 ws[i].focus = NULL;
945                 ws[i].winno = 0;
946                 TAILQ_INIT(&ws[i].winlist);
947         }
948
949         /* setup status bar */
950         bar_setup();
951
952         XSelectInput(display, root, SubstructureRedirectMask |
953             SubstructureNotifyMask | ButtonPressMask | KeyPressMask |
954             EnterWindowMask | LeaveWindowMask | StructureNotifyMask |
955             FocusChangeMask | PropertyChangeMask);
956
957         grabkeys();
958
959         while (running) {
960                 XNextEvent(display, &e);
961                 if (handler[e.type])
962                         handler[e.type](&e);
963         }
964
965         XCloseDisplay(display);
966
967         return (0);
968 }