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