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