JasonWoof Got questions, comments, patches, etc.? Contact Jason Woofenden
Add unobscure event so that we can rebuild the bar after dmenu exits.
[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         XSelectInput(display, bar_window, VisibilityChangeMask);
324         if (bar_enabled) {
325                 height -= bar_height; /* correct screen height */
326                 XMapWindow(display, bar_window);
327         }
328         DNPRINTF(SWM_D_MISC, "bar_setup: bar_window %d\n", (int)bar_window);
329
330         if (signal(SIGALRM, bar_signal) == SIG_ERR)
331                 err(1, "could not install bar_signal");
332         bar_print();
333 }
334
335 void
336 quit(union arg *args)
337 {
338         DNPRINTF(SWM_D_MISC, "quit\n");
339         running = 0;
340 }
341
342 void
343 spawn(union arg *args)
344 {
345         DNPRINTF(SWM_D_MISC, "spawn: %s\n", args->argv[0]);
346         /*
347          * The double-fork construct avoids zombie processes and keeps the code
348          * clean from stupid signal handlers.
349          */
350         if(fork() == 0) {
351                 if(fork() == 0) {
352                         if(display)
353                                 close(ConnectionNumber(display));
354                         setsid();
355                         execvp(args->argv[0], args->argv);
356                         fprintf(stderr, "execvp failed\n");
357                         perror(" failed");
358                 }
359                 exit(0);
360         }
361         wait(0);
362 }
363
364 void
365 focus_win(struct ws_win *win)
366 {
367         DNPRINTF(SWM_D_FOCUS, "focus_win: id: %lu\n", win->id);
368         XSetWindowBorder(display, win->id, color_focus);
369         XSetInputFocus(display, win->id, RevertToPointerRoot, CurrentTime);
370         ws[current_ws].focus = win;
371 }
372
373 void
374 unfocus_win(struct ws_win *win)
375 {
376         DNPRINTF(SWM_D_FOCUS, "unfocus_win: id: %lu\n", win->id);
377         XSetWindowBorder(display, win->id, color_unfocus);
378         if (ws[current_ws].focus == win)
379                 ws[current_ws].focus = NULL;
380 }
381
382 void
383 switchws(union arg *args)
384 {
385         int                     wsid = args->id;
386         struct ws_win           *win;
387
388         DNPRINTF(SWM_D_WS, "switchws: %d\n", wsid + 1);
389
390         if (wsid == current_ws)
391                 return;
392
393         /* map new window first to prevent ugly blinking */
394         TAILQ_FOREACH (win, &ws[wsid].winlist, entry)
395                 XMapRaised(display, win->id);
396         ws[wsid].visible = 1;
397
398         TAILQ_FOREACH (win, &ws[current_ws].winlist, entry)
399                 XUnmapWindow(display, win->id);
400         ws[current_ws].visible = 0;
401
402         current_ws = wsid;
403
404         ignore_enter = 1;
405         if (ws[wsid].restack) {
406                 stack();
407                 bar_print();
408         } else {
409                 if (ws[wsid].focus != NULL)
410                         focus_win(ws[wsid].focus);
411                 XSync(display, False);
412         }
413 }
414
415 void
416 focus(union arg *args)
417 {
418         struct ws_win           *winfocus, *winlostfocus;
419
420         DNPRINTF(SWM_D_FOCUS, "focus: id %d\n", args->id);
421         if (ws[current_ws].focus == NULL || ws[current_ws].winno == 0)
422                 return;
423
424         winlostfocus = ws[current_ws].focus;
425
426         switch (args->id) {
427         case SWM_ARG_ID_FOCUSPREV:
428                 ws[current_ws].focus =
429                     TAILQ_PREV(ws[current_ws].focus, ws_win_list, entry);
430                 if (ws[current_ws].focus == NULL)
431                         ws[current_ws].focus =
432                             TAILQ_LAST(&ws[current_ws].winlist, ws_win_list);
433                 break;
434
435         case SWM_ARG_ID_FOCUSNEXT:
436                 ws[current_ws].focus = TAILQ_NEXT(ws[current_ws].focus, entry);
437                 if (ws[current_ws].focus == NULL)
438                         ws[current_ws].focus =
439                             TAILQ_FIRST(&ws[current_ws].winlist);
440                 break;
441
442         case SWM_ARG_ID_FOCUSMAIN:
443                 ws[current_ws].focus = TAILQ_FIRST(&ws[current_ws].winlist);
444                 break;
445
446         default:
447                 return;
448         }
449
450         winfocus = ws[current_ws].focus;
451         unfocus_win(winlostfocus);
452         focus_win(winfocus);
453         XSync(display, False);
454 }
455
456 /* I know this sucks but it works well enough */
457 void
458 stack(void)
459 {
460         XWindowChanges          wc;
461         struct ws_win           wf, *win, *winfocus = &wf;
462         int                     i, h, w, x, y, hrh;
463
464         DNPRINTF(SWM_D_EVENT, "stack: workspace: %d\n", current_ws);
465
466         winfocus->id = root;
467
468         ws[current_ws].restack = 0;
469
470         if (ws[current_ws].winno == 0)
471                 return;
472
473         if (ws[current_ws].winno > 1)
474                 w = width / 2;
475         else
476                 w = width;
477
478         if (ws[current_ws].winno > 2)
479                 hrh = height / (ws[current_ws].winno - 1);
480         else
481                 hrh = 0;
482
483         x = 0;
484         y = bar_enabled ? bar_height : 0;
485         h = height;
486         i = 0;
487         TAILQ_FOREACH (win, &ws[current_ws].winlist, entry) {
488                 if (i == 1) {
489                         x += w + 2;
490                         w -= 2;
491                 }
492                 if (i != 0 && hrh != 0) {
493                         /* correct the last window for lost pixels */
494                         if (win == TAILQ_LAST(&ws[current_ws].winlist,
495                             ws_win_list)) {
496                                 h = height - (i * hrh);
497                                 if (h == 0)
498                                         h = hrh;
499                                 else
500                                         h += hrh;
501                                 y += hrh;
502                         } else {
503                                 h = hrh - 2;
504                                 /* leave first right hand window at y = 0 */
505                                 if (i > 1)
506                                         y += h + 2;
507                         }
508                 }
509
510                 bzero(&wc, sizeof wc);
511                 win->x = wc.x = x;
512                 win->y = wc.y = y;
513                 win->width = wc.width = w;
514                 win->height = wc.height = h;
515                 wc.border_width = 1;
516                 XConfigureWindow(display, win->id, CWX | CWY | CWWidth |
517                     CWHeight | CWBorderWidth, &wc);
518                 if (win == ws[current_ws].focus)
519                         winfocus = win;
520                 else
521                         unfocus_win(win);
522                 XMapRaised(display, win->id);
523                 i++;
524         }
525
526         focus_win(winfocus); /* this has to be done outside of the loop */
527         XSync(display, False);
528 }
529
530 void
531 swap_to_main(union arg *args)
532 {
533         struct ws_win           *tmpwin = TAILQ_FIRST(&ws[current_ws].winlist);
534
535         DNPRINTF(SWM_D_MISC, "swap_to_main: win: %lu\n",
536             ws[current_ws].focus ? ws[current_ws].focus->id : 0);
537
538         if (ws[current_ws].focus == NULL || ws[current_ws].focus == tmpwin)
539                 return;
540
541         TAILQ_REMOVE(&ws[current_ws].winlist, tmpwin, entry);
542         TAILQ_INSERT_AFTER(&ws[current_ws].winlist, ws[current_ws].focus,
543             tmpwin, entry);
544         TAILQ_REMOVE(&ws[current_ws].winlist, ws[current_ws].focus, entry);
545         TAILQ_INSERT_HEAD(&ws[current_ws].winlist, ws[current_ws].focus, entry);
546         ws[current_ws].focus = TAILQ_FIRST(&ws[current_ws].winlist);
547         ignore_enter = 2;
548         stack();
549 }
550
551 void
552 send_to_ws(union arg *args)
553 {
554         int                     wsid = args->id;
555         struct ws_win           *win = ws[current_ws].focus;
556
557         DNPRINTF(SWM_D_WS, "send_to_ws: win: %lu\n", win->id);
558
559         XUnmapWindow(display, win->id);
560
561         /* find a window to focus */
562         ws[current_ws].focus = TAILQ_PREV(win, ws_win_list,entry);
563         if (ws[current_ws].focus == NULL)
564                 ws[current_ws].focus = TAILQ_FIRST(&ws[current_ws].winlist);
565
566         TAILQ_REMOVE(&ws[current_ws].winlist, win, entry);
567         ws[current_ws].winno--;
568
569         TAILQ_INSERT_TAIL(&ws[wsid].winlist, win, entry);
570         if (ws[wsid].winno == 0)
571                 ws[wsid].focus = win;
572         ws[wsid].winno++;
573         ws[wsid].restack = 1;
574
575         stack();
576 }
577
578 /* key definitions */
579 struct key {
580         unsigned int            mod;
581         KeySym                  keysym;
582         void                    (*func)(union arg *);
583         union arg               args;
584 } keys[] = {
585         /* modifier             key     function                argument */
586         { MODKEY,               XK_Return,      swap_to_main,   {0} },
587         { MODKEY | ShiftMask,   XK_Return,      spawn,          {.argv = spawn_term} },
588         { MODKEY,               XK_p,           spawn,          {.argv = spawn_menu} },
589         { MODKEY | ShiftMask,   XK_q,           quit,           {0} },
590         { MODKEY,               XK_m,           focus,          {.id = SWM_ARG_ID_FOCUSMAIN} },
591         { MODKEY,               XK_1,           switchws,       {.id = 0} },
592         { MODKEY,               XK_2,           switchws,       {.id = 1} },
593         { MODKEY,               XK_3,           switchws,       {.id = 2} },
594         { MODKEY,               XK_4,           switchws,       {.id = 3} },
595         { MODKEY,               XK_5,           switchws,       {.id = 4} },
596         { MODKEY,               XK_6,           switchws,       {.id = 5} },
597         { MODKEY,               XK_7,           switchws,       {.id = 6} },
598         { MODKEY,               XK_8,           switchws,       {.id = 7} },
599         { MODKEY,               XK_9,           switchws,       {.id = 8} },
600         { MODKEY,               XK_0,           switchws,       {.id = 9} },
601         { MODKEY | ShiftMask,   XK_1,           send_to_ws,     {.id = 0} },
602         { MODKEY | ShiftMask,   XK_2,           send_to_ws,     {.id = 1} },
603         { MODKEY | ShiftMask,   XK_3,           send_to_ws,     {.id = 2} },
604         { MODKEY | ShiftMask,   XK_4,           send_to_ws,     {.id = 3} },
605         { MODKEY | ShiftMask,   XK_5,           send_to_ws,     {.id = 4} },
606         { MODKEY | ShiftMask,   XK_6,           send_to_ws,     {.id = 5} },
607         { MODKEY | ShiftMask,   XK_7,           send_to_ws,     {.id = 6} },
608         { MODKEY | ShiftMask,   XK_8,           send_to_ws,     {.id = 7} },
609         { MODKEY | ShiftMask,   XK_9,           send_to_ws,     {.id = 8} },
610         { MODKEY | ShiftMask,   XK_0,           send_to_ws,     {.id = 9} },
611         { MODKEY,               XK_b,           bar_toggle,     {0} },
612         { MODKEY,               XK_Tab,         focus,          {.id = SWM_ARG_ID_FOCUSNEXT} },
613         { MODKEY | ShiftMask,   XK_Tab,         focus,          {.id = SWM_ARG_ID_FOCUSPREV} },
614 };
615
616 void
617 updatenumlockmask(void)
618 {
619         unsigned int            i, j;
620         XModifierKeymap         *modmap;
621
622         DNPRINTF(SWM_D_MISC, "updatenumlockmask\n");
623         numlockmask = 0;
624         modmap = XGetModifierMapping(display);
625         for (i = 0; i < 8; i++)
626                 for (j = 0; j < modmap->max_keypermod; j++)
627                         if (modmap->modifiermap[i * modmap->max_keypermod + j]
628                           == XKeysymToKeycode(display, XK_Num_Lock))
629                                 numlockmask = (1 << i);
630
631         XFreeModifiermap(modmap);
632 }
633
634 void
635 grabkeys(void)
636 {
637         unsigned int            i, j;
638         KeyCode                 code;
639         unsigned int            modifiers[] =
640             { 0, LockMask, numlockmask, numlockmask | LockMask };
641
642         DNPRINTF(SWM_D_MISC, "grabkeys\n");
643         updatenumlockmask();
644
645         XUngrabKey(display, AnyKey, AnyModifier, root);
646         for(i = 0; i < LENGTH(keys); i++) {
647                 if((code = XKeysymToKeycode(display, keys[i].keysym)))
648                         for(j = 0; j < LENGTH(modifiers); j++)
649                                 XGrabKey(display, code,
650                                     keys[i].mod | modifiers[j], root,
651                                     True, GrabModeAsync, GrabModeAsync);
652         }
653 }
654 void
655 expose(XEvent *e)
656 {
657         DNPRINTF(SWM_D_EVENT, "expose: window: %lu\n", e->xexpose.window);
658 }
659
660 void
661 keypress(XEvent *e)
662 {
663         unsigned int            i;
664         KeySym                  keysym;
665         XKeyEvent               *ev = &e->xkey;
666
667         DNPRINTF(SWM_D_EVENT, "keypress: window: %lu\n", ev->window);
668
669         keysym = XKeycodeToKeysym(display, (KeyCode)ev->keycode, 0);
670         for(i = 0; i < LENGTH(keys); i++)
671                 if(keysym == keys[i].keysym
672                    && CLEANMASK(keys[i].mod) == CLEANMASK(ev->state)
673                    && keys[i].func)
674                         keys[i].func(&(keys[i].args));
675 }
676
677 void
678 buttonpress(XEvent *e)
679 {
680         XButtonPressedEvent     *ev = &e->xbutton;
681 #ifdef SWM_CLICKTOFOCUS
682         struct ws_win           *win;
683 #endif
684
685
686         DNPRINTF(SWM_D_EVENT, "buttonpress: window: %lu\n", ev->window);
687
688         if (ev->window == root)
689                 return;
690         if (ev->window == ws[current_ws].focus->id)
691                 return;
692 #ifdef SWM_CLICKTOFOCUS
693         TAILQ_FOREACH(win, &ws[current_ws].winlist, entry)
694                 if (win->id == ev->window) {
695                         /* focus in the clicked window */
696                         XSetWindowBorder(display, ev->window, 0xff0000);
697                         XSetWindowBorder(display,
698                             ws[current_ws].focus->id, 0x888888);
699                         XSetInputFocus(display, ev->window, RevertToPointerRoot,
700                             CurrentTime);
701                         ws[current_ws].focus = win;
702                         XSync(display, False);
703                         break;
704         }
705 #endif
706 }
707
708 void
709 configurerequest(XEvent *e)
710 {
711         XConfigureRequestEvent  *ev = &e->xconfigurerequest;
712         struct ws_win           *win;
713
714         DNPRINTF(SWM_D_EVENT, "configurerequest: window: %lu\n", ev->window);
715
716         TAILQ_FOREACH (win, &ws[current_ws].winlist, entry) {
717                 if (ev->window == win->id)
718                         return;
719         }
720
721         XSelectInput(display, ev->window, ButtonPressMask | EnterWindowMask |
722             FocusChangeMask);
723
724         if ((win = calloc(1, sizeof(struct ws_win))) == NULL)
725                 errx(1, "calloc: failed to allocate memory for new window");
726
727         win->id = ev->window;
728         TAILQ_INSERT_TAIL(&ws[current_ws].winlist, win, entry);
729         ws[current_ws].focus = win; /* make new win focused */
730         ws[current_ws].winno++;
731         stack();
732 }
733
734 void
735 configurenotify(XEvent *e)
736 {
737         DNPRINTF(SWM_D_EVENT, "configurenotify: window: %lu\n",
738             e->xconfigure.window);
739 }
740
741 void
742 destroynotify(XEvent *e)
743 {
744         struct ws_win           *win;
745         XDestroyWindowEvent     *ev = &e->xdestroywindow;
746
747         DNPRINTF(SWM_D_EVENT, "destroynotify: window %lu\n", ev->window);
748
749         TAILQ_FOREACH (win, &ws[current_ws].winlist, entry) {
750                 if (ev->window == win->id) {
751                         /* find a window to focus */
752                         ws[current_ws].focus =
753                             TAILQ_PREV(win, ws_win_list,entry);
754                         if (ws[current_ws].focus == NULL)
755                                 ws[current_ws].focus =
756                                     TAILQ_FIRST(&ws[current_ws].winlist);
757         
758                         TAILQ_REMOVE(&ws[current_ws].winlist, win, entry);
759                         free(win);
760                         ws[current_ws].winno--;
761                         break;
762                 }
763         }
764
765         stack();
766 }
767
768 void
769 enternotify(XEvent *e)
770 {
771         XCrossingEvent          *ev = &e->xcrossing;
772         struct ws_win           *win;
773
774         DNPRINTF(SWM_D_EVENT, "enternotify: window: %lu\n", ev->window);
775
776         if((ev->mode != NotifyNormal || ev->detail == NotifyInferior) &&
777             ev->window != root)
778                 return;
779         if (ignore_enter) {
780                 /* eat event(s) to prevent autofocus */
781                 ignore_enter--;
782                 return;
783         }
784         TAILQ_FOREACH (win, &ws[current_ws].winlist, entry) {
785                 if (win->id == ev->window)
786                         focus_win(win);
787                 else
788                         unfocus_win(win);
789         }
790 }
791
792 void
793 focusin(XEvent *e)
794 {
795         XFocusChangeEvent       *ev = &e->xfocus;
796
797         DNPRINTF(SWM_D_EVENT, "focusin: window: %lu\n", ev->window);
798
799         XSync(display, False); /* not sure this helps redrawing graphic apps */
800
801         if (ev->window == root)
802                 return;
803         /*
804          * kill grab for now so that we can cut and paste , this screws up
805          * click to focus
806          */
807         /*
808         DNPRINTF(SWM_D_EVENT, "focusin: window: %lu grabbing\n", ev->window);
809         XGrabButton(display, Button1, AnyModifier, ev->window, False,
810             ButtonPress, GrabModeAsync, GrabModeSync, None, None);
811         */
812 }
813
814 void
815 mappingnotify(XEvent *e)
816 {
817         XMappingEvent           *ev = &e->xmapping;
818
819         DNPRINTF(SWM_D_EVENT, "mappingnotify: window: %lu\n", ev->window);
820
821         XRefreshKeyboardMapping(ev);
822         if(ev->request == MappingKeyboard)
823                 grabkeys();
824 }
825
826 void
827 maprequest(XEvent *e)
828 {
829         DNPRINTF(SWM_D_EVENT, "maprequest: window: %lu\n",
830             e->xmaprequest.window);
831 }
832
833 void
834 propertynotify(XEvent *e)
835 {
836         DNPRINTF(SWM_D_EVENT, "propertynotify: window: %lu\n",
837             e->xproperty.window);
838 }
839
840 void
841 unmapnotify(XEvent *e)
842 {
843         DNPRINTF(SWM_D_EVENT, "unmapnotify: window: %lu\n", e->xunmap.window);
844 }
845
846 void
847 visibilitynotify(XEvent *e)
848 {
849         DNPRINTF(SWM_D_EVENT, "visibilitynotify: window: %lu\n", e->xvisibility.window);
850
851         if (e->xvisibility.window == bar_window &&
852             e->xvisibility.state == VisibilityUnobscured)
853                 bar_print();
854 }
855
856 void                    (*handler[LASTEvent])(XEvent *) = {
857                                 [Expose] = expose,
858                                 [KeyPress] = keypress,
859                                 [ButtonPress] = buttonpress,
860                                 [ConfigureRequest] = configurerequest,
861                                 [ConfigureNotify] = configurenotify,
862                                 [DestroyNotify] = destroynotify,
863                                 [EnterNotify] = enternotify,
864                                 [FocusIn] = focusin,
865                                 [MappingNotify] = mappingnotify,
866                                 [MapRequest] = maprequest,
867                                 [PropertyNotify] = propertynotify,
868                                 [UnmapNotify] = unmapnotify,
869                                 [VisibilityNotify] = visibilitynotify,
870 };
871
872 int
873 xerror_start(Display *d, XErrorEvent *ee)
874 {
875         other_wm = 1;
876         return (-1);
877 }
878
879 int
880 xerror(Display *d, XErrorEvent *ee)
881 {
882         fprintf(stderr, "error: %p %p\n", display, ee);
883
884         return (-1);
885 }
886
887 int
888 active_wm(void)
889 {
890         other_wm = 0;
891         xerrorxlib = XSetErrorHandler(xerror_start);
892
893         /* this causes an error if some other window manager is running */
894         XSelectInput(display, DefaultRootWindow(display),
895             SubstructureRedirectMask);
896         XSync(display, False);
897         if(other_wm)
898                 return (1);
899
900         XSetErrorHandler(xerror);
901         XSync(display, False);
902         return (0);
903 }
904
905 int
906 main(int argc, char *argv[])
907 {
908         struct passwd           *pwd;
909         char                    conf[PATH_MAX], *cfile = NULL;
910         struct stat             sb;
911         XEvent                  e;
912         int                     i;
913
914         fprintf(stderr, "Welcome to scrotwm V%s\n", SWM_VERSION);
915         if(!setlocale(LC_CTYPE, "") || !XSupportsLocale())
916                 warnx("no locale support");
917
918         if(!(display = XOpenDisplay(0)))
919                 errx(1, "can not open display");
920
921         if (active_wm())
922                 errx(1, "other wm running");
923
924         screen = DefaultScreen(display);
925         root = RootWindow(display, screen);
926         width = DisplayWidth(display, screen) - 2;
927         height = DisplayHeight(display, screen) - 2;
928
929         /* look for local and global conf file */
930         pwd = getpwuid(getuid());
931         if (pwd == NULL)
932                 errx(1, "invalid user %d", getuid());
933
934         snprintf(conf, sizeof conf, "%s/.%s", pwd->pw_dir, SWM_CONF_FILE);
935         if (stat(conf, &sb) != -1) {
936                 if (S_ISREG(sb.st_mode))
937                         cfile = conf;
938         } else {
939                 /* try global conf file */
940                 snprintf(conf, sizeof conf, "/etc/%s", SWM_CONF_FILE);
941                 if (!stat(conf, &sb))
942                         if (S_ISREG(sb.st_mode))
943                                 cfile = conf;
944         }
945         if (cfile)
946                 conf_load(cfile);
947
948         /* make work space 1 active */
949         ws[0].visible = 1;
950         ws[0].restack = 0;
951         ws[0].focus = NULL;
952         ws[0].winno = 0;
953         TAILQ_INIT(&ws[0].winlist);
954         for (i = 1; i < SWM_WS_MAX; i++) {
955                 ws[i].visible = 0;
956                 ws[i].restack = 0;
957                 ws[i].focus = NULL;
958                 ws[i].winno = 0;
959                 TAILQ_INIT(&ws[i].winlist);
960         }
961
962         /* setup status bar */
963         bar_setup();
964
965         XSelectInput(display, root, SubstructureRedirectMask |
966             SubstructureNotifyMask | ButtonPressMask | KeyPressMask |
967             EnterWindowMask | LeaveWindowMask | StructureNotifyMask |
968             FocusChangeMask | PropertyChangeMask);
969
970         grabkeys();
971
972         while (running) {
973                 XNextEvent(display, &e);
974                 if (handler[e.type])
975                         handler[e.type](&e);
976         }
977
978         XCloseDisplay(display);
979
980         return (0);
981 }