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