JasonWoof Got questions, comments, patches, etc.? Contact Jason Woofenden
Initial bits of support for different layouts, needs more splitting out of
[spectrwm.git] / scrotwm.c
1 /* $scrotwm$ */
2 /*
3  * Copyright (c) 2009 Marco Peereboom <marco@peereboom.us>
4  * Copyright (c) 2009 Ryan McBride <mcbride@countersiege.com>
5  *
6  * Permission to use, copy, modify, and distribute this software for any
7  * purpose with or without fee is hereby granted, provided that the above
8  * copyright notice and this permission notice appear in all copies.
9  *
10  * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
11  * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
12  * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
13  * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
14  * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
15  * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
16  * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
17  */
18 /*
19  * Much code and ideas taken from dwm under the following license:
20  * MIT/X Consortium License
21  * 
22  * 2006-2008 Anselm R Garbe <garbeam at gmail dot com>
23  * 2006-2007 Sander van Dijk <a dot h dot vandijk at gmail dot com>
24  * 2006-2007 Jukka Salmi <jukka at salmi dot ch>
25  * 2007 Premysl Hruby <dfenze at gmail dot com>
26  * 2007 Szabolcs Nagy <nszabolcs at gmail dot com>
27  * 2007 Christof Musik <christof at sendfax dot de>
28  * 2007-2008 Enno Gottox Boland <gottox at s01 dot de>
29  * 2007-2008 Peter Hartlich <sgkkr at hartlich dot com>
30  * 2008 Martin Hurton <martin dot hurton at gmail dot com>
31  * 
32  * Permission is hereby granted, free of charge, to any person obtaining a
33  * copy of this software and associated documentation files (the "Software"),
34  * to deal in the Software without restriction, including without limitation
35  * the rights to use, copy, modify, merge, publish, distribute, sublicense,
36  * and/or sell copies of the Software, and to permit persons to whom the
37  * Software is furnished to do so, subject to the following conditions:
38  * 
39  * The above copyright notice and this permission notice shall be included in
40  * all copies or substantial portions of the Software.
41  * 
42  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
43  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
44  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
45  * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
46  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
47  * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
48  * DEALINGS IN THE SOFTWARE.
49  */
50
51 #define SWM_VERSION     "0.5"
52
53 #include <stdio.h>
54 #include <stdlib.h>
55 #include <err.h>
56 #include <locale.h>
57 #include <unistd.h>
58 #include <time.h>
59 #include <signal.h>
60 #include <string.h>
61 #include <util.h>
62 #include <pwd.h>
63
64 #include <sys/types.h>
65 #include <sys/stat.h>
66 #include <sys/wait.h>
67 #include <sys/queue.h>
68 #include <sys/param.h>
69
70 #include <X11/cursorfont.h>
71 #include <X11/keysym.h>
72 #include <X11/Xatom.h>
73 #include <X11/Xlib.h>
74 #include <X11/Xproto.h>
75 #include <X11/Xutil.h>
76
77 /* #define SWM_DEBUG */
78 #ifdef SWM_DEBUG
79 #define DPRINTF(x...)           do { if (swm_debug) fprintf(stderr, x); } while(0)
80 #define DNPRINTF(n,x...)        do { if (swm_debug & n) fprintf(stderr, x); } while(0)
81 #define SWM_D_MISC              0x0001
82 #define SWM_D_EVENT             0x0002
83 #define SWM_D_WS                0x0004
84 #define SWM_D_FOCUS             0x0008
85 #define SWM_D_MOVE              0x0010
86
87 u_int32_t               swm_debug = 0
88                             | SWM_D_MISC
89                             | SWM_D_EVENT
90                             | SWM_D_WS
91                             | SWM_D_FOCUS
92                             | SWM_D_MOVE
93                             ;
94 #else
95 #define DPRINTF(x...)
96 #define DNPRINTF(n,x...)
97 #endif
98
99 #define LENGTH(x)               (sizeof x / sizeof x[0])
100 #define MODKEY                  Mod1Mask
101 #define CLEANMASK(mask)         (mask & ~(numlockmask | LockMask))
102
103 int                     (*xerrorxlib)(Display *, XErrorEvent *);
104 int                     other_wm;
105 int                     screen;
106 int                     width, height;
107 int                     running = 1;
108 int                     ignore_enter = 0;
109 unsigned int            numlockmask = 0;
110 unsigned long           color_focus = 0xff0000; /* XXX should this be per ws? */
111 unsigned long           color_unfocus = 0x888888;
112 Display                 *display;
113 Window                  root;
114
115 /* status bar */
116 int                     bar_enabled = 1;
117 int                     bar_height = 0;
118 unsigned long           bar_border = 0x008080;
119 unsigned long           bar_color = 0x000000;
120 unsigned long           bar_font_color = 0xa0a0a0;
121 Window                  bar_window;
122 GC                      bar_gc;
123 XGCValues               bar_gcv;
124 XFontStruct             *bar_fs;
125 char                    bar_text[128];
126 char                    *bar_fonts[] = {
127                             "-*-terminus-*-*-*-*-*-*-*-*-*-*-*-*",
128                             "-*-times-medium-r-*-*-*-*-*-*-*-*-*-*",
129                             NULL
130 };
131
132 /* terminal + args */
133 char                            *spawn_term[] = { "xterm", NULL };
134 char                            *spawn_menu[] = { "dmenu_run", NULL };
135 char                            *spawn_scrotwm[] = { "scrotwm", NULL };
136
137 /* layout manager data */
138 void    stack(void);
139 void    vertical_init(void);
140 void    vertical_stack(void);
141 void    horizontal_init(void);
142 void    horizontal_stack(void);
143 void    max_init(void);
144 void    max_stack(void);
145
146 struct layout {
147         void                    (*l_init)(void);        /* init/reset */
148         void                    (*l_stack)(void);       /* restack windows */
149 } layouts[] =  {
150         /* init                 stack */
151         { vertical_init,        vertical_stack},
152         { horizontal_init,      horizontal_stack},
153         /* XXX not working yet
154          * { max_init,          max_stack},
155          */
156         { NULL,                 NULL},
157 };
158
159 struct ws_win {
160         TAILQ_ENTRY(ws_win)     entry;
161         Window                  id;
162         int                     x;
163         int                     y;
164         int                     width;
165         int                     height;
166         int                     floating;
167         int                     transient;
168         XWindowAttributes       wa;
169 };
170
171 TAILQ_HEAD(ws_win_list, ws_win);
172
173 /* define work spaces */
174 #define SWM_WS_MAX              (10)
175 struct workspace {
176         int                     visible;        /* workspace visible */
177         int                     restack;        /* restack on switch */
178         struct layout           *cur_layout;    /* current layout handlers */
179         struct ws_win           *focus;         /* which win has focus */
180         struct ws_win_list      winlist;        /* list of windows in ws */
181 } ws[SWM_WS_MAX];
182 int                     current_ws = 0;
183
184 /* args to functions */
185 union arg {
186         int                     id;
187 #define SWM_ARG_ID_FOCUSNEXT    (0)
188 #define SWM_ARG_ID_FOCUSPREV    (1)
189 #define SWM_ARG_ID_FOCUSMAIN    (2)
190 #define SWM_ARG_ID_SWAPNEXT     (3)
191 #define SWM_ARG_ID_SWAPPREV     (4)
192 #define SWM_ARG_ID_SWAPMAIN     (5)
193         char                    **argv;
194 };
195
196
197
198 #define SWM_CONF_WS     "\n= \t"
199 #define SWM_CONF_FILE   "scrotwm.conf"
200 int
201 conf_load(char *filename)
202 {
203         FILE                    *config;
204         char                    *line, *cp, *var, *val;
205         size_t                   len, lineno = 0;
206
207         DNPRINTF(SWM_D_MISC, "conf_load: filename %s\n", filename);
208
209         if (filename == NULL)
210                 return (1);
211
212         if ((config = fopen(filename, "r")) == NULL)
213                 return (1);
214
215         for (;;) {
216                 if ((line = fparseln(config, &len, &lineno, NULL, 0)) == NULL)
217                         if (feof(config))
218                                 break;
219                 cp = line;
220                 cp += (long)strspn(cp, SWM_CONF_WS);
221                 if (cp[0] == '\0') {
222                         /* empty line */
223                         free(line);
224                         continue;
225                 }
226                 if ((var = strsep(&cp, SWM_CONF_WS)) == NULL || cp == NULL)
227                         break;
228                 cp += (long)strspn(cp, SWM_CONF_WS);
229                 if ((val = strsep(&cp, SWM_CONF_WS)) == NULL)
230                         break;
231
232                 DNPRINTF(SWM_D_MISC, "conf_load: %s=%s\n",var ,val);
233                 switch (var[0]) {
234                 case 'b':
235                         if (!strncmp(var, "bar_enabled", strlen("bar_enabled")))
236                                 bar_enabled = atoi(val);
237                         else if (!strncmp(var, "bar_border",
238                             strlen("bar_border")))
239                                 bar_border = strtol(val, NULL, 16);
240                         else if (!strncmp(var, "bar_color",
241                             strlen("bar_color")))
242                                 bar_color = strtol(val, NULL, 16);
243                         else if (!strncmp(var, "bar_font_color",
244                             strlen("bar_font_color")))
245                                 bar_font_color = strtol(val, NULL, 16);
246                         else if (!strncmp(var, "bar_font", strlen("bar_font")))
247                                 asprintf(&bar_fonts[0], "%s", val);
248                         else
249                                 goto bad;
250                         break;
251
252                 case 'c':
253                         if (!strncmp(var, "color_focus", strlen("color_focus")))
254                                 color_focus = strtol(val, NULL, 16);
255                         else if (!strncmp(var, "color_unfocus",
256                             strlen("color_unfocus")))
257                                 color_unfocus = strtol(val, NULL, 16);
258                         else
259                                 goto bad;
260                         break;
261
262                 case 's':
263                         if (!strncmp(var, "spawn_term", strlen("spawn_term")))
264                                 asprintf(&spawn_term[0], "%s", val); /* XXX args? */
265                         break;
266                 default:
267                         goto bad;
268                 }
269                 free(line);
270         }
271
272         fclose(config);
273         return (0);
274 bad:
275         errx(1, "invalid conf file entry: %s=%s", var, val);
276 }
277
278 void
279 bar_print(void)
280 {
281         time_t                  tmt;
282         struct tm               tm;
283
284         if (bar_enabled == 0)
285                 return;
286
287         /* clear old text */
288         XSetForeground(display, bar_gc, bar_color);
289         XDrawString(display, bar_window, bar_gc, 4, bar_fs->ascent, bar_text,
290             strlen(bar_text));
291
292         /* draw new text */
293         time(&tmt);
294         localtime_r(&tmt, &tm);
295         strftime(bar_text, sizeof bar_text, "%a %b %d %R %Z %Y", &tm);
296         XSetForeground(display, bar_gc, bar_font_color);
297         XDrawString(display, bar_window, bar_gc, 4, bar_fs->ascent, bar_text,
298             strlen(bar_text));
299         XSync(display, False);
300
301         alarm(60);
302 }
303
304 void
305 bar_signal(int sig)
306 {
307         /* XXX yeah yeah byte me */
308         bar_print();
309 }
310
311 void
312 bar_toggle(union arg *args)
313 {
314         int i;
315
316         DNPRINTF(SWM_D_MISC, "bar_toggle\n");
317
318         if (bar_enabled) {
319                 bar_enabled = 0;
320                 height += bar_height; /* correct screen height */
321                 XUnmapWindow(display, bar_window);
322         } else {
323                 bar_enabled = 1;
324                 height -= bar_height; /* correct screen height */
325                 XMapWindow(display, bar_window);
326         }
327         XSync(display, False);
328         for (i = 0; i < SWM_WS_MAX; i++)
329                 ws[i].restack = 1;
330
331         stack();
332         bar_print(); /* must be after stack */
333 }
334
335 void
336 bar_setup(void)
337 {
338         int                     i;
339
340         for (i = 0; bar_fonts[i] != NULL; i++) {
341                 bar_fs = XLoadQueryFont(display, bar_fonts[i]);
342                 if (bar_fs)
343                         break;
344         }
345         if (bar_fonts[i] == NULL)
346                         errx(1, "couldn't load font");
347         bar_height = bar_fs->ascent + bar_fs->descent + 3;
348
349         bar_window = XCreateSimpleWindow(display, root, 0, 0, width,
350             bar_height - 2, 1, bar_border, bar_color);
351         bar_gc = XCreateGC(display, bar_window, 0, &bar_gcv);
352         XSetFont(display, bar_gc, bar_fs->fid);
353         XSelectInput(display, bar_window, VisibilityChangeMask);
354         if (bar_enabled) {
355                 height -= bar_height; /* correct screen height */
356                 XMapWindow(display, bar_window);
357         }
358         DNPRINTF(SWM_D_MISC, "bar_setup: bar_window %d\n", (int)bar_window);
359
360         if (signal(SIGALRM, bar_signal) == SIG_ERR)
361                 err(1, "could not install bar_signal");
362         bar_print();
363 }
364
365 int
366 count_win(int wsid, int count_transient)
367 {
368         struct ws_win           *win;
369         int                     count = 0;
370
371         TAILQ_FOREACH (win, &ws[wsid].winlist, entry) {
372                 if (count_transient == 0 && win->transient)
373                         continue;
374                 count++;
375         }
376         DNPRINTF(SWM_D_MISC, "count_win: %d\n", count);
377
378         return (count);
379 }
380 void
381 quit(union arg *args)
382 {
383         DNPRINTF(SWM_D_MISC, "quit\n");
384         running = 0;
385 }
386
387
388 void
389 restart(union arg *args)
390 {       
391         XCloseDisplay(display);
392         execvp(args->argv[0], args->argv);
393         fprintf(stderr, "execvp failed\n");
394         perror(" failed");
395         quit(NULL);
396 }
397
398 void
399 spawn(union arg *args)
400 {
401         DNPRINTF(SWM_D_MISC, "spawn: %s\n", args->argv[0]);
402         /*
403          * The double-fork construct avoids zombie processes and keeps the code
404          * clean from stupid signal handlers.
405          */
406         if(fork() == 0) {
407                 if(fork() == 0) {
408                         if(display)
409                                 close(ConnectionNumber(display));
410                         setsid();
411                         execvp(args->argv[0], args->argv);
412                         fprintf(stderr, "execvp failed\n");
413                         perror(" failed");
414                 }
415                 exit(0);
416         }
417         wait(0);
418 }
419
420 void
421 focus_win(struct ws_win *win)
422 {
423         DNPRINTF(SWM_D_FOCUS, "focus_win: id: %lu\n", win->id);
424         XSetWindowBorder(display, win->id, color_focus);
425         XSetInputFocus(display, win->id, RevertToPointerRoot, CurrentTime);
426         ws[current_ws].focus = win;
427 }
428
429 void
430 unfocus_win(struct ws_win *win)
431 {
432         DNPRINTF(SWM_D_FOCUS, "unfocus_win: id: %lu\n", win->id);
433         XSetWindowBorder(display, win->id, color_unfocus);
434         if (ws[current_ws].focus == win)
435                 ws[current_ws].focus = NULL;
436 }
437
438 void
439 switchws(union arg *args)
440 {
441         int                     wsid = args->id;
442         struct ws_win           *win;
443
444         DNPRINTF(SWM_D_WS, "switchws: %d\n", wsid + 1);
445
446         if (wsid == current_ws)
447                 return;
448
449         /* map new window first to prevent ugly blinking */
450         TAILQ_FOREACH (win, &ws[wsid].winlist, entry)
451                 XMapRaised(display, win->id);
452         ws[wsid].visible = 1;
453
454         TAILQ_FOREACH (win, &ws[current_ws].winlist, entry)
455                 XUnmapWindow(display, win->id);
456         ws[current_ws].visible = 0;
457
458         current_ws = wsid;
459
460         ignore_enter = 1;
461         if (ws[wsid].restack) {
462                 stack();
463                 bar_print();
464         } else {
465                 if (ws[wsid].focus != NULL)
466                         focus_win(ws[wsid].focus);
467                 XSync(display, False);
468         }
469 }
470
471 void
472 swapwin(union arg *args)
473 {
474         struct ws_win           *target;
475
476         DNPRINTF(SWM_D_MOVE, "swapwin: id %d\n", args->id);
477         if (ws[current_ws].focus == NULL)
478                 return;
479
480         switch (args->id) {
481         case SWM_ARG_ID_SWAPPREV:
482                 target = TAILQ_PREV(ws[current_ws].focus, ws_win_list, entry);
483                 TAILQ_REMOVE(&ws[current_ws].winlist,
484                     ws[current_ws].focus, entry);
485                 if (target == NULL)
486                         TAILQ_INSERT_TAIL(&ws[current_ws].winlist,
487                             ws[current_ws].focus, entry);
488                 else
489                         TAILQ_INSERT_BEFORE(target, ws[current_ws].focus,
490                             entry);
491                 break;
492         case SWM_ARG_ID_SWAPNEXT: 
493                 target = TAILQ_NEXT(ws[current_ws].focus, entry);
494                 TAILQ_REMOVE(&ws[current_ws].winlist,
495                     ws[current_ws].focus, entry);
496                 if (target == NULL)
497                         TAILQ_INSERT_HEAD(&ws[current_ws].winlist,
498                             ws[current_ws].focus, entry);
499                 else
500                         TAILQ_INSERT_AFTER(&ws[current_ws].winlist, target,
501                             ws[current_ws].focus, entry);
502                 break;
503         case SWM_ARG_ID_SWAPMAIN:
504                 target = TAILQ_FIRST(&ws[current_ws].winlist);
505                 if (target == ws[current_ws].focus)
506                         return;
507                 TAILQ_REMOVE(&ws[current_ws].winlist, target, entry);
508                 TAILQ_INSERT_BEFORE(ws[current_ws].focus, target, entry);
509                 TAILQ_REMOVE(&ws[current_ws].winlist,
510                     ws[current_ws].focus, entry);
511                 TAILQ_INSERT_HEAD(&ws[current_ws].winlist,
512                     ws[current_ws].focus, entry);
513                 break;
514         default:
515                 DNPRINTF(SWM_D_MOVE, "invalid id: %d\n", args->id);
516                 return;
517         }
518
519         ignore_enter = 2;
520         stack();
521 }
522
523 void
524 focus(union arg *args)
525 {
526         struct ws_win           *winfocus, *winlostfocus;
527
528         DNPRINTF(SWM_D_FOCUS, "focus: id %d\n", args->id);
529         if (ws[current_ws].focus == NULL)
530                 return;
531
532         winlostfocus = ws[current_ws].focus;
533
534         switch (args->id) {
535         case SWM_ARG_ID_FOCUSPREV:
536                 winfocus = TAILQ_PREV(ws[current_ws].focus, ws_win_list, entry);
537                 if (winfocus == NULL)
538                         winfocus =
539                             TAILQ_LAST(&ws[current_ws].winlist, ws_win_list);
540                 break;
541
542         case SWM_ARG_ID_FOCUSNEXT:
543                 winfocus = TAILQ_NEXT(ws[current_ws].focus, entry);
544                 if (winfocus == NULL)
545                         winfocus = TAILQ_FIRST(&ws[current_ws].winlist);
546                 break;
547
548         case SWM_ARG_ID_FOCUSMAIN:
549                 winfocus = TAILQ_FIRST(&ws[current_ws].winlist);
550                 break;
551
552         default:
553                 return;
554         }
555
556         if (winfocus == winlostfocus)
557                 return;
558
559         unfocus_win(winlostfocus);
560         focus_win(winfocus);
561         XSync(display, False);
562 }
563
564 void
565 cycle_layout(union arg *args)
566 {
567         DNPRINTF(SWM_D_EVENT, "cycle_layout: workspace: %d\n", current_ws);
568
569         ws[current_ws].cur_layout++;
570         if (ws[current_ws].cur_layout->l_stack == NULL)
571                 ws[current_ws].cur_layout = &layouts[0];
572         stack();
573 }
574
575 void
576 stack(void) {
577         DNPRINTF(SWM_D_EVENT, "stack: workspace: %d\n", current_ws);
578
579         ws[current_ws].restack = 0;
580
581         ws[current_ws].cur_layout->l_stack();
582
583         XSync(display, False);
584 }
585
586 void
587 vertical_init(void)
588 {
589         DNPRINTF(SWM_D_EVENT, "vertical_init: workspace: %d\n", current_ws);
590 }
591
592 /* I know this sucks but it works well enough */
593 void
594 vertical_stack(void) {
595         XWindowChanges          wc;
596         struct ws_win           wf, *win, *winfocus = &wf;
597         int                     i, h, w, x, y, hrh, winno;
598         int floater = 0;
599         unsigned int mask;
600
601         DNPRINTF(SWM_D_EVENT, "vertical_stack: workspace: %d\n", current_ws);
602
603         winfocus->id = root;
604
605         winno = count_win(current_ws, 0);
606         if (winno == 0)
607                 return;
608
609         if (winno > 1)
610                 w = width / 2;
611         else
612                 w = width;
613
614         if (winno > 2)
615                 hrh = height / (winno - 1);
616         else
617                 hrh = 0;
618
619         x = 0;
620         y = bar_enabled ? bar_height : 0;
621         h = height;
622         i = 0;
623         TAILQ_FOREACH (win, &ws[current_ws].winlist, entry) {
624                 if (i == 1) {
625                         x += w + 2;
626                         w -= 2;
627                 }
628                 if (i != 0 && hrh != 0) {
629                         /* correct the last window for lost pixels */
630                         if (win == TAILQ_LAST(&ws[current_ws].winlist,
631                             ws_win_list)) {
632                                 h = height - (i * hrh);
633                                 if (h == 0)
634                                         h = hrh;
635                                 else
636                                         h += hrh;
637                                 y += hrh;
638                         } else {
639                                 h = hrh - 2;
640                                 /* leave first right hand window at y = 0 */
641                                 if (i > 1)
642                                         y += h + 2;
643                         }
644                 }
645
646                 if (win->transient != 0 || win->floating != 0)
647                         floater = 1;
648                 else
649                         floater = 0;
650
651                 bzero(&wc, sizeof wc);
652                 wc.border_width = 1;
653                 if (floater == 0) {
654                         win->x = wc.x = x;
655                         win->y = wc.y = y;
656                         win->width = wc.width = w;
657                         win->height = wc.height = h;
658                         mask = CWX | CWY | CWWidth | CWHeight | CWBorderWidth;
659                 } else {
660                         /* make sure we don't clobber the screen */
661                         if (win->wa.width > width)
662                                 win->wa.width = width;
663                         if (win->wa.height > height)
664                                 win->wa.width = height;
665                         win->x = wc.x = (width - win->wa.width) / 2;
666                         win->y = wc.y = (height - win->wa.height) / 2;
667                         mask = CWX | CWY | CWBorderWidth;
668                 }
669                 XConfigureWindow(display, win->id, mask, &wc);
670
671                 if (win == ws[current_ws].focus)
672                         winfocus = win;
673                 else
674                         unfocus_win(win);
675                 XMapRaised(display, win->id);
676                 i++;
677         }
678
679         focus_win(winfocus); /* this has to be done outside of the loop */
680 }
681
682 void
683 horizontal_init(void)
684 {
685         DNPRINTF(SWM_D_EVENT, "horizontal_init: workspace: %d\n", current_ws);
686 }
687
688 void
689 horizontal_stack(void) {
690         XWindowChanges          wc;
691         struct ws_win           wf, *win, *winfocus = &wf;
692         int                     i, h, w, x, y, hrw, winno;
693         int floater = 0;
694         unsigned int mask;
695
696         DNPRINTF(SWM_D_EVENT, "horizontal_stack: workspace: %d\n", current_ws);
697
698         winfocus->id = root;
699
700         winno = count_win(current_ws, 0);
701         if (winno == 0)
702                 return;
703
704         if (winno > 1)
705                 h = height / 2;
706         else
707                 h = height;
708
709         if (winno > 2)
710                 hrw = width / (winno - 1);
711         else
712                 hrw = 0;
713
714         x = 0;
715         y = bar_enabled ? bar_height : 0;
716         w = width;
717         i = 0;
718         TAILQ_FOREACH (win, &ws[current_ws].winlist, entry) {
719                 if (i == 1) {
720                         y += h + 2;
721                         h -= 2;
722                 }
723                 if (i != 0 && hrw != 0) {
724                         /* correct the last window for lost pixels */
725                         if (win == TAILQ_LAST(&ws[current_ws].winlist,
726                             ws_win_list)) {
727                                 w = width - (i * hrw);
728                                 if (w == 0)
729                                         w = hrw;
730                                 else
731                                         w += hrw;
732                                 x += hrw;
733                         } else {
734                                 w = hrw - 2;
735                                 /* leave first bottom window at x = 0 */
736                                 if (i > 1)
737                                         x += w + 2;
738                         }
739                 }
740
741                 if (win->transient != 0 || win->floating != 0)
742                         floater = 1;
743                 else
744                         floater = 0;
745
746                 bzero(&wc, sizeof wc);
747                 wc.border_width = 1;
748                 if (floater == 0) {
749                         win->x = wc.x = x;
750                         win->y = wc.y = y;
751                         win->width = wc.width = w;
752                         win->height = wc.height = h;
753                         mask = CWX | CWY | CWWidth | CWHeight | CWBorderWidth;
754                 } else {
755                         /* make sure we don't clobber the screen */
756                         if (win->wa.width > width)
757                                 win->wa.width = width;
758                         if (win->wa.height > height)
759                                 win->wa.width = height;
760                         win->x = wc.x = (width - win->wa.width) / 2;
761                         win->y = wc.y = (height - win->wa.height) / 2;
762                         mask = CWX | CWY | CWBorderWidth;
763                 }
764                 XConfigureWindow(display, win->id, mask, &wc);
765
766                 if (win == ws[current_ws].focus)
767                         winfocus = win;
768                 else
769                         unfocus_win(win);
770                 XMapRaised(display, win->id);
771                 i++;
772         }
773
774         focus_win(winfocus); /* this has to be done outside of the loop */
775 }
776
777 /* fullscreen view */
778 void
779 max_init(void)
780 {
781         DNPRINTF(SWM_D_EVENT, "max_init: workspace: %d\n", current_ws);
782 }
783
784 void
785 max_stack(void) {
786         XWindowChanges          wc;
787         struct ws_win           wf, *win, *winfocus = &wf;
788         int                     i, h, w, x, y, winno;
789         unsigned int mask;
790
791         DNPRINTF(SWM_D_EVENT, "max_stack: workspace: %d\n", current_ws);
792
793         winfocus->id = root;
794
795         winno = count_win(current_ws, 0);
796         if (winno == 0)
797                 return;
798
799         x = 0;
800         y = bar_enabled ? bar_height : 0;
801         TAILQ_FOREACH (win, &ws[current_ws].winlist, entry) {
802                 if (i == 1 && win->transient == 0 && win->floating != 0) {
803                         h = height - 2;
804                         w = width - 2;
805
806                         winfocus = win;
807
808                         bzero(&wc, sizeof wc);
809                         wc.border_width = 1;
810                         win->x = wc.x = x;
811                         win->y = wc.y = y;
812                         win->width = wc.width = w;
813                         win->height = wc.height = h;
814                         mask = CWX | CWY | CWWidth | CWHeight | CWBorderWidth;
815                         XConfigureWindow(display, win->id, mask, &wc);
816
817                         XMapRaised(display, win->id);
818                 } else {
819                         /* hide all but the master window */
820                         XUnmapWindow(display, win->id);
821                 }
822                 i++;
823         }
824
825         focus_win(winfocus); /* this has to be done outside of the loop */
826 }
827
828 void
829 send_to_ws(union arg *args)
830 {
831         int                     wsid = args->id;
832         struct ws_win           *win = ws[current_ws].focus;
833
834         DNPRINTF(SWM_D_MOVE, "send_to_ws: win: %lu\n", win->id);
835
836         XUnmapWindow(display, win->id);
837
838         /* find a window to focus */
839         ws[current_ws].focus = TAILQ_PREV(win, ws_win_list, entry);
840         if (ws[current_ws].focus == NULL)
841                 ws[current_ws].focus = TAILQ_FIRST(&ws[current_ws].winlist);
842         if (ws[current_ws].focus == win)
843                 ws[current_ws].focus = NULL;
844
845         TAILQ_REMOVE(&ws[current_ws].winlist, win, entry);
846
847         TAILQ_INSERT_TAIL(&ws[wsid].winlist, win, entry);
848         if (count_win(wsid, 1) == 0)
849                 ws[wsid].focus = win;
850         ws[wsid].restack = 1;
851
852         stack();
853 }
854
855 /* key definitions */
856 struct key {
857         unsigned int            mod;
858         KeySym                  keysym;
859         void                    (*func)(union arg *);
860         union arg               args;
861 } keys[] = {
862         /* modifier             key     function                argument */
863         /* XXX alt-c is temporary, until I figure out how to grab spacebar */
864         { MODKEY,               XK_c,           cycle_layout,   {0} }, 
865         { MODKEY,               XK_Return,      swapwin,        {.id = SWM_ARG_ID_SWAPMAIN} },
866         { MODKEY,               XK_j,           focus,          {.id = SWM_ARG_ID_FOCUSNEXT} },
867         { MODKEY,               XK_k,           focus,          {.id = SWM_ARG_ID_FOCUSPREV} },
868         { MODKEY | ShiftMask,   XK_j,           swapwin,        {.id = SWM_ARG_ID_SWAPNEXT} },
869         { MODKEY | ShiftMask,   XK_k,           swapwin,        {.id = SWM_ARG_ID_SWAPPREV} },
870         { MODKEY | ShiftMask,   XK_Return,      spawn,          {.argv = spawn_term} },
871         { MODKEY,               XK_p,           spawn,          {.argv = spawn_menu} },
872         { MODKEY | ShiftMask,   XK_q,           quit,           {0} },
873         { MODKEY,               XK_q,           restart,        {.argv = spawn_scrotwm } },
874         { MODKEY,               XK_m,           focus,          {.id = SWM_ARG_ID_FOCUSMAIN} },
875         { MODKEY,               XK_1,           switchws,       {.id = 0} },
876         { MODKEY,               XK_2,           switchws,       {.id = 1} },
877         { MODKEY,               XK_3,           switchws,       {.id = 2} },
878         { MODKEY,               XK_4,           switchws,       {.id = 3} },
879         { MODKEY,               XK_5,           switchws,       {.id = 4} },
880         { MODKEY,               XK_6,           switchws,       {.id = 5} },
881         { MODKEY,               XK_7,           switchws,       {.id = 6} },
882         { MODKEY,               XK_8,           switchws,       {.id = 7} },
883         { MODKEY,               XK_9,           switchws,       {.id = 8} },
884         { MODKEY,               XK_0,           switchws,       {.id = 9} },
885         { MODKEY | ShiftMask,   XK_1,           send_to_ws,     {.id = 0} },
886         { MODKEY | ShiftMask,   XK_2,           send_to_ws,     {.id = 1} },
887         { MODKEY | ShiftMask,   XK_3,           send_to_ws,     {.id = 2} },
888         { MODKEY | ShiftMask,   XK_4,           send_to_ws,     {.id = 3} },
889         { MODKEY | ShiftMask,   XK_5,           send_to_ws,     {.id = 4} },
890         { MODKEY | ShiftMask,   XK_6,           send_to_ws,     {.id = 5} },
891         { MODKEY | ShiftMask,   XK_7,           send_to_ws,     {.id = 6} },
892         { MODKEY | ShiftMask,   XK_8,           send_to_ws,     {.id = 7} },
893         { MODKEY | ShiftMask,   XK_9,           send_to_ws,     {.id = 8} },
894         { MODKEY | ShiftMask,   XK_0,           send_to_ws,     {.id = 9} },
895         { MODKEY,               XK_b,           bar_toggle,     {0} },
896         { MODKEY,               XK_Tab,         focus,          {.id = SWM_ARG_ID_FOCUSNEXT} },
897         { MODKEY | ShiftMask,   XK_Tab,         focus,          {.id = SWM_ARG_ID_FOCUSPREV} },
898 };
899
900 void
901 updatenumlockmask(void)
902 {
903         unsigned int            i, j;
904         XModifierKeymap         *modmap;
905
906         DNPRINTF(SWM_D_MISC, "updatenumlockmask\n");
907         numlockmask = 0;
908         modmap = XGetModifierMapping(display);
909         for (i = 0; i < 8; i++)
910                 for (j = 0; j < modmap->max_keypermod; j++)
911                         if (modmap->modifiermap[i * modmap->max_keypermod + j]
912                           == XKeysymToKeycode(display, XK_Num_Lock))
913                                 numlockmask = (1 << i);
914
915         XFreeModifiermap(modmap);
916 }
917
918 void
919 grabkeys(void)
920 {
921         unsigned int            i, j;
922         KeyCode                 code;
923         unsigned int            modifiers[] =
924             { 0, LockMask, numlockmask, numlockmask | LockMask };
925
926         DNPRINTF(SWM_D_MISC, "grabkeys\n");
927         updatenumlockmask();
928
929         XUngrabKey(display, AnyKey, AnyModifier, root);
930         for(i = 0; i < LENGTH(keys); i++) {
931                 if((code = XKeysymToKeycode(display, keys[i].keysym)))
932                         for(j = 0; j < LENGTH(modifiers); j++)
933                                 XGrabKey(display, code,
934                                     keys[i].mod | modifiers[j], root,
935                                     True, GrabModeAsync, GrabModeAsync);
936         }
937 }
938 void
939 expose(XEvent *e)
940 {
941         DNPRINTF(SWM_D_EVENT, "expose: window: %lu\n", e->xexpose.window);
942 }
943
944 void
945 keypress(XEvent *e)
946 {
947         unsigned int            i;
948         KeySym                  keysym;
949         XKeyEvent               *ev = &e->xkey;
950
951         DNPRINTF(SWM_D_EVENT, "keypress: window: %lu\n", ev->window);
952
953         keysym = XKeycodeToKeysym(display, (KeyCode)ev->keycode, 0);
954         for(i = 0; i < LENGTH(keys); i++)
955                 if(keysym == keys[i].keysym
956                    && CLEANMASK(keys[i].mod) == CLEANMASK(ev->state)
957                    && keys[i].func)
958                         keys[i].func(&(keys[i].args));
959 }
960
961 void
962 buttonpress(XEvent *e)
963 {
964         XButtonPressedEvent     *ev = &e->xbutton;
965 #ifdef SWM_CLICKTOFOCUS
966         struct ws_win           *win;
967 #endif
968
969
970         DNPRINTF(SWM_D_EVENT, "buttonpress: window: %lu\n", ev->window);
971
972         if (ev->window == root)
973                 return;
974         if (ev->window == ws[current_ws].focus->id)
975                 return;
976 #ifdef SWM_CLICKTOFOCUS
977         TAILQ_FOREACH(win, &ws[current_ws].winlist, entry)
978                 if (win->id == ev->window) {
979                         /* focus in the clicked window */
980                         XSetWindowBorder(display, ev->window, 0xff0000);
981                         XSetWindowBorder(display,
982                             ws[current_ws].focus->id, 0x888888);
983                         XSetInputFocus(display, ev->window, RevertToPointerRoot,
984                             CurrentTime);
985                         ws[current_ws].focus = win;
986                         XSync(display, False);
987                         break;
988         }
989 #endif
990 }
991
992 struct ws_win *
993 manage_window(Window id)
994 {
995         struct ws_win           *win;
996
997         TAILQ_FOREACH (win, &ws[current_ws].winlist, entry) {
998                 if (win->id == id)
999                         return (win);   /* already being managed */
1000         }
1001
1002         if ((win = calloc(1, sizeof(struct ws_win))) == NULL)
1003                 errx(1, "calloc: failed to allocate memory for new window");
1004
1005         win->id = id;
1006         TAILQ_INSERT_TAIL(&ws[current_ws].winlist, win, entry);
1007
1008         XSelectInput(display, id, ButtonPressMask | EnterWindowMask |
1009             FocusChangeMask | ExposureMask);
1010
1011         return win;
1012 }
1013
1014
1015 void
1016 configurerequest(XEvent *e)
1017 {
1018         XConfigureRequestEvent  *ev = &e->xconfigurerequest;
1019         Window                  trans;
1020         struct ws_win           *win;
1021
1022         DNPRINTF(SWM_D_EVENT, "configurerequest: window: %lu\n", ev->window);
1023
1024
1025         win = manage_window(ev->window);
1026         ws[current_ws].focus = win; /* make new win focused */
1027
1028         XGetTransientForHint(display, win->id, &trans);
1029         if (trans) {
1030                 win->transient = trans;
1031                 DNPRINTF(SWM_D_MISC, "configurerequest: win %u transient %u\n",
1032                     (unsigned)win->id, win->transient);
1033         }
1034         XGetWindowAttributes(display, win->id, &win->wa);
1035 #if 0
1036         XClassHint ch = { 0 };
1037         if(XGetClassHint(display, win->id, &ch)) {
1038                 fprintf(stderr, "class: %s name: %s\n", ch.res_class, ch.res_name);
1039                 if (!strcmp(ch.res_class, "Gvim") && !strcmp(ch.res_name, "gvim")) {
1040                         win->floating = 0;
1041                 }
1042                 if(ch.res_class)
1043                         XFree(ch.res_class);
1044                 if(ch.res_name)
1045                         XFree(ch.res_name);
1046         }
1047 #endif
1048         stack();
1049 }
1050
1051 void
1052 configurenotify(XEvent *e)
1053 {
1054         DNPRINTF(SWM_D_EVENT, "configurenotify: window: %lu\n",
1055             e->xconfigure.window);
1056 }
1057
1058 void
1059 destroynotify(XEvent *e)
1060 {
1061         struct ws_win           *win;
1062         XDestroyWindowEvent     *ev = &e->xdestroywindow;
1063
1064         DNPRINTF(SWM_D_EVENT, "destroynotify: window %lu\n", ev->window);
1065
1066         TAILQ_FOREACH (win, &ws[current_ws].winlist, entry) {
1067                 if (ev->window == win->id) {
1068                         /* find a window to focus */
1069                         ws[current_ws].focus = TAILQ_PREV(win,
1070                             ws_win_list, entry);
1071                         if (ws[current_ws].focus == NULL)
1072                                 ws[current_ws].focus =
1073                                     TAILQ_FIRST(&ws[current_ws].winlist);
1074                         if (win == ws[current_ws].focus)
1075                                 ws[current_ws].focus = NULL;
1076         
1077                         TAILQ_REMOVE(&ws[current_ws].winlist, win, entry);
1078                         free(win);
1079                         break;
1080                 }
1081         }
1082
1083         stack();
1084 }
1085
1086 void
1087 enternotify(XEvent *e)
1088 {
1089         XCrossingEvent          *ev = &e->xcrossing;
1090         struct ws_win           *win;
1091
1092         DNPRINTF(SWM_D_EVENT, "enternotify: window: %lu\n", ev->window);
1093
1094         if((ev->mode != NotifyNormal || ev->detail == NotifyInferior) &&
1095             ev->window != root)
1096                 return;
1097         if (ignore_enter) {
1098                 /* eat event(s) to prevent autofocus */
1099                 ignore_enter--;
1100                 return;
1101         }
1102         TAILQ_FOREACH (win, &ws[current_ws].winlist, entry) {
1103                 if (win->id == ev->window)
1104                         focus_win(win);
1105                 else
1106                         unfocus_win(win);
1107         }
1108 }
1109
1110 void
1111 focusin(XEvent *e)
1112 {
1113         XFocusChangeEvent       *ev = &e->xfocus;
1114
1115         DNPRINTF(SWM_D_EVENT, "focusin: window: %lu\n", ev->window);
1116
1117         XSync(display, False); /* not sure this helps redrawing graphic apps */
1118
1119         if (ev->window == root)
1120                 return;
1121         /*
1122          * kill grab for now so that we can cut and paste , this screws up
1123          * click to focus
1124          */
1125         /*
1126         DNPRINTF(SWM_D_EVENT, "focusin: window: %lu grabbing\n", ev->window);
1127         XGrabButton(display, Button1, AnyModifier, ev->window, False,
1128             ButtonPress, GrabModeAsync, GrabModeSync, None, None);
1129         */
1130 }
1131
1132 void
1133 mappingnotify(XEvent *e)
1134 {
1135         XMappingEvent           *ev = &e->xmapping;
1136
1137         DNPRINTF(SWM_D_EVENT, "mappingnotify: window: %lu\n", ev->window);
1138
1139         XRefreshKeyboardMapping(ev);
1140         if(ev->request == MappingKeyboard)
1141                 grabkeys();
1142 }
1143
1144 void
1145 maprequest(XEvent *e)
1146 {
1147         DNPRINTF(SWM_D_EVENT, "maprequest: window: %lu\n",
1148             e->xmaprequest.window);
1149
1150         manage_window(e->xmaprequest.window);
1151         stack();
1152 }
1153
1154 void
1155 propertynotify(XEvent *e)
1156 {
1157         DNPRINTF(SWM_D_EVENT, "propertynotify: window: %lu\n",
1158             e->xproperty.window);
1159 }
1160
1161 void
1162 unmapnotify(XEvent *e)
1163 {
1164         DNPRINTF(SWM_D_EVENT, "unmapnotify: window: %lu\n", e->xunmap.window);
1165 }
1166
1167 void
1168 visibilitynotify(XEvent *e)
1169 {
1170         DNPRINTF(SWM_D_EVENT, "visibilitynotify: window: %lu\n", e->xvisibility.window);
1171
1172         if (e->xvisibility.window == bar_window &&
1173             e->xvisibility.state == VisibilityUnobscured)
1174                 bar_print();
1175 }
1176
1177 void                    (*handler[LASTEvent])(XEvent *) = {
1178                                 [Expose] = expose,
1179                                 [KeyPress] = keypress,
1180                                 [ButtonPress] = buttonpress,
1181                                 [ConfigureRequest] = configurerequest,
1182                                 [ConfigureNotify] = configurenotify,
1183                                 [DestroyNotify] = destroynotify,
1184                                 [EnterNotify] = enternotify,
1185                                 [FocusIn] = focusin,
1186                                 [MappingNotify] = mappingnotify,
1187                                 [MapRequest] = maprequest,
1188                                 [PropertyNotify] = propertynotify,
1189                                 [UnmapNotify] = unmapnotify,
1190                                 [VisibilityNotify] = visibilitynotify,
1191 };
1192
1193 int
1194 xerror_start(Display *d, XErrorEvent *ee)
1195 {
1196         other_wm = 1;
1197         return (-1);
1198 }
1199
1200 int
1201 xerror(Display *d, XErrorEvent *ee)
1202 {
1203         fprintf(stderr, "error: %p %p\n", display, ee);
1204
1205         return (-1);
1206 }
1207
1208 int
1209 active_wm(void)
1210 {
1211         other_wm = 0;
1212         xerrorxlib = XSetErrorHandler(xerror_start);
1213
1214         /* this causes an error if some other window manager is running */
1215         XSelectInput(display, DefaultRootWindow(display),
1216             SubstructureRedirectMask);
1217         XSync(display, False);
1218         if(other_wm)
1219                 return (1);
1220
1221         XSetErrorHandler(xerror);
1222         XSync(display, False);
1223         return (0);
1224 }
1225
1226 int
1227 main(int argc, char *argv[])
1228 {
1229         struct passwd           *pwd;
1230         char                    conf[PATH_MAX], *cfile = NULL;
1231         struct stat             sb;
1232         XEvent                  e;
1233         unsigned int            i, num;
1234         Window                  d1, d2, *wins = NULL;
1235         XWindowAttributes       wa;
1236
1237         fprintf(stderr, "Welcome to scrotwm V%s\n", SWM_VERSION);
1238         if(!setlocale(LC_CTYPE, "") || !XSupportsLocale())
1239                 warnx("no locale support");
1240
1241         if(!(display = XOpenDisplay(0)))
1242                 errx(1, "can not open display");
1243
1244         if (active_wm())
1245                 errx(1, "other wm running");
1246
1247         screen = DefaultScreen(display);
1248         root = RootWindow(display, screen);
1249         width = DisplayWidth(display, screen) - 2;
1250         height = DisplayHeight(display, screen) - 2;
1251
1252         /* look for local and global conf file */
1253         pwd = getpwuid(getuid());
1254         if (pwd == NULL)
1255                 errx(1, "invalid user %d", getuid());
1256
1257         snprintf(conf, sizeof conf, "%s/.%s", pwd->pw_dir, SWM_CONF_FILE);
1258         if (stat(conf, &sb) != -1) {
1259                 if (S_ISREG(sb.st_mode))
1260                         cfile = conf;
1261         } else {
1262                 /* try global conf file */
1263                 snprintf(conf, sizeof conf, "/etc/%s", SWM_CONF_FILE);
1264                 if (!stat(conf, &sb))
1265                         if (S_ISREG(sb.st_mode))
1266                                 cfile = conf;
1267         }
1268         if (cfile)
1269                 conf_load(cfile);
1270
1271         /* init all workspaces */
1272         for (i = 0; i < SWM_WS_MAX; i++) {
1273                 ws[i].visible = 0;
1274                 ws[i].restack = 1;
1275                 ws[i].focus = NULL;
1276                 TAILQ_INIT(&ws[i].winlist);
1277                 ws[i].cur_layout = &layouts[0];
1278         }
1279         /* make work space 1 active */
1280         ws[0].visible = 1;
1281
1282         /* grab existing windows */
1283         if (XQueryTree(display, root, &d1, &d2, &wins, &num)) {
1284                 for (i = 0; i < num; i++) {
1285                         if (!XGetWindowAttributes(display, wins[i], &wa)
1286                             || wa.override_redirect ||
1287                             XGetTransientForHint(display, wins[i], &d1))
1288                                 continue;
1289                         manage_window(wins[i]);
1290                 }
1291                 if(wins)
1292                         XFree(wins);
1293         }
1294         ws[0].focus = TAILQ_FIRST(&ws[0].winlist);
1295
1296         /* setup status bar */
1297         bar_setup();
1298
1299         XSelectInput(display, root, SubstructureRedirectMask |
1300             SubstructureNotifyMask | ButtonPressMask | KeyPressMask |
1301             EnterWindowMask | LeaveWindowMask | StructureNotifyMask |
1302             FocusChangeMask | PropertyChangeMask | ExposureMask);
1303
1304         grabkeys();
1305         stack();
1306
1307         while (running) {
1308                 XNextEvent(display, &e);
1309                 if (handler[e.type])
1310                         handler[e.type](&e);
1311         }
1312
1313         XCloseDisplay(display);
1314
1315         return (0);
1316 }