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