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