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