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