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