JasonWoof Got questions, comments, patches, etc.? Contact Jason Woofenden
Fix last switchws bugglet where the bar appeared empty.
[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
62 #include <sys/types.h>
63 #include <sys/wait.h>
64 #include <sys/queue.h>
65
66 #include <X11/cursorfont.h>
67 #include <X11/keysym.h>
68 #include <X11/Xatom.h>
69 #include <X11/Xlib.h>
70 #include <X11/Xproto.h>
71 #include <X11/Xutil.h>
72
73 /* #define SWM_DEBUG */
74 #ifdef SWM_DEBUG
75 #define DPRINTF(x...)           do { if (swm_debug) fprintf(stderr, x); } while(0)
76 #define DNPRINTF(n,x...)        do { if (swm_debug & n) fprintf(stderr, x); } while(0)
77 #define SWM_D_EVENT             0x0001
78 #define SWM_D_WS                0x0002
79 #define SWM_D_FOCUS             0x0004
80 #define SWM_D_MISC              0x0008
81
82 uint32_t                swm_debug = 0
83                             | SWM_D_EVENT
84                             | SWM_D_WS
85                             | SWM_D_FOCUS
86                             | SWM_D_MISC
87                             ;
88 #else
89 #define DPRINTF(x...)
90 #define DNPRINTF(n,x...)
91 #endif
92
93 #define LENGTH(x)               (sizeof x / sizeof x[0])
94 #define MODKEY                  Mod1Mask
95 #define CLEANMASK(mask)         (mask & ~(numlockmask | LockMask))
96
97 int                     (*xerrorxlib)(Display *, XErrorEvent *);
98 int                     other_wm;
99 int                     screen;
100 int                     width, height;
101 int                     running = 1;
102 int                     ignore_enter = 0;
103 unsigned int            numlockmask = 0;
104 unsigned long           col_focus = 0xff0000;   /* XXX should this be per ws? */
105 unsigned long           col_unfocus = 0x888888;
106 Display                 *display;
107 Window                  root;
108
109 /* status bar */
110 int                     bar_enabled = 1;
111 int                     bar_height = 12;
112 Window                  bar_window;
113 GC                      bar_gc;
114 XGCValues               bar_gcv;
115 XFontStruct             *bar_fs;
116 char                    bar_text[128];
117
118 struct ws_win {
119         TAILQ_ENTRY(ws_win)     entry;
120         Window                  id;
121         int                     x;
122         int                     y;
123         int                     width;
124         int                     height;
125 };
126
127 TAILQ_HEAD(ws_win_list, ws_win);
128
129 /* define work spaces */
130 #define SWM_WS_MAX              (10)
131 struct workspace {
132         int                     visible;        /* workspace visible */
133         int                     restack;        /* restack on switch */
134         struct ws_win           *focus;         /* which win has focus */
135         int                     winno;          /* total nr of windows */
136         struct ws_win_list      winlist;        /* list of windows in ws */
137 } ws[SWM_WS_MAX];
138 int                     current_ws = 0;
139
140 /* args to functions */
141 union arg {
142         int                     id;
143 #define SWM_ARG_ID_FOCUSNEXT    (0)
144 #define SWM_ARG_ID_FOCUSPREV    (1)
145 #define SWM_ARG_ID_FOCUSMAIN    (2)
146         char                    **argv;
147 };
148
149
150 void    stack(void);
151
152 void
153 bar_print(void)
154 {
155         time_t                  tmt;
156         struct tm               tm;
157
158         if (bar_enabled == 0)
159                 return;
160
161         /* clear old text */
162         XSetForeground(display, bar_gc, 0x000000);
163         XDrawString(display, bar_window, bar_gc, 4, bar_fs->ascent, bar_text,
164             strlen(bar_text));
165
166         /* draw new text */
167         time(&tmt);
168         localtime_r(&tmt, &tm);
169         strftime(bar_text, sizeof bar_text, "%a %b %d %R %Z %Y", &tm);
170         XSetForeground(display, bar_gc, 0xa0a0a0);
171         XDrawString(display, bar_window, bar_gc, 4, bar_fs->ascent, bar_text,
172             strlen(bar_text));
173         XSync(display, False);
174
175         alarm(60);
176 }
177
178 void
179 bar_signal(int sig)
180 {
181         /* XXX yeah yeah byte me */
182         bar_print();
183 }
184
185 void
186 bar_toggle(union arg *args)
187 {
188         int i;
189
190         DNPRINTF(SWM_D_MISC, "bar_toggle\n");
191
192         if (bar_enabled) {
193                 bar_enabled = 0;
194                 height += bar_height; /* correct screen height */
195                 XUnmapWindow(display, bar_window);
196         } else {
197                 bar_enabled = 1;
198                 height -= bar_height; /* correct screen height */
199                 XMapWindow(display, bar_window);
200         }
201         XSync(display, False);
202         for (i = 0; i < SWM_WS_MAX; i++)
203                 ws[i].restack = 1;
204
205         stack();
206         bar_print(); /* must be after stack */
207 }
208
209 void
210 quit(union arg *args)
211 {
212         DNPRINTF(SWM_D_MISC, "quit\n");
213         running = 0;
214 }
215
216 void
217 spawn(union arg *args)
218 {
219         DNPRINTF(SWM_D_MISC, "spawn: %s\n", args->argv[0]);
220         /*
221          * The double-fork construct avoids zombie processes and keeps the code
222          * clean from stupid signal handlers.
223          */
224         if(fork() == 0) {
225                 if(fork() == 0) {
226                         if(display)
227                                 close(ConnectionNumber(display));
228                         setsid();
229                         execvp(args->argv[0], args->argv);
230                         fprintf(stderr, "execvp failed\n");
231                         perror(" failed");
232                 }
233                 exit(0);
234         }
235         wait(0);
236 }
237
238 void
239 focus_win(struct ws_win *win)
240 {
241         DNPRINTF(SWM_D_FOCUS, "focus_win: id: %lu\n", win->id);
242         XSetWindowBorder(display, win->id, col_focus);
243         XSetInputFocus(display, win->id, RevertToPointerRoot, CurrentTime);
244         ws[current_ws].focus = win;
245 }
246
247 void
248 unfocus_win(struct ws_win *win)
249 {
250         DNPRINTF(SWM_D_FOCUS, "unfocus_win: id: %lu\n", win->id);
251         XSetWindowBorder(display, win->id, col_unfocus);
252         if (ws[current_ws].focus == win)
253                 ws[current_ws].focus = NULL;
254 }
255
256 void
257 switchws(union arg *args)
258 {
259         int                     wsid = args->id;
260         struct ws_win           *win;
261
262         DNPRINTF(SWM_D_WS, "switchws: %d\n", wsid + 1);
263
264         if (wsid == current_ws)
265                 return;
266
267         /* map new window first to prevent ugly blinking */
268         TAILQ_FOREACH (win, &ws[wsid].winlist, entry)
269                 XMapWindow(display, win->id);
270         ws[wsid].visible = 1;
271
272         TAILQ_FOREACH (win, &ws[current_ws].winlist, entry)
273                 XUnmapWindow(display, win->id);
274         ws[current_ws].visible = 0;
275
276         current_ws = wsid;
277
278         ignore_enter = 1;
279         if (ws[wsid].restack) {
280                 stack();
281                 bar_print();
282         } else {
283                 if (ws[wsid].focus != NULL)
284                         focus_win(ws[wsid].focus);
285                 XSync(display, False);
286         }
287 }
288
289 void
290 focus(union arg *args)
291 {
292         struct ws_win           *winfocus, *winlostfocus;
293
294         DNPRINTF(SWM_D_FOCUS, "focus: id %d\n", args->id);
295         if (ws[current_ws].focus == NULL || ws[current_ws].winno == 0)
296                 return;
297
298         winlostfocus = ws[current_ws].focus;
299
300         switch (args->id) {
301         case SWM_ARG_ID_FOCUSPREV:
302                 ws[current_ws].focus =
303                     TAILQ_PREV(ws[current_ws].focus, ws_win_list, entry);
304                 if (ws[current_ws].focus == NULL)
305                         ws[current_ws].focus =
306                             TAILQ_LAST(&ws[current_ws].winlist, ws_win_list);
307                 break;
308
309         case SWM_ARG_ID_FOCUSNEXT:
310                 ws[current_ws].focus = TAILQ_NEXT(ws[current_ws].focus, entry);
311                 if (ws[current_ws].focus == NULL)
312                         ws[current_ws].focus =
313                             TAILQ_FIRST(&ws[current_ws].winlist);
314                 break;
315
316         case SWM_ARG_ID_FOCUSMAIN:
317                 ws[current_ws].focus = TAILQ_FIRST(&ws[current_ws].winlist);
318                 break;
319
320         default:
321                 return;
322         }
323
324         winfocus = ws[current_ws].focus;
325         unfocus_win(winlostfocus);
326         focus_win(winfocus);
327         XSync(display, False);
328 }
329
330 /* I know this sucks but it works well enough */
331 void
332 stack(void)
333 {
334         XWindowChanges          wc;
335         struct ws_win           wf, *win, *winfocus = &wf;
336         int                     i, h, w, x, y, hrh;
337
338         DNPRINTF(SWM_D_EVENT, "stack: workspace: %d\n", current_ws);
339
340         winfocus->id = root;
341
342         ws[current_ws].restack = 0;
343
344         if (ws[current_ws].winno == 0)
345                 return;
346
347         if (ws[current_ws].winno > 1)
348                 w = width / 2;
349         else
350                 w = width;
351
352         if (ws[current_ws].winno > 2)
353                 hrh = height / (ws[current_ws].winno - 1);
354         else
355                 hrh = 0;
356
357         x = 0;
358         y = bar_enabled ? bar_height : 0;
359         h = height;
360         i = 0;
361         TAILQ_FOREACH (win, &ws[current_ws].winlist, entry) {
362                 if (i == 1) {
363                         x += w + 2;
364                         w -= 2;
365                 }
366                 if (i != 0 && hrh != 0) {
367                         /* correct the last window for lost pixels */
368                         if (win == TAILQ_LAST(&ws[current_ws].winlist,
369                             ws_win_list)) {
370                                 h = height - (i * hrh);
371                                 if (h == 0)
372                                         h = hrh;
373                                 else
374                                         h += hrh;
375                                 y += hrh;
376                         } else {
377                                 h = hrh - 2;
378                                 /* leave first right hand window at y = 0 */
379                                 if (i > 1)
380                                         y += h + 2;
381                         }
382                 }
383
384                 bzero(&wc, sizeof wc);
385                 win->x = wc.x = x;
386                 win->y = wc.y = y;
387                 win->width = wc.width = w;
388                 win->height = wc.height = h;
389                 wc.border_width = 1;
390                 XConfigureWindow(display, win->id, CWX | CWY | CWWidth |
391                     CWHeight | CWBorderWidth, &wc);
392                 if (win == ws[current_ws].focus)
393                         winfocus = win;
394                 else
395                         unfocus_win(win);
396                 XMapWindow(display, win->id);
397                 i++;
398         }
399
400         focus_win(winfocus); /* this has to be done outside of the loop */
401         XSync(display, False);
402 }
403
404 void
405 swap_to_main(union arg *args)
406 {
407         struct ws_win           *tmpwin = TAILQ_FIRST(&ws[current_ws].winlist);
408
409         DNPRINTF(SWM_D_MISC, "swap_to_main: win: %lu\n",
410             ws[current_ws].focus ? ws[current_ws].focus->id : 0);
411
412         if (ws[current_ws].focus == NULL || ws[current_ws].focus == tmpwin)
413                 return;
414
415         TAILQ_REMOVE(&ws[current_ws].winlist, tmpwin, entry);
416         TAILQ_INSERT_AFTER(&ws[current_ws].winlist, ws[current_ws].focus,
417             tmpwin, entry);
418         TAILQ_REMOVE(&ws[current_ws].winlist, ws[current_ws].focus, entry);
419         TAILQ_INSERT_HEAD(&ws[current_ws].winlist, ws[current_ws].focus, entry);
420         ws[current_ws].focus = TAILQ_FIRST(&ws[current_ws].winlist);
421         ignore_enter = 2;
422         stack();
423 }
424
425 void
426 send_to_ws(union arg *args)
427 {
428         int                     wsid = args->id;
429         struct ws_win           *win = ws[current_ws].focus;
430
431         DNPRINTF(SWM_D_WS, "send_to_ws: win: %lu\n", win->id);
432
433         XUnmapWindow(display, win->id);
434
435         /* find a window to focus */
436         ws[current_ws].focus = TAILQ_PREV(win, ws_win_list,entry);
437         if (ws[current_ws].focus == NULL)
438                 ws[current_ws].focus = TAILQ_FIRST(&ws[current_ws].winlist);
439
440         TAILQ_REMOVE(&ws[current_ws].winlist, win, entry);
441         ws[current_ws].winno--;
442
443         TAILQ_INSERT_TAIL(&ws[wsid].winlist, win, entry);
444         if (ws[wsid].winno == 0)
445                 ws[wsid].focus = win;
446         ws[wsid].winno++;
447         ws[wsid].restack = 1;
448
449         stack();
450 }
451
452 /* terminal + args */
453 char                            *term[] = { "xterm", NULL };
454
455 /* key definitions */
456 struct key {
457         unsigned int            mod;
458         KeySym                  keysym;
459         void                    (*func)(union arg *);
460         union arg               args;
461 } keys[] = {
462         /* modifier             key     function                argument */
463         { MODKEY,               XK_Return,      swap_to_main,   {0} },
464         { MODKEY | ShiftMask,   XK_Return,      spawn,          {.argv = term } },
465         { MODKEY | ShiftMask,   XK_q,           quit,           {0} },
466         { MODKEY,               XK_m,           focus,          {.id = SWM_ARG_ID_FOCUSMAIN} },
467         { MODKEY,               XK_1,           switchws,       {.id = 0} },
468         { MODKEY,               XK_2,           switchws,       {.id = 1} },
469         { MODKEY,               XK_3,           switchws,       {.id = 2} },
470         { MODKEY,               XK_4,           switchws,       {.id = 3} },
471         { MODKEY,               XK_5,           switchws,       {.id = 4} },
472         { MODKEY,               XK_6,           switchws,       {.id = 5} },
473         { MODKEY,               XK_7,           switchws,       {.id = 6} },
474         { MODKEY,               XK_8,           switchws,       {.id = 7} },
475         { MODKEY,               XK_9,           switchws,       {.id = 8} },
476         { MODKEY,               XK_0,           switchws,       {.id = 9} },
477         { MODKEY | ShiftMask,   XK_1,           send_to_ws,     {.id = 0} },
478         { MODKEY | ShiftMask,   XK_2,           send_to_ws,     {.id = 1} },
479         { MODKEY | ShiftMask,   XK_3,           send_to_ws,     {.id = 2} },
480         { MODKEY | ShiftMask,   XK_4,           send_to_ws,     {.id = 3} },
481         { MODKEY | ShiftMask,   XK_5,           send_to_ws,     {.id = 4} },
482         { MODKEY | ShiftMask,   XK_6,           send_to_ws,     {.id = 5} },
483         { MODKEY | ShiftMask,   XK_7,           send_to_ws,     {.id = 6} },
484         { MODKEY | ShiftMask,   XK_8,           send_to_ws,     {.id = 7} },
485         { MODKEY | ShiftMask,   XK_9,           send_to_ws,     {.id = 8} },
486         { MODKEY | ShiftMask,   XK_0,           send_to_ws,     {.id = 9} },
487         { MODKEY,               XK_b,           bar_toggle,     {0} },
488         { MODKEY,               XK_Tab,         focus,          {.id = SWM_ARG_ID_FOCUSNEXT} },
489         { MODKEY | ShiftMask,   XK_Tab,         focus,          {.id = SWM_ARG_ID_FOCUSPREV} },
490 };
491
492 void
493 updatenumlockmask(void)
494 {
495         unsigned int            i, j;
496         XModifierKeymap         *modmap;
497
498         DNPRINTF(SWM_D_MISC, "updatenumlockmask\n");
499         numlockmask = 0;
500         modmap = XGetModifierMapping(display);
501         for (i = 0; i < 8; i++)
502                 for (j = 0; j < modmap->max_keypermod; j++)
503                         if (modmap->modifiermap[i * modmap->max_keypermod + j]
504                           == XKeysymToKeycode(display, XK_Num_Lock))
505                                 numlockmask = (1 << i);
506
507         XFreeModifiermap(modmap);
508 }
509
510 void
511 grabkeys(void)
512 {
513         unsigned int            i, j;
514         KeyCode                 code;
515         unsigned int            modifiers[] =
516             { 0, LockMask, numlockmask, numlockmask | LockMask };
517
518         DNPRINTF(SWM_D_MISC, "grabkeys\n");
519         updatenumlockmask();
520
521         XUngrabKey(display, AnyKey, AnyModifier, root);
522         for(i = 0; i < LENGTH(keys); i++) {
523                 if((code = XKeysymToKeycode(display, keys[i].keysym)))
524                         for(j = 0; j < LENGTH(modifiers); j++)
525                                 XGrabKey(display, code,
526                                     keys[i].mod | modifiers[j], root,
527                                     True, GrabModeAsync, GrabModeAsync);
528         }
529 }
530 void
531 expose(XEvent *e)
532 {
533         DNPRINTF(SWM_D_EVENT, "expose: window: %lu\n", e->xexpose.window);
534 }
535
536 void
537 keypress(XEvent *e)
538 {
539         unsigned int            i;
540         KeySym                  keysym;
541         XKeyEvent               *ev = &e->xkey;
542
543         DNPRINTF(SWM_D_EVENT, "keypress: window: %lu\n", ev->window);
544
545         keysym = XKeycodeToKeysym(display, (KeyCode)ev->keycode, 0);
546         for(i = 0; i < LENGTH(keys); i++)
547                 if(keysym == keys[i].keysym
548                    && CLEANMASK(keys[i].mod) == CLEANMASK(ev->state)
549                    && keys[i].func)
550                         keys[i].func(&(keys[i].args));
551 }
552
553 void
554 buttonpress(XEvent *e)
555 {
556         XButtonPressedEvent     *ev = &e->xbutton;
557 #ifdef SWM_CLICKTOFOCUS
558         struct ws_win           *win;
559 #endif
560
561
562         DNPRINTF(SWM_D_EVENT, "buttonpress: window: %lu\n", ev->window);
563
564         if (ev->window == root)
565                 return;
566         if (ev->window == ws[current_ws].focus->id)
567                 return;
568 #ifdef SWM_CLICKTOFOCUS
569         TAILQ_FOREACH(win, &ws[current_ws].winlist, entry)
570                 if (win->id == ev->window) {
571                         /* focus in the clicked window */
572                         XSetWindowBorder(display, ev->window, 0xff0000);
573                         XSetWindowBorder(display,
574                             ws[current_ws].focus->id, 0x888888);
575                         XSetInputFocus(display, ev->window, RevertToPointerRoot,
576                             CurrentTime);
577                         ws[current_ws].focus = win;
578                         XSync(display, False);
579                         break;
580         }
581 #endif
582 }
583
584 void
585 configurerequest(XEvent *e)
586 {
587         XConfigureRequestEvent  *ev = &e->xconfigurerequest;
588         struct ws_win           *win;
589
590         DNPRINTF(SWM_D_EVENT, "configurerequest: window: %lu\n", ev->window);
591
592         XSelectInput(display, ev->window, ButtonPressMask | EnterWindowMask |
593             FocusChangeMask);
594
595         if ((win = calloc(1, sizeof(struct ws_win))) == NULL)
596                 errx(1, "calloc: failed to allocate memory for new window");
597
598         win->id = ev->window;
599         TAILQ_INSERT_TAIL(&ws[current_ws].winlist, win, entry);
600         ws[current_ws].focus = win; /* make new win focused */
601         ws[current_ws].winno++;
602         stack();
603 }
604
605 void
606 configurenotify(XEvent *e)
607 {
608         DNPRINTF(SWM_D_EVENT, "configurenotify: window: %lu\n",
609             e->xconfigure.window);
610 }
611
612 void
613 destroynotify(XEvent *e)
614 {
615         struct ws_win           *win;
616         XDestroyWindowEvent     *ev = &e->xdestroywindow;
617
618         DNPRINTF(SWM_D_EVENT, "destroynotify: window %lu\n", ev->window);
619
620         TAILQ_FOREACH (win, &ws[current_ws].winlist, entry) {
621                 if (ev->window == win->id) {
622                         /* find a window to focus */
623                         ws[current_ws].focus =
624                             TAILQ_PREV(win, ws_win_list,entry);
625                         if (ws[current_ws].focus == NULL)
626                                 ws[current_ws].focus =
627                                     TAILQ_FIRST(&ws[current_ws].winlist);
628         
629                         TAILQ_REMOVE(&ws[current_ws].winlist, win, entry);
630                         free(win);
631                         ws[current_ws].winno--;
632                         break;
633                 }
634         }
635
636         stack();
637 }
638
639 void
640 enternotify(XEvent *e)
641 {
642         XCrossingEvent          *ev = &e->xcrossing;
643         struct ws_win           *win;
644
645         DNPRINTF(SWM_D_EVENT, "enternotify: window: %lu\n", ev->window);
646
647         if((ev->mode != NotifyNormal || ev->detail == NotifyInferior) &&
648             ev->window != root)
649                 return;
650         if (ignore_enter) {
651                 /* eat event(s) to prevent autofocus */
652                 ignore_enter--;
653                 return;
654         }
655         TAILQ_FOREACH (win, &ws[current_ws].winlist, entry) {
656                 if (win->id == ev->window)
657                         focus_win(win);
658                 else
659                         unfocus_win(win);
660         }
661 }
662
663 void
664 focusin(XEvent *e)
665 {
666         XFocusChangeEvent       *ev = &e->xfocus;
667
668         DNPRINTF(SWM_D_EVENT, "focusin: window: %lu\n", ev->window);
669
670         if (ev->window == root)
671                 return;
672
673         /*
674          * kill grab for now so that we can cut and paste , this screws up
675          * click to focus
676          */
677         /*
678         DNPRINTF(SWM_D_EVENT, "focusin: window: %lu grabbing\n", ev->window);
679         XGrabButton(display, Button1, AnyModifier, ev->window, False,
680             ButtonPress, GrabModeAsync, GrabModeSync, None, None);
681         */
682 }
683
684 void
685 mappingnotify(XEvent *e)
686 {
687         XMappingEvent           *ev = &e->xmapping;
688
689         DNPRINTF(SWM_D_EVENT, "mappingnotify: window: %lu\n", ev->window);
690
691         XRefreshKeyboardMapping(ev);
692         if(ev->request == MappingKeyboard)
693                 grabkeys();
694 }
695
696 void
697 maprequest(XEvent *e)
698 {
699         DNPRINTF(SWM_D_EVENT, "maprequest: window: %lu\n",
700             e->xmaprequest.window);
701 }
702
703 void
704 propertynotify(XEvent *e)
705 {
706         DNPRINTF(SWM_D_EVENT, "propertynotify: window: %lu\n",
707             e->xproperty.window);
708 }
709
710 void
711 unmapnotify(XEvent *e)
712 {
713         DNPRINTF(SWM_D_EVENT, "unmapnotify: window: %lu\n", e->xunmap.window);
714 }
715
716 void                    (*handler[LASTEvent])(XEvent *) = {
717                                 [Expose] = expose,
718                                 [KeyPress] = keypress,
719                                 [ButtonPress] = buttonpress,
720                                 [ConfigureRequest] = configurerequest,
721                                 [ConfigureNotify] = configurenotify,
722                                 [DestroyNotify] = destroynotify,
723                                 [EnterNotify] = enternotify,
724                                 [FocusIn] = focusin,
725                                 [MappingNotify] = mappingnotify,
726                                 [MapRequest] = maprequest,
727                                 [PropertyNotify] = propertynotify,
728                                 [UnmapNotify] = unmapnotify,
729 };
730
731 int
732 xerror_start(Display *d, XErrorEvent *ee)
733 {
734         other_wm = 1;
735         return (-1);
736 }
737
738 int
739 xerror(Display *d, XErrorEvent *ee)
740 {
741         fprintf(stderr, "error: %p %p\n", display, ee);
742
743         return (-1);
744 }
745
746 int
747 active_wm(void)
748 {
749         other_wm = 0;
750         xerrorxlib = XSetErrorHandler(xerror_start);
751
752         /* this causes an error if some other window manager is running */
753         XSelectInput(display, DefaultRootWindow(display),
754             SubstructureRedirectMask);
755         XSync(display, False);
756         if(other_wm)
757                 return (1);
758
759         XSetErrorHandler(xerror);
760         XSync(display, False);
761         return (0);
762 }
763
764 int
765 main(int argc, char *argv[])
766 {
767         XEvent                  e;
768         int                     i;
769
770         fprintf(stderr, "Welcome to scrotwm V%s\n", SWM_VERSION);
771         if(!setlocale(LC_CTYPE, "") || !XSupportsLocale())
772                 warnx("no locale support");
773
774         if(!(display = XOpenDisplay(0)))
775                 errx(1, "can not open display");
776
777         if (active_wm())
778                 errx(1, "other wm running");
779
780         screen = DefaultScreen(display);
781         root = RootWindow(display, screen);
782         width = DisplayWidth(display, screen) - 2;
783         height = DisplayHeight(display, screen) - 2;
784
785         /* make work space 1 active */
786         ws[0].visible = 1;
787         ws[0].restack = 0;
788         ws[0].focus = NULL;
789         ws[0].winno = 0;
790         TAILQ_INIT(&ws[0].winlist);
791         for (i = 1; i < SWM_WS_MAX; i++) {
792                 ws[i].visible = 0;
793                 ws[i].restack = 0;
794                 ws[i].focus = NULL;
795                 ws[i].winno = 0;
796                 TAILQ_INIT(&ws[i].winlist);
797         }
798
799         /* setup status bar */
800         bar_fs = XLoadQueryFont(display,
801             "-*-terminus-*-*-*-*-*-*-*-*-*-*-*-*");
802         if (bar_fs == NULL) {
803                 /* load a font that is default */
804                 bar_fs = XLoadQueryFont(display,
805                     "-*-times-medium-r-*-*-*-*-*-*-*-*-*-*");
806                 if (bar_fs == NULL)
807                         errx(1, "couldn't load font");
808         }
809         bar_height = bar_fs->ascent + bar_fs->descent + 3;
810
811         XSelectInput(display, root, SubstructureRedirectMask |
812             SubstructureNotifyMask | ButtonPressMask | KeyPressMask |
813             EnterWindowMask | LeaveWindowMask | StructureNotifyMask |
814             FocusChangeMask | PropertyChangeMask);
815
816         grabkeys();
817
818         bar_window = XCreateSimpleWindow(display, root, 0, 0, width,
819             bar_height - 2, 1, 0x008080, 0x000000);
820         bar_gc = XCreateGC(display, bar_window, 0, &bar_gcv);
821         XSetFont(display, bar_gc, bar_fs->fid);
822         if (bar_enabled) {
823                 height -= bar_height; /* correct screen height */
824                 XMapWindow(display, bar_window);
825         }
826
827         if (signal(SIGALRM, bar_signal) == SIG_ERR)
828                 err(1, "could not install bar_signal");
829         bar_print();
830
831         while (running) {
832                 XNextEvent(display, &e);
833                 if (handler[e.type])
834                         handler[e.type](&e);
835         }
836
837         XCloseDisplay(display);
838
839         return (0);
840 }