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