JasonWoof Got questions, comments, patches, etc.? Contact Jason Woofenden
a71f6195b20cb68fcc89d6107a3f83d6fee3749a
[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              0x0001
82 #define SWM_D_EVENT             0x0002
83 #define SWM_D_WS                0x0004
84 #define SWM_D_FOCUS             0x0008
85 #define SWM_D_MOVE              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 char                    **start_argv;
104 int                     (*xerrorxlib)(Display *, XErrorEvent *);
105 int                     other_wm;
106 int                     screen;
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
136 /* layout manager data */
137 struct swm_geometry {
138         int                     x;
139         int                     y;
140         int                     w;
141         int                     h;
142 };
143
144
145 struct ws_win {
146         TAILQ_ENTRY(ws_win)     entry;
147         Window                  id;
148         struct swm_geometry     g;
149         int                     floating;
150         int                     transient;
151         XWindowAttributes       wa;
152         XSizeHints              sh;
153 };
154 TAILQ_HEAD(ws_win_list, ws_win);
155
156 /* layout handlers */
157 void    stack(void);
158 void    vertical_init(int);
159 void    vertical_resize(int);
160 void    vertical_stack(struct swm_geometry *);
161 void    horizontal_init(int);
162 void    horizontal_resize(int);
163 void    horizontal_stack(struct swm_geometry *);
164 void    max_init(int);
165 void    max_focus(struct ws_win *);
166 void    max_stack(struct swm_geometry *);
167
168 struct layout {
169         void                    (*l_init)(int); /* init/reset */
170         void                    (*l_stack)(struct swm_geometry *);
171         void                    (*l_resize)(int);
172         void                    (*l_focus)(struct ws_win *);
173 } layouts[] =  {
174         /* init                 stack,                  resize */
175         { vertical_init,        vertical_stack,         vertical_resize,        NULL},
176         { horizontal_init,      horizontal_stack,       horizontal_resize,      NULL},
177         { NULL,                 max_stack,              NULL,                   max_focus},
178         { NULL,                 NULL,                   NULL,                   NULL},
179 };
180
181
182 /* define work spaces */
183 #define SWM_WS_MAX              (10)
184 struct workspace {
185         int                     visible;        /* workspace visible */
186         int                     restack;        /* restack on switch */
187         struct swm_geometry     g;
188         struct layout           *cur_layout;    /* current layout handlers */
189         struct ws_win           *focus;         /* which win has focus */
190         struct ws_win_list      winlist;        /* list of windows in ws */
191 } ws[SWM_WS_MAX];
192 int                     current_ws = 0;
193
194 /* args to functions */
195 union arg {
196         int                     id;
197 #define SWM_ARG_ID_FOCUSNEXT    (0)
198 #define SWM_ARG_ID_FOCUSPREV    (1)
199 #define SWM_ARG_ID_FOCUSMAIN    (2)
200 #define SWM_ARG_ID_SWAPNEXT     (3)
201 #define SWM_ARG_ID_SWAPPREV     (4)
202 #define SWM_ARG_ID_SWAPMAIN     (5)
203 #define SWM_ARG_ID_MASTERSHRINK (6)
204 #define SWM_ARG_ID_MASTERGROW   (7)
205         char                    **argv;
206 };
207
208 /* conf file stuff */
209 #define SWM_CONF_WS     "\n= \t"
210 #define SWM_CONF_FILE   "scrotwm.conf"
211 int
212 conf_load(char *filename)
213 {
214         FILE                    *config;
215         char                    *line, *cp, *var, *val;
216         size_t                   len, lineno = 0;
217
218         DNPRINTF(SWM_D_MISC, "conf_load: filename %s\n", filename);
219
220         if (filename == NULL)
221                 return (1);
222
223         if ((config = fopen(filename, "r")) == NULL)
224                 return (1);
225
226         for (;;) {
227                 if ((line = fparseln(config, &len, &lineno, NULL, 0)) == NULL)
228                         if (feof(config))
229                                 break;
230                 cp = line;
231                 cp += (long)strspn(cp, SWM_CONF_WS);
232                 if (cp[0] == '\0') {
233                         /* empty line */
234                         free(line);
235                         continue;
236                 }
237                 if ((var = strsep(&cp, SWM_CONF_WS)) == NULL || cp == NULL)
238                         break;
239                 cp += (long)strspn(cp, SWM_CONF_WS);
240                 if ((val = strsep(&cp, SWM_CONF_WS)) == NULL)
241                         break;
242
243                 DNPRINTF(SWM_D_MISC, "conf_load: %s=%s\n",var ,val);
244                 switch (var[0]) {
245                 case 'b':
246                         if (!strncmp(var, "bar_enabled", strlen("bar_enabled")))
247                                 bar_enabled = atoi(val);
248                         else if (!strncmp(var, "bar_border",
249                             strlen("bar_border")))
250                                 bar_border = strtol(val, NULL, 16);
251                         else if (!strncmp(var, "bar_color",
252                             strlen("bar_color")))
253                                 bar_color = strtol(val, NULL, 16);
254                         else if (!strncmp(var, "bar_font_color",
255                             strlen("bar_font_color")))
256                                 bar_font_color = strtol(val, NULL, 16);
257                         else if (!strncmp(var, "bar_font", strlen("bar_font")))
258                                 asprintf(&bar_fonts[0], "%s", val);
259                         else
260                                 goto bad;
261                         break;
262
263                 case 'c':
264                         if (!strncmp(var, "color_focus", strlen("color_focus")))
265                                 color_focus = strtol(val, NULL, 16);
266                         else if (!strncmp(var, "color_unfocus",
267                             strlen("color_unfocus")))
268                                 color_unfocus = strtol(val, NULL, 16);
269                         else
270                                 goto bad;
271                         break;
272
273                 case 's':
274                         if (!strncmp(var, "spawn_term", strlen("spawn_term")))
275                                 asprintf(&spawn_term[0], "%s", val); /* XXX args? */
276                         break;
277                 default:
278                         goto bad;
279                 }
280                 free(line);
281         }
282
283         fclose(config);
284         return (0);
285 bad:
286         errx(1, "invalid conf file entry: %s=%s", var, val);
287 }
288
289 void
290 bar_print(void)
291 {
292         time_t                  tmt;
293         struct tm               tm;
294
295         if (bar_enabled == 0)
296                 return;
297
298         /* clear old text */
299         XSetForeground(display, bar_gc, bar_color);
300         XDrawString(display, bar_window, bar_gc, 4, bar_fs->ascent, bar_text,
301             strlen(bar_text));
302
303         /* draw new text */
304         time(&tmt);
305         localtime_r(&tmt, &tm);
306         strftime(bar_text, sizeof bar_text, "%a %b %d %R %Z %Y", &tm);
307         XSetForeground(display, bar_gc, bar_font_color);
308         XDrawString(display, bar_window, bar_gc, 4, bar_fs->ascent, bar_text,
309             strlen(bar_text));
310         XSync(display, False);
311
312         alarm(60);
313 }
314
315 void
316 bar_signal(int sig)
317 {
318         /* XXX yeah yeah byte me */
319         bar_print();
320 }
321
322 void
323 bar_toggle(union arg *args)
324 {
325         int i;
326
327         DNPRINTF(SWM_D_MISC, "bar_toggle\n");
328
329         if (bar_enabled) {
330                 bar_enabled = 0;
331                 XUnmapWindow(display, bar_window);
332         } else {
333                 bar_enabled = 1;
334                 XMapRaised(display, bar_window);
335         }
336         XSync(display, False);
337         for (i = 0; i < SWM_WS_MAX; i++)
338                 ws[i].restack = 1;
339
340         stack();
341         bar_print(); /* must be after stack */
342 }
343
344 void
345 bar_setup(void)
346 {
347         int                     i;
348
349         for (i = 0; bar_fonts[i] != NULL; i++) {
350                 bar_fs = XLoadQueryFont(display, bar_fonts[i]);
351                 if (bar_fs)
352                         break;
353         }
354         if (bar_fonts[i] == NULL)
355                         errx(1, "couldn't load font");
356         bar_height = bar_fs->ascent + bar_fs->descent + 3;
357
358         bar_window = XCreateSimpleWindow(display, root, 0, 0,
359             ws[current_ws].g.w, bar_height - 2, 1, bar_border, bar_color);
360         bar_gc = XCreateGC(display, bar_window, 0, &bar_gcv);
361         XSetFont(display, bar_gc, bar_fs->fid);
362         XSelectInput(display, bar_window, VisibilityChangeMask);
363         if (bar_enabled) {
364                 XMapRaised(display, bar_window);
365         }
366         DNPRINTF(SWM_D_MISC, "bar_setup: bar_window %d\n", (int)bar_window);
367
368         if (signal(SIGALRM, bar_signal) == SIG_ERR)
369                 err(1, "could not install bar_signal");
370         bar_print();
371 }
372
373 void
374 config_win(struct ws_win *win)
375 {
376         XConfigureEvent         ce;
377
378         DNPRINTF(SWM_D_MISC, "config_win: win %lu x %d y %d w %d h %d\n",
379             win->id, win->g.x, win->g.y, win->g.w, win->g.h);
380         ce.type = ConfigureNotify;
381         ce.display = display;
382         ce.event = win->id;
383         ce.window = win->id;
384         ce.x = win->g.x;
385         ce.y = win->g.y;
386         ce.width = win->g.w;
387         ce.height = win->g.h;
388         ce.border_width = 1; /* XXX store this! */
389         ce.above = None;
390         ce.override_redirect = False;
391         XSendEvent(display, win->id, False, StructureNotifyMask, (XEvent *)&ce);
392 }
393
394 int
395 count_win(int wsid, int count_transient)
396 {
397         struct ws_win           *win;
398         int                     count = 0;
399
400         TAILQ_FOREACH (win, &ws[wsid].winlist, entry) {
401                 if (count_transient == 0 && win->floating)
402                         continue;
403                 if (count_transient == 0 && win->transient)
404                         continue;
405                 count++;
406         }
407         DNPRINTF(SWM_D_MISC, "count_win: %d\n", count);
408
409         return (count);
410 }
411 void
412 quit(union arg *args)
413 {
414         DNPRINTF(SWM_D_MISC, "quit\n");
415         running = 0;
416 }
417
418 void
419 restart(union arg *args)
420 {
421         DNPRINTF(SWM_D_MISC, "restart: %s\n", start_argv[0]);
422
423         XCloseDisplay(display);
424         execvp(start_argv[0], start_argv);
425         fprintf(stderr, "execvp failed\n");
426         perror(" failed");
427         quit(NULL);
428 }
429
430 void
431 spawn(union arg *args)
432 {
433         DNPRINTF(SWM_D_MISC, "spawn: %s\n", args->argv[0]);
434         /*
435          * The double-fork construct avoids zombie processes and keeps the code
436          * clean from stupid signal handlers.
437          */
438         if(fork() == 0) {
439                 if(fork() == 0) {
440                         if(display)
441                                 close(ConnectionNumber(display));
442                         setsid();
443                         execvp(args->argv[0], args->argv);
444                         fprintf(stderr, "execvp failed\n");
445                         perror(" failed");
446                 }
447                 exit(0);
448         }
449         wait(0);
450 }
451
452 void
453 focus_win(struct ws_win *win)
454 {
455         DNPRINTF(SWM_D_FOCUS, "focus_win: id: %lu\n", win->id);
456         XSetWindowBorder(display, win->id, color_focus);
457         XSetInputFocus(display, win->id, RevertToPointerRoot, CurrentTime);
458         ws[current_ws].focus = win;
459 }
460
461 void
462 unfocus_win(struct ws_win *win)
463 {
464         DNPRINTF(SWM_D_FOCUS, "unfocus_win: id: %lu\n", win->id);
465         XSetWindowBorder(display, win->id, color_unfocus);
466         if (ws[current_ws].focus == win)
467                 ws[current_ws].focus = NULL;
468 }
469
470 void
471 switchws(union arg *args)
472 {
473         int                     wsid = args->id;
474         struct ws_win           *win;
475
476         DNPRINTF(SWM_D_WS, "switchws: %d\n", wsid + 1);
477
478         if (wsid == current_ws)
479                 return;
480
481         /* map new window first to prevent ugly blinking */
482         TAILQ_FOREACH (win, &ws[wsid].winlist, entry)
483                 XMapRaised(display, win->id);
484         ws[wsid].visible = 1;
485
486         TAILQ_FOREACH (win, &ws[current_ws].winlist, entry)
487                 XUnmapWindow(display, win->id);
488         ws[current_ws].visible = 0;
489
490         current_ws = wsid;
491
492         ignore_enter = 1;
493         if (ws[wsid].restack) {
494                 stack();
495                 bar_print();
496         } else {
497                 if (ws[wsid].focus != NULL)
498                         focus_win(ws[wsid].focus);
499                 XSync(display, False);
500         }
501 }
502
503 void
504 swapwin(union arg *args)
505 {
506         struct ws_win           *target;
507
508         DNPRINTF(SWM_D_MOVE, "swapwin: id %d\n", args->id);
509         if (ws[current_ws].focus == NULL)
510                 return;
511
512         switch (args->id) {
513         case SWM_ARG_ID_SWAPPREV:
514                 target = TAILQ_PREV(ws[current_ws].focus, ws_win_list, entry);
515                 TAILQ_REMOVE(&ws[current_ws].winlist,
516                     ws[current_ws].focus, entry);
517                 if (target == NULL)
518                         TAILQ_INSERT_TAIL(&ws[current_ws].winlist,
519                             ws[current_ws].focus, entry);
520                 else
521                         TAILQ_INSERT_BEFORE(target, ws[current_ws].focus,
522                             entry);
523                 break;
524         case SWM_ARG_ID_SWAPNEXT: 
525                 target = TAILQ_NEXT(ws[current_ws].focus, entry);
526                 TAILQ_REMOVE(&ws[current_ws].winlist,
527                     ws[current_ws].focus, entry);
528                 if (target == NULL)
529                         TAILQ_INSERT_HEAD(&ws[current_ws].winlist,
530                             ws[current_ws].focus, entry);
531                 else
532                         TAILQ_INSERT_AFTER(&ws[current_ws].winlist, target,
533                             ws[current_ws].focus, entry);
534                 break;
535         case SWM_ARG_ID_SWAPMAIN:
536                 target = TAILQ_FIRST(&ws[current_ws].winlist);
537                 if (target == ws[current_ws].focus)
538                         return;
539                 TAILQ_REMOVE(&ws[current_ws].winlist, target, entry);
540                 TAILQ_INSERT_BEFORE(ws[current_ws].focus, target, entry);
541                 TAILQ_REMOVE(&ws[current_ws].winlist,
542                     ws[current_ws].focus, entry);
543                 TAILQ_INSERT_HEAD(&ws[current_ws].winlist,
544                     ws[current_ws].focus, entry);
545                 break;
546         default:
547                 DNPRINTF(SWM_D_MOVE, "invalid id: %d\n", args->id);
548                 return;
549         }
550
551         ignore_enter = 2;
552         stack();
553 }
554
555 void
556 focus(union arg *args)
557 {
558         struct ws_win           *winfocus, *winlostfocus;
559
560         DNPRINTF(SWM_D_FOCUS, "focus: id %d\n", args->id);
561         if (ws[current_ws].focus == NULL)
562                 return;
563
564         winlostfocus = ws[current_ws].focus;
565
566         switch (args->id) {
567         case SWM_ARG_ID_FOCUSPREV:
568                 winfocus = TAILQ_PREV(ws[current_ws].focus, ws_win_list, entry);
569                 if (winfocus == NULL)
570                         winfocus =
571                             TAILQ_LAST(&ws[current_ws].winlist, ws_win_list);
572                 break;
573
574         case SWM_ARG_ID_FOCUSNEXT:
575                 winfocus = TAILQ_NEXT(ws[current_ws].focus, entry);
576                 if (winfocus == NULL)
577                         winfocus = TAILQ_FIRST(&ws[current_ws].winlist);
578                 break;
579
580         case SWM_ARG_ID_FOCUSMAIN:
581                 winfocus = TAILQ_FIRST(&ws[current_ws].winlist);
582                 break;
583
584         default:
585                 return;
586         }
587
588         if (winfocus == winlostfocus)
589                 return;
590
591         unfocus_win(winlostfocus);
592         focus_win(winfocus);
593         /* XXX if we hook in focus_win(), we get a nasty cycle */
594         if (ws[current_ws].cur_layout->l_focus != NULL)
595                 ws[current_ws].cur_layout->l_focus(winfocus);
596         XSync(display, False);
597 }
598
599 void
600 cycle_layout(union arg *args)
601 {
602         DNPRINTF(SWM_D_EVENT, "cycle_layout: workspace: %d\n", current_ws);
603
604         ws[current_ws].cur_layout++;
605         if (ws[current_ws].cur_layout->l_stack == NULL)
606                 ws[current_ws].cur_layout = &layouts[0];
607         ignore_enter = 1;
608
609         stack();
610 }
611
612 void
613 resize_master(union arg *args)
614 {
615         DNPRINTF(SWM_D_EVENT, "resize_master: id %d\n", args->id);
616
617         if (ws[current_ws].cur_layout->l_resize != NULL)
618                 ws[current_ws].cur_layout->l_resize(args->id);
619 }
620
621 void
622 stack_reset(union arg *args)
623 {
624         DNPRINTF(SWM_D_EVENT, "stack_reset: ws %d\n", current_ws);
625
626         if (ws[current_ws].cur_layout->l_init != NULL) {
627                 ws[current_ws].cur_layout->l_init(current_ws);
628                 stack();
629         }
630 }
631
632 void
633 stack(void) {
634         struct swm_geometry g;
635         DNPRINTF(SWM_D_EVENT, "stack: workspace: %d\n", current_ws);
636
637         /* start with workspace geometry, adjust for bar */
638         g = ws[current_ws].g;
639         if (bar_enabled) {
640                 g.y += bar_height;
641                 g.h -= bar_height;
642         } 
643
644         ws[current_ws].restack = 0;
645         ws[current_ws].cur_layout->l_stack(&g);
646         XSync(display, False);
647 }
648
649 void
650 stack_floater(struct ws_win *win)
651 {
652         unsigned int            mask;
653         XWindowChanges          wc;
654
655 #if 0
656         bzero(&wc, sizeof wc);
657         wc.border_width = 1;
658         mask = CWX | CWY | CWBorderWidth;
659
660         win->g.w = wc.width = win->wa.width;
661         win->g.h = wc.height = win->wa.height;
662         win->g.x = wc.x = (ws[current_ws].g.w - win->wa.width) / 2;
663         win->g.y = wc.y = (ws[current_ws].g.h - win->wa.height) / 2;
664
665         DNPRINTF(SWM_D_EVENT, "stack_floater: win %d x %d y %d w %d h %d\n",
666             win, wc.x, wc.y, wc.width, wc.height);
667
668         XConfigureWindow(display, win->id, mask, &wc);
669 return;
670 #endif
671         bzero(&wc, sizeof wc);
672         wc.border_width = 1;
673         mask = CWX | CWY | CWBorderWidth;
674
675         /* use obsolete width height */
676         if (win->sh.flags & USPosition) {
677                 win->g.w = wc.width = win->sh.width;
678                 win->g.h = wc.height = win->sh.height;
679                 mask |= CWWidth | CWHeight;
680         }
681
682         /* try min max */
683         if (win->sh.flags & PMinSize) {
684                 /* some hints are retarded */
685                 if (win->sh.min_width < ws[current_ws].g.w / 10)
686                         win->sh.min_width = ws[current_ws].g.w / 3;
687                 if (win->sh.min_height < ws[current_ws].g.h / 10)
688                         win->sh.height = ws[current_ws].g.h / 3;
689
690                 win->g.w = wc.width = win->sh.min_width * 2;
691                 win->g.h = wc.height = win->sh.min_height * 2;
692                 mask |= CWWidth | CWHeight;
693         }
694         if (win->sh.flags & PMaxSize) {
695                 /* potentially override min values */
696                 if (win->sh.max_width < ws[current_ws].g.w) {
697                         win->g.w = wc.width = win->sh.max_width;
698                         mask |= CWWidth;
699                 }
700                 if (win->sh.max_height < ws[current_ws].g.h) {
701                         win->g.h = wc.height = win->sh.max_height;
702                         mask |= CWHeight;
703                 }
704         }
705
706         /* make sure we don't clobber the screen */
707         if ((mask & CWWidth) && win->wa.width > ws[current_ws].g.w)
708                 win->wa.width = ws[current_ws].g.w - 4;
709         if ((mask & CWHeight) && win->wa.height > ws[current_ws].g.h)
710                 win->wa.height = ws[current_ws].g.h - 4;
711
712         /* supposed to be obsolete */
713         if (win->sh.flags & USPosition) {
714                 win->g.x = wc.x = win->sh.x;
715                 win->g.y = wc.y = win->sh.y;
716         } else {
717                 win->g.x = wc.x = (ws[current_ws].g.w - win->wa.width) / 2;
718                 win->g.y = wc.y = (ws[current_ws].g.h - win->wa.height) / 2;
719         }
720         DNPRINTF(SWM_D_EVENT, "stack_floater: win %d x %d y %d w %d h %d\n",
721             win, wc.x, wc.y, wc.width, wc.height);
722
723         XConfigureWindow(display, win->id, mask, &wc);
724 }
725
726
727 int vertical_msize[SWM_WS_MAX];
728
729 void
730 vertical_init(int ws_idx)
731 {
732         DNPRINTF(SWM_D_MISC, "vertical_init: workspace: %d\n", current_ws);
733
734         vertical_msize[ws_idx] = ws[ws_idx].g.w / 2;
735 }
736
737 void
738 vertical_resize(int id)
739 {
740         DNPRINTF(SWM_D_MISC, "vertical_resize: workspace: %d\n", current_ws);
741
742         switch (id) {
743         case SWM_ARG_ID_MASTERSHRINK:
744                 vertical_msize[current_ws] -= ws[current_ws].g.w / 32;
745                 if ( vertical_msize[current_ws] < ws[current_ws].g.w / 16)
746                         vertical_msize[current_ws] = ws[current_ws].g.w / 16;
747                 break;
748         case SWM_ARG_ID_MASTERGROW:
749                 vertical_msize[current_ws] += ws[current_ws].g.w / 32;
750                 if ( vertical_msize[current_ws] >
751                    (ws[current_ws].g.w - (ws[current_ws].g.w / 16)))
752                         vertical_msize[current_ws] =
753                             ws[current_ws].g.w - ws[current_ws].g.w / 16;
754                 break;
755         default:
756                 return;
757         }
758         stack();
759 }
760
761 void
762 vertical_stack(struct swm_geometry *g) {
763         XWindowChanges          wc;
764         struct swm_geometry     gg = *g;
765         struct ws_win           wf, *win, *winfocus = &wf;
766         int                     i, hrh, winno;
767         unsigned int            mask;
768
769         DNPRINTF(SWM_D_EVENT, "vertical_stack: workspace: %d\n", current_ws);
770
771         winno = count_win(current_ws, 0);
772         if (winno == 0)
773                 return;
774         winfocus->id = root;
775
776         if (winno > 1)
777                 gg.w = vertical_msize[current_ws];
778
779         if (winno > 2)
780                 hrh = g->h / (winno - 1);
781         else
782                 hrh = 0;
783
784         i = 0;
785         TAILQ_FOREACH (win, &ws[current_ws].winlist, entry) {
786                 if (i == 1) {
787                         gg.x += vertical_msize[current_ws] + 2;
788                         gg.w = g->w - (vertical_msize[current_ws] + 2);
789                 }
790                 if (i != 0 && hrh != 0) {
791                         /* correct the last window for lost pixels */
792                         if (win == TAILQ_LAST(&ws[current_ws].winlist,
793                             ws_win_list)) {
794                                 gg.h = hrh + (g->h - (i * hrh));
795                                 gg.y += hrh;
796                         } else {
797                                 gg.h = hrh - 2;
798                                 /* leave first right hand window at y = 0 */
799                                 if (i > 1)
800                                         gg.y += gg.h + 2;
801                         }
802                 }
803
804                 if (win->transient != 0 || win->floating != 0)
805                         stack_floater(win);
806                 else {
807                         bzero(&wc, sizeof wc);
808                         wc.border_width = 1;
809                         win->g.x = wc.x = gg.x;
810                         win->g.y = wc.y = gg.y;
811                         win->g.w = wc.width = gg.w;
812                         win->g.h = wc.height = gg.h;
813                         mask = CWX | CWY | CWWidth | CWHeight | CWBorderWidth;
814                         XConfigureWindow(display, win->id, mask, &wc);
815                 }
816
817                 if (win == ws[current_ws].focus)
818                         winfocus = win;
819                 else
820                         unfocus_win(win);
821                 XMapRaised(display, win->id);
822                 i++;
823         }
824
825         focus_win(winfocus); /* this has to be done outside of the loop */
826 }
827
828 int horizontal_msize[SWM_WS_MAX];
829
830 void
831 horizontal_init(int ws_idx)
832 {
833         DNPRINTF(SWM_D_MISC, "horizontal_init: workspace: %d\n", current_ws);
834
835         horizontal_msize[ws_idx] = ws[ws_idx].g.h / 2;
836 }
837
838 void
839 horizontal_resize(int id)
840 {
841         DNPRINTF(SWM_D_MISC, "horizontal_resize: workspace: %d\n", current_ws);
842
843         switch (id) {
844         case SWM_ARG_ID_MASTERSHRINK:
845                 horizontal_msize[current_ws] -= ws[current_ws].g.h / 32;
846                 if ( horizontal_msize[current_ws] < ws[current_ws].g.h / 16)
847                         horizontal_msize[current_ws] = ws[current_ws].g.h / 16;
848                 break;
849         case SWM_ARG_ID_MASTERGROW:
850                 horizontal_msize[current_ws] += ws[current_ws].g.h / 32;
851                 if ( horizontal_msize[current_ws] >
852                    (ws[current_ws].g.h - (ws[current_ws].g.h / 16)))
853                         horizontal_msize[current_ws] =
854                             ws[current_ws].g.h - ws[current_ws].g.h / 16;
855                 break;
856         default:
857                 return;
858         }
859         stack();
860 }
861
862 void
863 horizontal_stack(struct swm_geometry *g) {
864         XWindowChanges          wc;
865         struct swm_geometry     gg = *g;
866         struct ws_win           wf, *win, *winfocus = &wf;
867         int                     i, hrw, winno;
868         unsigned int            mask;
869
870         DNPRINTF(SWM_D_EVENT, "horizontal_stack: workspace: %d\n", current_ws);
871
872         winno = count_win(current_ws, 0);
873         if (winno == 0)
874                 return;
875         winfocus->id = root;
876
877         if (winno > 1)
878                 gg.h = horizontal_msize[current_ws];
879
880         if (winno > 2)
881                 hrw = g->w / (winno - 1);
882         else
883                 hrw = 0;
884
885         i = 0;
886         TAILQ_FOREACH (win, &ws[current_ws].winlist, entry) {
887                 if (i == 1) {
888                         gg.y += horizontal_msize[current_ws] + 2;
889                         gg.h = g->h - (horizontal_msize[current_ws] + 2);
890                 }
891                 if (i != 0 && hrw != 0) {
892                         /* correct the last window for lost pixels */
893                         if (win == TAILQ_LAST(&ws[current_ws].winlist,
894                             ws_win_list)) {
895                                 gg.w = hrw + (g->w - (i * hrw));
896                                 gg.x += hrw;
897                         } else {
898                                 gg.w = hrw - 2;
899                                 /* leave first bottom window at x = 0 */
900                                 if (i > 1)
901                                         gg.x += gg.w + 2;
902                         }
903                 }
904
905                 if (win->transient != 0 || win->floating != 0)
906                         stack_floater(win);
907                 else {
908                         bzero(&wc, sizeof wc);
909                         wc.border_width = 1;
910                         win->g.x = wc.x = gg.x;
911                         win->g.y = wc.y = gg.y;
912                         win->g.w = wc.width = gg.w;
913                         win->g.h = wc.height = gg.h;
914                         mask = CWX | CWY | CWWidth | CWHeight | CWBorderWidth;
915                         XConfigureWindow(display, win->id, mask, &wc);
916                 }
917
918                 if (win == ws[current_ws].focus)
919                         winfocus = win;
920                 else
921                         unfocus_win(win);
922                 XMapRaised(display, win->id);
923                 i++;
924         }
925
926         focus_win(winfocus); /* this has to be done outside of the loop */
927 }
928
929 void
930 max_focus(struct ws_win *fwin)
931 {
932         struct ws_win *win;
933
934         TAILQ_FOREACH (win, &ws[current_ws].winlist, entry) {
935                 if (win->transient == 0 && win->floating == 0 && win == fwin)
936                         XMapRaised(display, win->id);
937                 else
938                         XUnmapWindow(display, win->id);
939         }
940 }
941
942 /* fullscreen view */
943 void
944 max_stack(struct swm_geometry *g) {
945         XWindowChanges          wc;
946         struct swm_geometry     gg = *g;
947         struct ws_win           *win, *winfocus;
948         unsigned int            mask;
949
950         DNPRINTF(SWM_D_EVENT, "max_stack: workspace: %d\n", current_ws);
951
952         if (count_win(current_ws, 0) == 0)
953                 return;
954
955         winfocus = ws[current_ws].focus;
956         if (!winfocus)
957                 winfocus = TAILQ_FIRST(&ws[current_ws].winlist);
958
959         TAILQ_FOREACH (win, &ws[current_ws].winlist, entry) {
960                 if (win->transient != 0 || win->floating != 0) {
961                         if (win == winfocus)
962                                 stack_floater(win); /* XXX maximize? */
963                         else
964                                 XUnmapWindow(display, win->id);
965                 } else {
966                         bzero(&wc, sizeof wc);
967                         wc.border_width = 1;
968                         win->g.x = wc.x = gg.x;
969                         win->g.y = wc.y = gg.y;
970                         win->g.w = wc.width = gg.w;
971                         win->g.h = wc.height = gg.h;
972                         mask = CWX | CWY | CWWidth | CWHeight | CWBorderWidth;
973                         XConfigureWindow(display, win->id, mask, &wc);
974
975                         if (winfocus == win)
976                                 XMapRaised(display, win->id);
977                         else
978                                 XUnmapWindow(display, win->id);
979                 }
980         }
981
982         focus_win(winfocus); /* this has to be done outside of the loop */
983 }
984
985 void
986 send_to_ws(union arg *args)
987 {
988         int                     wsid = args->id;
989         struct ws_win           *win = ws[current_ws].focus;
990
991         DNPRINTF(SWM_D_MOVE, "send_to_ws: win: %lu\n", win->id);
992
993         XUnmapWindow(display, win->id);
994
995         /* find a window to focus */
996         ws[current_ws].focus = TAILQ_PREV(win, ws_win_list, entry);
997         if (ws[current_ws].focus == NULL)
998                 ws[current_ws].focus = TAILQ_FIRST(&ws[current_ws].winlist);
999         if (ws[current_ws].focus == win)
1000                 ws[current_ws].focus = NULL;
1001
1002         TAILQ_REMOVE(&ws[current_ws].winlist, win, entry);
1003
1004         TAILQ_INSERT_TAIL(&ws[wsid].winlist, win, entry);
1005         if (count_win(wsid, 1) == 1)
1006                 ws[wsid].focus = win;
1007         ws[wsid].restack = 1;
1008
1009         stack();
1010 }
1011
1012 /* key definitions */
1013 struct key {
1014         unsigned int            mod;
1015         KeySym                  keysym;
1016         void                    (*func)(union arg *);
1017         union arg               args;
1018 } keys[] = {
1019         /* modifier             key     function                argument */
1020         { MODKEY,               XK_space,       cycle_layout,   {0} }, 
1021         { MODKEY | ShiftMask,   XK_space,       stack_reset,    {0} }, 
1022         { MODKEY,               XK_h,           resize_master,  {.id = SWM_ARG_ID_MASTERSHRINK} },
1023         { MODKEY,               XK_l,           resize_master,  {.id = SWM_ARG_ID_MASTERGROW} },
1024         { MODKEY,               XK_Return,      swapwin,        {.id = SWM_ARG_ID_SWAPMAIN} },
1025         { MODKEY,               XK_j,           focus,          {.id = SWM_ARG_ID_FOCUSNEXT} },
1026         { MODKEY,               XK_k,           focus,          {.id = SWM_ARG_ID_FOCUSPREV} },
1027         { MODKEY | ShiftMask,   XK_j,           swapwin,        {.id = SWM_ARG_ID_SWAPNEXT} },
1028         { MODKEY | ShiftMask,   XK_k,           swapwin,        {.id = SWM_ARG_ID_SWAPPREV} },
1029         { MODKEY | ShiftMask,   XK_Return,      spawn,          {.argv = spawn_term} },
1030         { MODKEY,               XK_p,           spawn,          {.argv = spawn_menu} },
1031         { MODKEY | ShiftMask,   XK_q,           quit,           {0} },
1032         { MODKEY,               XK_q,           restart,        {0} },
1033         { MODKEY,               XK_m,           focus,          {.id = SWM_ARG_ID_FOCUSMAIN} },
1034         { MODKEY,               XK_1,           switchws,       {.id = 0} },
1035         { MODKEY,               XK_2,           switchws,       {.id = 1} },
1036         { MODKEY,               XK_3,           switchws,       {.id = 2} },
1037         { MODKEY,               XK_4,           switchws,       {.id = 3} },
1038         { MODKEY,               XK_5,           switchws,       {.id = 4} },
1039         { MODKEY,               XK_6,           switchws,       {.id = 5} },
1040         { MODKEY,               XK_7,           switchws,       {.id = 6} },
1041         { MODKEY,               XK_8,           switchws,       {.id = 7} },
1042         { MODKEY,               XK_9,           switchws,       {.id = 8} },
1043         { MODKEY,               XK_0,           switchws,       {.id = 9} },
1044         { MODKEY | ShiftMask,   XK_1,           send_to_ws,     {.id = 0} },
1045         { MODKEY | ShiftMask,   XK_2,           send_to_ws,     {.id = 1} },
1046         { MODKEY | ShiftMask,   XK_3,           send_to_ws,     {.id = 2} },
1047         { MODKEY | ShiftMask,   XK_4,           send_to_ws,     {.id = 3} },
1048         { MODKEY | ShiftMask,   XK_5,           send_to_ws,     {.id = 4} },
1049         { MODKEY | ShiftMask,   XK_6,           send_to_ws,     {.id = 5} },
1050         { MODKEY | ShiftMask,   XK_7,           send_to_ws,     {.id = 6} },
1051         { MODKEY | ShiftMask,   XK_8,           send_to_ws,     {.id = 7} },
1052         { MODKEY | ShiftMask,   XK_9,           send_to_ws,     {.id = 8} },
1053         { MODKEY | ShiftMask,   XK_0,           send_to_ws,     {.id = 9} },
1054         { MODKEY,               XK_b,           bar_toggle,     {0} },
1055         { MODKEY,               XK_Tab,         focus,          {.id = SWM_ARG_ID_FOCUSNEXT} },
1056         { MODKEY | ShiftMask,   XK_Tab,         focus,          {.id = SWM_ARG_ID_FOCUSPREV} },
1057 };
1058
1059 void
1060 updatenumlockmask(void)
1061 {
1062         unsigned int            i, j;
1063         XModifierKeymap         *modmap;
1064
1065         DNPRINTF(SWM_D_MISC, "updatenumlockmask\n");
1066         numlockmask = 0;
1067         modmap = XGetModifierMapping(display);
1068         for (i = 0; i < 8; i++)
1069                 for (j = 0; j < modmap->max_keypermod; j++)
1070                         if (modmap->modifiermap[i * modmap->max_keypermod + j]
1071                           == XKeysymToKeycode(display, XK_Num_Lock))
1072                                 numlockmask = (1 << i);
1073
1074         XFreeModifiermap(modmap);
1075 }
1076
1077 void
1078 grabkeys(void)
1079 {
1080         unsigned int            i, j;
1081         KeyCode                 code;
1082         unsigned int            modifiers[] =
1083             { 0, LockMask, numlockmask, numlockmask | LockMask };
1084
1085         DNPRINTF(SWM_D_MISC, "grabkeys\n");
1086         updatenumlockmask();
1087
1088         XUngrabKey(display, AnyKey, AnyModifier, root);
1089         for(i = 0; i < LENGTH(keys); i++) {
1090                 if((code = XKeysymToKeycode(display, keys[i].keysym)))
1091                         for(j = 0; j < LENGTH(modifiers); j++)
1092                                 XGrabKey(display, code,
1093                                     keys[i].mod | modifiers[j], root,
1094                                     True, GrabModeAsync, GrabModeAsync);
1095         }
1096 }
1097 void
1098 expose(XEvent *e)
1099 {
1100         DNPRINTF(SWM_D_EVENT, "expose: window: %lu\n", e->xexpose.window);
1101 }
1102
1103 void
1104 keypress(XEvent *e)
1105 {
1106         unsigned int            i;
1107         KeySym                  keysym;
1108         XKeyEvent               *ev = &e->xkey;
1109
1110         DNPRINTF(SWM_D_EVENT, "keypress: window: %lu\n", ev->window);
1111
1112         keysym = XKeycodeToKeysym(display, (KeyCode)ev->keycode, 0);
1113         for(i = 0; i < LENGTH(keys); i++)
1114                 if(keysym == keys[i].keysym
1115                    && CLEANMASK(keys[i].mod) == CLEANMASK(ev->state)
1116                    && keys[i].func)
1117                         keys[i].func(&(keys[i].args));
1118 }
1119
1120 void
1121 buttonpress(XEvent *e)
1122 {
1123         XButtonPressedEvent     *ev = &e->xbutton;
1124 #ifdef SWM_CLICKTOFOCUS
1125         struct ws_win           *win;
1126 #endif
1127
1128
1129         DNPRINTF(SWM_D_EVENT, "buttonpress: window: %lu\n", ev->window);
1130
1131         if (ev->window == root)
1132                 return;
1133         if (ev->window == ws[current_ws].focus->id)
1134                 return;
1135 #ifdef SWM_CLICKTOFOCUS
1136         TAILQ_FOREACH(win, &ws[current_ws].winlist, entry)
1137                 if (win->id == ev->window) {
1138                         /* focus in the clicked window */
1139                         XSetWindowBorder(display, ev->window, 0xff0000);
1140                         XSetWindowBorder(display,
1141                             ws[current_ws].focus->id, 0x888888);
1142                         XSetInputFocus(display, ev->window, RevertToPointerRoot,
1143                             CurrentTime);
1144                         ws[current_ws].focus = win;
1145                         XSync(display, False);
1146                         break;
1147         }
1148 #endif
1149 }
1150
1151 struct ws_win *
1152 manage_window(Window id)
1153 {
1154         Window                  trans;
1155         struct ws_win           *win;
1156         XClassHint              ch;
1157
1158         TAILQ_FOREACH (win, &ws[current_ws].winlist, entry) {
1159                 if (win->id == id)
1160                         return (win);   /* already being managed */
1161         }
1162
1163         if ((win = calloc(1, sizeof(struct ws_win))) == NULL)
1164                 errx(1, "calloc: failed to allocate memory for new window");
1165
1166         win->id = id;
1167         TAILQ_INSERT_TAIL(&ws[current_ws].winlist, win, entry);
1168         ws[current_ws].focus = win; /* make new win focused */
1169
1170         XGetTransientForHint(display, win->id, &trans);
1171         if (trans) {
1172                 win->transient = trans;
1173                 DNPRINTF(SWM_D_MISC, "manage_window: win %u transient %u\n",
1174                     (unsigned)win->id, win->transient);
1175         }
1176         XGetWindowAttributes(display, win->id, &win->wa);
1177         XGetNormalHints(display, win->id, &win->sh);
1178
1179         /* XXX */
1180         bzero(&ch, sizeof ch);
1181         if(XGetClassHint(display, win->id, &ch)) {
1182                 /*fprintf(stderr, "class: %s name: %s\n", ch.res_class, ch.res_name); */
1183                 if (!strcmp(ch.res_class, "MPlayer") && !strcmp(ch.res_name, "xv")) {
1184                         win->floating = 1;
1185                 }
1186                 if(ch.res_class)
1187                         XFree(ch.res_class);
1188                 if(ch.res_name)
1189                         XFree(ch.res_name);
1190         }
1191
1192         XSelectInput(display, id, ButtonPressMask | EnterWindowMask |
1193             FocusChangeMask | ExposureMask);
1194
1195         return (win);
1196 }
1197
1198 void
1199 configurerequest(XEvent *e)
1200 {
1201         XConfigureRequestEvent  *ev = &e->xconfigurerequest;
1202         struct ws_win           *win;
1203         int                     new = 1;
1204         XWindowChanges          wc;
1205
1206         TAILQ_FOREACH (win, &ws[current_ws].winlist, entry) {
1207                 if (win->id == ev->window) {
1208                         new = 0;
1209                         break;
1210                 }
1211         }
1212
1213         if (new) {
1214                 DNPRINTF(SWM_D_EVENT, "configurerequest: new window: %lu\n",
1215                     ev->window);
1216                 bzero(&wc, sizeof wc);
1217                 wc.x = ev->x;
1218                 wc.y = ev->y;
1219                 wc.width = ev->width;
1220                 wc.height = ev->height;
1221                 wc.border_width = ev->border_width;
1222                 wc.sibling = ev->above;
1223                 wc.stack_mode = ev->detail;
1224                 XConfigureWindow(display, ev->window, ev->value_mask, &wc);
1225         } else {
1226                 DNPRINTF(SWM_D_EVENT, "configurerequest: change window: %lu\n",
1227                     ev->window);
1228                 config_win(win);
1229         }
1230 }
1231
1232 void
1233 configurenotify(XEvent *e)
1234 {
1235         DNPRINTF(SWM_D_EVENT, "configurenotify: window: %lu\n",
1236             e->xconfigure.window);
1237 }
1238
1239 void
1240 destroynotify(XEvent *e)
1241 {
1242         struct ws_win           *win;
1243         XDestroyWindowEvent     *ev = &e->xdestroywindow;
1244
1245         DNPRINTF(SWM_D_EVENT, "destroynotify: window %lu\n", ev->window);
1246
1247         TAILQ_FOREACH (win, &ws[current_ws].winlist, entry) {
1248                 if (ev->window == win->id) {
1249                         /* find a window to focus */
1250                         ws[current_ws].focus = TAILQ_PREV(win,
1251                             ws_win_list, entry);
1252                         if (ws[current_ws].focus == NULL)
1253                                 ws[current_ws].focus =
1254                                     TAILQ_FIRST(&ws[current_ws].winlist);
1255                         if (win == ws[current_ws].focus)
1256                                 ws[current_ws].focus = NULL;
1257         
1258                         TAILQ_REMOVE(&ws[current_ws].winlist, win, entry);
1259                         free(win);
1260                         break;
1261                 }
1262         }
1263
1264         stack();
1265 }
1266
1267 void
1268 enternotify(XEvent *e)
1269 {
1270         XCrossingEvent          *ev = &e->xcrossing;
1271         struct ws_win           *win;
1272
1273         DNPRINTF(SWM_D_EVENT, "enternotify: window: %lu\n", ev->window);
1274
1275         if((ev->mode != NotifyNormal || ev->detail == NotifyInferior) &&
1276             ev->window != root)
1277                 return;
1278         if (ignore_enter) {
1279                 /* eat event(s) to prevent autofocus */
1280                 ignore_enter--;
1281                 return;
1282         }
1283         TAILQ_FOREACH (win, &ws[current_ws].winlist, entry) {
1284                 if (win->id == ev->window)
1285                         focus_win(win);
1286                 else
1287                         unfocus_win(win);
1288         }
1289 }
1290
1291 void
1292 focusin(XEvent *e)
1293 {
1294         XFocusChangeEvent       *ev = &e->xfocus;
1295
1296         DNPRINTF(SWM_D_EVENT, "focusin: window: %lu\n", ev->window);
1297
1298         if (ev->window == root)
1299                 return;
1300         /*
1301          * kill grab for now so that we can cut and paste , this screws up
1302          * click to focus
1303          */
1304         /*
1305         DNPRINTF(SWM_D_EVENT, "focusin: window: %lu grabbing\n", ev->window);
1306         XGrabButton(display, Button1, AnyModifier, ev->window, False,
1307             ButtonPress, GrabModeAsync, GrabModeSync, None, None);
1308         */
1309 }
1310
1311 void
1312 mappingnotify(XEvent *e)
1313 {
1314         XMappingEvent           *ev = &e->xmapping;
1315
1316         DNPRINTF(SWM_D_EVENT, "mappingnotify: window: %lu\n", ev->window);
1317
1318         XRefreshKeyboardMapping(ev);
1319         if(ev->request == MappingKeyboard)
1320                 grabkeys();
1321 }
1322
1323 void
1324 maprequest(XEvent *e)
1325 {
1326         XMapRequestEvent        *ev = &e->xmaprequest;
1327         XWindowAttributes       wa;
1328
1329         DNPRINTF(SWM_D_EVENT, "maprequest: window: %lu\n",
1330             e->xmaprequest.window);
1331
1332         if(!XGetWindowAttributes(display, ev->window, &wa))
1333                 return;
1334         if(wa.override_redirect)
1335                 return;
1336         manage_window(e->xmaprequest.window);
1337         stack();
1338 }
1339
1340 void
1341 propertynotify(XEvent *e)
1342 {
1343         DNPRINTF(SWM_D_EVENT, "propertynotify: window: %lu\n",
1344             e->xproperty.window);
1345 }
1346
1347 void
1348 unmapnotify(XEvent *e)
1349 {
1350         DNPRINTF(SWM_D_EVENT, "unmapnotify: window: %lu\n", e->xunmap.window);
1351 }
1352
1353 void
1354 visibilitynotify(XEvent *e)
1355 {
1356         DNPRINTF(SWM_D_EVENT, "visibilitynotify: window: %lu\n", e->xvisibility.window);
1357
1358         if (e->xvisibility.window == bar_window &&
1359             e->xvisibility.state == VisibilityUnobscured)
1360                 bar_print();
1361 }
1362
1363 void                    (*handler[LASTEvent])(XEvent *) = {
1364                                 [Expose] = expose,
1365                                 [KeyPress] = keypress,
1366                                 [ButtonPress] = buttonpress,
1367                                 [ConfigureRequest] = configurerequest,
1368                                 [ConfigureNotify] = configurenotify,
1369                                 [DestroyNotify] = destroynotify,
1370                                 [EnterNotify] = enternotify,
1371                                 [FocusIn] = focusin,
1372                                 [MappingNotify] = mappingnotify,
1373                                 [MapRequest] = maprequest,
1374                                 [PropertyNotify] = propertynotify,
1375                                 [UnmapNotify] = unmapnotify,
1376                                 [VisibilityNotify] = visibilitynotify,
1377 };
1378
1379 int
1380 xerror_start(Display *d, XErrorEvent *ee)
1381 {
1382         other_wm = 1;
1383         return (-1);
1384 }
1385
1386 int
1387 xerror(Display *d, XErrorEvent *ee)
1388 {
1389         fprintf(stderr, "error: %p %p\n", display, ee);
1390
1391         return (-1);
1392 }
1393
1394 int
1395 active_wm(void)
1396 {
1397         other_wm = 0;
1398         xerrorxlib = XSetErrorHandler(xerror_start);
1399
1400         /* this causes an error if some other window manager is running */
1401         XSelectInput(display, DefaultRootWindow(display),
1402             SubstructureRedirectMask);
1403         XSync(display, False);
1404         if(other_wm)
1405                 return (1);
1406
1407         XSetErrorHandler(xerror);
1408         XSync(display, False);
1409         return (0);
1410 }
1411
1412 int
1413 main(int argc, char *argv[])
1414 {
1415         struct passwd           *pwd;
1416         char                    conf[PATH_MAX], *cfile = NULL;
1417         struct stat             sb;
1418         XEvent                  e;
1419         unsigned int            i, j, num;
1420         Window                  d1, d2, *wins = NULL;
1421         XWindowAttributes       wa;
1422
1423         start_argv = argv;
1424         fprintf(stderr, "Welcome to scrotwm V%s\n", SWM_VERSION);
1425         if(!setlocale(LC_CTYPE, "") || !XSupportsLocale())
1426                 warnx("no locale support");
1427
1428         if(!(display = XOpenDisplay(0)))
1429                 errx(1, "can not open display");
1430
1431         if (active_wm())
1432                 errx(1, "other wm running");
1433
1434         screen = DefaultScreen(display);
1435         root = RootWindow(display, screen);
1436
1437         /* look for local and global conf file */
1438         pwd = getpwuid(getuid());
1439         if (pwd == NULL)
1440                 errx(1, "invalid user %d", getuid());
1441
1442         snprintf(conf, sizeof conf, "%s/.%s", pwd->pw_dir, SWM_CONF_FILE);
1443         if (stat(conf, &sb) != -1) {
1444                 if (S_ISREG(sb.st_mode))
1445                         cfile = conf;
1446         } else {
1447                 /* try global conf file */
1448                 snprintf(conf, sizeof conf, "/etc/%s", SWM_CONF_FILE);
1449                 if (!stat(conf, &sb))
1450                         if (S_ISREG(sb.st_mode))
1451                                 cfile = conf;
1452         }
1453         if (cfile)
1454                 conf_load(cfile);
1455
1456         /* init all workspaces */
1457         for (i = 0; i < SWM_WS_MAX; i++) {
1458                 ws[i].visible = 0;
1459                 ws[i].restack = 1;
1460                 ws[i].focus = NULL;
1461                 ws[i].g.x = 0;
1462                 ws[i].g.y = 0;
1463                 ws[i].g.w = DisplayWidth(display, screen) - 2;
1464                 ws[i].g.h = DisplayHeight(display, screen) - 2;
1465                 TAILQ_INIT(&ws[i].winlist);
1466
1467                 for (j = 0; layouts[j].l_stack != NULL; j++) {
1468                         if (layouts[j].l_init != NULL)
1469                                 layouts[j].l_init(i);
1470                 }
1471                 ws[i].cur_layout = &layouts[0];
1472         }
1473         /* make work space 1 active */
1474         ws[0].visible = 1;
1475
1476         /* grab existing windows */
1477         if (XQueryTree(display, root, &d1, &d2, &wins, &num)) {
1478                 for (i = 0; i < num; i++) {
1479                         if (!XGetWindowAttributes(display, wins[i], &wa)
1480                             || wa.override_redirect
1481                             || wa.map_state != IsViewable)
1482                                 continue;
1483                         manage_window(wins[i]);
1484                 }
1485                 if(wins)
1486                         XFree(wins);
1487         }
1488         ws[0].focus = TAILQ_FIRST(&ws[0].winlist);
1489
1490         /* setup status bar */
1491         bar_setup();
1492
1493         XSelectInput(display, root, SubstructureRedirectMask |
1494             SubstructureNotifyMask | ButtonPressMask | KeyPressMask |
1495             EnterWindowMask | LeaveWindowMask | StructureNotifyMask |
1496             FocusChangeMask | PropertyChangeMask | ExposureMask);
1497
1498         grabkeys();
1499         stack();
1500
1501         while (running) {
1502                 XNextEvent(display, &e);
1503                 if (handler[e.type])
1504                         handler[e.type](&e);
1505         }
1506
1507         XCloseDisplay(display);
1508
1509         return (0);
1510 }