JasonWoof Got questions, comments, patches, etc.? Contact Jason Woofenden
Do screenshots and add example script for it.
[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 <errno.h>
57 #include <fcntl.h>
58 #include <locale.h>
59 #include <unistd.h>
60 #include <time.h>
61 #include <signal.h>
62 #include <string.h>
63 #include <util.h>
64 #include <pwd.h>
65 #include <ctype.h>
66
67 #include <sys/types.h>
68 #include <sys/time.h>
69 #include <sys/stat.h>
70 #include <sys/wait.h>
71 #include <sys/queue.h>
72 #include <sys/param.h>
73 #include <sys/select.h>
74
75 #include <X11/cursorfont.h>
76 #include <X11/keysym.h>
77 #include <X11/Xatom.h>
78 #include <X11/Xlib.h>
79 #include <X11/Xproto.h>
80 #include <X11/Xutil.h>
81 #include <X11/extensions/Xrandr.h>
82
83 #if RANDR_MAJOR < 1
84 #  error XRandR versions less than 1.0 are not supported
85 #endif
86
87 #if RANDR_MAJOR >= 1
88 #if RANDR_MINOR >= 2
89 #define SWM_XRR_HAS_CRTC
90 #endif
91 #endif
92
93 /* #define SWM_DEBUG */
94 #ifdef SWM_DEBUG
95 #define DPRINTF(x...)           do { if (swm_debug) fprintf(stderr, x); } while(0)
96 #define DNPRINTF(n,x...)        do { if (swm_debug & n) fprintf(stderr, x); } while(0)
97 #define SWM_D_MISC              0x0001
98 #define SWM_D_EVENT             0x0002
99 #define SWM_D_WS                0x0004
100 #define SWM_D_FOCUS             0x0008
101 #define SWM_D_MOVE              0x0010
102 #define SWM_D_STACK             0x0020
103 #define SWM_D_MOUSE             0x0040
104 #define SWM_D_PROP              0x0080
105
106
107 u_int32_t               swm_debug = 0
108                             | SWM_D_MISC
109                             | SWM_D_EVENT
110                             | SWM_D_WS
111                             | SWM_D_FOCUS
112                             | SWM_D_MOVE
113                             | SWM_D_STACK
114                             | SWM_D_PROP
115                             ;
116 #else
117 #define DPRINTF(x...)
118 #define DNPRINTF(n,x...)
119 #endif
120
121 #define LENGTH(x)               (sizeof x / sizeof x[0])
122 #define MODKEY                  Mod1Mask
123 #define CLEANMASK(mask)         (mask & ~(numlockmask | LockMask))
124 #define BUTTONMASK              (ButtonPressMask|ButtonReleaseMask)
125
126 #define X(r)            (r)->g.x        
127 #define Y(r)            (r)->g.y
128 #define WIDTH(r)        (r)->g.w        
129 #define HEIGHT(r)       (r)->g.h
130
131 #ifndef SWM_LIB
132 #define SWM_LIB         "/usr/X11R6/lib/swmhack.so"
133 #endif
134
135 #define SWM_PROPLEN     (16)
136
137 char                    **start_argv;
138 Atom                    astate;
139 int                     (*xerrorxlib)(Display *, XErrorEvent *);
140 int                     other_wm;
141 int                     running = 1;
142 int                     ss_enabled = 0;
143 int                     xrandr_eventbase;
144 int                     ignore_enter = 0;
145 unsigned int            numlockmask = 0;
146 Display                 *display;
147
148 int                     cycle_empty = 0;
149 int                     cycle_visible = 0;
150
151 /* dialog windows */
152 double                  dialog_ratio = .6;
153 /* status bar */
154 #define SWM_BAR_MAX     (128)
155 char                    *bar_argv[] = { NULL, NULL };
156 int                     bar_pipe[2];
157 char                    bar_ext[SWM_BAR_MAX];
158 sig_atomic_t            bar_alarm = 0;
159 int                     bar_delay = 30;
160 int                     bar_enabled = 1;
161 int                     bar_extra = 1;
162 int                     bar_extra_running = 0;
163 int                     bar_verbose = 1;
164 int                     bar_height = 0;
165 pid_t                   bar_pid;
166 GC                      bar_gc;
167 XGCValues               bar_gcv;
168 int                     bar_fidx = 0;
169 XFontStruct             *bar_fs;
170 char                    *bar_fonts[] = {
171                             "-*-terminus-*-*-*-*-*-*-*-*-*-*-*-*",
172                             "-*-times-medium-r-*-*-*-*-*-*-*-*-*-*",
173                             NULL
174 };
175
176 /* terminal + args */
177 char                    *spawn_term[] = { "xterm", NULL };
178 char                    *spawn_screenshot[] = { "screenshot.sh", NULL, NULL }; /* XXX get from conf */
179 char                    *spawn_menu[] = { "dmenu_run", "-fn", NULL,
180                             "-nb", NULL, "-nf", NULL, "-sb", NULL, "-sf", NULL, NULL };
181
182 #define SWM_MENU_FN     (2)
183 #define SWM_MENU_NB     (4)
184 #define SWM_MENU_NF     (6)
185 #define SWM_MENU_SB     (8)
186 #define SWM_MENU_SF     (10)
187
188 /* layout manager data */
189 struct swm_geometry {
190         int                     x;
191         int                     y;
192         int                     w;
193         int                     h;
194 };
195
196 struct swm_screen;
197 struct workspace;
198
199 /* virtual "screens" */
200 struct swm_region {
201         TAILQ_ENTRY(swm_region) entry;
202         struct swm_geometry     g;
203         Window                  bar_window;
204         struct workspace        *ws;    /* current workspace on this region */
205         struct swm_screen       *s;     /* screen idx */
206 }; 
207 TAILQ_HEAD(swm_region_list, swm_region);
208
209 struct ws_win {
210         TAILQ_ENTRY(ws_win)     entry;
211         Window                  id;
212         struct swm_geometry     g;
213         int                     got_focus;
214         int                     floating;
215         int                     transient;
216         struct workspace        *ws;    /* always valid */
217         struct swm_screen       *s;     /* always valid, never changes */
218         XWindowAttributes       wa;
219         XSizeHints              sh;
220 };
221 TAILQ_HEAD(ws_win_list, ws_win);
222
223 /* layout handlers */
224 void    stack(void);
225 void    vertical_config(struct workspace *, int);
226 void    vertical_stack(struct workspace *, struct swm_geometry *);
227 void    horizontal_config(struct workspace *, int);
228 void    horizontal_stack(struct workspace *, struct swm_geometry *);
229 void    max_stack(struct workspace *, struct swm_geometry *);
230
231 void    grabbuttons(struct ws_win *, int);
232
233 struct layout {
234         void            (*l_stack)(struct workspace *, struct swm_geometry *);
235         void            (*l_config)(struct workspace *, int);
236 } layouts[] =  {
237         /* stack,               configure */
238         { vertical_stack,       vertical_config},
239         { horizontal_stack,     horizontal_config},
240         { max_stack,            NULL},
241         { NULL,                 NULL},
242 };
243
244 #define SWM_H_SLICE             (32)
245 #define SWM_V_SLICE             (32)
246
247 /* define work spaces */
248 struct workspace {
249         int                     idx;            /* workspace index */
250         int                     restack;        /* restack on switch */
251         struct layout           *cur_layout;    /* current layout handlers */
252         struct ws_win           *focus;         /* may be NULL */
253         struct swm_region       *r;             /* may be NULL */
254         struct ws_win_list      winlist;        /* list of windows in ws */
255
256         /* stacker state */
257         struct {
258                                 int horizontal_msize;
259                                 int horizontal_mwin;
260                                 int vertical_msize;
261                                 int vertical_mwin;
262         } l_state;
263 };
264
265 enum    { SWM_S_COLOR_BAR, SWM_S_COLOR_BAR_BORDER, SWM_S_COLOR_BAR_FONT,
266           SWM_S_COLOR_FOCUS, SWM_S_COLOR_UNFOCUS, SWM_S_COLOR_MAX };
267
268 /* physical screen mapping */
269 #define SWM_WS_MAX              (10)            /* XXX Too small? */
270 struct swm_screen {
271         int                     idx;            /* screen index */
272         struct swm_region_list  rl;     /* list of regions on this screen */
273         Window                  root;
274         int                     xrandr_support;
275         struct workspace        ws[SWM_WS_MAX];
276
277         /* colors */
278         struct {
279                 unsigned long   color;
280                 char            *name;
281         } c[SWM_S_COLOR_MAX];
282 };
283 struct swm_screen       *screens;
284 int                     num_screens;
285
286 struct ws_win           *cur_focus = NULL;
287
288 /* args to functions */
289 union arg {
290         int                     id;
291 #define SWM_ARG_ID_FOCUSNEXT    (0)
292 #define SWM_ARG_ID_FOCUSPREV    (1)
293 #define SWM_ARG_ID_FOCUSMAIN    (2)
294 #define SWM_ARG_ID_SWAPNEXT     (3)
295 #define SWM_ARG_ID_SWAPPREV     (4)
296 #define SWM_ARG_ID_SWAPMAIN     (5)
297 #define SWM_ARG_ID_MASTERSHRINK (6)
298 #define SWM_ARG_ID_MASTERGROW   (7)
299 #define SWM_ARG_ID_MASTERADD    (8)
300 #define SWM_ARG_ID_MASTERDEL    (9)
301 #define SWM_ARG_ID_STACKRESET   (10)
302 #define SWM_ARG_ID_STACKINIT    (11)
303 #define SWM_ARG_ID_CYCLEWS_UP   (12)
304 #define SWM_ARG_ID_CYCLEWS_DOWN (13)
305 #define SWM_ARG_ID_SS_ALL       (0)
306 #define SWM_ARG_ID_SS_WINDOW    (1)
307         char                    **argv;
308 };
309
310 unsigned long
311 name_to_color(char *colorname)
312 {
313         Colormap                cmap;
314         Status                  status;
315         XColor                  screen_def, exact_def;
316         unsigned long           result = 0;
317         char                    cname[32] = "#";
318
319         cmap = DefaultColormap(display, screens[0].idx);
320         status = XAllocNamedColor(display, cmap, colorname,
321             &screen_def, &exact_def);
322         if (!status) {
323                 strlcat(cname, colorname + 2, sizeof cname - 1);
324                 status = XAllocNamedColor(display, cmap, cname, &screen_def,
325                     &exact_def);
326         }
327         if (status)
328                 result = screen_def.pixel;
329         else
330                 fprintf(stderr, "color '%s' not found.\n", colorname);
331
332         return (result);
333 }
334
335 void
336 setscreencolor(char *val, int i, int c)
337 {
338         if (i > 0 && i <= ScreenCount(display)) {
339                 screens[i - 1].c[c].color = name_to_color(val);
340                 if ((screens[i - 1].c[c].name = strdup(val)) == NULL)
341                         errx(1, "strdup");
342         } else if (i == -1) {
343                 for (i = 0; i < ScreenCount(display); i++)
344                         screens[i].c[c].color = name_to_color(val);
345                         if ((screens[i - 1].c[c].name = strdup(val)) == NULL)
346                                 errx(1, "strdup");
347         } else
348                 errx(1, "invalid screen index: %d out of bounds (maximum %d)\n",
349                     i, ScreenCount(display));
350 }
351
352 int
353 varmatch(char *var, char *name, int *index)
354 {
355         char                    *p, buf[5];
356         int                     i;
357
358         i = strncmp(var, name, 255);
359         if (index == NULL)
360                 return (i);
361
362         *index = -1;
363         if (i <= 0)
364                 return (i);
365         p = var + strlen(name);
366         if (*p++ != '[')
367                 return (i);
368         bzero(buf, sizeof buf);
369         i = 0;
370         while (isdigit(*p) && i < sizeof buf)
371                 buf[i++] = *p++;
372         if (i == 0 || i >= sizeof buf || *p != ']')
373                 return (1);
374         *index = strtonum(buf, 0, 99, NULL);
375         return (0);
376 }
377
378 /* conf file stuff */
379 #define SWM_CONF_WS     "\n= \t"
380 #define SWM_CONF_FILE   "scrotwm.conf"
381 int
382 conf_load(char *filename)
383 {
384         FILE                    *config;
385         char                    *line, *cp, *var, *val;
386         size_t                  len, lineno = 0;
387         int                     i, sc;
388
389         DNPRINTF(SWM_D_MISC, "conf_load: filename %s\n", filename);
390
391         if (filename == NULL)
392                 return (1);
393
394         if ((config = fopen(filename, "r")) == NULL)
395                 return (1);
396
397         for (sc = ScreenCount(display);;) {
398                 if ((line = fparseln(config, &len, &lineno, NULL, 0)) == NULL)
399                         if (feof(config))
400                                 break;
401                 cp = line;
402                 cp += (long)strspn(cp, SWM_CONF_WS);
403                 if (cp[0] == '\0') {
404                         /* empty line */
405                         free(line);
406                         continue;
407                 }
408                 if ((var = strsep(&cp, SWM_CONF_WS)) == NULL || cp == NULL)
409                         break;
410                 cp += (long)strspn(cp, SWM_CONF_WS);
411                 if ((val = strsep(&cp, SWM_CONF_WS)) == NULL)
412                         break;
413
414                 DNPRINTF(SWM_D_MISC, "conf_load: %s=%s\n",var ,val);
415                 switch (var[0]) {
416                 case 'b':
417                         if (!strncmp(var, "bar_enabled", strlen("bar_enabled")))
418                                 bar_enabled = atoi(val);
419                         else if (!varmatch(var, "bar_border", &i))
420                                 setscreencolor(val, i, SWM_S_COLOR_BAR_BORDER);
421                         else if (!varmatch(var, "bar_color", &i))
422                                 setscreencolor(val, i, SWM_S_COLOR_BAR);
423                         else if (!varmatch(var, "bar_font_color", &i))
424                                 setscreencolor(val, i, SWM_S_COLOR_BAR_FONT);
425                         else if (!strncmp(var, "bar_font", strlen("bar_font")))
426                                 asprintf(&bar_fonts[0], "%s", val);
427                         else if (!strncmp(var, "bar_action", strlen("bar_action")))
428                                 asprintf(&bar_argv[0], "%s", val);
429                         else if (!strncmp(var, "bar_delay", strlen("bar_delay")))
430                                 bar_delay = atoi(val);
431                         else
432                                 goto bad;
433                         break;
434
435                 case 'c':
436                         if (!varmatch(var, "color_focus", &i))
437                                 setscreencolor(val, i, SWM_S_COLOR_FOCUS);
438                         else if (!varmatch(var, "color_unfocus", &i))
439                                 setscreencolor(val, i, SWM_S_COLOR_UNFOCUS);
440                         else if (!strncmp(var, "cycle_empty", strlen("cycle_empty")))
441                                 cycle_visible = atoi(val);
442                         else if (!strncmp(var, "cycle_visible", strlen("cycle_visible")))
443                                 cycle_visible = atoi(val);
444                         else
445                                 goto bad;
446                         break;
447
448                 case 'd':
449                         if (!strncmp(var, "dialog_ratio",
450                             strlen("dialog_ratio"))) {
451                                 dialog_ratio = atof(val);
452                                 if (dialog_ratio > 1.0 || dialog_ratio <= .3)
453                                         dialog_ratio = .6;
454                         } else
455                                 goto bad;
456                         break;
457
458                 case 's':
459                         if (!strncmp(var, "spawn_term", strlen("spawn_term")))
460                                 asprintf(&spawn_term[0], "%s", val); /* XXX args? */
461                         if (!strncmp(var, "screenshot_enabled",
462                             strlen("screenshot_enabled")))
463                                 ss_enabled = atoi(val);
464                         break;
465                 default:
466                         goto bad;
467                 }
468                 free(line);
469         }
470
471         fclose(config);
472         return (0);
473
474 bad:
475         errx(1, "invalid conf file entry: %s=%s", var, val);
476 }
477
478 void
479 socket_setnonblock(int fd)
480 {
481         int                     flags;
482
483         if ((flags = fcntl(fd, F_GETFL, 0)) == -1)
484                 err(1, "fcntl F_GETFL");
485         flags |= O_NONBLOCK;
486         if ((flags = fcntl(fd, F_SETFL, flags)) == -1)
487                 err(1, "fcntl F_SETFL");
488 }
489
490 void
491 bar_print(struct swm_region *r, char *s)
492 {
493         XClearWindow(display, r->bar_window);
494         XSetForeground(display, bar_gc, r->s->c[SWM_S_COLOR_BAR_FONT].color);
495         XDrawString(display, r->bar_window, bar_gc, 4, bar_fs->ascent, s,
496             strlen(s));
497 }
498
499 void
500 bar_extra_stop(void)
501 {
502         if (bar_pipe[0]) {
503                 close(bar_pipe[0]);
504                 bzero(bar_pipe, sizeof bar_pipe);
505         }
506         if (bar_pid) {
507                 kill(bar_pid, SIGTERM);
508                 bar_pid = 0;
509         }
510         strlcpy(bar_ext, "", sizeof bar_ext);
511         bar_extra = 0;
512 }
513
514 void
515 bar_update(void)
516 {
517         time_t                  tmt;
518         struct tm               tm;
519         struct swm_region       *r;
520         int                     i, x;
521         size_t                  len;
522         char                    s[SWM_BAR_MAX];
523         char                    loc[SWM_BAR_MAX];
524         char                    *b;
525
526         if (bar_enabled == 0)
527                 return;
528
529         if (bar_extra && bar_extra_running) {
530                 /* ignore short reads; it'll correct itself */
531                 while ((b = fgetln(stdin, &len)) != NULL)
532                         if (b && b[len - 1] == '\n') {
533                                 b[len - 1] = '\0';
534                                 strlcpy(bar_ext, b, sizeof bar_ext);
535                         }
536                 if (b == NULL && errno != EAGAIN) {
537                         fprintf(stderr, "bar_extra failed: errno: %d %s\n",
538                             errno, strerror(errno));
539                         bar_extra_stop();
540                 }
541         } else
542                 strlcpy(bar_ext, "", sizeof bar_ext);
543
544         time(&tmt);
545         localtime_r(&tmt, &tm);
546         strftime(s, sizeof s, "%a %b %d %R %Z %Y", &tm);
547         for (i = 0; i < ScreenCount(display); i++) {
548                 x = 1;
549                 TAILQ_FOREACH(r, &screens[i].rl, entry) {
550                         snprintf(loc, sizeof loc, "%s     %d:%d    %s",
551                             s, x++, r->ws->idx + 1, bar_ext);
552                         bar_print(r, loc);
553                 }
554         }
555         XSync(display, False);
556         alarm(bar_delay);
557 }
558
559 void
560 bar_signal(int sig)
561 {
562         bar_alarm = 1;
563 }
564
565 void
566 bar_toggle(struct swm_region *r, union arg *args)
567 {
568         struct swm_region       *tmpr;
569         int                     i, j, sc = ScreenCount(display);
570
571         DNPRINTF(SWM_D_MISC, "bar_toggle\n");
572
573         if (bar_enabled) {
574                 for (i = 0; i < sc; i++)
575                         TAILQ_FOREACH(tmpr, &screens[i].rl, entry)
576                                 XUnmapWindow(display, tmpr->bar_window);
577         } else {
578                 for (i = 0; i < sc; i++)
579                         TAILQ_FOREACH(tmpr, &screens[i].rl, entry)
580                                 XMapRaised(display, tmpr->bar_window);
581         }
582         bar_enabled = !bar_enabled;
583         XSync(display, False);
584         for (i = 0; i < sc; i++)
585                 for (j = 0; j < SWM_WS_MAX; j++)
586                         screens[i].ws[j].restack = 1;
587
588         stack();
589         /* must be after stack */
590         for (i = 0; i < sc; i++)
591                 TAILQ_FOREACH(tmpr, &screens[i].rl, entry)
592                         bar_update();
593 }
594
595 void
596 bar_refresh(void)
597 {
598         XSetWindowAttributes    wa;
599         struct swm_region       *r;
600         int                     i;
601
602         /* do this here because the conf file is in memory */
603         if (bar_extra && bar_extra_running == 0 && bar_argv[0]) {
604                 /* launch external status app */
605                 bar_extra_running = 1;
606                 if (pipe(bar_pipe) == -1)
607                         err(1, "pipe error");
608                 socket_setnonblock(bar_pipe[0]);
609                 socket_setnonblock(bar_pipe[1]); /* XXX hmmm, really? */
610                 if (dup2(bar_pipe[0], 0) == -1)
611                         errx(1, "dup2");
612                 if (dup2(bar_pipe[1], 1) == -1)
613                         errx(1, "dup2");
614                 if (signal(SIGPIPE, SIG_IGN) == SIG_ERR)
615                         err(1, "could not disable SIGPIPE");
616                 switch (bar_pid = fork()) {
617                 case -1:
618                         err(1, "cannot fork");
619                         break;
620                 case 0: /* child */
621                         close(bar_pipe[0]);
622                         execvp(bar_argv[0], bar_argv);
623                         err(1, "%s external app failed", bar_argv[0]);
624                         break;
625                 default: /* parent */
626                         close(bar_pipe[1]);
627                         break;
628                 }
629         }
630
631         bzero(&wa, sizeof wa);
632         for (i = 0; i < ScreenCount(display); i++)
633                 TAILQ_FOREACH(r, &screens[i].rl, entry) {
634                         wa.border_pixel =
635                             screens[i].c[SWM_S_COLOR_BAR_BORDER].color;
636                         wa.background_pixel =
637                             screens[i].c[SWM_S_COLOR_BAR].color;
638                         XChangeWindowAttributes(display, r->bar_window,
639                             CWBackPixel | CWBorderPixel, &wa);
640                 }
641         bar_update();
642 }
643
644 void
645 bar_setup(struct swm_region *r)
646 {
647         int                     i;
648
649         for (i = 0; bar_fonts[i] != NULL; i++) {
650                 bar_fs = XLoadQueryFont(display, bar_fonts[i]);
651                 if (bar_fs) {
652                         bar_fidx = i;
653                         break;
654                 }
655         }
656         if (bar_fonts[i] == NULL)
657                         errx(1, "couldn't load font");
658         bar_height = bar_fs->ascent + bar_fs->descent + 3;
659
660         r->bar_window = XCreateSimpleWindow(display, 
661             r->s->root, X(r), Y(r), WIDTH(r) - 2, bar_height - 2,
662             1, r->s->c[SWM_S_COLOR_BAR_BORDER].color,
663             r->s->c[SWM_S_COLOR_BAR].color);
664         bar_gc = XCreateGC(display, r->bar_window, 0, &bar_gcv);
665         XSetFont(display, bar_gc, bar_fs->fid);
666         XSelectInput(display, r->bar_window, VisibilityChangeMask);
667         if (bar_enabled)
668                 XMapRaised(display, r->bar_window);
669         DNPRINTF(SWM_D_MISC, "bar_setup: bar_window %lu\n", r->bar_window);
670
671         if (signal(SIGALRM, bar_signal) == SIG_ERR)
672                 err(1, "could not install bar_signal");
673         bar_refresh();
674 }
675
676 void
677 config_win(struct ws_win *win)
678 {
679         XConfigureEvent         ce;
680
681         DNPRINTF(SWM_D_MISC, "config_win: win %lu x %d y %d w %d h %d\n",
682             win->id, win->g.x, win->g.y, win->g.w, win->g.h);
683         ce.type = ConfigureNotify;
684         ce.display = display;
685         ce.event = win->id;
686         ce.window = win->id;
687         ce.x = win->g.x;
688         ce.y = win->g.y;
689         ce.width = win->g.w;
690         ce.height = win->g.h;
691         ce.border_width = 1; /* XXX store this! */
692         ce.above = None;
693         ce.override_redirect = False;
694         XSendEvent(display, win->id, False, StructureNotifyMask, (XEvent *)&ce);
695 }
696
697 int
698 count_win(struct workspace *ws, int count_transient)
699 {
700         struct ws_win           *win;
701         int                     count = 0;
702
703         TAILQ_FOREACH(win, &ws->winlist, entry) {
704                 if (count_transient == 0 && win->floating)
705                         continue;
706                 if (count_transient == 0 && win->transient)
707                         continue;
708                 count++;
709         }
710         DNPRINTF(SWM_D_MISC, "count_win: %d\n", count);
711
712         return (count);
713 }
714
715 void
716 quit(struct swm_region *r, union arg *args)
717 {
718         DNPRINTF(SWM_D_MISC, "quit\n");
719         running = 0;
720 }
721
722 void
723 restart(struct swm_region *r, union arg *args)
724 {
725         DNPRINTF(SWM_D_MISC, "restart: %s\n", start_argv[0]);
726
727         /* disable alarm because the following code may not be interrupted */
728         alarm(0);
729         if (signal(SIGALRM, SIG_IGN) == SIG_ERR)
730                 errx(1, "can't disable alarm");
731
732         bar_extra_stop();
733         bar_extra = 1;
734         XCloseDisplay(display);
735         execvp(start_argv[0], start_argv);
736         fprintf(stderr, "execvp failed\n");
737         perror(" failed");
738         quit(NULL, NULL);
739 }
740
741 struct swm_region *
742 root_to_region(Window root)
743 {
744         struct swm_region       *r;
745         Window                  rr, cr;
746         int                     i, x, y, wx, wy;
747         unsigned int            mask;
748
749         for (i = 0; i < ScreenCount(display); i++)
750                 if (screens[i].root == root)
751                         break;
752
753         if (XQueryPointer(display, screens[i].root, 
754             &rr, &cr, &x, &y, &wx, &wy, &mask) == False) {
755                 /* if we can't query the pointer, grab the first region */
756                 r = TAILQ_FIRST(&screens[i].rl);
757         } else {
758                 /* otherwise, choose a region based on pointer location */
759                 TAILQ_FOREACH(r, &screens[i].rl, entry) {
760                         if (x >= X(r) && x <= X(r) + WIDTH(r) &&
761                             y >= Y(r) && y <= Y(r) + HEIGHT(r))
762                                 break;
763                 }
764
765                 if (r == NULL)
766                         r = TAILQ_FIRST(&screens[i].rl);
767         }
768         return (r);
769 }
770
771 struct ws_win *
772 find_window(Window id)
773 {
774         struct ws_win           *win;
775         int                     i, j;
776
777         for (i = 0; i < ScreenCount(display); i++)
778                 for (j = 0; j < SWM_WS_MAX; j++)
779                         TAILQ_FOREACH(win, &screens[i].ws[j].winlist, entry)
780                                 if (id == win->id)
781                                         return (win);
782         return (NULL);
783 }
784
785 void
786 spawn(struct swm_region *r, union arg *args)
787 {
788         char                    *ret;
789
790         DNPRINTF(SWM_D_MISC, "spawn: %s\n", args->argv[0]);
791         /*
792          * The double-fork construct avoids zombie processes and keeps the code
793          * clean from stupid signal handlers.
794          */
795         if (fork() == 0) {
796                 if (fork() == 0) {
797                         if (display)
798                                 close(ConnectionNumber(display));
799                         setenv("LD_PRELOAD", SWM_LIB, 1);
800                         if (asprintf(&ret, "%d", r->ws->idx)) {
801                                 setenv("_SWM_WS", ret, 1);
802                                 free(ret);
803                         }
804                         if (asprintf(&ret, "%d", getpid())) {
805                                 setenv("_SWM_PID", ret, 1);
806                                 free(ret);
807                         }
808                         setsid();
809                         execvp(args->argv[0], args->argv);
810                         fprintf(stderr, "execvp failed\n");
811                         perror(" failed");
812                 }
813                 exit(0);
814         }
815         wait(0);
816 }
817
818 void
819 spawnmenu(struct swm_region *r, union arg *args)
820 {
821         DNPRINTF(SWM_D_MISC, "spawnmenu\n");
822
823         spawn_menu[SWM_MENU_FN] = bar_fonts[bar_fidx];
824         spawn_menu[SWM_MENU_NB] = r->s->c[SWM_S_COLOR_BAR].name;
825         spawn_menu[SWM_MENU_NF] = r->s->c[SWM_S_COLOR_BAR_FONT].name;
826         spawn_menu[SWM_MENU_SB] = r->s->c[SWM_S_COLOR_BAR_BORDER].name;
827         spawn_menu[SWM_MENU_SF] = r->s->c[SWM_S_COLOR_BAR].name;
828
829         spawn(r, args);
830 }
831
832 void
833 unfocus_all(void)
834 {
835         struct ws_win           *win;
836         int                     i, j;
837
838         DNPRINTF(SWM_D_FOCUS, "unfocus_all:\n");
839
840         for (i = 0; i < ScreenCount(display); i++)
841                 for (j = 0; j < SWM_WS_MAX; j++)
842                         TAILQ_FOREACH(win, &screens[i].ws[j].winlist, entry) {
843                                 if (win->ws->r == NULL)
844                                         continue;
845                                 grabbuttons(win, 0);
846                                 XSetWindowBorder(display, win->id,
847                                     win->ws->r->s->c[SWM_S_COLOR_UNFOCUS].color);
848                                 win->got_focus = 0;
849                                 win->ws->focus = NULL;
850                                 cur_focus = NULL;
851                         }
852 }
853
854 void
855 focus_win(struct ws_win *win)
856 {
857         DNPRINTF(SWM_D_FOCUS, "focus_win: id: %lu\n", win ? win->id : 0);
858
859         if (win == NULL)
860                 return;
861
862         unfocus_all();
863         win->ws->focus = win;
864         if (win->ws->r != NULL) {
865                 cur_focus = win;
866                 if (!win->got_focus) {
867                         XSetWindowBorder(display, win->id,
868                             win->ws->r->s->c[SWM_S_COLOR_FOCUS].color);
869                         grabbuttons(win, 1);
870                 }
871                 win->got_focus = 1;
872                 XSetInputFocus(display, win->id,
873                     RevertToPointerRoot, CurrentTime);
874         }
875 }
876
877 void
878 switchws(struct swm_region *r, union arg *args)
879 {
880         int                     wsid = args->id;
881         struct swm_region       *this_r, *other_r;
882         struct ws_win           *win;
883         struct workspace        *new_ws, *old_ws;
884
885         this_r = r;
886         old_ws = this_r->ws;
887         new_ws = &this_r->s->ws[wsid];
888
889         DNPRINTF(SWM_D_WS, "switchws screen %d region %dx%d+%d+%d: "
890             "%d -> %d\n", r->s->idx, WIDTH(r), HEIGHT(r), X(r), Y(r),
891             old_ws->idx, wsid);
892
893         if (new_ws == old_ws)
894                 return;
895
896         other_r = new_ws->r;
897         if (!other_r) {
898                 /* if the other workspace is hidden, switch windows */
899                 /* map new window first to prevent ugly blinking */
900                 TAILQ_FOREACH(win, &new_ws->winlist, entry)
901                         XMapRaised(display, win->id);
902
903                 TAILQ_FOREACH(win, &old_ws->winlist, entry)
904                         XUnmapWindow(display, win->id);
905
906                 old_ws->r = NULL;
907                 old_ws->restack = 1;
908         } else {
909                 other_r->ws = old_ws;
910                 old_ws->r = other_r;
911         }
912         this_r->ws = new_ws;
913         new_ws->r = this_r;
914
915         ignore_enter = 1;
916         /* set focus */
917         if (new_ws->focus)
918                 focus_win(new_ws->focus);
919         stack();
920         bar_update();
921 }
922
923 void
924 cyclews(struct swm_region *r, union arg *args)
925 {
926         union                   arg a;
927         struct swm_screen       *s = r->s;
928
929         DNPRINTF(SWM_D_WS, "cyclews id %d "
930             "in screen %d region %dx%d+%d+%d ws %d\n", args->id,
931             r->s->idx, WIDTH(r), HEIGHT(r), X(r), Y(r), r->ws->idx);
932
933         a.id = r->ws->idx;
934
935         do {
936                 switch (args->id) {
937                 case SWM_ARG_ID_CYCLEWS_UP:
938                         if (a.id < SWM_WS_MAX - 1)
939                                 a.id++;
940                         else
941                                 a.id = 0;
942                         break;
943                 case SWM_ARG_ID_CYCLEWS_DOWN:
944                         if (a.id > 0)
945                                 a.id--;
946                         else
947                                 a.id = SWM_WS_MAX - 1;
948                         break;
949                 default:
950                         return;
951                 };
952
953                 if (cycle_empty == 0 && TAILQ_EMPTY(&s->ws[a.id].winlist))
954                         continue;
955                 if (cycle_visible == 0 && s->ws[a.id].r != NULL)
956                         continue;
957
958                 switchws(r, &a);
959         } while (a.id != r->ws->idx);
960 }
961
962 void
963 swapwin(struct swm_region *r, union arg *args)
964 {
965         struct ws_win           *target;
966         struct ws_win_list      *wl;
967
968
969         DNPRINTF(SWM_D_WS, "swapwin id %d "
970             "in screen %d region %dx%d+%d+%d ws %d\n", args->id,
971             r->s->idx, WIDTH(r), HEIGHT(r), X(r), Y(r), r->ws->idx);
972         if (cur_focus == NULL)
973                 return;
974
975         wl = &cur_focus->ws->winlist;
976
977         switch (args->id) {
978         case SWM_ARG_ID_SWAPPREV:
979                 target = TAILQ_PREV(cur_focus, ws_win_list, entry);
980                 TAILQ_REMOVE(wl, cur_focus, entry);
981                 if (target == NULL)
982                         TAILQ_INSERT_TAIL(wl, cur_focus, entry);
983                 else
984                         TAILQ_INSERT_BEFORE(target, cur_focus, entry);
985                 break;
986         case SWM_ARG_ID_SWAPNEXT: 
987                 target = TAILQ_NEXT(cur_focus, entry);
988                 TAILQ_REMOVE(wl, cur_focus, entry);
989                 if (target == NULL)
990                         TAILQ_INSERT_HEAD(wl, cur_focus, entry);
991                 else
992                         TAILQ_INSERT_AFTER(wl, target, cur_focus, entry);
993                 break;
994         case SWM_ARG_ID_SWAPMAIN:
995                 target = TAILQ_FIRST(wl);
996                 if (target == cur_focus)
997                         return;
998                 TAILQ_REMOVE(wl, target, entry);
999                 TAILQ_INSERT_BEFORE(cur_focus, target, entry);
1000                 TAILQ_REMOVE(wl, cur_focus, entry);
1001                 TAILQ_INSERT_HEAD(wl, cur_focus, entry);
1002                 break;
1003         default:
1004                 DNPRINTF(SWM_D_MOVE, "invalid id: %d\n", args->id);
1005                 return;
1006         }
1007
1008         ignore_enter = 2;
1009         stack();
1010 }
1011
1012 void
1013 focus(struct swm_region *r, union arg *args)
1014 {
1015         struct ws_win           *winfocus, *winlostfocus;
1016         struct ws_win_list      *wl;
1017
1018         DNPRINTF(SWM_D_FOCUS, "focus: id %d\n", args->id);
1019         if (cur_focus == NULL)
1020                 return;
1021
1022         wl = &cur_focus->ws->winlist;
1023
1024         winlostfocus = cur_focus;
1025
1026         switch (args->id) {
1027         case SWM_ARG_ID_FOCUSPREV:
1028                 winfocus = TAILQ_PREV(cur_focus, ws_win_list, entry);
1029                 if (winfocus == NULL)
1030                         winfocus = TAILQ_LAST(wl, ws_win_list);
1031                 break;
1032
1033         case SWM_ARG_ID_FOCUSNEXT:
1034                 winfocus = TAILQ_NEXT(cur_focus, entry);
1035                 if (winfocus == NULL)
1036                         winfocus = TAILQ_FIRST(wl);
1037                 break;
1038
1039         case SWM_ARG_ID_FOCUSMAIN:
1040                 winfocus = TAILQ_FIRST(wl);
1041                 break;
1042
1043         default:
1044                 return;
1045         }
1046
1047         if (winfocus == winlostfocus)
1048                 return;
1049
1050         XMapRaised(display, winfocus->id);
1051         focus_win(winfocus);
1052         XSync(display, False);
1053 }
1054
1055 void
1056 cycle_layout(struct swm_region *r, union arg *args)
1057 {
1058         struct workspace        *ws = r->ws;
1059
1060         DNPRINTF(SWM_D_EVENT, "cycle_layout: workspace: %d\n", ws->idx);
1061
1062         ws->cur_layout++;
1063         if (ws->cur_layout->l_stack == NULL)
1064                 ws->cur_layout = &layouts[0];
1065         ignore_enter = 1;
1066
1067         stack();
1068 }
1069
1070 void
1071 stack_config(struct swm_region *r, union arg *args)
1072 {
1073         struct workspace        *ws = r->ws;
1074
1075         DNPRINTF(SWM_D_STACK, "stack_config for workspace %d (id %d\n",
1076             args->id, ws->idx);
1077
1078         if (ws->cur_layout->l_config != NULL)
1079                 ws->cur_layout->l_config(ws, args->id);
1080
1081         if (args->id != SWM_ARG_ID_STACKINIT);
1082                 stack();
1083 }
1084
1085 void
1086 stack(void) {
1087         struct swm_geometry     g;
1088         struct swm_region       *r;
1089         int                     i, j;
1090
1091         DNPRINTF(SWM_D_STACK, "stack\n");
1092
1093         for (i = 0; i < ScreenCount(display); i++) {
1094                 j = 0;
1095                 TAILQ_FOREACH(r, &screens[i].rl, entry) {
1096                         DNPRINTF(SWM_D_STACK, "stacking workspace %d "
1097                             "(screen %d, region %d)\n", r->ws->idx, i, j++);
1098
1099                         /* start with screen geometry, adjust for bar */
1100                         g = r->g;
1101                         g.w -= 2;
1102                         g.h -= 2;
1103                         if (bar_enabled) {
1104                                 g.y += bar_height;
1105                                 g.h -= bar_height;
1106                         } 
1107
1108                         r->ws->restack = 0;
1109                         r->ws->cur_layout->l_stack(r->ws, &g);
1110                 }
1111         }
1112         XSync(display, False);
1113 }
1114
1115 void
1116 stack_floater(struct ws_win *win, struct swm_region *r)
1117 {
1118         unsigned int            mask;
1119         XWindowChanges          wc;
1120
1121         bzero(&wc, sizeof wc);
1122         mask = CWX | CWY | CWBorderWidth | CWWidth | CWHeight;
1123         wc.border_width = 1;
1124         if (win->transient) {
1125                 win->g.w = (double)WIDTH(r) * dialog_ratio;
1126                 win->g.h = (double)HEIGHT(r) * dialog_ratio;
1127         }
1128         wc.width = win->g.w;
1129         wc.height = win->g.h;
1130         wc.x = (WIDTH(r) - win->g.w) / 2;
1131         wc.y = (HEIGHT(r) - win->g.h) / 2;
1132
1133         DNPRINTF(SWM_D_STACK, "stack_floater: win %lu x %d y %d w %d h %d\n",
1134             win->id, wc.x, wc.y, wc.width, wc.height);
1135
1136         XConfigureWindow(display, win->id, mask, &wc);
1137 }
1138
1139 #define SWAPXY(g)       do {                            \
1140         int tmp;                                        \
1141         tmp = (g)->y; (g)->y = (g)->x; (g)->x = tmp;    \
1142         tmp = (g)->h; (g)->h = (g)->w; (g)->w = tmp;    \
1143 } while (0)
1144 void
1145 stack_master(struct workspace *ws, struct swm_geometry *g, int rot, int flip)
1146 {
1147         XWindowChanges          wc;
1148         struct swm_geometry     win_g, r_g = *g;
1149         struct ws_win           *win, *winfocus;
1150         int                     i, j, w_inc, h_inc, w_base, h_base;
1151         int                     hrh, extra, h_slice, last_h = 0;
1152         int                     split, colno, winno, mwin, msize, mscale;
1153         int                     remain, missing, v_slice;;
1154         unsigned int            mask;
1155
1156         DNPRINTF(SWM_D_STACK, "stack_master: workspace: %d\n rot=%s flip=%s",
1157             ws->idx, rot ? "yes" : "no", flip ? "yes" : "no");
1158
1159         if ((winno = count_win(ws, 0)) == 0)
1160                 return;
1161
1162         if (ws->focus == NULL)
1163                 ws->focus = TAILQ_FIRST(&ws->winlist);
1164         winfocus = cur_focus ? cur_focus : ws->focus;
1165
1166         win = TAILQ_FIRST(&ws->winlist);
1167         if (rot) {
1168                 w_inc = win->sh.width_inc;
1169                 w_base = win->sh.base_width;
1170                 mwin = ws->l_state.horizontal_mwin;
1171                 mscale = ws->l_state.horizontal_msize;
1172                 SWAPXY(&r_g);
1173         } else {
1174                 w_inc = win->sh.height_inc;
1175                 w_base = win->sh.base_height;
1176                 mwin = ws->l_state.vertical_mwin;
1177                 mscale = ws->l_state.vertical_msize;
1178         }
1179         win_g = r_g;
1180
1181         h_slice = r_g.h / SWM_H_SLICE;
1182         if (mwin && winno > mwin) {
1183                 v_slice = r_g.w / SWM_V_SLICE;
1184
1185                 split = mwin;
1186                 colno = split;
1187                 msize = v_slice * mscale;
1188
1189                 if (w_inc > 1 && w_inc < v_slice) {
1190                         /* adjust for window's requested size increment */
1191                         remain = (win_g.w - w_base) % w_inc;
1192                         missing = w_inc - remain;
1193
1194                         if (missing <= extra || j == 0) {
1195                                 extra -= missing;
1196                                 win_g.w += missing;
1197                         } else {
1198                                 win_g.w -= remain;
1199                                 extra += remain;
1200                         }
1201                 }
1202
1203                 win_g.w = msize;
1204                 if (flip) 
1205                         win_g.x += r_g.w - msize;
1206         } else {
1207                 colno = winno;
1208                 split = 0;
1209         }
1210         hrh = r_g.h / colno;
1211         extra = r_g.h - (colno * hrh);
1212         win_g.h = hrh - 2;
1213
1214         i = j = 0;
1215         TAILQ_FOREACH(win, &ws->winlist, entry) {
1216                 if (split && i == split) {
1217                         colno = winno - split;
1218                         hrh = (r_g.h / colno);
1219                         extra = r_g.h - (colno * hrh);
1220                         if (flip)
1221                                 win_g.x = r_g.x;
1222                         else
1223                                 win_g.x += msize + 2;
1224                         win_g.w = r_g.w - (msize + 2);
1225                         j = 0;
1226                 }
1227                 win_g.h = hrh - 2;
1228                 if (rot) {
1229                         h_inc = win->sh.width_inc;
1230                         h_base = win->sh.base_width;
1231                 } else {
1232                         h_inc = win->sh.height_inc;     
1233                         h_base = win->sh.base_height;
1234                 }
1235                 if (j == colno - 1) {
1236                         win_g.h = hrh + extra;
1237                 } else if (h_inc > 1 && h_inc < h_slice) {
1238                         /* adjust for window's requested size increment */
1239                         remain = (win_g.h - h_base) % h_inc;
1240                         missing = h_inc - remain;
1241
1242                         if (missing <= extra || j == 0) {
1243                                 extra -= missing;
1244                                 win_g.h += missing;
1245                         } else {
1246                                 win_g.h -= remain;
1247                                 extra += remain;
1248                         }
1249                 }
1250                  
1251                 if (j == 0)
1252                         win_g.y = r_g.y;
1253                 else
1254                         win_g.y += last_h + 2;
1255
1256                 if (win->transient != 0 || win->floating != 0)
1257                         stack_floater(win, ws->r);
1258                 else {
1259                         bzero(&wc, sizeof wc);
1260                         wc.border_width = 1;
1261                         if (rot) {
1262                                 win->g.x = wc.x = win_g.y;
1263                                 win->g.y = wc.y = win_g.x;
1264                                 win->g.w = wc.width = win_g.h;
1265                                 win->g.h = wc.height = win_g.w;
1266                         } else {
1267                                 win->g.x = wc.x = win_g.x;
1268                                 win->g.y = wc.y = win_g.y;
1269                                 win->g.w = wc.width = win_g.w;
1270                                 win->g.h = wc.height = win_g.h;
1271                         }
1272                         mask = CWX | CWY | CWWidth | CWHeight | CWBorderWidth;
1273                         XConfigureWindow(display, win->id, mask, &wc);
1274                         /*
1275                         fprintf(stderr, "vertical_stack: win %d x %d y %d w %d h %d bw %d\n", win->id, win->g.x, win->g.y, win->g.w , win->g.h, wc.border_width);
1276                         */
1277                 }
1278
1279                 XMapRaised(display, win->id);
1280                 last_h = win_g.h;
1281                 i++;
1282                 j++;
1283         }
1284
1285         if (winfocus)
1286                 focus_win(winfocus); /* has to be done outside of the loop */
1287 }
1288
1289 void
1290 vertical_config(struct workspace *ws, int id)
1291 {
1292         DNPRINTF(SWM_D_STACK, "vertical_resize: workspace: %d\n", ws->idx);
1293
1294         switch (id) {
1295         case SWM_ARG_ID_STACKRESET:
1296         case SWM_ARG_ID_STACKINIT:
1297                 ws->l_state.vertical_msize = SWM_V_SLICE / 2;
1298                 ws->l_state.vertical_mwin = 1;
1299                 break;
1300         case SWM_ARG_ID_MASTERSHRINK:
1301                 if (ws->l_state.vertical_msize > 1)
1302                         ws->l_state.vertical_msize--;
1303                 break;
1304         case SWM_ARG_ID_MASTERGROW:
1305                 if (ws->l_state.vertical_msize < SWM_V_SLICE - 1)
1306                         ws->l_state.vertical_msize++;
1307                 break;
1308         case SWM_ARG_ID_MASTERADD:
1309                 ws->l_state.vertical_mwin++;
1310                 break;
1311         case SWM_ARG_ID_MASTERDEL:
1312                 if (ws->l_state.vertical_mwin > 0)
1313                         ws->l_state.vertical_mwin--;
1314                 break;
1315         default:
1316                 return;
1317         }
1318 }
1319
1320 void
1321 vertical_stack(struct workspace *ws, struct swm_geometry *g)
1322 {
1323         DNPRINTF(SWM_D_STACK, "vertical_stack: workspace: %d\n", ws->idx);
1324
1325         stack_master(ws, g, 0, 0);
1326 }
1327
1328 void
1329 horizontal_config(struct workspace *ws, int id)
1330 {
1331         DNPRINTF(SWM_D_STACK, "horizontal_config: workspace: %d\n", ws->idx);
1332
1333         switch (id) {
1334         case SWM_ARG_ID_STACKRESET:
1335         case SWM_ARG_ID_STACKINIT:
1336                 ws->l_state.horizontal_mwin = 1;
1337                 ws->l_state.horizontal_msize = SWM_H_SLICE / 2;
1338                 break;
1339         case SWM_ARG_ID_MASTERSHRINK:
1340                 if (ws->l_state.horizontal_msize > 1)
1341                         ws->l_state.horizontal_msize--;
1342                 break;
1343         case SWM_ARG_ID_MASTERGROW:
1344                 if (ws->l_state.horizontal_msize < SWM_H_SLICE - 1)
1345                         ws->l_state.horizontal_msize++;
1346                 break;
1347         case SWM_ARG_ID_MASTERADD:
1348                 ws->l_state.horizontal_mwin++;
1349                 break;
1350         case SWM_ARG_ID_MASTERDEL:
1351                 if (ws->l_state.horizontal_mwin > 0)
1352                         ws->l_state.horizontal_mwin--;
1353                 break;
1354         default:
1355                 return;
1356         }
1357 }
1358
1359 void
1360 horizontal_stack(struct workspace *ws, struct swm_geometry *g)
1361 {
1362         DNPRINTF(SWM_D_STACK, "vertical_stack: workspace: %d\n", ws->idx);
1363
1364         stack_master(ws, g, 1, 0);
1365 }
1366
1367 /* fullscreen view */
1368 void
1369 max_stack(struct workspace *ws, struct swm_geometry *g) {
1370         XWindowChanges          wc;
1371         struct swm_geometry     gg = *g;
1372         struct ws_win           *win, *winfocus;
1373         unsigned int            mask;
1374
1375         DNPRINTF(SWM_D_STACK, "max_stack: workspace: %d\n", ws->idx);
1376
1377         if (count_win(ws, 0) == 0)
1378                 return;
1379
1380         if (ws->focus == NULL)
1381                 ws->focus = TAILQ_FIRST(&ws->winlist);
1382         winfocus = cur_focus ? cur_focus : ws->focus;
1383
1384         TAILQ_FOREACH(win, &ws->winlist, entry) {
1385                 if (win->transient != 0 || win->floating != 0) {
1386                         if (win == ws->focus) {
1387                                 /* XXX maximize? */
1388                                 stack_floater(win, ws->r);
1389                                 XMapRaised(display, win->id);
1390                         } else
1391                                 XUnmapWindow(display, win->id);
1392                 } else {
1393                         bzero(&wc, sizeof wc);
1394                         wc.border_width = 1;
1395                         win->g.x = wc.x = gg.x;
1396                         win->g.y = wc.y = gg.y;
1397                         win->g.w = wc.width = gg.w;
1398                         win->g.h = wc.height = gg.h;
1399                         mask = CWX | CWY | CWWidth | CWHeight | CWBorderWidth;
1400                         XConfigureWindow(display, win->id, mask, &wc);
1401
1402                         if (win == ws->focus) {
1403                                 XMapRaised(display, win->id);
1404                         } else
1405                                 XUnmapWindow(display, win->id);
1406                 }
1407         }
1408
1409         if (winfocus)
1410                 focus_win(winfocus); /* has to be done outside of the loop */
1411 }
1412
1413 void
1414 send_to_ws(struct swm_region *r, union arg *args)
1415 {
1416         int                     wsid = args->id;
1417         struct ws_win           *win = cur_focus;
1418         struct workspace        *ws, *nws;
1419         Atom                    ws_idx_atom = 0;
1420         unsigned char           ws_idx_str[SWM_PROPLEN];
1421
1422         DNPRINTF(SWM_D_MOVE, "send_to_ws: win: %lu\n", win->id);
1423
1424         ws = win->ws;
1425         nws = &win->s->ws[wsid];
1426
1427         XUnmapWindow(display, win->id);
1428
1429         /* find a window to focus */
1430         ws->focus = TAILQ_PREV(win, ws_win_list, entry);
1431         if (ws->focus == NULL)
1432                 ws->focus = TAILQ_FIRST(&ws->winlist);
1433         if (ws->focus == win)
1434                 ws->focus = NULL;
1435
1436         TAILQ_REMOVE(&ws->winlist, win, entry);
1437
1438         TAILQ_INSERT_TAIL(&nws->winlist, win, entry);
1439         win->ws = nws;
1440
1441         /* Try to update the window's workspace property */
1442         ws_idx_atom = XInternAtom(display, "_SWM_WS", False);
1443         if (ws_idx_atom &&
1444             snprintf(ws_idx_str, SWM_PROPLEN, "%d", nws->idx) < SWM_PROPLEN) {
1445                 DNPRINTF(SWM_D_PROP, "setting property _SWM_WS to %s\n",
1446                     ws_idx_str);
1447                 XChangeProperty(display, win->id, ws_idx_atom, XA_STRING, 8,
1448                     PropModeReplace, ws_idx_str, SWM_PROPLEN);
1449         }
1450
1451         if (count_win(nws, 1) == 1)
1452                 nws->focus = win;
1453         ws->restack = 1;
1454         nws->restack = 1;
1455
1456         stack();
1457 }
1458
1459 void
1460 wkill(struct swm_region *r, union arg *args)
1461 {
1462         DNPRINTF(SWM_D_MISC, "wkill\n");
1463         if(r->ws->focus != NULL)
1464                 XKillClient(display, r->ws->focus->id);
1465 }
1466
1467 void
1468 screenshot(struct swm_region *r, union arg *args)
1469 {
1470         union arg                       a;
1471
1472         DNPRINTF(SWM_D_MISC, "screenshot\n");
1473
1474         if (ss_enabled == 0)
1475                 return;
1476
1477         switch (args->id) {
1478         case SWM_ARG_ID_SS_ALL:
1479                 spawn_screenshot[1] = "full";
1480                 break;
1481         case SWM_ARG_ID_SS_WINDOW:
1482                 spawn_screenshot[1] = "window";
1483                 break;
1484         default:
1485                 return;
1486         }
1487         a.argv = spawn_screenshot;
1488         spawn(r, &a);
1489 }
1490
1491 /* key definitions */
1492 struct key {
1493         unsigned int            mod;
1494         KeySym                  keysym;
1495         void                    (*func)(struct swm_region *r, union arg *);
1496         union arg               args;
1497 } keys[] = {
1498         /* modifier             key     function                argument */
1499         { MODKEY,               XK_space,       cycle_layout,   {0} }, 
1500         { MODKEY | ShiftMask,   XK_space,       stack_config,   {.id = SWM_ARG_ID_STACKRESET} }, 
1501         { MODKEY,               XK_h,           stack_config,   {.id = SWM_ARG_ID_MASTERSHRINK} },
1502         { MODKEY,               XK_l,           stack_config,   {.id = SWM_ARG_ID_MASTERGROW} },
1503         { MODKEY,               XK_comma,       stack_config,   {.id = SWM_ARG_ID_MASTERADD} },
1504         { MODKEY,               XK_period,      stack_config,   {.id = SWM_ARG_ID_MASTERDEL} },
1505         { MODKEY,               XK_Return,      swapwin,        {.id = SWM_ARG_ID_SWAPMAIN} },
1506         { MODKEY,               XK_j,           focus,          {.id = SWM_ARG_ID_FOCUSNEXT} },
1507         { MODKEY,               XK_k,           focus,          {.id = SWM_ARG_ID_FOCUSPREV} },
1508         { MODKEY | ShiftMask,   XK_j,           swapwin,        {.id = SWM_ARG_ID_SWAPNEXT} },
1509         { MODKEY | ShiftMask,   XK_k,           swapwin,        {.id = SWM_ARG_ID_SWAPPREV} },
1510         { MODKEY | ShiftMask,   XK_Return,      spawn,          {.argv = spawn_term} },
1511         { MODKEY,               XK_p,           spawnmenu,      {.argv = spawn_menu} },
1512         { MODKEY | ShiftMask,   XK_q,           quit,           {0} },
1513         { MODKEY,               XK_q,           restart,        {0} },
1514         { MODKEY,               XK_m,           focus,          {.id = SWM_ARG_ID_FOCUSMAIN} },
1515         { MODKEY,               XK_1,           switchws,       {.id = 0} },
1516         { MODKEY,               XK_2,           switchws,       {.id = 1} },
1517         { MODKEY,               XK_3,           switchws,       {.id = 2} },
1518         { MODKEY,               XK_4,           switchws,       {.id = 3} },
1519         { MODKEY,               XK_5,           switchws,       {.id = 4} },
1520         { MODKEY,               XK_6,           switchws,       {.id = 5} },
1521         { MODKEY,               XK_7,           switchws,       {.id = 6} },
1522         { MODKEY,               XK_8,           switchws,       {.id = 7} },
1523         { MODKEY,               XK_9,           switchws,       {.id = 8} },
1524         { MODKEY,               XK_0,           switchws,       {.id = 9} },
1525         { MODKEY,               XK_Right,       cyclews,        {.id = SWM_ARG_ID_CYCLEWS_UP} }, 
1526         { MODKEY,               XK_Left,        cyclews,        {.id = SWM_ARG_ID_CYCLEWS_DOWN} }, 
1527         { MODKEY | ShiftMask,   XK_1,           send_to_ws,     {.id = 0} },
1528         { MODKEY | ShiftMask,   XK_2,           send_to_ws,     {.id = 1} },
1529         { MODKEY | ShiftMask,   XK_3,           send_to_ws,     {.id = 2} },
1530         { MODKEY | ShiftMask,   XK_4,           send_to_ws,     {.id = 3} },
1531         { MODKEY | ShiftMask,   XK_5,           send_to_ws,     {.id = 4} },
1532         { MODKEY | ShiftMask,   XK_6,           send_to_ws,     {.id = 5} },
1533         { MODKEY | ShiftMask,   XK_7,           send_to_ws,     {.id = 6} },
1534         { MODKEY | ShiftMask,   XK_8,           send_to_ws,     {.id = 7} },
1535         { MODKEY | ShiftMask,   XK_9,           send_to_ws,     {.id = 8} },
1536         { MODKEY | ShiftMask,   XK_0,           send_to_ws,     {.id = 9} },
1537         { MODKEY,               XK_b,           bar_toggle,     {0} },
1538         { MODKEY,               XK_Tab,         focus,          {.id = SWM_ARG_ID_FOCUSNEXT} },
1539         { MODKEY | ShiftMask,   XK_Tab,         focus,          {.id = SWM_ARG_ID_FOCUSPREV} },
1540         { MODKEY | ShiftMask,   XK_x,           wkill,          {0} },
1541         { MODKEY,               XK_s,           screenshot,     {.id = SWM_ARG_ID_SS_ALL} },
1542         { MODKEY | ShiftMask,   XK_s,           screenshot,     {.id = SWM_ARG_ID_SS_WINDOW} },
1543 };
1544
1545 void
1546 click(struct swm_region *r, union arg *args)
1547 {
1548         DNPRINTF(SWM_D_MOUSE, "click: button: %d\n", args->id);
1549
1550         switch (args->id) {
1551         case Button1:
1552                 break;
1553         case Button2:
1554                 break;
1555         case Button3:
1556                 break;
1557         default:
1558                 return;
1559         }
1560 }
1561
1562 /* mouse */
1563 enum { client_click, root_click };
1564 struct button {
1565         unsigned int            action;
1566         unsigned int            mask;
1567         unsigned int            button;
1568         void                    (*func)(struct swm_region *r, union arg *);
1569         union arg               args;
1570 } buttons[] = {
1571           /* action             key             mouse button    func            args */
1572         { client_click,         MODKEY,         Button1,        click, {.id=Button1} },
1573 };
1574
1575 void
1576 updatenumlockmask(void)
1577 {
1578         unsigned int            i, j;
1579         XModifierKeymap         *modmap;
1580
1581         DNPRINTF(SWM_D_MISC, "updatenumlockmask\n");
1582         numlockmask = 0;
1583         modmap = XGetModifierMapping(display);
1584         for (i = 0; i < 8; i++)
1585                 for (j = 0; j < modmap->max_keypermod; j++)
1586                         if (modmap->modifiermap[i * modmap->max_keypermod + j]
1587                           == XKeysymToKeycode(display, XK_Num_Lock))
1588                                 numlockmask = (1 << i);
1589
1590         XFreeModifiermap(modmap);
1591 }
1592
1593 void
1594 grabkeys(void)
1595 {
1596         unsigned int            i, j, k;
1597         KeyCode                 code;
1598         unsigned int            modifiers[] =
1599             { 0, LockMask, numlockmask, numlockmask | LockMask };
1600
1601         DNPRINTF(SWM_D_MISC, "grabkeys\n");
1602         updatenumlockmask();
1603
1604         for (k = 0; k < ScreenCount(display); k++) {
1605                 if (TAILQ_EMPTY(&screens[k].rl))
1606                         continue;
1607                 XUngrabKey(display, AnyKey, AnyModifier, screens[k].root);
1608                 for (i = 0; i < LENGTH(keys); i++) {
1609                         if ((code = XKeysymToKeycode(display, keys[i].keysym)))
1610                                 for (j = 0; j < LENGTH(modifiers); j++)
1611                                         XGrabKey(display, code,
1612                                             keys[i].mod | modifiers[j],
1613                                             screens[k].root, True,
1614                                             GrabModeAsync, GrabModeAsync);
1615                 }
1616         }
1617 }
1618
1619 void
1620 grabbuttons(struct ws_win *win, int focused)
1621 {
1622         unsigned int            i, j;
1623         unsigned int            modifiers[] =
1624             { 0, LockMask, numlockmask, numlockmask|LockMask };
1625
1626         updatenumlockmask();
1627         XUngrabButton(display, AnyButton, AnyModifier, win->id);
1628         if(focused) {
1629                 for (i = 0; i < LENGTH(buttons); i++)
1630                         if (buttons[i].action == client_click)
1631                                 for (j = 0; j < LENGTH(modifiers); j++)
1632                                         XGrabButton(display, buttons[i].button,
1633                                             buttons[i].mask | modifiers[j],
1634                                             win->id, False, BUTTONMASK,
1635                                             GrabModeAsync, GrabModeSync, None,
1636                                             None);
1637         } else
1638                 XGrabButton(display, AnyButton, AnyModifier, win->id, False,
1639                     BUTTONMASK, GrabModeAsync, GrabModeSync, None, None);
1640 }
1641
1642 void
1643 expose(XEvent *e)
1644 {
1645         DNPRINTF(SWM_D_EVENT, "expose: window: %lu\n", e->xexpose.window);
1646 }
1647
1648 void
1649 keypress(XEvent *e)
1650 {
1651         unsigned int            i;
1652         KeySym                  keysym;
1653         XKeyEvent               *ev = &e->xkey;
1654
1655         DNPRINTF(SWM_D_EVENT, "keypress: window: %lu\n", ev->window);
1656
1657         keysym = XKeycodeToKeysym(display, (KeyCode)ev->keycode, 0);
1658         for (i = 0; i < LENGTH(keys); i++)
1659                 if (keysym == keys[i].keysym
1660                    && CLEANMASK(keys[i].mod) == CLEANMASK(ev->state)
1661                    && keys[i].func)
1662                         keys[i].func(root_to_region(ev->root),
1663                             &(keys[i].args));
1664 }
1665
1666 void
1667 buttonpress(XEvent *e)
1668 {
1669         XButtonPressedEvent     *ev = &e->xbutton;
1670
1671         struct ws_win           *win;
1672         int                     i, action;
1673
1674         DNPRINTF(SWM_D_EVENT, "buttonpress: window: %lu\n", ev->window);
1675
1676         action = root_click;
1677         if ((win = find_window(ev->window)) == NULL)
1678                 return;
1679         else {
1680                 focus_win(win);
1681                 action = client_click;
1682         }
1683
1684         for (i = 0; i < LENGTH(buttons); i++)
1685                 if (action == buttons[i].action && buttons[i].func &&
1686                     buttons[i].button == ev->button &&
1687                     CLEANMASK(buttons[i].mask) == CLEANMASK(ev->state))
1688                         buttons[i].func(root_to_region(ev->root),
1689                         &buttons[i].args);
1690 }
1691
1692 void
1693 set_win_state(struct ws_win *win, long state)
1694 {
1695         long                    data[] = {state, None};
1696
1697         DNPRINTF(SWM_D_EVENT, "set_win_state: window: %lu\n", win->id);
1698
1699         XChangeProperty(display, win->id, astate, astate, 32, PropModeReplace,
1700             (unsigned char *)data, 2);
1701 }
1702
1703 struct ws_win *
1704 manage_window(Window id)
1705 {
1706         Window                  trans;
1707         struct workspace        *ws;
1708         struct ws_win           *win;
1709         XClassHint              ch;
1710         int                     format;
1711         unsigned long           nitems, bytes;
1712         Atom                    ws_idx_atom = 0, type;
1713         unsigned char           ws_idx_str[SWM_PROPLEN], *prop = NULL;
1714         struct swm_region       *r;
1715         long                    mask;
1716
1717         if ((win = find_window(id)) != NULL)
1718                         return (win);   /* already being managed */
1719
1720         if ((win = calloc(1, sizeof(struct ws_win))) == NULL)
1721                 errx(1, "calloc: failed to allocate memory for new window");
1722
1723         ws_idx_atom = XInternAtom(display, "_SWM_WS", False);
1724         if (ws_idx_atom)
1725                 XGetWindowProperty(display, id, ws_idx_atom, 0, SWM_PROPLEN,
1726                     False, XA_STRING, &type, &format, &nitems, &bytes, &prop);
1727
1728         XGetWindowAttributes(display, id, &win->wa);
1729         r = root_to_region(win->wa.root);
1730         /* If the window was managed before, put it in the same workspace */
1731         if (prop) {
1732                 int             ws_idx;
1733                 const char      *errstr;
1734
1735                 DNPRINTF(SWM_D_PROP, "got property _SWM_WS=%s\n", prop);
1736                 ws_idx = strtonum(prop, 0, 9, &errstr);
1737                 if (errstr)
1738                         DNPRINTF(SWM_D_EVENT, "window idx is %s: %s",
1739                             errstr, prop);
1740                 ws = &r->s->ws[ws_idx];
1741         } else
1742                 ws = r->ws;
1743
1744         win->id = id;
1745         win->ws = ws;
1746         win->s = r->s;  /* this never changes */
1747         TAILQ_INSERT_TAIL(&ws->winlist, win, entry);
1748
1749         /* make new win focused */
1750         focus_win(win);
1751
1752         XGetTransientForHint(display, win->id, &trans);
1753         if (trans) {
1754                 win->transient = trans;
1755                 DNPRINTF(SWM_D_MISC, "manage_window: win %u transient %u\n",
1756                     (unsigned)win->id, win->transient);
1757         }
1758         win->g.w = win->wa.width;
1759         win->g.h = win->wa.height;
1760         win->g.x = win->wa.x;
1761         win->g.y = win->wa.y;
1762
1763         XGetWMNormalHints(display, win->id, &win->sh, &mask);
1764
1765         if (ws_idx_atom && prop == NULL &&
1766             snprintf(ws_idx_str, SWM_PROPLEN, "%d", ws->idx) < SWM_PROPLEN) {
1767                 DNPRINTF(SWM_D_PROP, "setting property _SWM_WS to %s\n",
1768                     ws_idx_str);
1769                 XChangeProperty(display, win->id, ws_idx_atom, XA_STRING, 8,
1770                     PropModeReplace, ws_idx_str, SWM_PROPLEN);
1771         }
1772         XFree(prop);
1773
1774         /*
1775         fprintf(stderr, "manage window: %d x %d y %d w %d h %d\n", win->id, win->g.x, win->g.y, win->g.w, win->g.h);
1776         */
1777
1778         /* XXX make this a table */
1779         bzero(&ch, sizeof ch);
1780         if (XGetClassHint(display, win->id, &ch)) {
1781                 /*fprintf(stderr, "class: %s name: %s\n", ch.res_class, ch.res_name); */
1782                 if (!strcmp(ch.res_class, "MPlayer") && !strcmp(ch.res_name, "xv")) {
1783                         win->floating = 1;
1784                 }
1785                 if (ch.res_class)
1786                         XFree(ch.res_class);
1787                 if (ch.res_name)
1788                         XFree(ch.res_name);
1789         }
1790
1791         XSelectInput(display, id, EnterWindowMask | FocusChangeMask |
1792             PropertyChangeMask | StructureNotifyMask);
1793
1794         set_win_state(win, NormalState);
1795
1796         return (win);
1797 }
1798
1799 void
1800 configurerequest(XEvent *e)
1801 {
1802         XConfigureRequestEvent  *ev = &e->xconfigurerequest;
1803         struct ws_win           *win;
1804         int                     new = 0;
1805         XWindowChanges          wc;
1806
1807         if ((win = find_window(ev->window)) == NULL)
1808                 new = 1;
1809
1810         if (new) {
1811                 DNPRINTF(SWM_D_EVENT, "configurerequest: new window: %lu\n",
1812                     ev->window);
1813                 /*
1814                 fprintf(stderr, "configurerequest: new window: %lu x %d y %d w %d h %d bw %d s %d sm %d\n",
1815                     ev->window, ev->x, ev->y, ev->width, ev->height, ev->border_width, ev->above, ev->detail);
1816                 */
1817                 bzero(&wc, sizeof wc);
1818                 wc.x = ev->x;
1819                 wc.y = ev->y;
1820                 wc.width = ev->width;
1821                 wc.height = ev->height;
1822                 wc.border_width = ev->border_width;
1823                 wc.sibling = ev->above;
1824                 wc.stack_mode = ev->detail;
1825                 XConfigureWindow(display, ev->window, ev->value_mask, &wc);
1826         } else {
1827                 /*
1828                 fprintf(stderr, "configurerequest: change window: %lu\n",
1829                     ev->window);
1830                 */
1831                 DNPRINTF(SWM_D_EVENT, "configurerequest: change window: %lu\n",
1832                     ev->window);
1833                 if (win->floating) {
1834                         if (ev->value_mask & CWX)
1835                                 win->g.x = ev->x;
1836                         if (ev->value_mask & CWY)
1837                                 win->g.y = ev->y;
1838                         if (ev->value_mask & CWWidth)
1839                                 win->g.w = ev->width;
1840                         if (ev->value_mask & CWHeight)
1841                                 win->g.h = ev->height;
1842                         if (win->ws->r != NULL) {
1843                                 /* this seems to be full screen */
1844                                 if (win->g.w > WIDTH(win->ws->r)) {
1845                                         /* kill border */
1846                                         win->g.x -= 1;
1847                                         win->g.w += 1;
1848                                 }
1849                                 if (win->g.h > HEIGHT(win->ws->r)) {
1850                                         /* kill border */
1851                                         win->g.y -= 1;
1852                                         win->g.h += 1;
1853                                 }
1854                         }
1855                         if ((ev->value_mask & (CWX|CWY)) &&
1856                             !(ev->value_mask & (CWWidth|CWHeight)))
1857                                 config_win(win);
1858                         XMoveResizeWindow(display, win->id,
1859                             win->g.x, win->g.y, win->g.w, win->g.h);
1860                 } else
1861                         config_win(win);
1862         }
1863 }
1864
1865 void
1866 configurenotify(XEvent *e)
1867 {
1868         DNPRINTF(SWM_D_EVENT, "configurenotify: window: %lu\n",
1869             e->xconfigure.window);
1870 }
1871
1872 void
1873 destroynotify(XEvent *e)
1874 {
1875         struct ws_win           *win;
1876         XDestroyWindowEvent     *ev = &e->xdestroywindow;
1877         struct workspace        *ws;
1878
1879         DNPRINTF(SWM_D_EVENT, "destroynotify: window %lu\n", ev->window);
1880
1881         if ((win = find_window(ev->window)) != NULL) {
1882                 ws = win->ws;
1883                 /* find a window to focus */
1884                 if (ws->focus == win)
1885                         ws->focus = TAILQ_PREV(win, ws_win_list, entry);
1886                 if (ws->focus == NULL)
1887                         ws->focus = TAILQ_FIRST(&ws->winlist);
1888                 if (ws->focus == win)
1889                         ws->focus = NULL;
1890                 if (cur_focus == win)
1891                         focus_win(ws->focus);
1892
1893                 TAILQ_REMOVE(&ws->winlist, win, entry);
1894                 set_win_state(win, WithdrawnState);
1895                 free(win);
1896         }
1897         stack();
1898 }
1899
1900 void
1901 enternotify(XEvent *e)
1902 {
1903         XCrossingEvent          *ev = &e->xcrossing;
1904         struct ws_win           *win;
1905
1906         DNPRINTF(SWM_D_EVENT, "enternotify: window: %lu\n", ev->window);
1907
1908         if (ignore_enter) {
1909                 /* eat event(r) to prevent autofocus */
1910                 ignore_enter--;
1911                 return;
1912         }
1913
1914         if ((win = find_window(ev->window)) != NULL)
1915                 focus_win(win);
1916 }
1917
1918 void
1919 focusin(XEvent *e)
1920 {
1921         DNPRINTF(SWM_D_EVENT, "focusin: window: %lu\n", e->xfocus.window);
1922 }
1923
1924 void
1925 mappingnotify(XEvent *e)
1926 {
1927         XMappingEvent           *ev = &e->xmapping;
1928
1929         DNPRINTF(SWM_D_EVENT, "mappingnotify: window: %lu\n", ev->window);
1930
1931         XRefreshKeyboardMapping(ev);
1932         if (ev->request == MappingKeyboard)
1933                 grabkeys();
1934 }
1935
1936 void
1937 maprequest(XEvent *e)
1938 {
1939         XMapRequestEvent        *ev = &e->xmaprequest;
1940         XWindowAttributes       wa;
1941
1942         DNPRINTF(SWM_D_EVENT, "maprequest: window: %lu\n",
1943             e->xmaprequest.window);
1944
1945         if (!XGetWindowAttributes(display, ev->window, &wa))
1946                 return;
1947         if (wa.override_redirect)
1948                 return;
1949         manage_window(e->xmaprequest.window);
1950         stack();
1951 }
1952
1953 void
1954 propertynotify(XEvent *e)
1955 {
1956         DNPRINTF(SWM_D_EVENT, "propertynotify: window: %lu\n",
1957             e->xproperty.window);
1958 }
1959
1960 void
1961 unmapnotify(XEvent *e)
1962 {
1963         DNPRINTF(SWM_D_EVENT, "unmapnotify: window: %lu\n", e->xunmap.window);
1964 }
1965
1966 void
1967 visibilitynotify(XEvent *e)
1968 {
1969         int                     i;
1970         struct swm_region       *r;
1971
1972         DNPRINTF(SWM_D_EVENT, "visibilitynotify: window: %lu\n",
1973             e->xvisibility.window);
1974         if (e->xvisibility.state == VisibilityUnobscured)
1975                 for (i = 0; i < ScreenCount(display); i++) 
1976                         TAILQ_FOREACH(r, &screens[i].rl, entry)
1977                                 if (e->xvisibility.window == r->bar_window)
1978                                         bar_update();
1979 }
1980
1981 void                    (*handler[LASTEvent])(XEvent *) = {
1982                                 [Expose] = expose,
1983                                 [KeyPress] = keypress,
1984                                 [ButtonPress] = buttonpress,
1985                                 [ConfigureRequest] = configurerequest,
1986                                 [ConfigureNotify] = configurenotify,
1987                                 [DestroyNotify] = destroynotify,
1988                                 [EnterNotify] = enternotify,
1989                                 [FocusIn] = focusin,
1990                                 [MappingNotify] = mappingnotify,
1991                                 [MapRequest] = maprequest,
1992                                 [PropertyNotify] = propertynotify,
1993                                 [UnmapNotify] = unmapnotify,
1994                                 [VisibilityNotify] = visibilitynotify,
1995 };
1996
1997 int
1998 xerror_start(Display *d, XErrorEvent *ee)
1999 {
2000         other_wm = 1;
2001         return (-1);
2002 }
2003
2004 int
2005 xerror(Display *d, XErrorEvent *ee)
2006 {
2007         /* fprintf(stderr, "error: %p %p\n", display, ee); */
2008         return (-1);
2009 }
2010
2011 int
2012 active_wm(void)
2013 {
2014         other_wm = 0;
2015         xerrorxlib = XSetErrorHandler(xerror_start);
2016
2017         /* this causes an error if some other window manager is running */
2018         XSelectInput(display, DefaultRootWindow(display),
2019             SubstructureRedirectMask);
2020         XSync(display, False);
2021         if (other_wm)
2022                 return (1);
2023
2024         XSetErrorHandler(xerror);
2025         XSync(display, False);
2026         return (0);
2027 }
2028
2029 long
2030 getstate(Window w)
2031 {
2032         int                     format, status;
2033         long                    result = -1;
2034         unsigned char           *p = NULL;
2035         unsigned long           n, extra;
2036         Atom                    real;
2037
2038         astate = XInternAtom(display, "WM_STATE", False);
2039         status = XGetWindowProperty(display, w, astate, 0L, 2L, False, astate,
2040             &real, &format, &n, &extra, (unsigned char **)&p);
2041         if (status != Success)
2042                 return (-1);
2043         if (n != 0)
2044                 result = *p;
2045         XFree(p);
2046         return (result);
2047 }
2048
2049 void
2050 new_region(struct swm_screen *s, struct workspace *ws,
2051     int x, int y, int w, int h)
2052 {
2053         struct swm_region       *r;
2054
2055         DNPRINTF(SWM_D_MISC, "new region on screen %d: %dx%d (%d, %d)\n",
2056              s->idx, x, y, w, h);
2057
2058         if ((r = calloc(1, sizeof(struct swm_region))) == NULL)
2059                 errx(1, "calloc: failed to allocate memory for screen");
2060
2061         X(r) = x;
2062         Y(r) = y;
2063         WIDTH(r) = w;
2064         HEIGHT(r) = h;
2065         r->s = s;
2066         r->ws = ws;
2067         ws->r = r;
2068         TAILQ_INSERT_TAIL(&s->rl, r, entry);
2069         bar_setup(r);
2070 }
2071
2072 void
2073 setup_screens(void)
2074 {
2075 #ifdef SWM_XRR_HAS_CRTC
2076         XRRCrtcInfo             *ci;
2077         XRRScreenResources      *sr;
2078         int                     c;
2079 #endif /* SWM_XRR_HAS_CRTC */
2080         Window                  d1, d2, *wins = NULL;
2081         XWindowAttributes       wa;
2082         struct swm_region       *r;
2083         unsigned int            no;
2084         int                     errorbase, major, minor;
2085         int                     ncrtc = 0, w = 0;
2086         int                     i, j, k;
2087         struct workspace        *ws;
2088         int                     ws_idx_atom;
2089
2090
2091         if ((screens = calloc(ScreenCount(display),
2092              sizeof(struct swm_screen))) == NULL)
2093                 errx(1, "calloc: screens");
2094
2095         ws_idx_atom = XInternAtom(display, "_SWM_WS", False);
2096         
2097
2098         /* map physical screens */
2099         for (i = 0; i < ScreenCount(display); i++) {
2100                 DNPRINTF(SWM_D_WS, "setup_screens: init screen %d\n", i);
2101                 screens[i].idx = i;
2102                 TAILQ_INIT(&screens[i].rl);
2103                 screens[i].root = RootWindow(display, i);
2104
2105                 /* set default colors */
2106                 setscreencolor("red", i + 1, SWM_S_COLOR_FOCUS);
2107                 setscreencolor("rgb:88/88/88", i + 1, SWM_S_COLOR_UNFOCUS);
2108                 setscreencolor("rgb:00/80/80", i + 1, SWM_S_COLOR_BAR_BORDER);
2109                 setscreencolor("black", i + 1, SWM_S_COLOR_BAR);
2110                 setscreencolor("rgb:a0/a0/a0", i + 1, SWM_S_COLOR_BAR_FONT);
2111
2112                 /* init all workspaces */
2113                 for (j = 0; j < SWM_WS_MAX; j++) {
2114                         ws = &screens[i].ws[j];
2115                         ws->idx = j;
2116                         ws->restack = 1;
2117                         ws->focus = NULL;
2118                         ws->r = NULL;
2119                         TAILQ_INIT(&ws->winlist);
2120
2121                         for (k = 0; layouts[k].l_stack != NULL; k++)
2122                                 if (layouts[k].l_config != NULL)
2123                                         layouts[k].l_config(ws,
2124                                             SWM_ARG_ID_STACKINIT);
2125                         ws->cur_layout = &layouts[0];
2126                 }
2127
2128                 /* map virtual screens onto physical screens */
2129                 screens[i].xrandr_support = XRRQueryExtension(display,
2130                     &xrandr_eventbase, &errorbase);
2131                 if (screens[i].xrandr_support)
2132                         if (XRRQueryVersion(display, &major, &minor) &&
2133                             major < 1)
2134                                 screens[i].xrandr_support = 0;
2135
2136 #if 0   /* not ready for dynamic screen changes */
2137                 if (screens[i].xrandr_support)
2138                         XRRSelectInput(display,
2139                             screens[r->s].root,
2140                             RRScreenChangeNotifyMask);
2141 #endif
2142
2143                 /* grab existing windows (before we build the bars)*/
2144                 if (!XQueryTree(display, screens[i].root, &d1, &d2, &wins, &no))
2145                         continue;
2146
2147 #ifdef SWM_XRR_HAS_CRTC
2148                 sr = XRRGetScreenResources(display, screens[i].root);
2149                 if (sr == NULL)
2150                         new_region(&screens[i], &screens[i].ws[w],
2151                             0, 0, DisplayWidth(display, i),
2152                             DisplayHeight(display, i)); 
2153                 else 
2154                         ncrtc = sr->ncrtc;
2155
2156                 for (c = 0, ci = NULL; c < ncrtc; c++) {
2157                         ci = XRRGetCrtcInfo(display, sr, sr->crtcs[c]);
2158                         if (ci->noutput == 0)
2159                                 continue;
2160
2161                         if (ci != NULL && ci->mode == None)
2162                                 new_region(&screens[i], &screens[i].ws[w], 0, 0,
2163                                     DisplayWidth(display, i),
2164                                     DisplayHeight(display, i)); 
2165                         else
2166                                 new_region(&screens[i], &screens[i].ws[w],
2167                                     ci->x, ci->y, ci->width, ci->height);
2168                         w++;
2169                 }
2170                 if (ci)
2171                         XRRFreeCrtcInfo(ci);
2172                 XRRFreeScreenResources(sr);
2173 #else
2174                 new_region(&screens[i], &screens[i].ws[w], 0, 0,
2175                     DisplayWidth(display, i),
2176                     DisplayHeight(display, i)); 
2177 #endif /* SWM_XRR_HAS_CRTC */
2178
2179                 /* attach windows to a region */
2180                 /* normal windows */
2181                 if ((r = TAILQ_FIRST(&screens[i].rl)) == NULL)
2182                         errx(1, "no regions on screen %d", i);
2183
2184                 for (i = 0; i < no; i++) {
2185                         XGetWindowAttributes(display, wins[i], &wa);
2186                         if (!XGetWindowAttributes(display, wins[i], &wa) ||
2187                             wa.override_redirect ||
2188                             XGetTransientForHint(display, wins[i], &d1))
2189                                 continue;
2190
2191                         if (wa.map_state == IsViewable ||
2192                             getstate(wins[i]) == NormalState)
2193                                 manage_window(wins[i]);
2194                 }
2195                 /* transient windows */
2196                 for (i = 0; i < no; i++) {
2197                         if (!XGetWindowAttributes(display, wins[i], &wa))
2198                                 continue;
2199
2200                         if (XGetTransientForHint(display, wins[i], &d1) &&
2201                             (wa.map_state == IsViewable || getstate(wins[i]) ==
2202                             NormalState))
2203                                 manage_window(wins[i]);
2204                 }
2205                 if (wins) {
2206                         XFree(wins);
2207                         wins = NULL;
2208                 }
2209         }
2210 }
2211
2212 int
2213 main(int argc, char *argv[])
2214 {
2215         struct passwd           *pwd;
2216         char                    conf[PATH_MAX], *cfile = NULL;
2217         struct stat             sb;
2218         XEvent                  e;
2219         int                     xfd;
2220         fd_set                  rd;
2221
2222         start_argv = argv;
2223         fprintf(stderr, "Welcome to scrotwm V%s\n", SWM_VERSION);
2224         if (!setlocale(LC_CTYPE, "") || !XSupportsLocale())
2225                 warnx("no locale support");
2226
2227         if (!(display = XOpenDisplay(0)))
2228                 errx(1, "can not open display");
2229
2230         if (active_wm())
2231                 errx(1, "other wm running");
2232
2233         astate = XInternAtom(display, "WM_STATE", False);
2234
2235         /* look for local and global conf file */
2236         pwd = getpwuid(getuid());
2237         if (pwd == NULL)
2238                 errx(1, "invalid user %d", getuid());
2239
2240         setup_screens();
2241
2242         snprintf(conf, sizeof conf, "%s/.%s", pwd->pw_dir, SWM_CONF_FILE);
2243         if (stat(conf, &sb) != -1) {
2244                 if (S_ISREG(sb.st_mode))
2245                         cfile = conf;
2246         } else {
2247                 /* try global conf file */
2248                 snprintf(conf, sizeof conf, "/etc/%s", SWM_CONF_FILE);
2249                 if (!stat(conf, &sb))
2250                         if (S_ISREG(sb.st_mode))
2251                                 cfile = conf;
2252         }
2253         if (cfile)
2254                 conf_load(cfile);
2255         bar_refresh();
2256
2257         /* ws[0].focus = TAILQ_FIRST(&ws[0].winlist); */
2258
2259         grabkeys();
2260         stack();
2261
2262         xfd = ConnectionNumber(display);
2263         while (running) {
2264                 FD_ZERO(&rd);
2265                 FD_SET(xfd, &rd);
2266                 if (select(xfd + 1, &rd, NULL, NULL, NULL) == -1)
2267                         if (errno != EINTR)
2268                                 errx(1, "select failed");
2269                 if (bar_alarm) {
2270                         bar_alarm = 0;
2271                         bar_update();
2272                 }
2273                 while(XPending(display)) {
2274                         XNextEvent(display, &e);
2275                         if (handler[e.type])
2276                                 handler[e.type](&e);
2277                 }
2278         }
2279
2280         XCloseDisplay(display);
2281
2282         return (0);
2283 }