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