JasonWoof Got questions, comments, patches, etc.? Contact Jason Woofenden
Put some lower bounds on resize; from Alexander Hall
[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 static const char       *cvstag = "$scrotwm$";
52
53 #define SWM_VERSION     "0.8"
54
55 #include <stdio.h>
56 #include <stdlib.h>
57 #include <err.h>
58 #include <errno.h>
59 #include <fcntl.h>
60 #include <locale.h>
61 #include <unistd.h>
62 #include <time.h>
63 #include <signal.h>
64 #include <string.h>
65 #include <util.h>
66 #include <pwd.h>
67 #include <ctype.h>
68
69 #include <sys/types.h>
70 #include <sys/time.h>
71 #include <sys/stat.h>
72 #include <sys/wait.h>
73 #include <sys/queue.h>
74 #include <sys/param.h>
75 #include <sys/select.h>
76
77 #include <X11/cursorfont.h>
78 #include <X11/keysym.h>
79 #include <X11/Xatom.h>
80 #include <X11/Xlib.h>
81 #include <X11/Xproto.h>
82 #include <X11/Xutil.h>
83 #include <X11/extensions/Xrandr.h>
84
85 #if RANDR_MAJOR < 1
86 #  error XRandR versions less than 1.0 are not supported
87 #endif
88
89 #if RANDR_MAJOR >= 1
90 #if RANDR_MINOR >= 2
91 #define SWM_XRR_HAS_CRTC
92 #endif
93 #endif
94
95 /* #define SWM_DEBUG */
96 #ifdef SWM_DEBUG
97 #define DPRINTF(x...)           do { if (swm_debug) fprintf(stderr, x); } while(0)
98 #define DNPRINTF(n,x...)        do { if (swm_debug & n) fprintf(stderr, x); } while(0)
99 #define SWM_D_MISC              0x0001
100 #define SWM_D_EVENT             0x0002
101 #define SWM_D_WS                0x0004
102 #define SWM_D_FOCUS             0x0008
103 #define SWM_D_MOVE              0x0010
104 #define SWM_D_STACK             0x0020
105 #define SWM_D_MOUSE             0x0040
106 #define SWM_D_PROP              0x0080
107 #define SWM_D_CLASS             0x0100
108
109 u_int32_t               swm_debug = 0
110                             | SWM_D_MISC
111                             | SWM_D_EVENT
112                             | SWM_D_WS
113                             | SWM_D_FOCUS
114                             | SWM_D_MOVE
115                             | SWM_D_STACK
116                             | SWM_D_MOUSE
117                             | SWM_D_PROP
118                             | SWM_D_CLASS
119                             ;
120 #else
121 #define DPRINTF(x...)
122 #define DNPRINTF(n,x...)
123 #endif
124
125 #define LENGTH(x)               (sizeof x / sizeof x[0])
126 #define MODKEY                  Mod1Mask
127 #define CLEANMASK(mask)         (mask & ~(numlockmask | LockMask))
128 #define BUTTONMASK              (ButtonPressMask|ButtonReleaseMask)
129 #define MOUSEMASK               (BUTTONMASK|PointerMotionMask)
130 #define SWM_PROPLEN             (16)
131 #define X(r)                    (r)->g.x
132 #define Y(r)                    (r)->g.y
133 #define WIDTH(r)                (r)->g.w
134 #define HEIGHT(r)               (r)->g.h
135 #define SWM_MAX_FONT_STEPS      (3)
136
137 #ifndef SWM_LIB
138 #define SWM_LIB                 "/usr/X11R6/lib/swmhack.so"
139 #endif
140
141 char                    **start_argv;
142 Atom                    astate;
143 int                     (*xerrorxlib)(Display *, XErrorEvent *);
144 int                     other_wm;
145 int                     running = 1;
146 int                     ss_enabled = 0;
147 int                     xrandr_support;
148 int                     xrandr_eventbase;
149 int                     ignore_enter = 0;
150 unsigned int            numlockmask = 0;
151 Display                 *display;
152
153 int                     cycle_empty = 0;
154 int                     cycle_visible = 0;
155 int                     term_width = 0;
156 int                     font_adjusted = 0;
157
158 /* dialog windows */
159 double                  dialog_ratio = .6;
160 /* status bar */
161 #define SWM_BAR_MAX     (128)
162 char                    *bar_argv[] = { NULL, NULL };
163 int                     bar_pipe[2];
164 char                    bar_ext[SWM_BAR_MAX];
165 char                    bar_vertext[SWM_BAR_MAX];
166 int                     bar_version = 0;
167 sig_atomic_t            bar_alarm = 0;
168 int                     bar_delay = 30;
169 int                     bar_enabled = 1;
170 int                     bar_extra = 1;
171 int                     bar_extra_running = 0;
172 int                     bar_verbose = 1;
173 int                     bar_height = 0;
174 pid_t                   bar_pid;
175 GC                      bar_gc;
176 XGCValues               bar_gcv;
177 int                     bar_fidx = 0;
178 XFontStruct             *bar_fs;
179 char                    *bar_fonts[] = {
180                             "-*-terminus-*-*-*-*-*-*-*-*-*-*-*-*",
181                             "-*-times-medium-r-*-*-*-*-*-*-*-*-*-*",
182                             NULL
183 };
184
185 /* terminal + args */
186 char                    *spawn_term[] = { "xterm", NULL };
187 char                    *spawn_screenshot[] = { "screenshot.sh", NULL, NULL };
188 char                    *spawn_lock[] = { "xlock", NULL };
189 char                    *spawn_initscr[] = { "initscreen.sh", NULL };
190 char                    *spawn_menu[] = { "dmenu_run", "-fn", NULL, "-nb", NULL,
191                             "-nf", NULL, "-sb", NULL, "-sf", NULL, NULL };
192
193 #define SWM_MENU_FN     (2)
194 #define SWM_MENU_NB     (4)
195 #define SWM_MENU_NF     (6)
196 #define SWM_MENU_SB     (8)
197 #define SWM_MENU_SF     (10)
198
199 /* layout manager data */
200 struct swm_geometry {
201         int                     x;
202         int                     y;
203         int                     w;
204         int                     h;
205 };
206
207 struct swm_screen;
208 struct workspace;
209
210 /* virtual "screens" */
211 struct swm_region {
212         TAILQ_ENTRY(swm_region) entry;
213         struct swm_geometry     g;
214         struct workspace        *ws;    /* current workspace on this region */
215         struct swm_screen       *s;     /* screen idx */
216         Window                  bar_window;
217 }; 
218 TAILQ_HEAD(swm_region_list, swm_region);
219
220 struct ws_win {
221         TAILQ_ENTRY(ws_win)     entry;
222         Window                  id;
223         struct swm_geometry     g;
224         int                     got_focus;
225         int                     floating;
226         int                     transient;
227         int                     manual;
228         int                     font_size_boundary[SWM_MAX_FONT_STEPS];
229         int                     font_steps;
230         int                     last_inc;
231         unsigned long           quirks;
232         struct workspace        *ws;    /* always valid */
233         struct swm_screen       *s;     /* always valid, never changes */
234         XWindowAttributes       wa;
235         XSizeHints              sh;
236         XClassHint              ch;
237 };
238 TAILQ_HEAD(ws_win_list, ws_win);
239
240 /* layout handlers */
241 void    stack(void);
242 void    vertical_config(struct workspace *, int);
243 void    vertical_stack(struct workspace *, struct swm_geometry *);
244 void    horizontal_config(struct workspace *, int);
245 void    horizontal_stack(struct workspace *, struct swm_geometry *);
246 void    max_stack(struct workspace *, struct swm_geometry *);
247
248 void    grabbuttons(struct ws_win *, int);
249
250 struct layout {
251         void            (*l_stack)(struct workspace *, struct swm_geometry *);
252         void            (*l_config)(struct workspace *, int);
253 } layouts[] =  {
254         /* stack,               configure */
255         { vertical_stack,       vertical_config},
256         { horizontal_stack,     horizontal_config},
257         { max_stack,            NULL},
258         { NULL,                 NULL},
259 };
260
261 #define SWM_H_SLICE             (32)
262 #define SWM_V_SLICE             (32)
263
264 /* define work spaces */
265 struct workspace {
266         int                     idx;            /* workspace index */
267         int                     restack;        /* restack on switch */
268         struct layout           *cur_layout;    /* current layout handlers */
269         struct ws_win           *focus;         /* may be NULL */
270         struct ws_win           *focus_prev;    /* may be NULL */
271         struct swm_region       *r;             /* may be NULL */
272         struct ws_win_list      winlist;        /* list of windows in ws */
273
274         /* stacker state */
275         struct {
276                                 int horizontal_msize;
277                                 int horizontal_mwin;
278                                 int horizontal_stacks;
279                                 int vertical_msize;
280                                 int vertical_mwin;
281                                 int vertical_stacks;
282         } l_state;
283 };
284
285 enum    { SWM_S_COLOR_BAR, SWM_S_COLOR_BAR_BORDER, SWM_S_COLOR_BAR_FONT,
286           SWM_S_COLOR_FOCUS, SWM_S_COLOR_UNFOCUS, SWM_S_COLOR_MAX };
287
288 /* physical screen mapping */
289 #define SWM_WS_MAX              (10)            /* XXX Too small? */
290 struct swm_screen {
291         int                     idx;            /* screen index */
292         struct swm_region_list  rl;     /* list of regions on this screen */
293         struct swm_region_list  orl;    /* list of old regions */
294         Window                  root;
295         struct workspace        ws[SWM_WS_MAX];
296
297         /* colors */
298         struct {
299                 unsigned long   color;
300                 char            *name;
301         } c[SWM_S_COLOR_MAX];
302 };
303 struct swm_screen       *screens;
304 int                     num_screens;
305
306 struct ws_win           *cur_focus = NULL;
307
308 /* args to functions */
309 union arg {
310         int                     id;
311 #define SWM_ARG_ID_FOCUSNEXT    (0)
312 #define SWM_ARG_ID_FOCUSPREV    (1)
313 #define SWM_ARG_ID_FOCUSMAIN    (2)
314 #define SWM_ARG_ID_SWAPNEXT     (3)
315 #define SWM_ARG_ID_SWAPPREV     (4)
316 #define SWM_ARG_ID_SWAPMAIN     (5)
317 #define SWM_ARG_ID_MASTERSHRINK (6)
318 #define SWM_ARG_ID_MASTERGROW   (7)
319 #define SWM_ARG_ID_MASTERADD    (8)
320 #define SWM_ARG_ID_MASTERDEL    (9)
321 #define SWM_ARG_ID_STACKRESET   (10)
322 #define SWM_ARG_ID_STACKINIT    (11)
323 #define SWM_ARG_ID_CYCLEWS_UP   (12)
324 #define SWM_ARG_ID_CYCLEWS_DOWN (13)
325 #define SWM_ARG_ID_CYCLESC_UP   (14)
326 #define SWM_ARG_ID_CYCLESC_DOWN (15)
327 #define SWM_ARG_ID_STACKINC     (16)
328 #define SWM_ARG_ID_STACKDEC     (17)
329 #define SWM_ARG_ID_SS_ALL       (0)
330 #define SWM_ARG_ID_SS_WINDOW    (1)
331 #define SWM_ARG_ID_DONTCENTER   (0)
332 #define SWM_ARG_ID_CENTER       (1)
333         char                    **argv;
334 };
335
336 /* quirks */
337 struct quirk {
338         char                    *class;
339         char                    *name;
340         unsigned long           quirk;
341 #define SWM_Q_FLOAT             (1<<0)  /* float this window */
342 #define SWM_Q_TRANSSZ           (1<<1)  /* transiend window size too small */
343 #define SWM_Q_ANYWHERE          (1<<2)  /* don't position this window */
344 #define SWM_Q_XTERM_FONTADJ     (1<<3)  /* adjust xterm fonts when resizing */
345 } quirks[] = {
346         { "MPlayer",            "xv",           SWM_Q_FLOAT },
347         { "OpenOffice.org 2.4", "VCLSalFrame",  SWM_Q_FLOAT },
348         { "OpenOffice.org 3.0", "VCLSalFrame",  SWM_Q_FLOAT },
349         { "Firefox-bin",        "firefox-bin",  SWM_Q_TRANSSZ},
350         { "Gimp",               "gimp",         SWM_Q_FLOAT | SWM_Q_ANYWHERE},
351         { "XTerm",              "xterm",        SWM_Q_XTERM_FONTADJ},
352         { NULL,                 NULL,           0},
353 };
354
355 /* events */
356 void                    expose(XEvent *);
357 void                    keypress(XEvent *);
358 void                    buttonpress(XEvent *);
359 void                    configurerequest(XEvent *);
360 void                    configurenotify(XEvent *);
361 void                    destroynotify(XEvent *);
362 void                    enternotify(XEvent *);
363 void                    focusin(XEvent *);
364 void                    mappingnotify(XEvent *);
365 void                    maprequest(XEvent *);
366 void                    propertynotify(XEvent *);
367 void                    unmapnotify(XEvent *);
368 void                    visibilitynotify(XEvent *);
369
370 void                    (*handler[LASTEvent])(XEvent *) = {
371                                 [Expose] = expose,
372                                 [KeyPress] = keypress,
373                                 [ButtonPress] = buttonpress,
374                                 [ConfigureRequest] = configurerequest,
375                                 [ConfigureNotify] = configurenotify,
376                                 [DestroyNotify] = destroynotify,
377                                 [EnterNotify] = enternotify,
378                                 [FocusIn] = focusin,
379                                 [MappingNotify] = mappingnotify,
380                                 [MapRequest] = maprequest,
381                                 [PropertyNotify] = propertynotify,
382                                 [UnmapNotify] = unmapnotify,
383                                 [VisibilityNotify] = visibilitynotify,
384 };
385
386 unsigned long
387 name_to_color(char *colorname)
388 {
389         Colormap                cmap;
390         Status                  status;
391         XColor                  screen_def, exact_def;
392         unsigned long           result = 0;
393         char                    cname[32] = "#";
394
395         cmap = DefaultColormap(display, screens[0].idx);
396         status = XAllocNamedColor(display, cmap, colorname,
397             &screen_def, &exact_def);
398         if (!status) {
399                 strlcat(cname, colorname + 2, sizeof cname - 1);
400                 status = XAllocNamedColor(display, cmap, cname, &screen_def,
401                     &exact_def);
402         }
403         if (status)
404                 result = screen_def.pixel;
405         else
406                 fprintf(stderr, "color '%s' not found.\n", colorname);
407
408         return (result);
409 }
410
411 void
412 setscreencolor(char *val, int i, int c)
413 {
414         if (i > 0 && i <= ScreenCount(display)) {
415                 screens[i - 1].c[c].color = name_to_color(val);
416                 if ((screens[i - 1].c[c].name = strdup(val)) == NULL)
417                         errx(1, "strdup");
418         } else if (i == -1) {
419                 for (i = 0; i < ScreenCount(display); i++)
420                         screens[i].c[c].color = name_to_color(val);
421                         if ((screens[i - 1].c[c].name = strdup(val)) == NULL)
422                                 errx(1, "strdup");
423         } else
424                 errx(1, "invalid screen index: %d out of bounds (maximum %d)\n",
425                     i, ScreenCount(display));
426 }
427
428 void            new_region(struct swm_screen *, int, int, int, int);
429
430 void
431 custom_region(char *val)
432 {
433         unsigned int                    sidx, x, y, w, h;
434
435         if (sscanf(val, "screen[%u]:%ux%u+%u+%u", &sidx, &w, &h, &x, &y) != 5)
436                 errx(1, "invalid custom region, "
437                     "should be 'screen[<n>]:<n>x<n>+<n>+<n>\n");
438         if (sidx < 1 || sidx > ScreenCount(display))
439                 errx(1, "invalid screen index: %d out of bounds (maximum %d)\n",
440                     sidx, ScreenCount(display));
441         sidx--;
442
443         if (w < 1 || h < 1)
444                 errx(1, "region %ux%u+%u+%u too small\n", w, h, x, y);
445
446         if (x  < 0 || x > DisplayWidth(display, sidx) ||
447             y < 0 || y > DisplayHeight(display, sidx) ||
448             w + x > DisplayWidth(display, sidx) ||
449             h + y > DisplayHeight(display, sidx))
450                 errx(1, "region %ux%u+%u+%u not within screen boundaries "
451                     "(%ux%u)\n", w, h, x, y,
452                     DisplayWidth(display, sidx), DisplayHeight(display, sidx));
453             
454         new_region(&screens[sidx], x, y, w, h);
455 }
456
457 int
458 varmatch(char *var, char *name, int *index)
459 {
460         char                    *p, buf[5];
461         int                     i;
462
463         i = strncmp(var, name, 255);
464         if (index == NULL)
465                 return (i);
466
467         *index = -1;
468         if (i <= 0)
469                 return (i);
470         p = var + strlen(name);
471         if (*p++ != '[')
472                 return (i);
473         bzero(buf, sizeof buf);
474         i = 0;
475         while (isdigit(*p) && i < sizeof buf)
476                 buf[i++] = *p++;
477         if (i == 0 || i >= sizeof buf || *p != ']')
478                 return (1);
479         *index = strtonum(buf, 0, 99, NULL);
480         return (0);
481 }
482
483 /* conf file stuff */
484 #define SWM_CONF_WS     "\n= \t"
485 #define SWM_CONF_FILE   "scrotwm.conf"
486 int
487 conf_load(char *filename)
488 {
489         FILE                    *config;
490         char                    *line, *cp, *var, *val;
491         size_t                  len, lineno = 0;
492         int                     i, sc;
493
494         DNPRINTF(SWM_D_MISC, "conf_load: filename %s\n", filename);
495
496         if (filename == NULL)
497                 return (1);
498
499         if ((config = fopen(filename, "r")) == NULL)
500                 return (1);
501
502         for (sc = ScreenCount(display);;) {
503                 if ((line = fparseln(config, &len, &lineno, NULL, 0)) == NULL)
504                         if (feof(config))
505                                 break;
506                 cp = line;
507                 cp += (long)strspn(cp, SWM_CONF_WS);
508                 if (cp[0] == '\0') {
509                         /* empty line */
510                         free(line);
511                         continue;
512                 }
513                 if ((var = strsep(&cp, SWM_CONF_WS)) == NULL || cp == NULL)
514                         break;
515                 cp += (long)strspn(cp, SWM_CONF_WS);
516                 if ((val = strsep(&cp, SWM_CONF_WS)) == NULL)
517                         break;
518
519                 DNPRINTF(SWM_D_MISC, "conf_load: %s=%s\n",var ,val);
520                 switch (var[0]) {
521                 case 'b':
522                         if (!strncmp(var, "bar_enabled", strlen("bar_enabled")))
523                                 bar_enabled = atoi(val);
524                         else if (!varmatch(var, "bar_border", &i))
525                                 setscreencolor(val, i, SWM_S_COLOR_BAR_BORDER);
526                         else if (!varmatch(var, "bar_color", &i))
527                                 setscreencolor(val, i, SWM_S_COLOR_BAR);
528                         else if (!varmatch(var, "bar_font_color", &i))
529                                 setscreencolor(val, i, SWM_S_COLOR_BAR_FONT);
530                         else if (!strncmp(var, "bar_font", strlen("bar_font")))
531                                 asprintf(&bar_fonts[0], "%s", val);
532                         else if (!strncmp(var, "bar_action", strlen("bar_action")))
533                                 asprintf(&bar_argv[0], "%s", val);
534                         else if (!strncmp(var, "bar_delay", strlen("bar_delay")))
535                                 bar_delay = atoi(val);
536                         else
537                                 goto bad;
538                         break;
539
540                 case 'c':
541                         if (!varmatch(var, "color_focus", &i))
542                                 setscreencolor(val, i, SWM_S_COLOR_FOCUS);
543                         else if (!varmatch(var, "color_unfocus", &i))
544                                 setscreencolor(val, i, SWM_S_COLOR_UNFOCUS);
545                         else if (!strncmp(var, "cycle_empty", strlen("cycle_empty")))
546                                 cycle_visible = atoi(val);
547                         else if (!strncmp(var, "cycle_visible", strlen("cycle_visible")))
548                                 cycle_visible = atoi(val);
549                         else
550                                 goto bad;
551                         break;
552
553                 case 'd':
554                         if (!strncmp(var, "dialog_ratio",
555                             strlen("dialog_ratio"))) {
556                                 dialog_ratio = atof(val);
557                                 if (dialog_ratio > 1.0 || dialog_ratio <= .3)
558                                         dialog_ratio = .6;
559                         } else
560                                 goto bad;
561                         break;
562
563                 case 'r':
564                         if (!strncmp(var, "region", strlen("region")))
565                                 custom_region(val);
566                         else
567                                 goto bad;
568                         break;
569
570                 case 's':
571                         if (!strncmp(var, "spawn_term", strlen("spawn_term")))
572                                 asprintf(&spawn_term[0], "%s", val);
573                         else if (!strncmp(var, "screenshot_enabled",
574                             strlen("screenshot_enabled")))
575                                 ss_enabled = atoi(val);
576                         else if (!strncmp(var, "screenshot_app",
577                             strlen("screenshot_app")))
578                                 asprintf(&spawn_screenshot[0], "%s", val);
579                         else
580                                 goto bad;
581                         break;
582
583                 case 't':
584                         if (!strncmp(var, "term_width", strlen("term_width")))
585                                 term_width = atoi(val);
586                         else
587                                 goto bad;
588                         break;
589
590                 default:
591                         goto bad;
592                 }
593                 free(line);
594         }
595
596         fclose(config);
597         return (0);
598
599 bad:
600         errx(1, "invalid conf file entry: %s=%s", var, val);
601 }
602
603 void
604 socket_setnonblock(int fd)
605 {
606         int                     flags;
607
608         if ((flags = fcntl(fd, F_GETFL, 0)) == -1)
609                 err(1, "fcntl F_GETFL");
610         flags |= O_NONBLOCK;
611         if ((flags = fcntl(fd, F_SETFL, flags)) == -1)
612                 err(1, "fcntl F_SETFL");
613 }
614
615 void
616 bar_print(struct swm_region *r, char *s)
617 {
618         XClearWindow(display, r->bar_window);
619         XSetForeground(display, bar_gc, r->s->c[SWM_S_COLOR_BAR_FONT].color);
620         XDrawString(display, r->bar_window, bar_gc, 4, bar_fs->ascent, s,
621             strlen(s));
622 }
623
624 void
625 bar_extra_stop(void)
626 {
627         if (bar_pipe[0]) {
628                 close(bar_pipe[0]);
629                 bzero(bar_pipe, sizeof bar_pipe);
630         }
631         if (bar_pid) {
632                 kill(bar_pid, SIGTERM);
633                 bar_pid = 0;
634         }
635         strlcpy(bar_ext, "", sizeof bar_ext);
636         bar_extra = 0;
637 }
638
639 void
640 bar_update(void)
641 {
642         time_t                  tmt;
643         struct tm               tm;
644         struct swm_region       *r;
645         int                     i, x;
646         size_t                  len;
647         char                    s[SWM_BAR_MAX];
648         char                    loc[SWM_BAR_MAX];
649         char                    *b;
650
651         if (bar_enabled == 0)
652                 return;
653         if (bar_extra && bar_extra_running) {
654                 /* ignore short reads; it'll correct itself */
655                 while ((b = fgetln(stdin, &len)) != NULL)
656                         if (b && b[len - 1] == '\n') {
657                                 b[len - 1] = '\0';
658                                 strlcpy(bar_ext, b, sizeof bar_ext);
659                         }
660                 if (b == NULL && errno != EAGAIN) {
661                         fprintf(stderr, "bar_extra failed: errno: %d %s\n",
662                             errno, strerror(errno));
663                         bar_extra_stop();
664                 }
665         } else
666                 strlcpy(bar_ext, "", sizeof bar_ext);
667
668         time(&tmt);
669         localtime_r(&tmt, &tm);
670         strftime(s, sizeof s, "%a %b %d %R %Z %Y", &tm);
671         for (i = 0; i < ScreenCount(display); i++) {
672                 x = 1;
673                 TAILQ_FOREACH(r, &screens[i].rl, entry) {
674                         snprintf(loc, sizeof loc, "%s     %d:%d    %s    %s",
675                             s, x++, r->ws->idx + 1, bar_ext, bar_vertext);
676                         bar_print(r, loc);
677                 }
678         }
679         XSync(display, False);
680         alarm(bar_delay);
681 }
682
683 void
684 bar_signal(int sig)
685 {
686         bar_alarm = 1;
687 }
688
689 void
690 bar_toggle(struct swm_region *r, union arg *args)
691 {
692         struct swm_region       *tmpr;
693         int                     i, j, sc = ScreenCount(display);
694
695         DNPRINTF(SWM_D_MISC, "bar_toggle\n");
696
697         if (bar_enabled) {
698                 for (i = 0; i < sc; i++)
699                         TAILQ_FOREACH(tmpr, &screens[i].rl, entry)
700                                 XUnmapWindow(display, tmpr->bar_window);
701         } else {
702                 for (i = 0; i < sc; i++)
703                         TAILQ_FOREACH(tmpr, &screens[i].rl, entry)
704                                 XMapRaised(display, tmpr->bar_window);
705         }
706         bar_enabled = !bar_enabled;
707         for (i = 0; i < sc; i++)
708                 for (j = 0; j < SWM_WS_MAX; j++)
709                         screens[i].ws[j].restack = 1;
710
711         stack();
712         /* must be after stack */
713         bar_update();
714 }
715
716 void
717 bar_refresh(void)
718 {
719         XSetWindowAttributes    wa;
720         struct swm_region       *r;
721         int                     i;
722
723         /* do this here because the conf file is in memory */
724         if (bar_extra && bar_extra_running == 0 && bar_argv[0]) {
725                 /* launch external status app */
726                 bar_extra_running = 1;
727                 if (pipe(bar_pipe) == -1)
728                         err(1, "pipe error");
729                 socket_setnonblock(bar_pipe[0]);
730                 socket_setnonblock(bar_pipe[1]); /* XXX hmmm, really? */
731                 if (dup2(bar_pipe[0], 0) == -1)
732                         errx(1, "dup2");
733                 if (dup2(bar_pipe[1], 1) == -1)
734                         errx(1, "dup2");
735                 if (signal(SIGPIPE, SIG_IGN) == SIG_ERR)
736                         err(1, "could not disable SIGPIPE");
737                 switch (bar_pid = fork()) {
738                 case -1:
739                         err(1, "cannot fork");
740                         break;
741                 case 0: /* child */
742                         close(bar_pipe[0]);
743                         execvp(bar_argv[0], bar_argv);
744                         err(1, "%s external app failed", bar_argv[0]);
745                         break;
746                 default: /* parent */
747                         close(bar_pipe[1]);
748                         break;
749                 }
750         }
751
752         bzero(&wa, sizeof wa);
753         for (i = 0; i < ScreenCount(display); i++)
754                 TAILQ_FOREACH(r, &screens[i].rl, entry) {
755                         wa.border_pixel =
756                             screens[i].c[SWM_S_COLOR_BAR_BORDER].color;
757                         wa.background_pixel =
758                             screens[i].c[SWM_S_COLOR_BAR].color;
759                         XChangeWindowAttributes(display, r->bar_window,
760                             CWBackPixel | CWBorderPixel, &wa);
761                 }
762         bar_update();
763 }
764
765 void
766 bar_setup(struct swm_region *r)
767 {
768         int                     i;
769
770         for (i = 0; bar_fonts[i] != NULL; i++) {
771                 bar_fs = XLoadQueryFont(display, bar_fonts[i]);
772                 if (bar_fs) {
773                         bar_fidx = i;
774                         break;
775                 }
776         }
777         if (bar_fonts[i] == NULL)
778                         errx(1, "couldn't load font");
779         bar_height = bar_fs->ascent + bar_fs->descent + 3;
780
781         r->bar_window = XCreateSimpleWindow(display, 
782             r->s->root, X(r), Y(r), WIDTH(r) - 2, bar_height - 2,
783             1, r->s->c[SWM_S_COLOR_BAR_BORDER].color,
784             r->s->c[SWM_S_COLOR_BAR].color);
785         bar_gc = XCreateGC(display, r->bar_window, 0, &bar_gcv);
786         XSetFont(display, bar_gc, bar_fs->fid);
787         XSelectInput(display, r->bar_window, VisibilityChangeMask);
788         if (bar_enabled)
789                 XMapRaised(display, r->bar_window);
790         DNPRINTF(SWM_D_MISC, "bar_setup: bar_window %lu\n", r->bar_window);
791
792         if (signal(SIGALRM, bar_signal) == SIG_ERR)
793                 err(1, "could not install bar_signal");
794         bar_refresh();
795 }
796
797 void
798 version(struct swm_region *r, union arg *args)
799 {
800         bar_version = !bar_version;
801         if (bar_version)
802                 strlcpy(bar_vertext, cvstag, sizeof bar_vertext);
803         else
804                 strlcpy(bar_vertext, "", sizeof bar_vertext);
805         bar_update();
806 }
807
808 void
809 config_win(struct ws_win *win)
810 {
811         XConfigureEvent         ce;
812
813         DNPRINTF(SWM_D_MISC, "config_win: win %lu x %d y %d w %d h %d\n",
814             win->id, win->g.x, win->g.y, win->g.w, win->g.h);
815         ce.type = ConfigureNotify;
816         ce.display = display;
817         ce.event = win->id;
818         ce.window = win->id;
819         ce.x = win->g.x;
820         ce.y = win->g.y;
821         ce.width = win->g.w;
822         ce.height = win->g.h;
823         ce.border_width = 1; /* XXX store this! */
824         ce.above = None;
825         ce.override_redirect = False;
826         XSendEvent(display, win->id, False, StructureNotifyMask, (XEvent *)&ce);
827 }
828
829 int
830 count_win(struct workspace *ws, int count_transient)
831 {
832         struct ws_win           *win;
833         int                     count = 0;
834
835         TAILQ_FOREACH(win, &ws->winlist, entry) {
836                 if (count_transient == 0 && win->floating)
837                         continue;
838                 if (count_transient == 0 && win->transient)
839                         continue;
840                 count++;
841         }
842         DNPRINTF(SWM_D_MISC, "count_win: %d\n", count);
843
844         return (count);
845 }
846
847 void
848 quit(struct swm_region *r, union arg *args)
849 {
850         DNPRINTF(SWM_D_MISC, "quit\n");
851         running = 0;
852 }
853
854 void
855 unmap_all(void)
856 {
857         struct ws_win           *win;
858         int                     i, j;
859
860         for (i = 0; i < ScreenCount(display); i++)
861                 for (j = 0; j < SWM_WS_MAX; j++)
862                         TAILQ_FOREACH(win, &screens[i].ws[j].winlist, entry)
863                                 XUnmapWindow(display, win->id);
864 }
865
866 void
867 fake_keypress(struct ws_win *win, int keysym, int modifiers)
868 {
869         XKeyEvent event;
870
871         event.display = display;        /* Ignored, but what the hell */
872         event.window = win->id;
873         event.root = win->s->root;
874         event.subwindow = None;
875         event.time = CurrentTime;
876         event.x = win->g.x;
877         event.y = win->g.y;
878         event.x_root = 1;
879         event.y_root = 1;
880         event.same_screen = True;
881         event.keycode = XKeysymToKeycode(display, keysym);
882         event.state = modifiers;
883
884         event.type = KeyPress;
885         XSendEvent(event.display, event.window, True,
886             KeyPressMask, (XEvent *)&event);
887
888         event.type = KeyRelease;
889         XSendEvent(event.display, event.window, True,
890             KeyPressMask, (XEvent *)&event);
891
892 }
893
894 void
895 restart(struct swm_region *r, union arg *args)
896 {
897         DNPRINTF(SWM_D_MISC, "restart: %s\n", start_argv[0]);
898
899         /* disable alarm because the following code may not be interrupted */
900         alarm(0);
901         if (signal(SIGALRM, SIG_IGN) == SIG_ERR)
902                 errx(1, "can't disable alarm");
903
904         bar_extra_stop();
905         bar_extra = 1;
906         unmap_all();
907         XCloseDisplay(display);
908         execvp(start_argv[0], start_argv);
909         fprintf(stderr, "execvp failed\n");
910         perror(" failed");
911         quit(NULL, NULL);
912 }
913
914 struct swm_region *
915 root_to_region(Window root)
916 {
917         struct swm_region       *r = NULL;
918         Window                  rr, cr;
919         int                     i, x, y, wx, wy;
920         unsigned int            mask;
921
922         for (i = 0; i < ScreenCount(display); i++)
923                 if (screens[i].root == root)
924                         break;
925
926         if (XQueryPointer(display, screens[i].root, 
927             &rr, &cr, &x, &y, &wx, &wy, &mask) != False) {
928                 /* choose a region based on pointer location */
929                 TAILQ_FOREACH(r, &screens[i].rl, entry)
930                         if (x >= X(r) && x <= X(r) + WIDTH(r) &&
931                             y >= Y(r) && y <= Y(r) + HEIGHT(r))
932                                 break;
933         }
934
935         if (r == NULL)
936                 r = TAILQ_FIRST(&screens[i].rl);
937
938         return (r);
939 }
940
941 struct ws_win *
942 find_window(Window id)
943 {
944         struct ws_win           *win;
945         int                     i, j;
946
947         for (i = 0; i < ScreenCount(display); i++)
948                 for (j = 0; j < SWM_WS_MAX; j++)
949                         TAILQ_FOREACH(win, &screens[i].ws[j].winlist, entry)
950                                 if (id == win->id)
951                                         return (win);
952         return (NULL);
953 }
954
955 void
956 spawn(struct swm_region *r, union arg *args)
957 {
958         char                    *ret;
959         int                     si;
960
961         DNPRINTF(SWM_D_MISC, "spawn: %s\n", args->argv[0]);
962         /*
963          * The double-fork construct avoids zombie processes and keeps the code
964          * clean from stupid signal handlers.
965          */
966         if (fork() == 0) {
967                 if (fork() == 0) {
968                         if (display)
969                                 close(ConnectionNumber(display));
970                         setenv("LD_PRELOAD", SWM_LIB, 1);
971                         if (asprintf(&ret, "%d", r->ws->idx)) {
972                                 setenv("_SWM_WS", ret, 1);
973                                 free(ret);
974                         }
975                         if (asprintf(&ret, "%d", getpid())) {
976                                 setenv("_SWM_PID", ret, 1);
977                                 free(ret);
978                         }
979                         setsid();
980                         /* kill stdin, mplayer, ssh-add etc. need that */
981                         si = open("/dev/null", O_RDONLY, 0);
982                         if (si == -1)
983                                 err(1, "open /dev/null");
984                         if (dup2(si, 0) == -1)
985                                 err(1, "dup2 /dev/null");
986                         execvp(args->argv[0], args->argv);
987                         fprintf(stderr, "execvp failed\n");
988                         perror(" failed");
989                 }
990                 exit(0);
991         }
992         wait(0);
993 }
994
995 void
996 spawnterm(struct swm_region *r, union arg *args)
997 {
998         DNPRINTF(SWM_D_MISC, "spawnterm\n");
999
1000         if (term_width)
1001                 setenv("_SWM_XTERM_FONTADJ", "", 1);
1002         spawn(r, args);
1003 }
1004
1005 void
1006 spawnmenu(struct swm_region *r, union arg *args)
1007 {
1008         DNPRINTF(SWM_D_MISC, "spawnmenu\n");
1009
1010         spawn_menu[SWM_MENU_FN] = bar_fonts[bar_fidx];
1011         spawn_menu[SWM_MENU_NB] = r->s->c[SWM_S_COLOR_BAR].name;
1012         spawn_menu[SWM_MENU_NF] = r->s->c[SWM_S_COLOR_BAR_FONT].name;
1013         spawn_menu[SWM_MENU_SB] = r->s->c[SWM_S_COLOR_BAR_BORDER].name;
1014         spawn_menu[SWM_MENU_SF] = r->s->c[SWM_S_COLOR_BAR].name;
1015
1016         spawn(r, args);
1017 }
1018
1019 void
1020 unfocus_all(void)
1021 {
1022         struct ws_win           *win;
1023         int                     i, j;
1024
1025         DNPRINTF(SWM_D_FOCUS, "unfocus_all:\n");
1026
1027         for (i = 0; i < ScreenCount(display); i++)
1028                 for (j = 0; j < SWM_WS_MAX; j++)
1029                         TAILQ_FOREACH(win, &screens[i].ws[j].winlist, entry) {
1030                                 if (win->ws->r == NULL)
1031                                         continue;
1032                                 grabbuttons(win, 0);
1033                                 XSetWindowBorder(display, win->id,
1034                                     win->ws->r->s->c[SWM_S_COLOR_UNFOCUS].color);
1035                                 win->got_focus = 0;
1036                                 win->ws->focus = NULL;
1037                                 cur_focus = NULL;
1038                         }
1039 }
1040
1041 void
1042 focus_win(struct ws_win *win)
1043 {
1044         DNPRINTF(SWM_D_FOCUS, "focus_win: id: %lu\n", win ? win->id : 0);
1045
1046         if (win == NULL)
1047                 return;
1048
1049         if (win->ws->focus != win && win->ws->focus != NULL)
1050                 win->ws->focus_prev = win->ws->focus;
1051
1052         unfocus_all();
1053         win->ws->focus = win;
1054         if (win->ws->r != NULL) {
1055                 cur_focus = win;
1056                 if (!win->got_focus) {
1057                         XSetWindowBorder(display, win->id,
1058                             win->ws->r->s->c[SWM_S_COLOR_FOCUS].color);
1059                         grabbuttons(win, 1);
1060                 }
1061                 win->got_focus = 1;
1062                 XSetInputFocus(display, win->id,
1063                     RevertToPointerRoot, CurrentTime);
1064         }
1065 }
1066
1067 void
1068 switchws(struct swm_region *r, union arg *args)
1069 {
1070         int                     wsid = args->id;
1071         struct swm_region       *this_r, *other_r;
1072         struct ws_win           *win;
1073         struct workspace        *new_ws, *old_ws;
1074
1075         this_r = r;
1076         old_ws = this_r->ws;
1077         new_ws = &this_r->s->ws[wsid];
1078
1079         DNPRINTF(SWM_D_WS, "switchws screen[%d]:%dx%d+%d+%d: "
1080             "%d -> %d\n", r->s->idx, WIDTH(r), HEIGHT(r), X(r), Y(r),
1081             old_ws->idx, wsid);
1082
1083         if (new_ws == old_ws)
1084                 return;
1085
1086         other_r = new_ws->r;
1087         if (!other_r) {
1088                 /* if the other workspace is hidden, switch windows */
1089                 /* map new window first to prevent ugly blinking */
1090                 old_ws->r = NULL;
1091                 old_ws->restack = 1;
1092
1093                 TAILQ_FOREACH(win, &new_ws->winlist, entry)
1094                         XMapRaised(display, win->id);
1095
1096                 TAILQ_FOREACH(win, &old_ws->winlist, entry)
1097                         XUnmapWindow(display, win->id);
1098         } else {
1099                 other_r->ws = old_ws;
1100                 old_ws->r = other_r;
1101         }
1102         this_r->ws = new_ws;
1103         new_ws->r = this_r;
1104
1105         ignore_enter = 1;
1106         /* set focus */
1107         if (new_ws->focus)
1108                 focus_win(new_ws->focus);
1109         stack();
1110         bar_update();
1111 }
1112
1113 void
1114 cyclews(struct swm_region *r, union arg *args)
1115 {
1116         union                   arg a;
1117         struct swm_screen       *s = r->s;
1118
1119         DNPRINTF(SWM_D_WS, "cyclews id %d "
1120             "in screen[%d]:%dx%d+%d+%d ws %d\n", args->id,
1121             r->s->idx, WIDTH(r), HEIGHT(r), X(r), Y(r), r->ws->idx);
1122
1123         a.id = r->ws->idx;
1124         do {
1125                 switch (args->id) {
1126                 case SWM_ARG_ID_CYCLEWS_UP:
1127                         if (a.id < SWM_WS_MAX - 1)
1128                                 a.id++;
1129                         else
1130                                 a.id = 0;
1131                         break;
1132                 case SWM_ARG_ID_CYCLEWS_DOWN:
1133                         if (a.id > 0)
1134                                 a.id--;
1135                         else
1136                                 a.id = SWM_WS_MAX - 1;
1137                         break;
1138                 default:
1139                         return;
1140                 };
1141
1142                 if (cycle_empty == 0 && TAILQ_EMPTY(&s->ws[a.id].winlist))
1143                         continue;
1144                 if (cycle_visible == 0 && s->ws[a.id].r != NULL)
1145                         continue;
1146
1147                 switchws(r, &a);
1148         } while (a.id != r->ws->idx);
1149 }
1150
1151 void
1152 cyclescr(struct swm_region *r, union arg *args)
1153 {
1154         struct swm_region       *rr;
1155         int                     i;
1156
1157         i = r->s->idx;
1158         switch (args->id) {
1159         case SWM_ARG_ID_CYCLESC_UP:
1160                 rr = TAILQ_NEXT(r, entry);
1161                 if (rr == NULL)
1162                         rr = TAILQ_FIRST(&screens[i].rl);
1163                 break;
1164         case SWM_ARG_ID_CYCLESC_DOWN:
1165                 rr = TAILQ_PREV(r, swm_region_list, entry);
1166                 if (rr == NULL)
1167                         rr = TAILQ_LAST(&screens[i].rl, swm_region_list);
1168                 break;
1169         default:
1170                 return;
1171         };
1172         unfocus_all();
1173         XSetInputFocus(display, PointerRoot, RevertToPointerRoot, CurrentTime);
1174         XWarpPointer(display, None, rr->s[i].root, 0, 0, 0, 0, rr->g.x,
1175             rr->g.y + bar_enabled ? bar_height : 0);
1176 }
1177
1178 void
1179 swapwin(struct swm_region *r, union arg *args)
1180 {
1181         struct ws_win           *target, *source;
1182         struct ws_win_list      *wl;
1183
1184
1185         DNPRINTF(SWM_D_WS, "swapwin id %d "
1186             "in screen %d region %dx%d+%d+%d ws %d\n", args->id,
1187             r->s->idx, WIDTH(r), HEIGHT(r), X(r), Y(r), r->ws->idx);
1188         if (cur_focus == NULL)
1189                 return;
1190
1191         source = cur_focus;
1192         wl = &source->ws->winlist;
1193
1194         switch (args->id) {
1195         case SWM_ARG_ID_SWAPPREV:
1196                 target = TAILQ_PREV(source, ws_win_list, entry);
1197                 TAILQ_REMOVE(wl, cur_focus, entry);
1198                 if (target == NULL)
1199                         TAILQ_INSERT_TAIL(wl, source, entry);
1200                 else
1201                         TAILQ_INSERT_BEFORE(target, source, entry);
1202                 break;
1203         case SWM_ARG_ID_SWAPNEXT: 
1204                 target = TAILQ_NEXT(source, entry);
1205                 TAILQ_REMOVE(wl, source, entry);
1206                 if (target == NULL)
1207                         TAILQ_INSERT_HEAD(wl, source, entry);
1208                 else
1209                         TAILQ_INSERT_AFTER(wl, target, source, entry);
1210                 break;
1211         case SWM_ARG_ID_SWAPMAIN:
1212                 target = TAILQ_FIRST(wl);
1213                 if (target == source) {
1214                         if (source->ws->focus_prev != NULL &&
1215                             source->ws->focus_prev != target)  
1216                                 
1217                                 source = source->ws->focus_prev;
1218                         else
1219                                 return;
1220                 }
1221                 source->ws->focus_prev = target;
1222                 TAILQ_REMOVE(wl, target, entry);
1223                 TAILQ_INSERT_BEFORE(source, target, entry);
1224                 TAILQ_REMOVE(wl, source, entry);
1225                 TAILQ_INSERT_HEAD(wl, source, entry);
1226                 break;
1227         default:
1228                 DNPRINTF(SWM_D_MOVE, "invalid id: %d\n", args->id);
1229                 return;
1230         }
1231
1232         ignore_enter = 1;
1233         stack();
1234 }
1235
1236 void
1237 focus(struct swm_region *r, union arg *args)
1238 {
1239         struct ws_win           *winfocus, *winlostfocus;
1240         struct ws_win_list      *wl;
1241
1242         DNPRINTF(SWM_D_FOCUS, "focus: id %d\n", args->id);
1243         if (cur_focus == NULL)
1244                 return;
1245
1246         wl = &cur_focus->ws->winlist;
1247
1248         winlostfocus = cur_focus;
1249
1250         switch (args->id) {
1251         case SWM_ARG_ID_FOCUSPREV:
1252                 winfocus = TAILQ_PREV(cur_focus, ws_win_list, entry);
1253                 if (winfocus == NULL)
1254                         winfocus = TAILQ_LAST(wl, ws_win_list);
1255                 break;
1256
1257         case SWM_ARG_ID_FOCUSNEXT:
1258                 winfocus = TAILQ_NEXT(cur_focus, entry);
1259                 if (winfocus == NULL)
1260                         winfocus = TAILQ_FIRST(wl);
1261                 break;
1262
1263         case SWM_ARG_ID_FOCUSMAIN:
1264                 winfocus = TAILQ_FIRST(wl);
1265                 break;
1266
1267         default:
1268                 return;
1269         }
1270
1271         if (winfocus == winlostfocus || winfocus == NULL)
1272                 return;
1273
1274         XMapRaised(display, winfocus->id);
1275         focus_win(winfocus);
1276         XSync(display, False);
1277 }
1278
1279 void
1280 cycle_layout(struct swm_region *r, union arg *args)
1281 {
1282         struct workspace        *ws = r->ws;
1283
1284         DNPRINTF(SWM_D_EVENT, "cycle_layout: workspace: %d\n", ws->idx);
1285
1286         ws->cur_layout++;
1287         if (ws->cur_layout->l_stack == NULL)
1288                 ws->cur_layout = &layouts[0];
1289         ignore_enter = 1;
1290         stack();
1291 }
1292
1293 void
1294 stack_config(struct swm_region *r, union arg *args)
1295 {
1296         struct workspace        *ws = r->ws;
1297
1298         DNPRINTF(SWM_D_STACK, "stack_config for workspace %d (id %d\n",
1299             args->id, ws->idx);
1300
1301         if (ws->cur_layout->l_config != NULL)
1302                 ws->cur_layout->l_config(ws, args->id);
1303
1304         if (args->id != SWM_ARG_ID_STACKINIT);
1305                 stack();
1306 }
1307
1308 void
1309 stack(void) {
1310         struct swm_geometry     g;
1311         struct swm_region       *r;
1312         int                     i, j;
1313
1314         DNPRINTF(SWM_D_STACK, "stack\n");
1315
1316         for (i = 0; i < ScreenCount(display); i++) {
1317                 j = 0;
1318                 TAILQ_FOREACH(r, &screens[i].rl, entry) {
1319                         DNPRINTF(SWM_D_STACK, "stacking workspace %d "
1320                             "(screen %d, region %d)\n", r->ws->idx, i, j++);
1321
1322                         /* start with screen geometry, adjust for bar */
1323                         g = r->g;
1324                         g.w -= 2;
1325                         g.h -= 2;
1326                         if (bar_enabled) {
1327                                 g.y += bar_height;
1328                                 g.h -= bar_height;
1329                         } 
1330
1331                         r->ws->restack = 0;
1332                         r->ws->cur_layout->l_stack(r->ws, &g);
1333                 }
1334         }
1335         if (font_adjusted)
1336                 font_adjusted--;
1337         XSync(display, False);
1338 }
1339
1340 void
1341 stack_floater(struct ws_win *win, struct swm_region *r)
1342 {
1343         unsigned int            mask;
1344         XWindowChanges          wc;
1345
1346         bzero(&wc, sizeof wc);
1347         mask = CWX | CWY | CWBorderWidth | CWWidth | CWHeight;
1348         wc.border_width = 1;
1349         if (win->transient && (win->quirks & SWM_Q_TRANSSZ)) {
1350                 win->g.w = (double)WIDTH(r) * dialog_ratio;
1351                 win->g.h = (double)HEIGHT(r) * dialog_ratio;
1352         }
1353         wc.width = win->g.w;
1354         wc.height = win->g.h;
1355         if (win->manual) {
1356                 wc.x = win->g.x;
1357                 wc.y = win->g.y;
1358         } else {
1359                 wc.x = (WIDTH(r) - win->g.w) / 2;
1360                 wc.y = (HEIGHT(r) - win->g.h) / 2;
1361         }
1362
1363         DNPRINTF(SWM_D_STACK, "stack_floater: win %lu x %d y %d w %d h %d\n",
1364             win->id, wc.x, wc.y, wc.width, wc.height);
1365
1366         XConfigureWindow(display, win->id, mask, &wc);
1367 }
1368
1369 /*
1370  * Send keystrokes to terminal to decrease/increase the font size as the
1371  * window size changes.
1372  */
1373 void
1374 adjust_font(struct ws_win *win)
1375 {
1376         if (!(win->quirks & SWM_Q_XTERM_FONTADJ) ||
1377             win->floating || win->transient)
1378                 return;
1379         
1380         if (win->sh.width_inc && win->last_inc != win->sh.width_inc &&
1381             win->g.w / win->sh.width_inc < term_width &&
1382             win->font_steps < SWM_MAX_FONT_STEPS) {
1383                 win->font_size_boundary[win->font_steps] =
1384                     (win->sh.width_inc * term_width) + win->sh.base_width;
1385                 win->font_steps++;
1386                 font_adjusted++;
1387                 win->last_inc = win->sh.width_inc;
1388                 fake_keypress(win, XK_KP_Subtract, ShiftMask);
1389         } else if (win->font_steps && win->last_inc != win->sh.width_inc &&
1390             win->g.w > win->font_size_boundary[win->font_steps - 1]) {
1391                 win->font_steps--;
1392                 font_adjusted++;
1393                 win->last_inc = win->sh.width_inc;
1394                 fake_keypress(win, XK_KP_Add, ShiftMask);
1395         }
1396 }
1397
1398 #define SWAPXY(g)       do {                            \
1399         int tmp;                                        \
1400         tmp = (g)->y; (g)->y = (g)->x; (g)->x = tmp;    \
1401         tmp = (g)->h; (g)->h = (g)->w; (g)->w = tmp;    \
1402 } while (0)
1403 void
1404 stack_master(struct workspace *ws, struct swm_geometry *g, int rot, int flip)
1405 {
1406         XWindowChanges          wc;
1407         struct swm_geometry     win_g, r_g = *g;
1408         struct ws_win           *win, *winfocus;
1409         int                     i, j, s, stacks; 
1410         int                     w_inc = 1, h_inc, w_base = 1, h_base;
1411         int                     hrh, extra = 0, h_slice, last_h = 0;
1412         int                     split, colno, winno, mwin, msize, mscale;
1413         int                     remain, missing, v_slice;;
1414         unsigned int            mask;
1415
1416         DNPRINTF(SWM_D_STACK, "stack_master: workspace: %d\n rot=%s flip=%s",
1417             ws->idx, rot ? "yes" : "no", flip ? "yes" : "no");
1418
1419         if ((winno = count_win(ws, 0)) == 0)
1420                 return;
1421
1422         if (ws->focus == NULL)
1423                 ws->focus = TAILQ_FIRST(&ws->winlist);
1424         winfocus = cur_focus ? cur_focus : ws->focus;
1425
1426         TAILQ_FOREACH(win, &ws->winlist, entry)
1427                 if (win->transient == 0 && win->floating == 0)
1428                         break;
1429
1430         if (win == NULL)
1431                 goto notiles;
1432
1433         if (rot) {
1434                 w_inc = win->sh.width_inc;
1435                 w_base = win->sh.base_width;
1436                 mwin = ws->l_state.horizontal_mwin;
1437                 mscale = ws->l_state.horizontal_msize;
1438                 stacks = ws->l_state.horizontal_stacks;
1439                 SWAPXY(&r_g);
1440         } else {
1441                 w_inc = win->sh.height_inc;
1442                 w_base = win->sh.base_height;
1443                 mwin = ws->l_state.vertical_mwin;
1444                 mscale = ws->l_state.vertical_msize;
1445                 stacks = ws->l_state.vertical_stacks;
1446         }
1447         win_g = r_g;
1448
1449         if (stacks > winno - mwin)
1450                 stacks = winno - mwin;
1451         if (stacks < 1)
1452                 stacks = 1;
1453
1454         h_slice = r_g.h / SWM_H_SLICE;
1455         if (mwin && winno > mwin) {
1456                 v_slice = r_g.w / SWM_V_SLICE;
1457
1458                 split = mwin;
1459                 colno = split;
1460                 win_g.w = v_slice * mscale;
1461
1462                 if (w_inc > 1 && w_inc < v_slice) {
1463                         /* adjust for window's requested size increment */
1464                         remain = (win_g.w - w_base) % w_inc;
1465                         missing = w_inc - remain;
1466                         win_g.w -= remain;
1467                         extra += remain;
1468                 }
1469
1470                 msize = win_g.w;
1471                 if (flip) 
1472                         win_g.x += r_g.w - msize;
1473         } else {
1474                 msize = -2;
1475                 colno = split = winno / stacks;
1476                 win_g.w = ((r_g.w - (stacks * 2) + 2) / stacks);
1477         }
1478         hrh = r_g.h / colno;
1479         extra = r_g.h - (colno * hrh);
1480         win_g.h = hrh - 2;
1481
1482         /*  stack all the tiled windows */
1483         i = j = 0, s = stacks;
1484         TAILQ_FOREACH(win, &ws->winlist, entry) {
1485                 if (win->transient != 0 || win->floating != 0)
1486                         continue;
1487
1488                 if (split && i == split) {
1489                         colno = (winno - mwin) / stacks;
1490                         if (s <= (winno - mwin) % stacks)
1491                                 colno++;
1492                         split = split + colno;
1493                         hrh = (r_g.h / colno);
1494                         extra = r_g.h - (colno * hrh);
1495                         if (flip)
1496                                 win_g.x = r_g.x;
1497                         else
1498                                 win_g.x += win_g.w + 2;
1499                         win_g.w = (r_g.w - msize - (stacks * 2)) / stacks;
1500                         if (s == 1)
1501                                 win_g.w += (r_g.w - msize - (stacks * 2)) %
1502                                     stacks;
1503                         s--;
1504                         j = 0;
1505                 }
1506                 win_g.h = hrh - 2;
1507                 if (rot) {
1508                         h_inc = win->sh.width_inc;
1509                         h_base = win->sh.base_width;
1510                 } else {
1511                         h_inc = win->sh.height_inc;
1512                         h_base = win->sh.base_height;
1513                 }
1514                 if (j == colno - 1) {
1515                         win_g.h = hrh + extra;
1516                 } else if (h_inc > 1 && h_inc < h_slice) {
1517                         /* adjust for window's requested size increment */
1518                         remain = (win_g.h - h_base) % h_inc;
1519                         missing = h_inc - remain;
1520
1521                         if (missing <= extra || j == 0) {
1522                                 extra -= missing;
1523                                 win_g.h += missing;
1524                         } else {
1525                                 win_g.h -= remain;
1526                                 extra += remain;
1527                         }
1528                 }
1529                  
1530                 if (j == 0)
1531                         win_g.y = r_g.y;
1532                 else
1533                         win_g.y += last_h + 2;
1534
1535                 bzero(&wc, sizeof wc);
1536                 wc.border_width = 1;
1537                 if (rot) {
1538                         win->g.x = wc.x = win_g.y;
1539                         win->g.y = wc.y = win_g.x;
1540                         win->g.w = wc.width = win_g.h;
1541                         win->g.h = wc.height = win_g.w;
1542                 } else {
1543                         win->g.x = wc.x = win_g.x;
1544                         win->g.y = wc.y = win_g.y;
1545                         win->g.w = wc.width = win_g.w;
1546                         win->g.h = wc.height = win_g.h;
1547                 }
1548                 adjust_font(win);
1549                 mask = CWX | CWY | CWWidth | CWHeight | CWBorderWidth;
1550                 XConfigureWindow(display, win->id, mask, &wc);
1551                 XMapRaised(display, win->id);
1552
1553                 last_h = win_g.h;
1554                 i++;
1555                 j++;
1556         }
1557
1558  notiles:
1559         /* now, stack all the floaters and transients */
1560         TAILQ_FOREACH(win, &ws->winlist, entry) {
1561                 if (win->transient == 0 && win->floating == 0)
1562                         continue;
1563
1564                 stack_floater(win, ws->r);
1565                 XMapRaised(display, win->id);
1566         }
1567
1568         if (winfocus)
1569                 focus_win(winfocus); /* has to be done outside of the loop */
1570 }
1571
1572 void
1573 vertical_config(struct workspace *ws, int id)
1574 {
1575         DNPRINTF(SWM_D_STACK, "vertical_resize: workspace: %d\n", ws->idx);
1576
1577         switch (id) {
1578         case SWM_ARG_ID_STACKRESET:
1579         case SWM_ARG_ID_STACKINIT:
1580                 ws->l_state.vertical_msize = SWM_V_SLICE / 2;
1581                 ws->l_state.vertical_mwin = 1;
1582                 ws->l_state.vertical_stacks = 1;
1583                 break;
1584         case SWM_ARG_ID_MASTERSHRINK:
1585                 if (ws->l_state.vertical_msize > 1)
1586                         ws->l_state.vertical_msize--;
1587                 break;
1588         case SWM_ARG_ID_MASTERGROW:
1589                 if (ws->l_state.vertical_msize < SWM_V_SLICE - 1)
1590                         ws->l_state.vertical_msize++;
1591                 break;
1592         case SWM_ARG_ID_MASTERADD:
1593                 ws->l_state.vertical_mwin++;
1594                 break;
1595         case SWM_ARG_ID_MASTERDEL:
1596                 if (ws->l_state.vertical_mwin > 0)
1597                         ws->l_state.vertical_mwin--;
1598                 break;
1599         case SWM_ARG_ID_STACKINC:
1600                 ws->l_state.vertical_stacks++;
1601                 break;
1602         case SWM_ARG_ID_STACKDEC:
1603                 if (ws->l_state.vertical_stacks > 1)
1604                         ws->l_state.vertical_stacks--;
1605                 break;
1606         default:
1607                 return;
1608         }
1609 }
1610
1611 void
1612 vertical_stack(struct workspace *ws, struct swm_geometry *g)
1613 {
1614         DNPRINTF(SWM_D_STACK, "vertical_stack: workspace: %d\n", ws->idx);
1615
1616         stack_master(ws, g, 0, 0);
1617 }
1618
1619 void
1620 horizontal_config(struct workspace *ws, int id)
1621 {
1622         DNPRINTF(SWM_D_STACK, "horizontal_config: workspace: %d\n", ws->idx);
1623
1624         switch (id) {
1625         case SWM_ARG_ID_STACKRESET:
1626         case SWM_ARG_ID_STACKINIT:
1627                 ws->l_state.horizontal_mwin = 1;
1628                 ws->l_state.horizontal_msize = SWM_H_SLICE / 2;
1629                 ws->l_state.horizontal_stacks = 1;
1630                 break;
1631         case SWM_ARG_ID_MASTERSHRINK:
1632                 if (ws->l_state.horizontal_msize > 1)
1633                         ws->l_state.horizontal_msize--;
1634                 break;
1635         case SWM_ARG_ID_MASTERGROW:
1636                 if (ws->l_state.horizontal_msize < SWM_H_SLICE - 1)
1637                         ws->l_state.horizontal_msize++;
1638                 break;
1639         case SWM_ARG_ID_MASTERADD:
1640                 ws->l_state.horizontal_mwin++;
1641                 break;
1642         case SWM_ARG_ID_MASTERDEL:
1643                 if (ws->l_state.horizontal_mwin > 0)
1644                         ws->l_state.horizontal_mwin--;
1645                 break;
1646         case SWM_ARG_ID_STACKINC:
1647                 ws->l_state.horizontal_stacks++;
1648                 break;
1649         case SWM_ARG_ID_STACKDEC:
1650                 if (ws->l_state.horizontal_stacks > 1)
1651                         ws->l_state.horizontal_stacks--;
1652                 break;
1653         default:
1654                 return;
1655         }
1656 }
1657
1658 void
1659 horizontal_stack(struct workspace *ws, struct swm_geometry *g)
1660 {
1661         DNPRINTF(SWM_D_STACK, "vertical_stack: workspace: %d\n", ws->idx);
1662
1663         stack_master(ws, g, 1, 0);
1664 }
1665
1666 /* fullscreen view */
1667 void
1668 max_stack(struct workspace *ws, struct swm_geometry *g) {
1669         XWindowChanges          wc;
1670         struct swm_geometry     gg = *g;
1671         struct ws_win           *win, *winfocus;
1672         unsigned int            mask;
1673
1674         DNPRINTF(SWM_D_STACK, "max_stack: workspace: %d\n", ws->idx);
1675
1676         if (count_win(ws, 0) == 0)
1677                 return;
1678
1679         if (ws->focus == NULL)
1680                 ws->focus = TAILQ_FIRST(&ws->winlist);
1681         winfocus = cur_focus ? cur_focus : ws->focus;
1682
1683         TAILQ_FOREACH(win, &ws->winlist, entry) {
1684                 if (win->transient != 0 || win->floating != 0) {
1685                         if (win == ws->focus) {
1686                                 /* XXX maximize? */
1687                                 stack_floater(win, ws->r);
1688                                 XMapRaised(display, win->id);
1689                         } else
1690                                 XUnmapWindow(display, win->id);
1691                 } else {
1692                         bzero(&wc, sizeof wc);
1693                         wc.border_width = 1;
1694                         win->g.x = wc.x = gg.x;
1695                         win->g.y = wc.y = gg.y;
1696                         win->g.w = wc.width = gg.w;
1697                         win->g.h = wc.height = gg.h;
1698                         mask = CWX | CWY | CWWidth | CWHeight | CWBorderWidth;
1699                         XConfigureWindow(display, win->id, mask, &wc);
1700
1701                         if (win == ws->focus) {
1702                                 XMapRaised(display, win->id);
1703                         } else
1704                                 XUnmapWindow(display, win->id);
1705                 }
1706         }
1707
1708         if (winfocus)
1709                 focus_win(winfocus); /* has to be done outside of the loop */
1710 }
1711
1712 void
1713 send_to_ws(struct swm_region *r, union arg *args)
1714 {
1715         int                     wsid = args->id;
1716         struct ws_win           *win = cur_focus;
1717         struct workspace        *ws, *nws;
1718         Atom                    ws_idx_atom = 0;
1719         unsigned char           ws_idx_str[SWM_PROPLEN];
1720
1721         if (win == NULL)
1722                 return;
1723
1724         DNPRINTF(SWM_D_MOVE, "send_to_ws: win: %lu\n", win->id);
1725
1726         ws = win->ws;
1727         nws = &win->s->ws[wsid];
1728
1729         XUnmapWindow(display, win->id);
1730
1731         /* find a window to focus */
1732         ws->focus = TAILQ_PREV(win, ws_win_list, entry);
1733         if (ws->focus == NULL)
1734                 ws->focus = TAILQ_FIRST(&ws->winlist);
1735         if (ws->focus == win)
1736                 ws->focus = NULL;
1737
1738         TAILQ_REMOVE(&ws->winlist, win, entry);
1739
1740         TAILQ_INSERT_TAIL(&nws->winlist, win, entry);
1741         win->ws = nws;
1742
1743         /* Try to update the window's workspace property */
1744         ws_idx_atom = XInternAtom(display, "_SWM_WS", False);
1745         if (ws_idx_atom &&
1746             snprintf(ws_idx_str, SWM_PROPLEN, "%d", nws->idx) < SWM_PROPLEN) {
1747                 DNPRINTF(SWM_D_PROP, "setting property _SWM_WS to %s\n",
1748                     ws_idx_str);
1749                 XChangeProperty(display, win->id, ws_idx_atom, XA_STRING, 8,
1750                     PropModeReplace, ws_idx_str, SWM_PROPLEN);
1751         }
1752
1753         if (count_win(nws, 1) == 1)
1754                 nws->focus = win;
1755         ws->restack = 1;
1756         nws->restack = 1;
1757
1758         stack();
1759 }
1760
1761 void
1762 wkill(struct swm_region *r, union arg *args)
1763 {
1764         DNPRINTF(SWM_D_MISC, "wkill\n");
1765         if(r->ws->focus != NULL)
1766                 XKillClient(display, r->ws->focus->id);
1767 }
1768
1769 void
1770 screenshot(struct swm_region *r, union arg *args)
1771 {
1772         union arg                       a;
1773
1774         DNPRINTF(SWM_D_MISC, "screenshot\n");
1775
1776         if (ss_enabled == 0)
1777                 return;
1778
1779         switch (args->id) {
1780         case SWM_ARG_ID_SS_ALL:
1781                 spawn_screenshot[1] = "full";
1782                 break;
1783         case SWM_ARG_ID_SS_WINDOW:
1784                 spawn_screenshot[1] = "window";
1785                 break;
1786         default:
1787                 return;
1788         }
1789         a.argv = spawn_screenshot;
1790         spawn(r, &a);
1791 }
1792
1793 void
1794 floating_toggle(struct swm_region *r, union arg *args)
1795 {
1796         struct ws_win   *win = cur_focus;
1797
1798         if (win == NULL)
1799                 return;
1800
1801         win->floating = !win->floating;
1802         win->manual = 0;
1803         stack();
1804         focus_win(win);
1805 }
1806
1807 /* key definitions */
1808 struct key {
1809         unsigned int            mod;
1810         KeySym                  keysym;
1811         void                    (*func)(struct swm_region *r, union arg *);
1812         union arg               args;
1813 } keys[] = {
1814         /* modifier             key     function                argument */
1815         { MODKEY,               XK_space,       cycle_layout,   {0} }, 
1816         { MODKEY | ShiftMask,   XK_space,       stack_config,   {.id = SWM_ARG_ID_STACKRESET} }, 
1817         { MODKEY,               XK_h,           stack_config,   {.id = SWM_ARG_ID_MASTERSHRINK} },
1818         { MODKEY,               XK_l,           stack_config,   {.id = SWM_ARG_ID_MASTERGROW} },
1819         { MODKEY,               XK_comma,       stack_config,   {.id = SWM_ARG_ID_MASTERADD} },
1820         { MODKEY,               XK_period,      stack_config,   {.id = SWM_ARG_ID_MASTERDEL} },
1821         { MODKEY | ShiftMask,   XK_comma,       stack_config,   {.id = SWM_ARG_ID_STACKINC} },
1822         { MODKEY | ShiftMask,   XK_period,      stack_config,   {.id = SWM_ARG_ID_STACKDEC} },
1823         { MODKEY,               XK_Return,      swapwin,        {.id = SWM_ARG_ID_SWAPMAIN} },
1824         { MODKEY,               XK_j,           focus,          {.id = SWM_ARG_ID_FOCUSNEXT} },
1825         { MODKEY,               XK_k,           focus,          {.id = SWM_ARG_ID_FOCUSPREV} },
1826         { MODKEY | ShiftMask,   XK_j,           swapwin,        {.id = SWM_ARG_ID_SWAPNEXT} },
1827         { MODKEY | ShiftMask,   XK_k,           swapwin,        {.id = SWM_ARG_ID_SWAPPREV} },
1828         { MODKEY | ShiftMask,   XK_Return,      spawnterm,      {.argv = spawn_term} },
1829         { MODKEY,               XK_p,           spawnmenu,      {.argv = spawn_menu} },
1830         { MODKEY | ShiftMask,   XK_q,           quit,           {0} },
1831         { MODKEY,               XK_q,           restart,        {0} },
1832         { MODKEY,               XK_m,           focus,          {.id = SWM_ARG_ID_FOCUSMAIN} },
1833         { MODKEY,               XK_1,           switchws,       {.id = 0} },
1834         { MODKEY,               XK_2,           switchws,       {.id = 1} },
1835         { MODKEY,               XK_3,           switchws,       {.id = 2} },
1836         { MODKEY,               XK_4,           switchws,       {.id = 3} },
1837         { MODKEY,               XK_5,           switchws,       {.id = 4} },
1838         { MODKEY,               XK_6,           switchws,       {.id = 5} },
1839         { MODKEY,               XK_7,           switchws,       {.id = 6} },
1840         { MODKEY,               XK_8,           switchws,       {.id = 7} },
1841         { MODKEY,               XK_9,           switchws,       {.id = 8} },
1842         { MODKEY,               XK_0,           switchws,       {.id = 9} },
1843         { MODKEY,               XK_Right,       cyclews,        {.id = SWM_ARG_ID_CYCLEWS_UP} }, 
1844         { MODKEY,               XK_Left,        cyclews,        {.id = SWM_ARG_ID_CYCLEWS_DOWN} }, 
1845         { MODKEY | ShiftMask,   XK_Right,       cyclescr,       {.id = SWM_ARG_ID_CYCLESC_UP} }, 
1846         { MODKEY | ShiftMask,   XK_Left,        cyclescr,       {.id = SWM_ARG_ID_CYCLESC_DOWN} }, 
1847         { MODKEY | ShiftMask,   XK_1,           send_to_ws,     {.id = 0} },
1848         { MODKEY | ShiftMask,   XK_2,           send_to_ws,     {.id = 1} },
1849         { MODKEY | ShiftMask,   XK_3,           send_to_ws,     {.id = 2} },
1850         { MODKEY | ShiftMask,   XK_4,           send_to_ws,     {.id = 3} },
1851         { MODKEY | ShiftMask,   XK_5,           send_to_ws,     {.id = 4} },
1852         { MODKEY | ShiftMask,   XK_6,           send_to_ws,     {.id = 5} },
1853         { MODKEY | ShiftMask,   XK_7,           send_to_ws,     {.id = 6} },
1854         { MODKEY | ShiftMask,   XK_8,           send_to_ws,     {.id = 7} },
1855         { MODKEY | ShiftMask,   XK_9,           send_to_ws,     {.id = 8} },
1856         { MODKEY | ShiftMask,   XK_0,           send_to_ws,     {.id = 9} },
1857         { MODKEY,               XK_b,           bar_toggle,     {0} },
1858         { MODKEY,               XK_Tab,         focus,          {.id = SWM_ARG_ID_FOCUSNEXT} },
1859         { MODKEY | ShiftMask,   XK_Tab,         focus,          {.id = SWM_ARG_ID_FOCUSPREV} },
1860         { MODKEY | ShiftMask,   XK_x,           wkill,          {0} },
1861         { MODKEY,               XK_s,           screenshot,     {.id = SWM_ARG_ID_SS_ALL} },
1862         { MODKEY | ShiftMask,   XK_s,           screenshot,     {.id = SWM_ARG_ID_SS_WINDOW} },
1863         { MODKEY,               XK_t,           floating_toggle,{0} },
1864         { MODKEY | ShiftMask,   XK_v,           version,        {0} },
1865         { MODKEY | ShiftMask,   XK_Delete,      spawn,          {.argv = spawn_lock} },
1866         { MODKEY | ShiftMask,   XK_i,           spawn,          {.argv = spawn_initscr} },
1867 };
1868
1869 void
1870 resize_window(struct ws_win *win, int center)
1871 {
1872         unsigned int            mask;
1873         XWindowChanges          wc;
1874         struct swm_region       *r;
1875
1876         r = root_to_region(win->wa.root);
1877         bzero(&wc, sizeof wc);
1878         mask = CWBorderWidth | CWWidth | CWHeight;
1879         wc.border_width = 1;
1880         wc.width = win->g.w;
1881         wc.height = win->g.h;
1882         if (center == SWM_ARG_ID_CENTER) {
1883                 wc.x = (WIDTH(r) - win->g.w) / 2;
1884                 wc.y = (HEIGHT(r) - win->g.h) / 2;
1885                 mask |= CWX | CWY;
1886         }
1887
1888         DNPRINTF(SWM_D_STACK, "resize_window: win %lu x %d y %d w %d h %d\n",
1889             win->id, wc.x, wc.y, wc.width, wc.height);
1890
1891         XConfigureWindow(display, win->id, mask, &wc);
1892         config_win(win);
1893 }
1894
1895 void
1896 resize(struct ws_win *win, union arg *args)
1897 {
1898         XEvent                  ev;
1899         Time                    time = 0;
1900
1901         DNPRINTF(SWM_D_MOUSE, "resize: win %lu floating %d trans %d\n",
1902             win->id, win->floating, win->transient);
1903
1904         if (!(win->transient != 0 || win->floating != 0))
1905                 return;
1906
1907         if (XGrabPointer(display, win->id, False, MOUSEMASK, GrabModeAsync,
1908             GrabModeAsync, None, None /* cursor */, CurrentTime) != GrabSuccess)
1909                 return;
1910         XWarpPointer(display, None, win->id, 0, 0, 0, 0, win->g.w, win->g.h);
1911         do {
1912                 XMaskEvent(display, MOUSEMASK | ExposureMask |
1913                     SubstructureRedirectMask, &ev);
1914                 switch(ev.type) {
1915                 case ConfigureRequest:
1916                 case Expose:
1917                 case MapRequest:
1918                         handler[ev.type](&ev);
1919                         break;
1920                 case MotionNotify:
1921                         if (ev.xmotion.x <= 1)
1922                                 ev.xmotion.x = 1;
1923                         if (ev.xmotion.y <= 1)
1924                                 ev.xmotion.y = 1;
1925                         win->g.w = ev.xmotion.x;
1926                         win->g.h = ev.xmotion.y;
1927
1928                         /* not free, don't sync more than 60 times / second */
1929                         if ((ev.xmotion.time - time) > (1000 / 60) ) {
1930                                 time = ev.xmotion.time;
1931                                 XSync(display, False);
1932                                 resize_window(win, args->id);
1933                         }
1934                         break;
1935                 }
1936         } while (ev.type != ButtonRelease);
1937         if (time) {
1938                 XSync(display, False);
1939                 resize_window(win, args->id);
1940         }
1941         XWarpPointer(display, None, win->id, 0, 0, 0, 0, win->g.w - 1,
1942             win->g.h - 1);
1943         XUngrabPointer(display, CurrentTime);
1944
1945         /* drain events */
1946         while (XCheckMaskEvent(display, EnterWindowMask, &ev));
1947 }
1948
1949 void
1950 move_window(struct ws_win *win)
1951 {
1952         unsigned int            mask;
1953         XWindowChanges          wc;
1954         struct swm_region       *r;
1955
1956         r = root_to_region(win->wa.root);
1957         bzero(&wc, sizeof wc);
1958         mask = CWX | CWY;
1959         wc.x = win->g.x;
1960         wc.y = win->g.y;
1961
1962         DNPRINTF(SWM_D_STACK, "move_window: win %lu x %d y %d w %d h %d\n",
1963             win->id, wc.x, wc.y, wc.width, wc.height);
1964
1965         XConfigureWindow(display, win->id, mask, &wc);
1966         config_win(win);
1967 }
1968
1969 void
1970 move(struct ws_win *win, union arg *args)
1971 {
1972         XEvent                  ev;
1973         Time                    time = 0;
1974         int                     restack = 0;
1975
1976         DNPRINTF(SWM_D_MOUSE, "move: win %lu floating %d trans %d\n",
1977             win->id, win->floating, win->transient);
1978
1979         if (win->floating == 0) {
1980                 win->floating = 1;
1981                 win->manual = 1;
1982                 restack = 1;
1983         }
1984
1985         if (XGrabPointer(display, win->id, False, MOUSEMASK, GrabModeAsync,
1986             GrabModeAsync, None, None /* cursor */, CurrentTime) != GrabSuccess)
1987                 return;
1988         XWarpPointer(display, None, win->id, 0, 0, 0, 0, 0, 0);
1989         do {
1990                 XMaskEvent(display, MOUSEMASK | ExposureMask |
1991                     SubstructureRedirectMask, &ev);
1992                 switch(ev.type) {
1993                 case ConfigureRequest:
1994                 case Expose:
1995                 case MapRequest:
1996                         handler[ev.type](&ev);
1997                         break;
1998                 case MotionNotify:
1999                         win->g.x = ev.xmotion.x_root;
2000                         win->g.y = ev.xmotion.y_root;
2001
2002                         /* not free, don't sync more than 60 times / second */
2003                         if ((ev.xmotion.time - time) > (1000 / 60) ) {
2004                                 time = ev.xmotion.time;
2005                                 XSync(display, False);
2006                                 move_window(win);
2007                         }
2008                         break;
2009                 }
2010         } while (ev.type != ButtonRelease);
2011         if (time) {
2012                 XSync(display, False);
2013                 move_window(win);
2014         }
2015         XWarpPointer(display, None, win->id, 0, 0, 0, 0, 0, 0);
2016         XUngrabPointer(display, CurrentTime);
2017         if (restack)
2018                 stack();
2019
2020         /* drain events */
2021         while (XCheckMaskEvent(display, EnterWindowMask, &ev));
2022 }
2023
2024 /* mouse */
2025 enum { client_click, root_click };
2026 struct button {
2027         unsigned int            action;
2028         unsigned int            mask;
2029         unsigned int            button;
2030         void                    (*func)(struct ws_win *, union arg *);
2031         union arg               args;
2032 } buttons[] = {
2033           /* action             key             mouse button    func            args */
2034         { client_click,         MODKEY,         Button3,        resize,         {.id = SWM_ARG_ID_DONTCENTER} },
2035         { client_click,         MODKEY | ShiftMask, Button3,    resize,         {.id = SWM_ARG_ID_CENTER} },
2036         { client_click,         MODKEY,         Button1,        move,           {0} },
2037 };
2038
2039 void
2040 updatenumlockmask(void)
2041 {
2042         unsigned int            i, j;
2043         XModifierKeymap         *modmap;
2044
2045         DNPRINTF(SWM_D_MISC, "updatenumlockmask\n");
2046         numlockmask = 0;
2047         modmap = XGetModifierMapping(display);
2048         for (i = 0; i < 8; i++)
2049                 for (j = 0; j < modmap->max_keypermod; j++)
2050                         if (modmap->modifiermap[i * modmap->max_keypermod + j]
2051                           == XKeysymToKeycode(display, XK_Num_Lock))
2052                                 numlockmask = (1 << i);
2053
2054         XFreeModifiermap(modmap);
2055 }
2056
2057 void
2058 grabkeys(void)
2059 {
2060         unsigned int            i, j, k;
2061         KeyCode                 code;
2062         unsigned int            modifiers[] =
2063             { 0, LockMask, numlockmask, numlockmask | LockMask };
2064
2065         DNPRINTF(SWM_D_MISC, "grabkeys\n");
2066         updatenumlockmask();
2067
2068         for (k = 0; k < ScreenCount(display); k++) {
2069                 if (TAILQ_EMPTY(&screens[k].rl))
2070                         continue;
2071                 XUngrabKey(display, AnyKey, AnyModifier, screens[k].root);
2072                 for (i = 0; i < LENGTH(keys); i++) {
2073                         if ((code = XKeysymToKeycode(display, keys[i].keysym)))
2074                                 for (j = 0; j < LENGTH(modifiers); j++)
2075                                         XGrabKey(display, code,
2076                                             keys[i].mod | modifiers[j],
2077                                             screens[k].root, True,
2078                                             GrabModeAsync, GrabModeAsync);
2079                 }
2080         }
2081 }
2082
2083 void
2084 grabbuttons(struct ws_win *win, int focused)
2085 {
2086         unsigned int            i, j;
2087         unsigned int            modifiers[] =
2088             { 0, LockMask, numlockmask, numlockmask|LockMask };
2089
2090         updatenumlockmask();
2091         XUngrabButton(display, AnyButton, AnyModifier, win->id);
2092         if(focused) {
2093                 for (i = 0; i < LENGTH(buttons); i++)
2094                         if (buttons[i].action == client_click)
2095                                 for (j = 0; j < LENGTH(modifiers); j++)
2096                                         XGrabButton(display, buttons[i].button,
2097                                             buttons[i].mask | modifiers[j],
2098                                             win->id, False, BUTTONMASK,
2099                                             GrabModeAsync, GrabModeSync, None,
2100                                             None);
2101         } else
2102                 XGrabButton(display, AnyButton, AnyModifier, win->id, False,
2103                     BUTTONMASK, GrabModeAsync, GrabModeSync, None, None);
2104 }
2105
2106 void
2107 expose(XEvent *e)
2108 {
2109         DNPRINTF(SWM_D_EVENT, "expose: window: %lu\n", e->xexpose.window);
2110 }
2111
2112 void
2113 keypress(XEvent *e)
2114 {
2115         unsigned int            i;
2116         KeySym                  keysym;
2117         XKeyEvent               *ev = &e->xkey;
2118
2119         DNPRINTF(SWM_D_EVENT, "keypress: window: %lu\n", ev->window);
2120
2121         keysym = XKeycodeToKeysym(display, (KeyCode)ev->keycode, 0);
2122         for (i = 0; i < LENGTH(keys); i++)
2123                 if (keysym == keys[i].keysym
2124                    && CLEANMASK(keys[i].mod) == CLEANMASK(ev->state)
2125                    && keys[i].func)
2126                         keys[i].func(root_to_region(ev->root),
2127                             &(keys[i].args));
2128 }
2129
2130 void
2131 buttonpress(XEvent *e)
2132 {
2133         XButtonPressedEvent     *ev = &e->xbutton;
2134
2135         struct ws_win           *win;
2136         int                     i, action;
2137
2138         DNPRINTF(SWM_D_EVENT, "buttonpress: window: %lu\n", ev->window);
2139
2140         action = root_click;
2141         if ((win = find_window(ev->window)) == NULL)
2142                 return;
2143         else {
2144                 focus_win(win);
2145                 action = client_click;
2146         }
2147
2148         for (i = 0; i < LENGTH(buttons); i++)
2149                 if (action == buttons[i].action && buttons[i].func &&
2150                     buttons[i].button == ev->button &&
2151                     CLEANMASK(buttons[i].mask) == CLEANMASK(ev->state))
2152                         buttons[i].func(win, &buttons[i].args);
2153 }
2154
2155 void
2156 set_win_state(struct ws_win *win, long state)
2157 {
2158         long                    data[] = {state, None};
2159
2160         DNPRINTF(SWM_D_EVENT, "set_win_state: window: %lu\n", win->id);
2161
2162         XChangeProperty(display, win->id, astate, astate, 32, PropModeReplace,
2163             (unsigned char *)data, 2);
2164 }
2165
2166 struct ws_win *
2167 manage_window(Window id)
2168 {
2169         Window                  trans;
2170         struct workspace        *ws;
2171         struct ws_win           *win;
2172         int                     format, i, ws_idx;
2173         unsigned long           nitems, bytes;
2174         Atom                    ws_idx_atom = 0, type;
2175         unsigned char           ws_idx_str[SWM_PROPLEN], *prop = NULL;
2176         struct swm_region       *r;
2177         long                    mask;
2178         const char              *errstr;
2179         XWindowChanges          wc;
2180
2181         if ((win = find_window(id)) != NULL)
2182                         return (win);   /* already being managed */
2183
2184         if ((win = calloc(1, sizeof(struct ws_win))) == NULL)
2185                 errx(1, "calloc: failed to allocate memory for new window");
2186
2187         /* Get all the window data in one shot */
2188         ws_idx_atom = XInternAtom(display, "_SWM_WS", False);
2189         if (ws_idx_atom)
2190                 XGetWindowProperty(display, id, ws_idx_atom, 0, SWM_PROPLEN,
2191                     False, XA_STRING, &type, &format, &nitems, &bytes, &prop);
2192         XGetWindowAttributes(display, id, &win->wa);
2193         XGetTransientForHint(display, id, &trans);
2194         XGetWMNormalHints(display, id, &win->sh, &mask); /* XXX function? */
2195         if (trans) {
2196                 win->transient = trans;
2197                 DNPRINTF(SWM_D_MISC, "manage_window: win %u transient %u\n",
2198                     (unsigned)win->id, win->transient);
2199         }
2200
2201         /*
2202          * Figure out where to put the window. If it was previously assigned to
2203          * a workspace (either by spawn() or manually moving), and isn't
2204          * transient, * put it in the same workspace
2205          */
2206         r = root_to_region(win->wa.root);
2207         if (prop && win->transient == 0) {
2208                 DNPRINTF(SWM_D_PROP, "got property _SWM_WS=%s\n", prop);
2209                 ws_idx = strtonum(prop, 0, 9, &errstr);
2210                 if (errstr) {
2211                         DNPRINTF(SWM_D_EVENT, "window idx is %s: %s",
2212                             errstr, prop);
2213                 }
2214                 ws = &r->s->ws[ws_idx];
2215         } else
2216                 ws = r->ws;
2217
2218         /* set up the window layout */
2219         win->id = id;
2220         win->ws = ws;
2221         win->s = r->s;  /* this never changes */
2222         TAILQ_INSERT_TAIL(&ws->winlist, win, entry);
2223
2224         win->g.w = win->wa.width;
2225         win->g.h = win->wa.height;
2226         win->g.x = win->wa.x;
2227         win->g.y = win->wa.y;
2228
2229         /* Set window properties so we can remember this after reincarnation */
2230         if (ws_idx_atom && prop == NULL &&
2231             snprintf(ws_idx_str, SWM_PROPLEN, "%d", ws->idx) < SWM_PROPLEN) {
2232                 DNPRINTF(SWM_D_PROP, "setting property _SWM_WS to %s\n",
2233                     ws_idx_str);
2234                 XChangeProperty(display, win->id, ws_idx_atom, XA_STRING, 8,
2235                     PropModeReplace, ws_idx_str, SWM_PROPLEN);
2236         }
2237         XFree(prop);
2238
2239         if (XGetClassHint(display, win->id, &win->ch)) {
2240                 DNPRINTF(SWM_D_CLASS, "class: %s name: %s\n",
2241                     win->ch.res_class, win->ch.res_name);
2242                 for (i = 0; quirks[i].class != NULL && quirks[i].name != NULL &&
2243                     quirks[i].quirk != 0; i++){
2244                         if (!strcmp(win->ch.res_class, quirks[i].class) &&
2245                             !strcmp(win->ch.res_name, quirks[i].name)) {
2246                                 DNPRINTF(SWM_D_CLASS, "found: %s name: %s\n",
2247                                     win->ch.res_class, win->ch.res_name);
2248                                 if (quirks[i].quirk & SWM_Q_FLOAT)
2249                                         win->floating = 1;
2250                                 win->quirks = quirks[i].quirk;
2251                         }
2252                 }
2253         }
2254
2255         /* alter window position if quirky */
2256         if (win->quirks & SWM_Q_ANYWHERE) {
2257                 win->manual = 1; /* don't center the quirky windows */
2258                 bzero(&wc, sizeof wc);
2259                 mask = 0;
2260                 if (win->g.y < bar_height) {
2261                         win->g.y = wc.y = bar_height;
2262                         mask |= CWY;
2263                 }
2264                 if (win->g.w + win->g.x > WIDTH(r)) {
2265                         win->g.x = wc.x = WIDTH(win->ws->r) - win->g.w - 2;
2266                         mask |= CWX;
2267                 }
2268                 wc.border_width = 1;
2269                 mask |= CWBorderWidth;
2270                 XConfigureWindow(display, win->id, mask, &wc);
2271         }
2272
2273         XSelectInput(display, id, EnterWindowMask | FocusChangeMask |
2274             PropertyChangeMask | StructureNotifyMask);
2275
2276         set_win_state(win, NormalState);
2277
2278         /* floaters need to be mapped if they are in the current workspace */
2279         if (win->floating && (ws->idx == r->ws->idx))
2280                 XMapRaised(display, win->id);
2281
2282         /* make new win focused */
2283         focus_win(win);
2284
2285         return (win);
2286 }
2287
2288 void
2289 unmanage_window(struct ws_win *win)
2290 {
2291         struct workspace        *ws;
2292
2293         if (win == NULL)
2294                 return;
2295
2296         DNPRINTF(SWM_D_MISC, "unmanage_window:  %lu\n", win->id);
2297
2298         /* don't unmanage if we are switching workspaces */
2299         ws = win->ws;
2300         if (ws->restack)
2301                 return;
2302
2303         /* find a window to focus */
2304         if (ws->focus == win)
2305                 ws->focus = TAILQ_PREV(win, ws_win_list, entry);
2306         if (ws->focus == NULL)
2307                 ws->focus = TAILQ_FIRST(&ws->winlist);
2308         if (ws->focus == NULL || ws->focus == win) {
2309                 ws->focus = NULL;
2310                 unfocus_all();
2311         } else
2312                 focus_win(ws->focus);
2313         if (ws->focus_prev == win)
2314                 ws->focus_prev = NULL;
2315
2316         TAILQ_REMOVE(&win->ws->winlist, win, entry);
2317         set_win_state(win, WithdrawnState);
2318         if (win->ch.res_class)
2319                 XFree(win->ch.res_class);
2320         if (win->ch.res_name)
2321                 XFree(win->ch.res_name);
2322         free(win);
2323 }
2324
2325 void
2326 configurerequest(XEvent *e)
2327 {
2328         XConfigureRequestEvent  *ev = &e->xconfigurerequest;
2329         struct ws_win           *win;
2330         int                     new = 0;
2331         XWindowChanges          wc;
2332
2333         if ((win = find_window(ev->window)) == NULL)
2334                 new = 1;
2335
2336         if (new) {
2337                 DNPRINTF(SWM_D_EVENT, "configurerequest: new window: %lu\n",
2338                     ev->window);
2339                 bzero(&wc, sizeof wc);
2340                 wc.x = ev->x;
2341                 wc.y = ev->y;
2342                 wc.width = ev->width;
2343                 wc.height = ev->height;
2344                 wc.border_width = ev->border_width;
2345                 wc.sibling = ev->above;
2346                 wc.stack_mode = ev->detail;
2347                 XConfigureWindow(display, ev->window, ev->value_mask, &wc);
2348         } else {
2349                 DNPRINTF(SWM_D_EVENT, "configurerequest: change window: %lu\n",
2350                     ev->window);
2351                 if (win->floating) {
2352                         if (ev->value_mask & CWX)
2353                                 win->g.x = ev->x;
2354                         if (ev->value_mask & CWY)
2355                                 win->g.y = ev->y;
2356                         if (ev->value_mask & CWWidth)
2357                                 win->g.w = ev->width;
2358                         if (ev->value_mask & CWHeight)
2359                                 win->g.h = ev->height;
2360                         if (win->ws->r != NULL) {
2361                                 /* this seems to be full screen */
2362                                 if (win->g.w >= WIDTH(win->ws->r)) {
2363                                         win->g.x = -1;
2364                                         win->g.w = WIDTH(win->ws->r);
2365                                         ev->value_mask |= CWX | CWWidth;
2366                                 }
2367                                 if (win->g.h >= HEIGHT(win->ws->r)) {
2368                                         /* kill border */
2369                                         win->g.y = -1;
2370                                         win->g.h = HEIGHT(win->ws->r);
2371                                         ev->value_mask |= CWY | CWHeight;
2372                                 }
2373                         }
2374                         if ((ev->value_mask & (CWX | CWY)) &&
2375                             !(ev->value_mask & (CWWidth | CWHeight)))
2376                                 config_win(win);
2377                         XMoveResizeWindow(display, win->id,
2378                             win->g.x, win->g.y, win->g.w, win->g.h);
2379                 } else
2380                         config_win(win);
2381         }
2382 }
2383
2384 void
2385 configurenotify(XEvent *e)
2386 {
2387         struct ws_win           *win;
2388         long                    mask;
2389
2390         DNPRINTF(SWM_D_EVENT, "configurenotify: window: %lu\n",
2391             e->xconfigure.window);
2392
2393         win = find_window(e->xconfigure.window);
2394         XMapWindow(display, win->id);
2395         XGetWMNormalHints(display, win->id, &win->sh, &mask);
2396         adjust_font(win);
2397         XMapWindow(display, win->id);
2398         if (font_adjusted)
2399                 stack();
2400 }
2401
2402 void
2403 destroynotify(XEvent *e)
2404 {
2405         struct ws_win           *win;
2406         XDestroyWindowEvent     *ev = &e->xdestroywindow;
2407
2408         DNPRINTF(SWM_D_EVENT, "destroynotify: window %lu\n", ev->window);
2409
2410         if ((win = find_window(ev->window)) != NULL) {
2411                 unmanage_window(win);
2412                 stack();
2413         }
2414 }
2415
2416 void
2417 enternotify(XEvent *e)
2418 {
2419         XCrossingEvent          *ev = &e->xcrossing;
2420         struct ws_win           *win;
2421
2422         DNPRINTF(SWM_D_EVENT, "enternotify: window: %lu\n", ev->window);
2423
2424         if (ignore_enter) {
2425                 /* eat event(r) to prevent autofocus */
2426                 ignore_enter--;
2427                 return;
2428         }
2429
2430         if ((win = find_window(ev->window)) != NULL)
2431                 focus_win(win);
2432 }
2433
2434 void
2435 focusin(XEvent *e)
2436 {
2437         DNPRINTF(SWM_D_EVENT, "focusin: window: %lu\n", e->xfocus.window);
2438 }
2439
2440 void
2441 mappingnotify(XEvent *e)
2442 {
2443         XMappingEvent           *ev = &e->xmapping;
2444
2445         DNPRINTF(SWM_D_EVENT, "mappingnotify: window: %lu\n", ev->window);
2446
2447         XRefreshKeyboardMapping(ev);
2448         if (ev->request == MappingKeyboard)
2449                 grabkeys();
2450 }
2451
2452 void
2453 maprequest(XEvent *e)
2454 {
2455         XMapRequestEvent        *ev = &e->xmaprequest;
2456         XWindowAttributes       wa;
2457
2458         DNPRINTF(SWM_D_EVENT, "maprequest: window: %lu\n",
2459             e->xmaprequest.window);
2460
2461         if (!XGetWindowAttributes(display, ev->window, &wa))
2462                 return;
2463         if (wa.override_redirect)
2464                 return;
2465         manage_window(e->xmaprequest.window);
2466
2467         stack();
2468 }
2469
2470 void
2471 propertynotify(XEvent *e)
2472 {
2473         struct ws_win           *win;
2474         XPropertyEvent          *ev = &e->xproperty;
2475
2476         DNPRINTF(SWM_D_EVENT, "propertynotify: window: %lu\n",
2477             ev->window);
2478
2479         if (ev->state == PropertyDelete)
2480                 return; /* ignore */
2481         win = find_window(ev->window);
2482         if (win == NULL)
2483                 return;
2484
2485         switch (ev->atom) {
2486         case XA_WM_NORMAL_HINTS:
2487 #if 0
2488                 long            mask;
2489                 XGetWMNormalHints(display, win->id, &win->sh, &mask);
2490                 fprintf(stderr, "normal hints: flag 0x%x\n", win->sh.flags);
2491                 if (win->sh.flags & PMinSize) {
2492                         win->g.w = win->sh.min_width;
2493                         win->g.h = win->sh.min_height;
2494                         fprintf(stderr, "min %d %d\n", win->g.w, win->g.h);
2495                 }
2496                 XMoveResizeWindow(display, win->id,
2497                     win->g.x, win->g.y, win->g.w, win->g.h);
2498 #endif
2499                 break;
2500         default:
2501                 break;
2502         }
2503 }
2504
2505 void
2506 unmapnotify(XEvent *e)
2507 {
2508         XDestroyWindowEvent     *ev = &e->xdestroywindow;
2509         struct ws_win           *win;
2510
2511         DNPRINTF(SWM_D_EVENT, "unmapnotify: window: %lu\n", e->xunmap.window);
2512
2513         if ((win = find_window(ev->window)) != NULL)
2514                 if (win->transient)
2515                         unmanage_window(win);
2516 }
2517
2518 void
2519 visibilitynotify(XEvent *e)
2520 {
2521         int                     i;
2522         struct swm_region       *r;
2523
2524         DNPRINTF(SWM_D_EVENT, "visibilitynotify: window: %lu\n",
2525             e->xvisibility.window);
2526         if (e->xvisibility.state == VisibilityUnobscured)
2527                 for (i = 0; i < ScreenCount(display); i++) 
2528                         TAILQ_FOREACH(r, &screens[i].rl, entry)
2529                                 if (e->xvisibility.window == r->bar_window)
2530                                         bar_update();
2531 }
2532
2533 int
2534 xerror_start(Display *d, XErrorEvent *ee)
2535 {
2536         other_wm = 1;
2537         return (-1);
2538 }
2539
2540 int
2541 xerror(Display *d, XErrorEvent *ee)
2542 {
2543         /* fprintf(stderr, "error: %p %p\n", display, ee); */
2544         return (-1);
2545 }
2546
2547 int
2548 active_wm(void)
2549 {
2550         other_wm = 0;
2551         xerrorxlib = XSetErrorHandler(xerror_start);
2552
2553         /* this causes an error if some other window manager is running */
2554         XSelectInput(display, DefaultRootWindow(display),
2555             SubstructureRedirectMask);
2556         XSync(display, False);
2557         if (other_wm)
2558                 return (1);
2559
2560         XSetErrorHandler(xerror);
2561         XSync(display, False);
2562         return (0);
2563 }
2564
2565 long
2566 getstate(Window w)
2567 {
2568         int                     format, status;
2569         long                    result = -1;
2570         unsigned char           *p = NULL;
2571         unsigned long           n, extra;
2572         Atom                    real;
2573
2574         astate = XInternAtom(display, "WM_STATE", False);
2575         status = XGetWindowProperty(display, w, astate, 0L, 2L, False, astate,
2576             &real, &format, &n, &extra, (unsigned char **)&p);
2577         if (status != Success)
2578                 return (-1);
2579         if (n != 0)
2580                 result = *p;
2581         XFree(p);
2582         return (result);
2583 }
2584
2585 void
2586 new_region(struct swm_screen *s, int x, int y, int w, int h)
2587 {
2588         struct swm_region       *r, *n;
2589         struct workspace        *ws = NULL;
2590         int                     i;
2591
2592         DNPRINTF(SWM_D_MISC, "new region: screen[%d]:%dx%d+%d+%d\n",
2593              s->idx, w, h, x, y);
2594
2595         /* remove any conflicting regions */
2596         n = TAILQ_FIRST(&s->rl);
2597         while (n) {
2598                 r = n;
2599                 n = TAILQ_NEXT(r, entry);
2600                 if (X(r) < (x + w) &&
2601                     (X(r) + WIDTH(r)) > x &&
2602                     Y(r) < (y + h) &&
2603                     (Y(r) + HEIGHT(r)) > y) {
2604                         XDestroyWindow(display, r->bar_window);
2605                         TAILQ_REMOVE(&s->rl, r, entry);
2606                         TAILQ_INSERT_TAIL(&s->orl, r, entry);
2607                 }
2608         }
2609
2610         /* search old regions for one to reuse */
2611
2612         /* size + location match */
2613         TAILQ_FOREACH(r, &s->orl, entry)
2614                 if (X(r) == x && Y(r) == y &&
2615                     HEIGHT(r) == h && WIDTH(r) == w)
2616                         break;
2617
2618         /* size match */
2619         TAILQ_FOREACH(r, &s->orl, entry)
2620                 if (HEIGHT(r) == h && WIDTH(r) == w)
2621                         break;
2622
2623         if (r != NULL) {
2624                 TAILQ_REMOVE(&s->orl, r, entry);
2625                 /* try to use old region's workspace */
2626                 if (r->ws->r == NULL)
2627                         ws = r->ws;
2628         } else
2629                 if ((r = calloc(1, sizeof(struct swm_region))) == NULL)
2630                         errx(1, "calloc: failed to allocate memory for screen");
2631
2632         /* if we don't have a workspace already, find one */
2633         if (ws == NULL) {
2634                 for (i = 0; i < SWM_WS_MAX; i++)
2635                         if (s->ws[i].r == NULL) {
2636                                 ws = &s->ws[i];
2637                                 break;
2638                         }
2639         }
2640
2641         if (ws == NULL)
2642                 errx(1, "no free workspaces\n");
2643
2644         X(r) = x;
2645         Y(r) = y;
2646         WIDTH(r) = w;
2647         HEIGHT(r) = h;
2648         r->s = s;
2649         r->ws = ws;
2650         ws->r = r;
2651         TAILQ_INSERT_TAIL(&s->rl, r, entry);
2652 }
2653
2654 void
2655 scan_xrandr(int i)
2656 {
2657 #ifdef SWM_XRR_HAS_CRTC
2658         XRRCrtcInfo             *ci;
2659         XRRScreenResources      *sr;
2660         int                     c;
2661         int                     ncrtc = 0;
2662 #endif /* SWM_XRR_HAS_CRTC */
2663         struct swm_region       *r;
2664
2665
2666         if (i >= ScreenCount(display))
2667                 errx(1, "invalid screen");
2668
2669         /* remove any old regions */
2670         while ((r = TAILQ_FIRST(&screens[i].rl)) != NULL) {
2671                 r->ws->r = NULL;
2672                 XDestroyWindow(display, r->bar_window);
2673                 TAILQ_REMOVE(&screens[i].rl, r, entry);
2674                 TAILQ_INSERT_TAIL(&screens[i].orl, r, entry);
2675         }
2676
2677         /* map virtual screens onto physical screens */
2678 #ifdef SWM_XRR_HAS_CRTC
2679         if (xrandr_support) {
2680                 sr = XRRGetScreenResources(display, screens[i].root);
2681                 if (sr == NULL)
2682                         new_region(&screens[i], 0, 0,
2683                             DisplayWidth(display, i),
2684                             DisplayHeight(display, i)); 
2685                 else 
2686                         ncrtc = sr->ncrtc;
2687
2688                 for (c = 0, ci = NULL; c < ncrtc; c++) {
2689                         ci = XRRGetCrtcInfo(display, sr, sr->crtcs[c]);
2690                         if (ci->noutput == 0)
2691                                 continue;
2692
2693                         if (ci != NULL && ci->mode == None)
2694                                 new_region(&screens[i], 0, 0,
2695                                     DisplayWidth(display, i),
2696                                     DisplayHeight(display, i)); 
2697                         else
2698                                 new_region(&screens[i],
2699                                     ci->x, ci->y, ci->width, ci->height);
2700                 }
2701                 if (ci)
2702                         XRRFreeCrtcInfo(ci);
2703                 XRRFreeScreenResources(sr);
2704         } else
2705 #endif /* SWM_XRR_HAS_CRTC */
2706         {
2707                 new_region(&screens[i], 0, 0, DisplayWidth(display, i),
2708                     DisplayHeight(display, i)); 
2709         }
2710 }
2711
2712 void
2713 screenchange(XEvent *e) {
2714         XRRScreenChangeNotifyEvent      *xe = (XRRScreenChangeNotifyEvent *)e;
2715         struct swm_region               *r;
2716         struct ws_win                   *win;
2717         int                             i;
2718
2719         DNPRINTF(SWM_D_EVENT, "screenchange: %lu\n", xe->root);
2720
2721         if (!XRRUpdateConfiguration(e))
2722                 return;
2723
2724         /* silly event doesn't include the screen index */
2725         for (i = 0; i < ScreenCount(display); i++)
2726                 if (screens[i].root == xe->root)
2727                         break;
2728         if (i >= ScreenCount(display))
2729                 errx(1, "screenchange: screen not found\n");
2730
2731         /* brute force for now, just re-enumerate the regions */
2732         scan_xrandr(i);
2733
2734         /* hide any windows that went away */
2735         TAILQ_FOREACH(r, &screens[i].rl, entry)
2736                 TAILQ_FOREACH(win, &r->ws->winlist, entry)
2737                         XUnmapWindow(display, win->id);
2738         stack();
2739 }
2740
2741 void
2742 setup_screens(void)
2743 {
2744         Window                  d1, d2, *wins = NULL;
2745         XWindowAttributes       wa;
2746         unsigned int            no;
2747         int                     i, j, k;
2748         int                     errorbase, major, minor;
2749         struct workspace        *ws;
2750         int                     ws_idx_atom;
2751
2752
2753         if ((screens = calloc(ScreenCount(display),
2754              sizeof(struct swm_screen))) == NULL)
2755                 errx(1, "calloc: screens");
2756
2757         ws_idx_atom = XInternAtom(display, "_SWM_WS", False);
2758
2759         /* initial Xrandr setup */
2760         xrandr_support = XRRQueryExtension(display,
2761             &xrandr_eventbase, &errorbase);
2762         if (xrandr_support)
2763                 if (XRRQueryVersion(display, &major, &minor) && major < 1)
2764                         xrandr_support = 0;
2765
2766         /* map physical screens */
2767         for (i = 0; i < ScreenCount(display); i++) {
2768                 DNPRINTF(SWM_D_WS, "setup_screens: init screen %d\n", i);
2769                 screens[i].idx = i;
2770                 TAILQ_INIT(&screens[i].rl);
2771                 TAILQ_INIT(&screens[i].orl);
2772                 screens[i].root = RootWindow(display, i);
2773
2774                 /* set default colors */
2775                 setscreencolor("red", i + 1, SWM_S_COLOR_FOCUS);
2776                 setscreencolor("rgb:88/88/88", i + 1, SWM_S_COLOR_UNFOCUS);
2777                 setscreencolor("rgb:00/80/80", i + 1, SWM_S_COLOR_BAR_BORDER);
2778                 setscreencolor("black", i + 1, SWM_S_COLOR_BAR);
2779                 setscreencolor("rgb:a0/a0/a0", i + 1, SWM_S_COLOR_BAR_FONT);
2780
2781                 /* init all workspaces */
2782                 /* XXX these should be dynamically allocated too */
2783                 for (j = 0; j < SWM_WS_MAX; j++) {
2784                         ws = &screens[i].ws[j];
2785                         ws->idx = j;
2786                         ws->restack = 1;
2787                         ws->focus = NULL;
2788                         ws->r = NULL;
2789                         TAILQ_INIT(&ws->winlist);
2790
2791                         for (k = 0; layouts[k].l_stack != NULL; k++)
2792                                 if (layouts[k].l_config != NULL)
2793                                         layouts[k].l_config(ws,
2794                                             SWM_ARG_ID_STACKINIT);
2795                         ws->cur_layout = &layouts[0];
2796                 }
2797                 /* grab existing windows (before we build the bars)*/
2798                 if (!XQueryTree(display, screens[i].root, &d1, &d2, &wins, &no))
2799                         continue;
2800
2801                 scan_xrandr(i);
2802
2803                 if (xrandr_support)
2804                         XRRSelectInput(display, screens[i].root,
2805                             RRScreenChangeNotifyMask);
2806
2807                 /* attach windows to a region */
2808                 /* normal windows */
2809                 for (j = 0; j < no; j++) {
2810                         XGetWindowAttributes(display, wins[j], &wa);
2811                         if (!XGetWindowAttributes(display, wins[j], &wa) ||
2812                             wa.override_redirect ||
2813                             XGetTransientForHint(display, wins[j], &d1))
2814                                 continue;
2815
2816                         if (wa.map_state == IsViewable ||
2817                             getstate(wins[j]) == NormalState)
2818                                 manage_window(wins[j]);
2819                 }
2820                 /* transient windows */
2821                 for (j = 0; j < no; j++) {
2822                         if (!XGetWindowAttributes(display, wins[j], &wa))
2823                                 continue;
2824
2825                         if (XGetTransientForHint(display, wins[j], &d1) &&
2826                             (wa.map_state == IsViewable || getstate(wins[j]) ==
2827                             NormalState))
2828                                 manage_window(wins[j]);
2829                 }
2830                 if (wins) {
2831                         XFree(wins);
2832                         wins = NULL;
2833                 }
2834         }
2835 }
2836
2837 int
2838 main(int argc, char *argv[])
2839 {
2840         struct passwd           *pwd;
2841         struct swm_region       *r;
2842         char                    conf[PATH_MAX], *cfile = NULL;
2843         struct stat             sb;
2844         XEvent                  e;
2845         int                     xfd, i;
2846         fd_set                  rd;
2847
2848         start_argv = argv;
2849         fprintf(stderr, "Welcome to scrotwm V%s cvs tag: %s\n",
2850             SWM_VERSION, cvstag);
2851         if (!setlocale(LC_CTYPE, "") || !XSupportsLocale())
2852                 warnx("no locale support");
2853
2854         if (!(display = XOpenDisplay(0)))
2855                 errx(1, "can not open display");
2856
2857         if (active_wm())
2858                 errx(1, "other wm running");
2859
2860         astate = XInternAtom(display, "WM_STATE", False);
2861
2862         /* look for local and global conf file */
2863         pwd = getpwuid(getuid());
2864         if (pwd == NULL)
2865                 errx(1, "invalid user %d", getuid());
2866
2867         setup_screens();
2868
2869         snprintf(conf, sizeof conf, "%s/.%s", pwd->pw_dir, SWM_CONF_FILE);
2870         if (stat(conf, &sb) != -1) {
2871                 if (S_ISREG(sb.st_mode))
2872                         cfile = conf;
2873         } else {
2874                 /* try global conf file */
2875                 snprintf(conf, sizeof conf, "/etc/%s", SWM_CONF_FILE);
2876                 if (!stat(conf, &sb))
2877                         if (S_ISREG(sb.st_mode))
2878                                 cfile = conf;
2879         }
2880         if (cfile)
2881                 conf_load(cfile);
2882
2883         /* setup all bars */
2884         for (i = 0; i < ScreenCount(display); i++)
2885                 TAILQ_FOREACH(r, &screens[i].rl, entry)
2886                         bar_setup(r);
2887
2888         /* ws[0].focus = TAILQ_FIRST(&ws[0].winlist); */
2889
2890         grabkeys();
2891         stack();
2892
2893         xfd = ConnectionNumber(display);
2894         while (running) {
2895                 FD_ZERO(&rd);
2896                 FD_SET(xfd, &rd);
2897                 if (select(xfd + 1, &rd, NULL, NULL, NULL) == -1)
2898                         if (errno != EINTR)
2899                                 errx(1, "select failed");
2900                 if (bar_alarm) {
2901                         bar_alarm = 0;
2902                         bar_update();
2903                 }
2904                 while (XPending(display)) {
2905                         XNextEvent(display, &e);
2906                         if (e.type < LASTEvent) {
2907                                 if (handler[e.type])
2908                                         handler[e.type](&e);
2909                                 else
2910                                         DNPRINTF(SWM_D_EVENT,
2911                                             "win: %lu unknown event: %d\n",
2912                                             e.xany.window, e.type);
2913                         } else {
2914                                 switch (e.type - xrandr_eventbase) {
2915                                 case RRScreenChangeNotify:
2916                                         screenchange(&e);
2917                                         break;
2918                                 default:
2919                                         DNPRINTF(SWM_D_EVENT,
2920                                             "win: %lu unknown xrandr event: "
2921                                             "%d\n", e.xany.window, e.type);
2922                                         break;
2923                                 }
2924                         }
2925                 }
2926         }
2927
2928         XCloseDisplay(display);
2929
2930         return (0);
2931 }