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