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