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