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