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