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