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