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