JasonWoof Got questions, comments, patches, etc.? Contact Jason Woofenden
Break out static quirks list into dynamic list, initialized to match the
[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.2"
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                 strlcpy(bar_vertext, cvstag, sizeof bar_vertext);
916         else
917                 strlcpy(bar_vertext, "", sizeof bar_vertext);
918         bar_update();
919 }
920
921 void
922 client_msg(struct ws_win *win, Atom a)
923 {
924         XClientMessageEvent     cm;
925
926         bzero(&cm, sizeof cm);
927         cm.type = ClientMessage;
928         cm.window = win->id;
929         cm.message_type = aprot;
930         cm.format = 32;
931         cm.data.l[0] = a;
932         cm.data.l[1] = CurrentTime;
933         XSendEvent(display, win->id, False, 0L, (XEvent *)&cm);
934 }
935
936 void
937 config_win(struct ws_win *win)
938 {
939         XConfigureEvent         ce;
940
941         DNPRINTF(SWM_D_MISC, "config_win: win %lu x %d y %d w %d h %d\n",
942             win->id, win->g.x, win->g.y, win->g.w, win->g.h);
943         ce.type = ConfigureNotify;
944         ce.display = display;
945         ce.event = win->id;
946         ce.window = win->id;
947         ce.x = win->g.x;
948         ce.y = win->g.y;
949         ce.width = win->g.w;
950         ce.height = win->g.h;
951         ce.border_width = 1; /* XXX store this! */
952         ce.above = None;
953         ce.override_redirect = False;
954         XSendEvent(display, win->id, False, StructureNotifyMask, (XEvent *)&ce);
955 }
956
957 int
958 count_win(struct workspace *ws, int count_transient)
959 {
960         struct ws_win           *win;
961         int                     count = 0;
962
963         TAILQ_FOREACH(win, &ws->winlist, entry) {
964                 if (count_transient == 0 && win->floating)
965                         continue;
966                 if (count_transient == 0 && win->transient)
967                         continue;
968                 count++;
969         }
970         DNPRINTF(SWM_D_MISC, "count_win: %d\n", count);
971
972         return (count);
973 }
974
975 void
976 quit(struct swm_region *r, union arg *args)
977 {
978         DNPRINTF(SWM_D_MISC, "quit\n");
979         running = 0;
980 }
981
982 void
983 unmap_all(void)
984 {
985         struct ws_win           *win;
986         int                     i, j;
987
988         for (i = 0; i < ScreenCount(display); i++)
989                 for (j = 0; j < SWM_WS_MAX; j++)
990                         TAILQ_FOREACH(win, &screens[i].ws[j].winlist, entry)
991                                 XUnmapWindow(display, win->id);
992 }
993
994 void
995 fake_keypress(struct ws_win *win, int keysym, int modifiers)
996 {
997         XKeyEvent event;
998
999         event.display = display;        /* Ignored, but what the hell */
1000         event.window = win->id;
1001         event.root = win->s->root;
1002         event.subwindow = None;
1003         event.time = CurrentTime;
1004         event.x = win->g.x;
1005         event.y = win->g.y;
1006         event.x_root = 1;
1007         event.y_root = 1;
1008         event.same_screen = True;
1009         event.keycode = XKeysymToKeycode(display, keysym);
1010         event.state = modifiers;
1011
1012         event.type = KeyPress;
1013         XSendEvent(event.display, event.window, True,
1014             KeyPressMask, (XEvent *)&event);
1015
1016         event.type = KeyRelease;
1017         XSendEvent(event.display, event.window, True,
1018             KeyPressMask, (XEvent *)&event);
1019
1020 }
1021
1022 void
1023 restart(struct swm_region *r, union arg *args)
1024 {
1025         DNPRINTF(SWM_D_MISC, "restart: %s\n", start_argv[0]);
1026
1027         /* disable alarm because the following code may not be interrupted */
1028         alarm(0);
1029         if (signal(SIGALRM, SIG_IGN) == SIG_ERR)
1030                 errx(1, "can't disable alarm");
1031
1032         bar_extra_stop();
1033         bar_extra = 1;
1034         unmap_all();
1035         XCloseDisplay(display);
1036         execvp(start_argv[0], start_argv);
1037         fprintf(stderr, "execvp failed\n");
1038         perror(" failed");
1039         quit(NULL, NULL);
1040 }
1041
1042 struct swm_region *
1043 root_to_region(Window root)
1044 {
1045         struct swm_region       *r = NULL;
1046         Window                  rr, cr;
1047         int                     i, x, y, wx, wy;
1048         unsigned int            mask;
1049
1050         for (i = 0; i < ScreenCount(display); i++)
1051                 if (screens[i].root == root)
1052                         break;
1053
1054         if (XQueryPointer(display, screens[i].root, 
1055             &rr, &cr, &x, &y, &wx, &wy, &mask) != False) {
1056                 /* choose a region based on pointer location */
1057                 TAILQ_FOREACH(r, &screens[i].rl, entry)
1058                         if (x >= X(r) && x <= X(r) + WIDTH(r) &&
1059                             y >= Y(r) && y <= Y(r) + HEIGHT(r))
1060                                 break;
1061         }
1062
1063         if (r == NULL)
1064                 r = TAILQ_FIRST(&screens[i].rl);
1065
1066         return (r);
1067 }
1068
1069 struct ws_win *
1070 find_window(Window id)
1071 {
1072         struct ws_win           *win;
1073         int                     i, j;
1074
1075         for (i = 0; i < ScreenCount(display); i++)
1076                 for (j = 0; j < SWM_WS_MAX; j++)
1077                         TAILQ_FOREACH(win, &screens[i].ws[j].winlist, entry)
1078                                 if (id == win->id)
1079                                         return (win);
1080         return (NULL);
1081 }
1082
1083 void
1084 spawn(struct swm_region *r, union arg *args)
1085 {
1086         char                    *ret;
1087         int                     si;
1088
1089         DNPRINTF(SWM_D_MISC, "spawn: %s\n", args->argv[0]);
1090         /*
1091          * The double-fork construct avoids zombie processes and keeps the code
1092          * clean from stupid signal handlers.
1093          */
1094         if (fork() == 0) {
1095                 if (fork() == 0) {
1096                         if (display)
1097                                 close(ConnectionNumber(display));
1098                         setenv("LD_PRELOAD", SWM_LIB, 1);
1099                         if (asprintf(&ret, "%d", r->ws->idx)) {
1100                                 setenv("_SWM_WS", ret, 1);
1101                                 free(ret);
1102                         }
1103                         if (asprintf(&ret, "%d", getpid())) {
1104                                 setenv("_SWM_PID", ret, 1);
1105                                 free(ret);
1106                         }
1107                         setsid();
1108                         /* kill stdin, mplayer, ssh-add etc. need that */
1109                         si = open("/dev/null", O_RDONLY, 0);
1110                         if (si == -1)
1111                                 err(1, "open /dev/null");
1112                         if (dup2(si, 0) == -1)
1113                                 err(1, "dup2 /dev/null");
1114                         execvp(args->argv[0], args->argv);
1115                         fprintf(stderr, "execvp failed\n");
1116                         perror(" failed");
1117                 }
1118                 exit(0);
1119         }
1120         wait(0);
1121 }
1122
1123 void
1124 spawnterm(struct swm_region *r, union arg *args)
1125 {
1126         DNPRINTF(SWM_D_MISC, "spawnterm\n");
1127
1128         if (term_width)
1129                 setenv("_SWM_XTERM_FONTADJ", "", 1);
1130         spawn(r, args);
1131 }
1132
1133 void
1134 spawnmenu(struct swm_region *r, union arg *args)
1135 {
1136         DNPRINTF(SWM_D_MISC, "spawnmenu\n");
1137
1138         spawn_menu[SWM_MENU_FN] = bar_fonts[bar_fidx];
1139         spawn_menu[SWM_MENU_NB] = r->s->c[SWM_S_COLOR_BAR].name;
1140         spawn_menu[SWM_MENU_NF] = r->s->c[SWM_S_COLOR_BAR_FONT].name;
1141         spawn_menu[SWM_MENU_SB] = r->s->c[SWM_S_COLOR_BAR_BORDER].name;
1142         spawn_menu[SWM_MENU_SF] = r->s->c[SWM_S_COLOR_BAR].name;
1143
1144         spawn(r, args);
1145 }
1146
1147 void
1148 unfocus_win(struct ws_win *win)
1149 {
1150         if (win == NULL)
1151                 return;
1152
1153         if (win->ws->focus != win && win->ws->focus != NULL)
1154                 win->ws->focus_prev = win->ws->focus;
1155
1156         if (win->ws->r == NULL)
1157                 return;
1158
1159         grabbuttons(win, 0);
1160         XSetWindowBorder(display, win->id,
1161             win->ws->r->s->c[SWM_S_COLOR_UNFOCUS].color);
1162         win->got_focus = 0;
1163         if (win->ws->focus == win)
1164                 win->ws->focus = NULL;
1165         if (cur_focus == win)
1166                 cur_focus = NULL;
1167 }
1168
1169 void
1170 unfocus_all(void)
1171 {
1172         struct ws_win           *win;
1173         int                     i, j;
1174
1175         DNPRINTF(SWM_D_FOCUS, "unfocus_all:\n");
1176
1177         for (i = 0; i < ScreenCount(display); i++)
1178                 for (j = 0; j < SWM_WS_MAX; j++)
1179                         TAILQ_FOREACH(win, &screens[i].ws[j].winlist, entry)
1180                                 unfocus_win(win);
1181 }
1182
1183 void
1184 focus_win(struct ws_win *win)
1185 {
1186         DNPRINTF(SWM_D_FOCUS, "focus_win: id: %lu\n", win ? win->id : 0);
1187
1188         if (win == NULL)
1189                 return;
1190
1191         if (cur_focus)
1192                 unfocus_win(cur_focus);
1193         if (win->ws->focus) {
1194                 /* probably shouldn't happen due to the previous unfocus_win */
1195                 DNPRINTF(SWM_D_FOCUS, "unfocusing win->ws->focus: %lu\n",
1196                     win->ws->focus->id);
1197                 unfocus_win(win->ws->focus);
1198         }
1199         win->ws->focus = win;
1200         if (win->ws->r != NULL) {
1201                 cur_focus = win;
1202                 if (!win->got_focus) {
1203                         XSetWindowBorder(display, win->id,
1204                             win->ws->r->s->c[SWM_S_COLOR_FOCUS].color);
1205                         grabbuttons(win, 1);
1206                 }
1207                 win->got_focus = 1;
1208                 XSetInputFocus(display, win->id,
1209                     RevertToPointerRoot, CurrentTime);
1210         }
1211 }
1212
1213 void
1214 switchws(struct swm_region *r, union arg *args)
1215 {
1216         int                     wsid = args->id;
1217         struct swm_region       *this_r, *other_r;
1218         struct ws_win           *win;
1219         struct workspace        *new_ws, *old_ws;
1220
1221         this_r = r;
1222         old_ws = this_r->ws;
1223         new_ws = &this_r->s->ws[wsid];
1224
1225         DNPRINTF(SWM_D_WS, "switchws screen[%d]:%dx%d+%d+%d: "
1226             "%d -> %d\n", r->s->idx, WIDTH(r), HEIGHT(r), X(r), Y(r),
1227             old_ws->idx, wsid);
1228
1229         if (new_ws == old_ws)
1230                 return;
1231
1232         other_r = new_ws->r;
1233         if (!other_r) {
1234                 /* if the other workspace is hidden, switch windows */
1235                 /* map new window first to prevent ugly blinking */
1236                 old_ws->r = NULL;
1237                 old_ws->restack = 1;
1238
1239                 TAILQ_FOREACH(win, &new_ws->winlist, entry)
1240                         XMapRaised(display, win->id);
1241
1242                 TAILQ_FOREACH(win, &old_ws->winlist, entry)
1243                         XUnmapWindow(display, win->id);
1244         } else {
1245                 other_r->ws = old_ws;
1246                 old_ws->r = other_r;
1247         }
1248         this_r->ws = new_ws;
1249         new_ws->r = this_r;
1250
1251         ignore_enter = 1;
1252         /* set focus */
1253         if (new_ws->focus == NULL)
1254                 new_ws->focus = TAILQ_FIRST(&new_ws->winlist);
1255         if (new_ws->focus)
1256                 focus_win(new_ws->focus);
1257         stack();
1258         bar_update();
1259 }
1260
1261 void
1262 cyclews(struct swm_region *r, union arg *args)
1263 {
1264         union                   arg a;
1265         struct swm_screen       *s = r->s;
1266
1267         DNPRINTF(SWM_D_WS, "cyclews id %d "
1268             "in screen[%d]:%dx%d+%d+%d ws %d\n", args->id,
1269             r->s->idx, WIDTH(r), HEIGHT(r), X(r), Y(r), r->ws->idx);
1270
1271         a.id = r->ws->idx;
1272         do {
1273                 switch (args->id) {
1274                 case SWM_ARG_ID_CYCLEWS_UP:
1275                         if (a.id < SWM_WS_MAX - 1)
1276                                 a.id++;
1277                         else
1278                                 a.id = 0;
1279                         break;
1280                 case SWM_ARG_ID_CYCLEWS_DOWN:
1281                         if (a.id > 0)
1282                                 a.id--;
1283                         else
1284                                 a.id = SWM_WS_MAX - 1;
1285                         break;
1286                 default:
1287                         return;
1288                 };
1289
1290                 if (cycle_empty == 0 && TAILQ_EMPTY(&s->ws[a.id].winlist))
1291                         continue;
1292                 if (cycle_visible == 0 && s->ws[a.id].r != NULL)
1293                         continue;
1294
1295                 switchws(r, &a);
1296         } while (a.id != r->ws->idx);
1297 }
1298
1299 void
1300 cyclescr(struct swm_region *r, union arg *args)
1301 {
1302         struct swm_region       *rr;
1303         int                     i;
1304
1305         i = r->s->idx;
1306         switch (args->id) {
1307         case SWM_ARG_ID_CYCLESC_UP:
1308                 rr = TAILQ_NEXT(r, entry);
1309                 if (rr == NULL)
1310                         rr = TAILQ_FIRST(&screens[i].rl);
1311                 break;
1312         case SWM_ARG_ID_CYCLESC_DOWN:
1313                 rr = TAILQ_PREV(r, swm_region_list, entry);
1314                 if (rr == NULL)
1315                         rr = TAILQ_LAST(&screens[i].rl, swm_region_list);
1316                 break;
1317         default:
1318                 return;
1319         };
1320         unfocus_all();
1321         XSetInputFocus(display, PointerRoot, RevertToPointerRoot, CurrentTime);
1322         XWarpPointer(display, None, rr->s[i].root, 0, 0, 0, 0, rr->g.x,
1323             rr->g.y + bar_enabled ? bar_height : 0);
1324 }
1325
1326 void
1327 swapwin(struct swm_region *r, union arg *args)
1328 {
1329         struct ws_win           *target, *source;
1330         struct ws_win_list      *wl;
1331
1332
1333         DNPRINTF(SWM_D_WS, "swapwin id %d "
1334             "in screen %d region %dx%d+%d+%d ws %d\n", args->id,
1335             r->s->idx, WIDTH(r), HEIGHT(r), X(r), Y(r), r->ws->idx);
1336         if (cur_focus == NULL)
1337                 return;
1338
1339         source = cur_focus;
1340         wl = &source->ws->winlist;
1341
1342         switch (args->id) {
1343         case SWM_ARG_ID_SWAPPREV:
1344                 target = TAILQ_PREV(source, ws_win_list, entry);
1345                 TAILQ_REMOVE(wl, cur_focus, entry);
1346                 if (target == NULL)
1347                         TAILQ_INSERT_TAIL(wl, source, entry);
1348                 else
1349                         TAILQ_INSERT_BEFORE(target, source, entry);
1350                 break;
1351         case SWM_ARG_ID_SWAPNEXT: 
1352                 target = TAILQ_NEXT(source, entry);
1353                 TAILQ_REMOVE(wl, source, entry);
1354                 if (target == NULL)
1355                         TAILQ_INSERT_HEAD(wl, source, entry);
1356                 else
1357                         TAILQ_INSERT_AFTER(wl, target, source, entry);
1358                 break;
1359         case SWM_ARG_ID_SWAPMAIN:
1360                 target = TAILQ_FIRST(wl);
1361                 if (target == source) {
1362                         if (source->ws->focus_prev != NULL &&
1363                             source->ws->focus_prev != target)  
1364                                 
1365                                 source = source->ws->focus_prev;
1366                         else
1367                                 return;
1368                 }
1369                 source->ws->focus_prev = target;
1370                 TAILQ_REMOVE(wl, target, entry);
1371                 TAILQ_INSERT_BEFORE(source, target, entry);
1372                 TAILQ_REMOVE(wl, source, entry);
1373                 TAILQ_INSERT_HEAD(wl, source, entry);
1374                 break;
1375         default:
1376                 DNPRINTF(SWM_D_MOVE, "invalid id: %d\n", args->id);
1377                 return;
1378         }
1379
1380         ignore_enter = 1;
1381         stack();
1382 }
1383
1384 void
1385 focus(struct swm_region *r, union arg *args)
1386 {
1387         struct ws_win           *winfocus, *winlostfocus;
1388         struct ws_win_list      *wl;
1389
1390         DNPRINTF(SWM_D_FOCUS, "focus: id %d\n", args->id);
1391         if (cur_focus == NULL)
1392                 return;
1393
1394         wl = &cur_focus->ws->winlist;
1395
1396         winlostfocus = cur_focus;
1397
1398         switch (args->id) {
1399         case SWM_ARG_ID_FOCUSPREV:
1400                 winfocus = TAILQ_PREV(cur_focus, ws_win_list, entry);
1401                 if (winfocus == NULL)
1402                         winfocus = TAILQ_LAST(wl, ws_win_list);
1403                 break;
1404
1405         case SWM_ARG_ID_FOCUSNEXT:
1406                 winfocus = TAILQ_NEXT(cur_focus, entry);
1407                 if (winfocus == NULL)
1408                         winfocus = TAILQ_FIRST(wl);
1409                 break;
1410
1411         case SWM_ARG_ID_FOCUSMAIN:
1412                 winfocus = TAILQ_FIRST(wl);
1413                 if (winfocus == cur_focus)
1414                         winfocus = cur_focus->ws->focus_prev;
1415                 if (winfocus == NULL)
1416                         return;
1417                 break;
1418
1419         default:
1420                 return;
1421         }
1422
1423         if (winfocus == winlostfocus || winfocus == NULL)
1424                 return;
1425
1426         XMapRaised(display, winfocus->id);
1427         focus_win(winfocus);
1428         XSync(display, False);
1429 }
1430
1431 void
1432 cycle_layout(struct swm_region *r, union arg *args)
1433 {
1434         struct workspace        *ws = r->ws;
1435
1436         DNPRINTF(SWM_D_EVENT, "cycle_layout: workspace: %d\n", ws->idx);
1437
1438         ws->cur_layout++;
1439         if (ws->cur_layout->l_stack == NULL)
1440                 ws->cur_layout = &layouts[0];
1441         ignore_enter = 1;
1442         stack();
1443 }
1444
1445 void
1446 stack_config(struct swm_region *r, union arg *args)
1447 {
1448         struct workspace        *ws = r->ws;
1449
1450         DNPRINTF(SWM_D_STACK, "stack_config for workspace %d (id %d\n",
1451             args->id, ws->idx);
1452
1453         if (ws->cur_layout->l_config != NULL)
1454                 ws->cur_layout->l_config(ws, args->id);
1455
1456         if (args->id != SWM_ARG_ID_STACKINIT);
1457                 stack();
1458 }
1459
1460 void
1461 stack(void) {
1462         struct swm_geometry     g;
1463         struct swm_region       *r;
1464         int                     i, j;
1465
1466         DNPRINTF(SWM_D_STACK, "stack\n");
1467
1468         for (i = 0; i < ScreenCount(display); i++) {
1469                 j = 0;
1470                 TAILQ_FOREACH(r, &screens[i].rl, entry) {
1471                         DNPRINTF(SWM_D_STACK, "stacking workspace %d "
1472                             "(screen %d, region %d)\n", r->ws->idx, i, j++);
1473
1474                         /* start with screen geometry, adjust for bar */
1475                         g = r->g;
1476                         g.w -= 2;
1477                         g.h -= 2;
1478                         if (bar_enabled) {
1479                                 g.y += bar_height;
1480                                 g.h -= bar_height;
1481                         } 
1482
1483                         r->ws->restack = 0;
1484                         r->ws->cur_layout->l_stack(r->ws, &g);
1485                 }
1486         }
1487         if (font_adjusted)
1488                 font_adjusted--;
1489         XSync(display, False);
1490 }
1491
1492 void
1493 stack_floater(struct ws_win *win, struct swm_region *r)
1494 {
1495         unsigned int            mask;
1496         XWindowChanges          wc;
1497
1498         bzero(&wc, sizeof wc);
1499         mask = CWX | CWY | CWBorderWidth | CWWidth | CWHeight;
1500         if ((win->quirks & SWM_Q_FULLSCREEN) && (win->g.w == WIDTH(r)) &&
1501             (win->g.h == HEIGHT(r)))
1502                 wc.border_width = 0;
1503         else
1504                 wc.border_width = 1;
1505         if (win->transient && (win->quirks & SWM_Q_TRANSSZ)) {
1506                 win->g.w = (double)WIDTH(r) * dialog_ratio;
1507                 win->g.h = (double)HEIGHT(r) * dialog_ratio;
1508         }
1509         wc.width = win->g.w;
1510         wc.height = win->g.h;
1511         if (win->manual) {
1512                 wc.x = win->g.x;
1513                 wc.y = win->g.y;
1514         } else {
1515                 wc.x = (WIDTH(r) - win->g.w) / 2;
1516                 wc.y = (HEIGHT(r) - win->g.h) / 2;
1517         }
1518
1519         DNPRINTF(SWM_D_STACK, "stack_floater: win %lu x %d y %d w %d h %d\n",
1520             win->id, wc.x, wc.y, wc.width, wc.height);
1521
1522         XConfigureWindow(display, win->id, mask, &wc);
1523 }
1524
1525 /*
1526  * Send keystrokes to terminal to decrease/increase the font size as the
1527  * window size changes.
1528  */
1529 void
1530 adjust_font(struct ws_win *win)
1531 {
1532         if (!(win->quirks & SWM_Q_XTERM_FONTADJ) ||
1533             win->floating || win->transient)
1534                 return;
1535         
1536         if (win->sh.width_inc && win->last_inc != win->sh.width_inc &&
1537             win->g.w / win->sh.width_inc < term_width &&
1538             win->font_steps < SWM_MAX_FONT_STEPS) {
1539                 win->font_size_boundary[win->font_steps] =
1540                     (win->sh.width_inc * term_width) + win->sh.base_width;
1541                 win->font_steps++;
1542                 font_adjusted++;
1543                 win->last_inc = win->sh.width_inc;
1544                 fake_keypress(win, XK_KP_Subtract, ShiftMask);
1545         } else if (win->font_steps && win->last_inc != win->sh.width_inc &&
1546             win->g.w > win->font_size_boundary[win->font_steps - 1]) {
1547                 win->font_steps--;
1548                 font_adjusted++;
1549                 win->last_inc = win->sh.width_inc;
1550                 fake_keypress(win, XK_KP_Add, ShiftMask);
1551         }
1552 }
1553
1554 #define SWAPXY(g)       do {                            \
1555         int tmp;                                        \
1556         tmp = (g)->y; (g)->y = (g)->x; (g)->x = tmp;    \
1557         tmp = (g)->h; (g)->h = (g)->w; (g)->w = tmp;    \
1558 } while (0)
1559 void
1560 stack_master(struct workspace *ws, struct swm_geometry *g, int rot, int flip)
1561 {
1562         XWindowChanges          wc;
1563         struct swm_geometry     win_g, r_g = *g;
1564         struct ws_win           *win, *winfocus;
1565         int                     i, j, s, stacks; 
1566         int                     w_inc = 1, h_inc, w_base = 1, h_base;
1567         int                     hrh, extra = 0, h_slice, last_h = 0;
1568         int                     split, colno, winno, mwin, msize, mscale;
1569         int                     remain, missing, v_slice;;
1570         unsigned int            mask;
1571
1572         DNPRINTF(SWM_D_STACK, "stack_master: workspace: %d\n rot=%s flip=%s",
1573             ws->idx, rot ? "yes" : "no", flip ? "yes" : "no");
1574
1575         if ((winno = count_win(ws, 0)) == 0)
1576                 return;
1577
1578         if (ws->focus == NULL)
1579                 ws->focus = TAILQ_FIRST(&ws->winlist);
1580         winfocus = cur_focus ? cur_focus : ws->focus;
1581
1582         TAILQ_FOREACH(win, &ws->winlist, entry)
1583                 if (win->transient == 0 && win->floating == 0)
1584                         break;
1585
1586         if (win == NULL)
1587                 goto notiles;
1588
1589         if (rot) {
1590                 w_inc = win->sh.width_inc;
1591                 w_base = win->sh.base_width;
1592                 mwin = ws->l_state.horizontal_mwin;
1593                 mscale = ws->l_state.horizontal_msize;
1594                 stacks = ws->l_state.horizontal_stacks;
1595                 SWAPXY(&r_g);
1596         } else {
1597                 w_inc = win->sh.height_inc;
1598                 w_base = win->sh.base_height;
1599                 mwin = ws->l_state.vertical_mwin;
1600                 mscale = ws->l_state.vertical_msize;
1601                 stacks = ws->l_state.vertical_stacks;
1602         }
1603         win_g = r_g;
1604
1605         if (stacks > winno - mwin)
1606                 stacks = winno - mwin;
1607         if (stacks < 1)
1608                 stacks = 1;
1609
1610         h_slice = r_g.h / SWM_H_SLICE;
1611         if (mwin && winno > mwin) {
1612                 v_slice = r_g.w / SWM_V_SLICE;
1613
1614                 split = mwin;
1615                 colno = split;
1616                 win_g.w = v_slice * mscale;
1617
1618                 if (w_inc > 1 && w_inc < v_slice) {
1619                         /* adjust for window's requested size increment */
1620                         remain = (win_g.w - w_base) % w_inc;
1621                         missing = w_inc - remain;
1622                         win_g.w -= remain;
1623                         extra += remain;
1624                 }
1625
1626                 msize = win_g.w;
1627                 if (flip) 
1628                         win_g.x += r_g.w - msize;
1629         } else {
1630                 msize = -2;
1631                 colno = split = winno / stacks;
1632                 win_g.w = ((r_g.w - (stacks * 2) + 2) / stacks);
1633         }
1634         hrh = r_g.h / colno;
1635         extra = r_g.h - (colno * hrh);
1636         win_g.h = hrh - 2;
1637
1638         /*  stack all the tiled windows */
1639         i = j = 0, s = stacks;
1640         TAILQ_FOREACH(win, &ws->winlist, entry) {
1641                 if (win->transient != 0 || win->floating != 0)
1642                         continue;
1643
1644                 if (split && i == split) {
1645                         colno = (winno - mwin) / stacks;
1646                         if (s <= (winno - mwin) % stacks)
1647                                 colno++;
1648                         split = split + colno;
1649                         hrh = (r_g.h / colno);
1650                         extra = r_g.h - (colno * hrh);
1651                         if (flip)
1652                                 win_g.x = r_g.x;
1653                         else
1654                                 win_g.x += win_g.w + 2;
1655                         win_g.w = (r_g.w - msize - (stacks * 2)) / stacks;
1656                         if (s == 1)
1657                                 win_g.w += (r_g.w - msize - (stacks * 2)) %
1658                                     stacks;
1659                         s--;
1660                         j = 0;
1661                 }
1662                 win_g.h = hrh - 2;
1663                 if (rot) {
1664                         h_inc = win->sh.width_inc;
1665                         h_base = win->sh.base_width;
1666                 } else {
1667                         h_inc = win->sh.height_inc;
1668                         h_base = win->sh.base_height;
1669                 }
1670                 if (j == colno - 1) {
1671                         win_g.h = hrh + extra;
1672                 } else if (h_inc > 1 && h_inc < h_slice) {
1673                         /* adjust for window's requested size increment */
1674                         remain = (win_g.h - h_base) % h_inc;
1675                         missing = h_inc - remain;
1676
1677                         if (missing <= extra || j == 0) {
1678                                 extra -= missing;
1679                                 win_g.h += missing;
1680                         } else {
1681                                 win_g.h -= remain;
1682                                 extra += remain;
1683                         }
1684                 }
1685                  
1686                 if (j == 0)
1687                         win_g.y = r_g.y;
1688                 else
1689                         win_g.y += last_h + 2;
1690
1691                 bzero(&wc, sizeof wc);
1692                 wc.border_width = 1;
1693                 if (rot) {
1694                         win->g.x = wc.x = win_g.y;
1695                         win->g.y = wc.y = win_g.x;
1696                         win->g.w = wc.width = win_g.h;
1697                         win->g.h = wc.height = win_g.w;
1698                 } else {
1699                         win->g.x = wc.x = win_g.x;
1700                         win->g.y = wc.y = win_g.y;
1701                         win->g.w = wc.width = win_g.w;
1702                         win->g.h = wc.height = win_g.h;
1703                 }
1704                 adjust_font(win);
1705                 mask = CWX | CWY | CWWidth | CWHeight | CWBorderWidth;
1706                 XConfigureWindow(display, win->id, mask, &wc);
1707                 XMapRaised(display, win->id);
1708
1709                 last_h = win_g.h;
1710                 i++;
1711                 j++;
1712         }
1713
1714  notiles:
1715         /* now, stack all the floaters and transients */
1716         TAILQ_FOREACH(win, &ws->winlist, entry) {
1717                 if (win->transient == 0 && win->floating == 0)
1718                         continue;
1719
1720                 stack_floater(win, ws->r);
1721                 XMapRaised(display, win->id);
1722         }
1723
1724         if (winfocus)
1725                 focus_win(winfocus); /* has to be done outside of the loop */
1726 }
1727
1728 void
1729 vertical_config(struct workspace *ws, int id)
1730 {
1731         DNPRINTF(SWM_D_STACK, "vertical_resize: workspace: %d\n", ws->idx);
1732
1733         switch (id) {
1734         case SWM_ARG_ID_STACKRESET:
1735         case SWM_ARG_ID_STACKINIT:
1736                 ws->l_state.vertical_msize = SWM_V_SLICE / 2;
1737                 ws->l_state.vertical_mwin = 1;
1738                 ws->l_state.vertical_stacks = 1;
1739                 break;
1740         case SWM_ARG_ID_MASTERSHRINK:
1741                 if (ws->l_state.vertical_msize > 1)
1742                         ws->l_state.vertical_msize--;
1743                 break;
1744         case SWM_ARG_ID_MASTERGROW:
1745                 if (ws->l_state.vertical_msize < SWM_V_SLICE - 1)
1746                         ws->l_state.vertical_msize++;
1747                 break;
1748         case SWM_ARG_ID_MASTERADD:
1749                 ws->l_state.vertical_mwin++;
1750                 break;
1751         case SWM_ARG_ID_MASTERDEL:
1752                 if (ws->l_state.vertical_mwin > 0)
1753                         ws->l_state.vertical_mwin--;
1754                 break;
1755         case SWM_ARG_ID_STACKINC:
1756                 ws->l_state.vertical_stacks++;
1757                 break;
1758         case SWM_ARG_ID_STACKDEC:
1759                 if (ws->l_state.vertical_stacks > 1)
1760                         ws->l_state.vertical_stacks--;
1761                 break;
1762         default:
1763                 return;
1764         }
1765 }
1766
1767 void
1768 vertical_stack(struct workspace *ws, struct swm_geometry *g)
1769 {
1770         DNPRINTF(SWM_D_STACK, "vertical_stack: workspace: %d\n", ws->idx);
1771
1772         stack_master(ws, g, 0, 0);
1773 }
1774
1775 void
1776 horizontal_config(struct workspace *ws, int id)
1777 {
1778         DNPRINTF(SWM_D_STACK, "horizontal_config: workspace: %d\n", ws->idx);
1779
1780         switch (id) {
1781         case SWM_ARG_ID_STACKRESET:
1782         case SWM_ARG_ID_STACKINIT:
1783                 ws->l_state.horizontal_mwin = 1;
1784                 ws->l_state.horizontal_msize = SWM_H_SLICE / 2;
1785                 ws->l_state.horizontal_stacks = 1;
1786                 break;
1787         case SWM_ARG_ID_MASTERSHRINK:
1788                 if (ws->l_state.horizontal_msize > 1)
1789                         ws->l_state.horizontal_msize--;
1790                 break;
1791         case SWM_ARG_ID_MASTERGROW:
1792                 if (ws->l_state.horizontal_msize < SWM_H_SLICE - 1)
1793                         ws->l_state.horizontal_msize++;
1794                 break;
1795         case SWM_ARG_ID_MASTERADD:
1796                 ws->l_state.horizontal_mwin++;
1797                 break;
1798         case SWM_ARG_ID_MASTERDEL:
1799                 if (ws->l_state.horizontal_mwin > 0)
1800                         ws->l_state.horizontal_mwin--;
1801                 break;
1802         case SWM_ARG_ID_STACKINC:
1803                 ws->l_state.horizontal_stacks++;
1804                 break;
1805         case SWM_ARG_ID_STACKDEC:
1806                 if (ws->l_state.horizontal_stacks > 1)
1807                         ws->l_state.horizontal_stacks--;
1808                 break;
1809         default:
1810                 return;
1811         }
1812 }
1813
1814 void
1815 horizontal_stack(struct workspace *ws, struct swm_geometry *g)
1816 {
1817         DNPRINTF(SWM_D_STACK, "vertical_stack: workspace: %d\n", ws->idx);
1818
1819         stack_master(ws, g, 1, 0);
1820 }
1821
1822 /* fullscreen view */
1823 void
1824 max_stack(struct workspace *ws, struct swm_geometry *g) {
1825         XWindowChanges          wc;
1826         struct swm_geometry     gg = *g;
1827         struct ws_win           *win, *winfocus;
1828         unsigned int            mask;
1829
1830         DNPRINTF(SWM_D_STACK, "max_stack: workspace: %d\n", ws->idx);
1831
1832         if (count_win(ws, 0) == 0)
1833                 return;
1834
1835         if (ws->focus == NULL)
1836                 ws->focus = TAILQ_FIRST(&ws->winlist);
1837         winfocus = cur_focus ? cur_focus : ws->focus;
1838
1839         TAILQ_FOREACH(win, &ws->winlist, entry) {
1840                 if (win->transient != 0 || win->floating != 0) {
1841                         if (win == ws->focus) {
1842                                 /* XXX maximize? */
1843                                 stack_floater(win, ws->r);
1844                                 XMapRaised(display, win->id);
1845                         } else
1846                                 XUnmapWindow(display, win->id);
1847                 } else {
1848                         bzero(&wc, sizeof wc);
1849                         wc.border_width = 1;
1850                         win->g.x = wc.x = gg.x;
1851                         win->g.y = wc.y = gg.y;
1852                         win->g.w = wc.width = gg.w;
1853                         win->g.h = wc.height = gg.h;
1854                         mask = CWX | CWY | CWWidth | CWHeight | CWBorderWidth;
1855                         XConfigureWindow(display, win->id, mask, &wc);
1856
1857                         if (win == ws->focus) {
1858                                 XMapRaised(display, win->id);
1859                         } else
1860                                 XUnmapWindow(display, win->id);
1861                 }
1862         }
1863
1864         if (winfocus)
1865                 focus_win(winfocus); /* has to be done outside of the loop */
1866 }
1867
1868 void
1869 send_to_ws(struct swm_region *r, union arg *args)
1870 {
1871         int                     wsid = args->id;
1872         struct ws_win           *win = cur_focus;
1873         struct workspace        *ws, *nws;
1874         Atom                    ws_idx_atom = 0;
1875         unsigned char           ws_idx_str[SWM_PROPLEN];
1876
1877         if (win == NULL)
1878                 return;
1879
1880         DNPRINTF(SWM_D_MOVE, "send_to_ws: win: %lu\n", win->id);
1881
1882         ws = win->ws;
1883         nws = &win->s->ws[wsid];
1884
1885         XUnmapWindow(display, win->id);
1886
1887         /* find a window to focus */
1888         ws->focus = TAILQ_PREV(win, ws_win_list, entry);
1889         if (ws->focus == NULL)
1890                 ws->focus = TAILQ_FIRST(&ws->winlist);
1891         if (ws->focus == win)
1892                 ws->focus = NULL;
1893
1894         TAILQ_REMOVE(&ws->winlist, win, entry);
1895
1896         TAILQ_INSERT_TAIL(&nws->winlist, win, entry);
1897         win->ws = nws;
1898
1899         /* Try to update the window's workspace property */
1900         ws_idx_atom = XInternAtom(display, "_SWM_WS", False);
1901         if (ws_idx_atom &&
1902             snprintf(ws_idx_str, SWM_PROPLEN, "%d", nws->idx) < SWM_PROPLEN) {
1903                 DNPRINTF(SWM_D_PROP, "setting property _SWM_WS to %s\n",
1904                     ws_idx_str);
1905                 XChangeProperty(display, win->id, ws_idx_atom, XA_STRING, 8,
1906                     PropModeReplace, ws_idx_str, SWM_PROPLEN);
1907         }
1908
1909         if (count_win(nws, 1) == 1)
1910                 nws->focus = win;
1911         ws->restack = 1;
1912         nws->restack = 1;
1913
1914         stack();
1915 }
1916
1917 void
1918 wkill(struct swm_region *r, union arg *args)
1919 {
1920         DNPRINTF(SWM_D_MISC, "wkill %d\n", args->id);
1921
1922         if(r->ws->focus == NULL)
1923                 return;
1924
1925         if (args->id == SWM_ARG_ID_KILLWINDOW)
1926                 XKillClient(display, r->ws->focus->id);
1927         else
1928                 if (r->ws->focus->can_delete)
1929                         client_msg(r->ws->focus, adelete);
1930 }
1931
1932 void
1933 screenshot(struct swm_region *r, union arg *args)
1934 {
1935         union arg                       a;
1936
1937         DNPRINTF(SWM_D_MISC, "screenshot\n");
1938
1939         if (ss_enabled == 0)
1940                 return;
1941
1942         switch (args->id) {
1943         case SWM_ARG_ID_SS_ALL:
1944                 spawn_screenshot[1] = "full";
1945                 break;
1946         case SWM_ARG_ID_SS_WINDOW:
1947                 spawn_screenshot[1] = "window";
1948                 break;
1949         default:
1950                 return;
1951         }
1952         a.argv = spawn_screenshot;
1953         spawn(r, &a);
1954 }
1955
1956 void
1957 floating_toggle(struct swm_region *r, union arg *args)
1958 {
1959         struct ws_win   *win = cur_focus;
1960
1961         if (win == NULL)
1962                 return;
1963
1964         win->floating = !win->floating;
1965         win->manual = 0;
1966         stack();
1967         focus_win(win);
1968 }
1969
1970 void
1971 resize_window(struct ws_win *win, int center)
1972 {
1973         unsigned int            mask;
1974         XWindowChanges          wc;
1975         struct swm_region       *r;
1976
1977         r = root_to_region(win->wa.root);
1978         bzero(&wc, sizeof wc);
1979         mask = CWBorderWidth | CWWidth | CWHeight;
1980         wc.border_width = 1;
1981         wc.width = win->g.w;
1982         wc.height = win->g.h;
1983         if (center == SWM_ARG_ID_CENTER) {
1984                 wc.x = (WIDTH(r) - win->g.w) / 2;
1985                 wc.y = (HEIGHT(r) - win->g.h) / 2;
1986                 mask |= CWX | CWY;
1987         }
1988
1989         DNPRINTF(SWM_D_STACK, "resize_window: win %lu x %d y %d w %d h %d\n",
1990             win->id, wc.x, wc.y, wc.width, wc.height);
1991
1992         XConfigureWindow(display, win->id, mask, &wc);
1993         config_win(win);
1994 }
1995
1996 void
1997 resize(struct ws_win *win, union arg *args)
1998 {
1999         XEvent                  ev;
2000         Time                    time = 0;
2001
2002         DNPRINTF(SWM_D_MOUSE, "resize: win %lu floating %d trans %d\n",
2003             win->id, win->floating, win->transient);
2004
2005         if (!(win->transient != 0 || win->floating != 0))
2006                 return;
2007
2008         if (XGrabPointer(display, win->id, False, MOUSEMASK, GrabModeAsync,
2009             GrabModeAsync, None, None /* cursor */, CurrentTime) != GrabSuccess)
2010                 return;
2011         XWarpPointer(display, None, win->id, 0, 0, 0, 0, win->g.w, win->g.h);
2012         do {
2013                 XMaskEvent(display, MOUSEMASK | ExposureMask |
2014                     SubstructureRedirectMask, &ev);
2015                 switch(ev.type) {
2016                 case ConfigureRequest:
2017                 case Expose:
2018                 case MapRequest:
2019                         handler[ev.type](&ev);
2020                         break;
2021                 case MotionNotify:
2022                         if (ev.xmotion.x <= 1)
2023                                 ev.xmotion.x = 1;
2024                         if (ev.xmotion.y <= 1)
2025                                 ev.xmotion.y = 1;
2026                         win->g.w = ev.xmotion.x;
2027                         win->g.h = ev.xmotion.y;
2028
2029                         /* not free, don't sync more than 60 times / second */
2030                         if ((ev.xmotion.time - time) > (1000 / 60) ) {
2031                                 time = ev.xmotion.time;
2032                                 XSync(display, False);
2033                                 resize_window(win, args->id);
2034                         }
2035                         break;
2036                 }
2037         } while (ev.type != ButtonRelease);
2038         if (time) {
2039                 XSync(display, False);
2040                 resize_window(win, args->id);
2041         }
2042         XWarpPointer(display, None, win->id, 0, 0, 0, 0, win->g.w - 1,
2043             win->g.h - 1);
2044         XUngrabPointer(display, CurrentTime);
2045
2046         /* drain events */
2047         while (XCheckMaskEvent(display, EnterWindowMask, &ev));
2048 }
2049
2050 void
2051 move_window(struct ws_win *win)
2052 {
2053         unsigned int            mask;
2054         XWindowChanges          wc;
2055         struct swm_region       *r;
2056
2057         r = root_to_region(win->wa.root);
2058         bzero(&wc, sizeof wc);
2059         mask = CWX | CWY;
2060         wc.x = win->g.x;
2061         wc.y = win->g.y;
2062
2063         DNPRINTF(SWM_D_STACK, "move_window: win %lu x %d y %d w %d h %d\n",
2064             win->id, wc.x, wc.y, wc.width, wc.height);
2065
2066         XConfigureWindow(display, win->id, mask, &wc);
2067         config_win(win);
2068 }
2069
2070 void
2071 move(struct ws_win *win, union arg *args)
2072 {
2073         XEvent                  ev;
2074         Time                    time = 0;
2075         int                     restack = 0;
2076
2077         DNPRINTF(SWM_D_MOUSE, "move: win %lu floating %d trans %d\n",
2078             win->id, win->floating, win->transient);
2079
2080         if (win->floating == 0) {
2081                 win->floating = 1;
2082                 win->manual = 1;
2083                 restack = 1;
2084         }
2085
2086         if (XGrabPointer(display, win->id, False, MOUSEMASK, GrabModeAsync,
2087             GrabModeAsync, None, None /* cursor */, CurrentTime) != GrabSuccess)
2088                 return;
2089         XWarpPointer(display, None, win->id, 0, 0, 0, 0, 0, 0);
2090         do {
2091                 XMaskEvent(display, MOUSEMASK | ExposureMask |
2092                     SubstructureRedirectMask, &ev);
2093                 switch(ev.type) {
2094                 case ConfigureRequest:
2095                 case Expose:
2096                 case MapRequest:
2097                         handler[ev.type](&ev);
2098                         break;
2099                 case MotionNotify:
2100                         win->g.x = ev.xmotion.x_root;
2101                         win->g.y = ev.xmotion.y_root;
2102
2103                         /* not free, don't sync more than 60 times / second */
2104                         if ((ev.xmotion.time - time) > (1000 / 60) ) {
2105                                 time = ev.xmotion.time;
2106                                 XSync(display, False);
2107                                 move_window(win);
2108                         }
2109                         break;
2110                 }
2111         } while (ev.type != ButtonRelease);
2112         if (time) {
2113                 XSync(display, False);
2114                 move_window(win);
2115         }
2116         XWarpPointer(display, None, win->id, 0, 0, 0, 0, 0, 0);
2117         XUngrabPointer(display, CurrentTime);
2118         if (restack)
2119                 stack();
2120
2121         /* drain events */
2122         while (XCheckMaskEvent(display, EnterWindowMask, &ev));
2123 }
2124
2125 /* key definitions */
2126 struct keyfunc {
2127         char                    name[SWM_FUNCNAME_LEN];
2128         void                    (*func)(struct swm_region *r, union arg *);
2129         union arg               args;
2130 } keyfuncs[kf_invalid] = {
2131         /* name                 function        argument */
2132         { "cycle_layout",       cycle_layout,   {0} }, 
2133         { "stack_reset",        stack_config,   {.id = SWM_ARG_ID_STACKRESET} }, 
2134         { "master_shrink",      stack_config,   {.id = SWM_ARG_ID_MASTERSHRINK} },
2135         { "master_grow",        stack_config,   {.id = SWM_ARG_ID_MASTERGROW} },
2136         { "master_add",         stack_config,   {.id = SWM_ARG_ID_MASTERADD} },
2137         { "master_del",         stack_config,   {.id = SWM_ARG_ID_MASTERDEL} },
2138         { "stack_inc",          stack_config,   {.id = SWM_ARG_ID_STACKINC} },
2139         { "stack_dec",          stack_config,   {.id = SWM_ARG_ID_STACKDEC} },
2140         { "swap_main",          swapwin,        {.id = SWM_ARG_ID_SWAPMAIN} },
2141         { "focus_next",         focus,          {.id = SWM_ARG_ID_FOCUSNEXT} },
2142         { "focus_prev",         focus,          {.id = SWM_ARG_ID_FOCUSPREV} },
2143         { "swap_next",          swapwin,        {.id = SWM_ARG_ID_SWAPNEXT} },
2144         { "swap_prev",          swapwin,        {.id = SWM_ARG_ID_SWAPPREV} },
2145         { "spawn_term",         spawnterm,      {.argv = spawn_term} },
2146         { "spawn_menu",         spawnmenu,      {.argv = spawn_menu} },
2147         { "quit",               quit,           {0} },
2148         { "restart",            restart,        {0} },
2149         { "focus_main",         focus,          {.id = SWM_ARG_ID_FOCUSMAIN} },
2150         { "ws_1",               switchws,       {.id = 0} },
2151         { "ws_2",               switchws,       {.id = 1} },
2152         { "ws_3",               switchws,       {.id = 2} },
2153         { "ws_4",               switchws,       {.id = 3} },
2154         { "ws_5",               switchws,       {.id = 4} },
2155         { "ws_6",               switchws,       {.id = 5} },
2156         { "ws_7",               switchws,       {.id = 6} },
2157         { "ws_8",               switchws,       {.id = 7} },
2158         { "ws_9",               switchws,       {.id = 8} },
2159         { "ws_10",              switchws,       {.id = 9} },
2160         { "ws_next",            cyclews,        {.id = SWM_ARG_ID_CYCLEWS_UP} }, 
2161         { "ws_prev",            cyclews,        {.id = SWM_ARG_ID_CYCLEWS_DOWN} }, 
2162         { "screen_next",        cyclescr,       {.id = SWM_ARG_ID_CYCLESC_UP} }, 
2163         { "screen_prev",        cyclescr,       {.id = SWM_ARG_ID_CYCLESC_DOWN} }, 
2164         { "mvws_1",             send_to_ws,     {.id = 0} },
2165         { "mvws_2",             send_to_ws,     {.id = 1} },
2166         { "mvws_3",             send_to_ws,     {.id = 2} },
2167         { "mvws_4",             send_to_ws,     {.id = 3} },
2168         { "mvws_5",             send_to_ws,     {.id = 4} },
2169         { "mvws_6",             send_to_ws,     {.id = 5} },
2170         { "mvws_7",             send_to_ws,     {.id = 6} },
2171         { "mvws_8",             send_to_ws,     {.id = 7} },
2172         { "mvws_9",             send_to_ws,     {.id = 8} },
2173         { "mvws_10",            send_to_ws,     {.id = 9} },
2174         { "bar_toggle",         bar_toggle,     {0} },
2175         { "wind_kill",          wkill,          {.id = SWM_ARG_ID_KILLWINDOW} },
2176         { "wind_del",           wkill,          {.id = SWM_ARG_ID_DELETEWINDOW} },
2177         { "screenshot_all",     screenshot,     {.id = SWM_ARG_ID_SS_ALL} },
2178         { "screenshot_wind",    screenshot,     {.id = SWM_ARG_ID_SS_WINDOW} },
2179         { "float_toggle",       floating_toggle,{0} },
2180         { "version",            version,        {0} },
2181         { "spawn_lock",         spawn,          {.argv = spawn_lock} },
2182         { "spawn_initscr",      spawn,          {.argv = spawn_initscr} },
2183 };
2184 struct key {
2185         unsigned int            mod;
2186         KeySym                  keysym;
2187         enum keyfuncid          funcid;
2188 };
2189 int                             keys_size = 0, keys_length = 0;
2190 struct key                      *keys = NULL;
2191
2192 /* mouse */
2193 enum { client_click, root_click };
2194 struct button {
2195         unsigned int            action;
2196         unsigned int            mask;
2197         unsigned int            button;
2198         void                    (*func)(struct ws_win *, union arg *);
2199         union arg               args;
2200 } buttons[] = {
2201           /* action             key             mouse button    func            args */
2202         { client_click,         MODKEY,         Button3,        resize,         {.id = SWM_ARG_ID_DONTCENTER} },
2203         { client_click,         MODKEY | ShiftMask, Button3,    resize,         {.id = SWM_ARG_ID_CENTER} },
2204         { client_click,         MODKEY,         Button1,        move,           {0} },
2205 };
2206
2207 void
2208 update_modkey(unsigned int mod)
2209 {
2210         int                     i;
2211
2212         for (i = 0; i < keys_length; i++)
2213                 if (keys[i].mod & ShiftMask)
2214                         keys[i].mod = mod | ShiftMask;
2215                 else
2216                         keys[i].mod = mod;
2217
2218         for (i = 0; i < LENGTH(buttons); i++)
2219                 if (buttons[i].mask & ShiftMask)
2220                         buttons[i].mask = mod | ShiftMask;
2221                 else
2222                         buttons[i].mask = mod;
2223 }
2224
2225 #define SWM_MODNAME_SIZE        32
2226 #define SWM_KEY_WS              "\n+ \t"
2227 int
2228 parsekeys(char *keystr, unsigned int currmod, unsigned int *mod, KeySym *ks)
2229 {
2230         char                    *cp, *name;
2231         KeySym                  uks;
2232         if (mod == NULL || ks == NULL)
2233                 return (0);
2234         cp = keystr;
2235         *mod = 0;
2236         while ((name = strsep(&cp, SWM_KEY_WS)) != NULL) {
2237                 if (cp)
2238                         cp += (long)strspn(cp, SWM_KEY_WS);
2239                 if (strncasecmp(name, "MOD", SWM_MODNAME_SIZE) == 0)
2240                         *mod |= currmod;
2241                 else if (!strncasecmp(name, "Mod1", SWM_MODNAME_SIZE))
2242                         *mod |= Mod1Mask;
2243                 else if (!strncasecmp(name, "Mod2", SWM_MODNAME_SIZE))
2244                         *mod += Mod2Mask;
2245                 else if (!strncmp(name, "Mod3", SWM_MODNAME_SIZE))
2246                         *mod |= Mod3Mask;
2247                 else if (!strncmp(name, "Mod4", SWM_MODNAME_SIZE))
2248                         *mod |= Mod4Mask;
2249                 else if (strncasecmp(name, "SHIFT", SWM_MODNAME_SIZE) == 0)
2250                         *mod |= ShiftMask;
2251                 else {
2252                         *ks = XStringToKeysym(name);
2253                         XConvertCase(*ks, ks, &uks);
2254                         if (ks == NoSymbol) {
2255                                 DNPRINTF(SWM_D_KEY,
2256                                     "parsekeys: invalid key %s\n",
2257                                     name);
2258                                 return (0);
2259                         }
2260                 }
2261         }
2262         return (1);
2263 }
2264 int
2265 bindmatch(const char *var, const char *name, unsigned int currmod, char *keystr,
2266     enum keyfuncid *kfid, unsigned int *mod, KeySym *ks)
2267 {
2268         char                    *p;
2269         int                     i;
2270         char                    funcname[SWM_FUNCNAME_LEN];
2271         i = strncmp(var, name, 255);
2272         if (kfid == NULL || mod == NULL || ks == NULL)
2273                 return (i);
2274         *kfid = kf_invalid;
2275         *mod = 0;
2276         *ks = NoSymbol;
2277         bzero(funcname, LENGTH(funcname));
2278         if (i <= 0)
2279                 return (i);
2280         p = (char *)var + strlen(name);
2281         if (*p++ != '[')
2282                 return (i);
2283         i = 0;
2284         while (isgraph(*p) && *p != ']' && i < LENGTH(funcname))
2285                 funcname[i++] = *p++;
2286         if (i >= LENGTH(funcname) || *p != ']')
2287                 return (1);
2288         if (i == 0)
2289                 return (!parsekeys(keystr, currmod, mod, ks));
2290         for (*kfid = 0; *kfid < kf_invalid; (*kfid)++) {
2291                 if (strncasecmp(funcname, keyfuncs[*kfid].name,
2292                     SWM_FUNCNAME_LEN) == 0) {
2293                         return (!parsekeys(keystr, currmod, mod, ks));
2294                 }
2295
2296         }
2297         return (1);
2298 }
2299 void
2300 setkeybinding(unsigned int mod, KeySym ks, enum keyfuncid kfid)
2301 {
2302         int                     i, j;
2303         /* find existing */
2304         for (i = 0; i < keys_length; i++) {
2305                 if (keys[i].mod == mod && keys[i].keysym == ks) {
2306                         if (kfid == kf_invalid) {
2307                                 /* found: delete */
2308                                 DNPRINTF(SWM_D_KEY,
2309                                     "setkeybinding: delete #%d %s\n",
2310                                     i, keyfuncs[keys[i].funcid].name);
2311                                 j = keys_length - 1;
2312                                 if (i < j)
2313                                         keys[i] = keys[j];
2314                                 keys_length--;
2315                                 return;
2316                         } else {
2317                                 /* found: replace */
2318                                 DNPRINTF(SWM_D_KEY,
2319                                     "setkeybinding: replace #%d %s\n",
2320                                     i, keyfuncs[keys[i].funcid].name);
2321                                 keys[i].mod = mod;
2322                                 keys[i].keysym = ks;
2323                                 keys[i].funcid = kfid;
2324                                 return;
2325                         }
2326                 }
2327         }
2328         if (kfid == kf_invalid) {
2329                 fprintf(stderr,
2330                     "error: setkeybinding: cannot find mod/key combination");
2331                 return;
2332         }
2333         /* not found: add */
2334         if (keys_size == 0 || keys == NULL) {
2335                 keys_size = 4;
2336                 DNPRINTF(SWM_D_KEY, "setkeybinding: init list %d\n", keys_size);
2337                 keys = malloc((size_t)keys_size * sizeof(struct key));
2338                 if (!keys) {
2339                         fprintf(stderr, "malloc failed\n");
2340                         perror(" failed");
2341                         quit(NULL, NULL);
2342                 }
2343         } else if (keys_length == keys_size) {
2344                 keys_size *= 2;
2345                 DNPRINTF(SWM_D_KEY, "setkeybinding: grow list %d\n", keys_size);
2346                 keys = realloc(keys, (size_t)keys_size * sizeof(struct key));
2347                 if (!keys) {
2348                         fprintf(stderr, "realloc failed\n");
2349                         perror(" failed");
2350                         quit(NULL, NULL);
2351                 }
2352         }
2353         if (keys_length < keys_size) {
2354                 DNPRINTF(SWM_D_KEY, "setkeybinding: add %d\n", keys_length);
2355                 j = keys_length++;
2356                 keys[j].mod = mod;
2357                 keys[j].keysym = ks;
2358                 keys[j].funcid = kfid;
2359         } else {
2360                 fprintf(stderr, "keys array problem?\n");
2361                 if (!keys) {
2362                         fprintf(stderr, "keys array problem\n");
2363                         quit(NULL, NULL);
2364                 }
2365         }
2366 }
2367 void
2368 setup_keys(void)
2369 {
2370         setkeybinding(MODKEY,           XK_space,       kf_cycle_layout); 
2371         setkeybinding(MODKEY|ShiftMask, XK_space,       kf_stack_reset);
2372         setkeybinding(MODKEY,           XK_h,           kf_master_shrink);
2373         setkeybinding(MODKEY,           XK_l,           kf_master_grow);
2374         setkeybinding(MODKEY,           XK_comma,       kf_master_add);
2375         setkeybinding(MODKEY,           XK_period,      kf_master_del);
2376         setkeybinding(MODKEY|ShiftMask, XK_comma,       kf_stack_inc);
2377         setkeybinding(MODKEY|ShiftMask, XK_period,      kf_stack_dec);
2378         setkeybinding(MODKEY,           XK_Return,      kf_swap_main);
2379         setkeybinding(MODKEY,           XK_j,           kf_focus_next);
2380         setkeybinding(MODKEY,           XK_k,           kf_focus_prev);
2381         setkeybinding(MODKEY|ShiftMask, XK_j,           kf_swap_next);
2382         setkeybinding(MODKEY|ShiftMask, XK_k,           kf_swap_prev);
2383         setkeybinding(MODKEY|ShiftMask, XK_Return,      kf_spawn_term);
2384         setkeybinding(MODKEY,           XK_p,           kf_spawn_menu);
2385         setkeybinding(MODKEY|ShiftMask, XK_q,           kf_quit);
2386         setkeybinding(MODKEY,           XK_q,           kf_restart);
2387         setkeybinding(MODKEY,           XK_m,           kf_focus_main);
2388         setkeybinding(MODKEY,           XK_1,           kf_ws_1);
2389         setkeybinding(MODKEY,           XK_2,           kf_ws_2);
2390         setkeybinding(MODKEY,           XK_3,           kf_ws_3);
2391         setkeybinding(MODKEY,           XK_4,           kf_ws_4);
2392         setkeybinding(MODKEY,           XK_5,           kf_ws_5);
2393         setkeybinding(MODKEY,           XK_6,           kf_ws_6);
2394         setkeybinding(MODKEY,           XK_7,           kf_ws_7);
2395         setkeybinding(MODKEY,           XK_8,           kf_ws_8);
2396         setkeybinding(MODKEY,           XK_9,           kf_ws_9);
2397         setkeybinding(MODKEY,           XK_0,           kf_ws_10);
2398         setkeybinding(MODKEY,           XK_Right,       kf_ws_next);
2399         setkeybinding(MODKEY,           XK_Left,        kf_ws_prev);
2400         setkeybinding(MODKEY|ShiftMask, XK_Right,       kf_screen_next);
2401         setkeybinding(MODKEY|ShiftMask, XK_Left,        kf_screen_prev);
2402         setkeybinding(MODKEY|ShiftMask, XK_1,           kf_mvws_1);
2403         setkeybinding(MODKEY|ShiftMask, XK_2,           kf_mvws_2);
2404         setkeybinding(MODKEY|ShiftMask, XK_3,           kf_mvws_3);
2405         setkeybinding(MODKEY|ShiftMask, XK_4,           kf_mvws_4);
2406         setkeybinding(MODKEY|ShiftMask, XK_5,           kf_mvws_5);
2407         setkeybinding(MODKEY|ShiftMask, XK_6,           kf_mvws_6);
2408         setkeybinding(MODKEY|ShiftMask, XK_7,           kf_mvws_7);
2409         setkeybinding(MODKEY|ShiftMask, XK_8,           kf_mvws_8);
2410         setkeybinding(MODKEY|ShiftMask, XK_9,           kf_mvws_9);
2411         setkeybinding(MODKEY|ShiftMask, XK_0,           kf_mvws_10);
2412         setkeybinding(MODKEY,           XK_b,           kf_bar_toggle);
2413         setkeybinding(MODKEY,           XK_Tab,         kf_focus_next);
2414         setkeybinding(MODKEY|ShiftMask, XK_Tab,         kf_focus_prev);
2415         setkeybinding(MODKEY|ShiftMask, XK_x,           kf_wind_kill);
2416         setkeybinding(MODKEY,           XK_x,           kf_wind_del);
2417         setkeybinding(MODKEY,           XK_s,           kf_screenshot_all);
2418         setkeybinding(MODKEY|ShiftMask, XK_s,           kf_screenshot_wind);
2419         setkeybinding(MODKEY,           XK_t,           kf_float_toggle);
2420         setkeybinding(MODKEY|ShiftMask, XK_v,           kf_version);
2421         setkeybinding(MODKEY|ShiftMask, XK_Delete,      kf_spawn_lock);
2422         setkeybinding(MODKEY|ShiftMask, XK_i,           kf_spawn_initscr);
2423 }
2424 void
2425 updatenumlockmask(void)
2426 {
2427         unsigned int            i, j;
2428         XModifierKeymap         *modmap;
2429
2430         DNPRINTF(SWM_D_MISC, "updatenumlockmask\n");
2431         numlockmask = 0;
2432         modmap = XGetModifierMapping(display);
2433         for (i = 0; i < 8; i++)
2434                 for (j = 0; j < modmap->max_keypermod; j++)
2435                         if (modmap->modifiermap[i * modmap->max_keypermod + j]
2436                           == XKeysymToKeycode(display, XK_Num_Lock))
2437                                 numlockmask = (1 << i);
2438
2439         XFreeModifiermap(modmap);
2440 }
2441
2442 void
2443 grabkeys(void)
2444 {
2445         unsigned int            i, j, k;
2446         KeyCode                 code;
2447         unsigned int            modifiers[] =
2448             { 0, LockMask, numlockmask, numlockmask | LockMask };
2449
2450         DNPRINTF(SWM_D_MISC, "grabkeys\n");
2451         updatenumlockmask();
2452
2453         for (k = 0; k < ScreenCount(display); k++) {
2454                 if (TAILQ_EMPTY(&screens[k].rl))
2455                         continue;
2456                 XUngrabKey(display, AnyKey, AnyModifier, screens[k].root);
2457                 for (i = 0; i < keys_length; i++) {
2458                         if ((code = XKeysymToKeycode(display, keys[i].keysym)))
2459                                 for (j = 0; j < LENGTH(modifiers); j++)
2460                                         XGrabKey(display, code,
2461                                             keys[i].mod | modifiers[j],
2462                                             screens[k].root, True,
2463                                             GrabModeAsync, GrabModeAsync);
2464                 }
2465         }
2466 }
2467
2468 void
2469 grabbuttons(struct ws_win *win, int focused)
2470 {
2471         unsigned int            i, j;
2472         unsigned int            modifiers[] =
2473             { 0, LockMask, numlockmask, numlockmask|LockMask };
2474
2475         updatenumlockmask();
2476         XUngrabButton(display, AnyButton, AnyModifier, win->id);
2477         if(focused) {
2478                 for (i = 0; i < LENGTH(buttons); i++)
2479                         if (buttons[i].action == client_click)
2480                                 for (j = 0; j < LENGTH(modifiers); j++)
2481                                         XGrabButton(display, buttons[i].button,
2482                                             buttons[i].mask | modifiers[j],
2483                                             win->id, False, BUTTONMASK,
2484                                             GrabModeAsync, GrabModeSync, None,
2485                                             None);
2486         } else
2487                 XGrabButton(display, AnyButton, AnyModifier, win->id, False,
2488                     BUTTONMASK, GrabModeAsync, GrabModeSync, None, None);
2489 }
2490
2491 void
2492 expose(XEvent *e)
2493 {
2494         DNPRINTF(SWM_D_EVENT, "expose: window: %lu\n", e->xexpose.window);
2495 }
2496
2497 void
2498 keypress(XEvent *e)
2499 {
2500         unsigned int            i;
2501         KeySym                  keysym;
2502         XKeyEvent               *ev = &e->xkey;
2503
2504         DNPRINTF(SWM_D_EVENT, "keypress: window: %lu\n", ev->window);
2505
2506         keysym = XKeycodeToKeysym(display, (KeyCode)ev->keycode, 0);
2507         for (i = 0; i < keys_length; i++)
2508                 if (keysym == keys[i].keysym
2509                    && CLEANMASK(keys[i].mod) == CLEANMASK(ev->state)
2510                    && keyfuncs[keys[i].funcid].func)
2511                         keyfuncs[keys[i].funcid].func(
2512                             root_to_region(ev->root),
2513                             &(keyfuncs[keys[i].funcid].args)
2514                             );
2515 }
2516
2517 void
2518 buttonpress(XEvent *e)
2519 {
2520         XButtonPressedEvent     *ev = &e->xbutton;
2521
2522         struct ws_win           *win;
2523         int                     i, action;
2524
2525         DNPRINTF(SWM_D_EVENT, "buttonpress: window: %lu\n", ev->window);
2526
2527         action = root_click;
2528         if ((win = find_window(ev->window)) == NULL)
2529                 return;
2530         else {
2531                 focus_win(win);
2532                 action = client_click;
2533         }
2534
2535         for (i = 0; i < LENGTH(buttons); i++)
2536                 if (action == buttons[i].action && buttons[i].func &&
2537                     buttons[i].button == ev->button &&
2538                     CLEANMASK(buttons[i].mask) == CLEANMASK(ev->state))
2539                         buttons[i].func(win, &buttons[i].args);
2540 }
2541
2542 void
2543 set_win_state(struct ws_win *win, long state)
2544 {
2545         long                    data[] = {state, None};
2546
2547         DNPRINTF(SWM_D_EVENT, "set_win_state: window: %lu\n", win->id);
2548
2549         XChangeProperty(display, win->id, astate, astate, 32, PropModeReplace,
2550             (unsigned char *)data, 2);
2551 }
2552
2553 const char *quirkname[] = {
2554         "NONE",         /* config string for "no value" */
2555         "FLOAT",
2556         "TRANSSZ",
2557         "ANYWHERE",
2558         "XTERM_FONTADJ",
2559         "FULLSCREEN",
2560 };
2561
2562 #define SWM_Q_WS                "\n| \t"
2563 int
2564 parsequirks(char *qstr, unsigned long *quirk)
2565 {
2566         char                    *cp, *name;
2567         int                     i;
2568         if (quirk == NULL)
2569                 return (0);
2570         cp = qstr;
2571         *quirk = 0;
2572         while ((name = strsep(&cp, SWM_Q_WS)) != NULL) {
2573                 if (cp)
2574                         cp += (long)strspn(cp, SWM_Q_WS);
2575                 for (i = 0; i < LENGTH(quirkname); i++) {
2576                         if (!strncasecmp(name, quirkname[i], SWM_QUIRK_LEN)) {
2577                                 DNPRINTF(SWM_D_QUIRK, "parsequirks: %s\n", name);
2578                                 if (i == 0) {
2579                                         *quirk = 0;
2580                                         return (1);
2581                                 }
2582                                 *quirk |= 1 << (i-1);
2583                                 break;
2584                         }
2585                 }
2586                 if (i >= LENGTH(quirkname)) {
2587                         DNPRINTF(SWM_D_QUIRK,
2588                             "parsequirks: invalid quirk [%s]\n", name);
2589                         return (0);
2590                 }
2591         }
2592         return (1);
2593 }
2594 int
2595 quirkmatch(const char *var, const char *name, char *qstr, char *qclass,
2596     char *qname, unsigned long *qquirk)
2597 {
2598         char                    *p;
2599         int                     i;
2600         char                    classname[SWM_QUIRK_LEN*2+1];
2601         DNPRINTF(SWM_D_QUIRK, "quirkmatch: in [%s]\n", var);
2602         i = strncmp(var, name, 255);
2603         if (qclass == NULL || qname == NULL || qquirk == NULL)
2604                 return (i);
2605         *qquirk = 0;
2606         *qclass = '\0';
2607         *qname  = '\0';
2608         bzero(classname, LENGTH(classname));
2609         if (i <= 0)
2610                 return (i);
2611         p = (char *)var + strlen(name);
2612         if (*p++ != '[')
2613                 return (i);
2614         i = 0;
2615         while (isgraph(*p) && *p != ']' && i < LENGTH(classname))
2616                 classname[i++] = *p++;
2617         if (i >= LENGTH(classname) || *p != ']')
2618                 return (1);
2619         if ((p = strchr(classname, ':')) == NULL || p-classname >= SWM_QUIRK_LEN)
2620                 return (1);
2621         strlcpy(qclass, classname, p-classname+1);
2622         strlcpy(qname, ++p, SWM_QUIRK_LEN);
2623         for (p = qclass; *p && p-qclass < SWM_QUIRK_LEN; p++)
2624                 if (*p == '_')
2625                         *p = ' ';
2626         for (p = qname; *p && p-qname < SWM_QUIRK_LEN; p++)
2627                 if (*p == '_')
2628                         *p = ' ';
2629         i = (!parsequirks(qstr, qquirk));
2630         DNPRINTF(SWM_D_QUIRK, "quirkmatch: [%s][%s] %d\n", qclass, qname, i);
2631         return (i);
2632 }
2633 void
2634 setquirk(const char *class, const char *name, const int quirk)
2635 {
2636         int                     i, j;
2637         /* find existing */
2638         for (i = 0; i < quirks_length; i++) {
2639                 if (!strcmp(quirks[i].class, class) &&
2640                     !strcmp(quirks[i].name, name)) {
2641                         if (!quirk) {
2642                                 /* found: delete */
2643                                 DNPRINTF(SWM_D_QUIRK,
2644                                     "setquirk: delete #%d %s:%s\n",
2645                                     i, quirks[i].class, quirks[i].name);
2646                                 j = quirks_length - 1;
2647                                 if (i < j)
2648                                         quirks[i] = quirks[j];
2649                                 quirks_length--;
2650                                 return;
2651                         } else {
2652                                 /* found: replace */
2653                                 DNPRINTF(SWM_D_QUIRK,
2654                                     "setquirk: replace #%d %s:%s\n",
2655                                     i, quirks[i].class, quirks[i].name);
2656                                 strlcpy(quirks[i].class, class,
2657                                     sizeof quirks->class);
2658                                 strlcpy(quirks[i].name, name,
2659                                     sizeof quirks->name);
2660                                 quirks[i].quirk = quirk;
2661                                 return;
2662                         }
2663                 }
2664         }
2665         if (!quirk) {
2666                 fprintf(stderr,
2667                     "error: setquirk: cannot find class/name combination");
2668                 return;
2669         }
2670         /* not found: add */
2671         if (quirks_size == 0 || quirks == NULL) {
2672                 quirks_size = 4;
2673                 DNPRINTF(SWM_D_QUIRK, "setquirk: init list %d\n", quirks_size);
2674                 quirks = malloc((size_t)quirks_size * sizeof(struct quirk));
2675                 if (!quirks) {
2676                         fprintf(stderr, "setquirk: malloc failed\n");
2677                         perror(" failed");
2678                         quit(NULL, NULL);
2679                 }
2680         } else if (quirks_length == quirks_size) {
2681                 quirks_size *= 2;
2682                 DNPRINTF(SWM_D_QUIRK, "setquirk: grow list %d\n", quirks_size);
2683                 quirks = realloc(quirks, (size_t)quirks_size * sizeof(struct quirk));
2684                 if (!quirks) {
2685                         fprintf(stderr, "setquirk: realloc failed\n");
2686                         perror(" failed");
2687                         quit(NULL, NULL);
2688                 }
2689         }
2690         if (quirks_length < quirks_size) {
2691                 DNPRINTF(SWM_D_QUIRK, "setquirk: add %d\n", quirks_length);
2692                 j = quirks_length++;
2693                 strlcpy(quirks[j].class, class, sizeof quirks->class);
2694                 strlcpy(quirks[j].name, name, sizeof quirks->name);
2695                 quirks[j].quirk = quirk;
2696         } else {
2697                 fprintf(stderr, "quirks array problem?\n");
2698                 if (!quirks) {
2699                         fprintf(stderr, "quirks array problem!\n");
2700                         quit(NULL, NULL);
2701                 }
2702         }
2703 }
2704
2705 void
2706 setup_quirks(void)
2707 {
2708         setquirk("MPlayer",             "xv",           SWM_Q_FLOAT | SWM_Q_FULLSCREEN);
2709         setquirk("OpenOffice.org 2.4",  "VCLSalFrame",  SWM_Q_FLOAT);
2710         setquirk("OpenOffice.org 3.0",  "VCLSalFrame",  SWM_Q_FLOAT);
2711         setquirk("Firefox-bin",         "firefox-bin",  SWM_Q_TRANSSZ);
2712         setquirk("Firefox",             "Dialog",       SWM_Q_FLOAT);
2713         setquirk("Gimp",                "gimp",         SWM_Q_FLOAT | SWM_Q_ANYWHERE);
2714         setquirk("XTerm",               "xterm",        SWM_Q_XTERM_FONTADJ);
2715         setquirk("xine",                "Xine Window",  SWM_Q_FLOAT | SWM_Q_ANYWHERE);
2716         setquirk("Xitk",                "Xitk Combo",   SWM_Q_FLOAT | SWM_Q_ANYWHERE);
2717         setquirk("xine",                "xine Panel",   SWM_Q_FLOAT | SWM_Q_ANYWHERE);
2718         setquirk("Xitk",                "Xine Window",  SWM_Q_FLOAT | SWM_Q_ANYWHERE);
2719         setquirk("xine",                "xine Video Fullscreen Window", SWM_Q_FULLSCREEN | SWM_Q_FLOAT);
2720         setquirk("pcb",                 "pcb",          SWM_Q_FLOAT);
2721 }
2722
2723 struct ws_win *
2724 manage_window(Window id)
2725 {
2726         Window                  trans;
2727         struct workspace        *ws;
2728         struct ws_win           *win;
2729         int                     format, i, ws_idx, n;
2730         unsigned long           nitems, bytes;
2731         Atom                    ws_idx_atom = 0, type;
2732         Atom                    *prot = NULL, *pp;
2733         unsigned char           ws_idx_str[SWM_PROPLEN], *prop = NULL;
2734         struct swm_region       *r;
2735         long                    mask;
2736         const char              *errstr;
2737         XWindowChanges          wc;
2738
2739         if ((win = find_window(id)) != NULL)
2740                         return (win);   /* already being managed */
2741
2742         if ((win = calloc(1, sizeof(struct ws_win))) == NULL)
2743                 errx(1, "calloc: failed to allocate memory for new window");
2744
2745         /* Get all the window data in one shot */
2746         ws_idx_atom = XInternAtom(display, "_SWM_WS", False);
2747         if (ws_idx_atom)
2748                 XGetWindowProperty(display, id, ws_idx_atom, 0, SWM_PROPLEN,
2749                     False, XA_STRING, &type, &format, &nitems, &bytes, &prop);
2750         XGetWindowAttributes(display, id, &win->wa);
2751         XGetTransientForHint(display, id, &trans);
2752         XGetWMNormalHints(display, id, &win->sh, &mask); /* XXX function? */
2753         if (trans) {
2754                 win->transient = trans;
2755                 DNPRINTF(SWM_D_MISC, "manage_window: win %u transient %u\n",
2756                     (unsigned)win->id, win->transient);
2757         }
2758         /* get supported protocols */
2759         if (XGetWMProtocols(display, id, &prot, &n)) {
2760                 for (i = 0, pp = prot; i < n; i++, pp++)
2761                         if (*pp == adelete)
2762                                 win->can_delete = 1;
2763                 if (prot)
2764                         XFree(prot);
2765         }
2766
2767         /*
2768          * Figure out where to put the window. If it was previously assigned to
2769          * a workspace (either by spawn() or manually moving), and isn't
2770          * transient, * put it in the same workspace
2771          */
2772         r = root_to_region(win->wa.root);
2773         if (prop && win->transient == 0) {
2774                 DNPRINTF(SWM_D_PROP, "got property _SWM_WS=%s\n", prop);
2775                 ws_idx = strtonum(prop, 0, 9, &errstr);
2776                 if (errstr) {
2777                         DNPRINTF(SWM_D_EVENT, "window idx is %s: %s",
2778                             errstr, prop);
2779                 }
2780                 ws = &r->s->ws[ws_idx];
2781         } else
2782                 ws = r->ws;
2783
2784         /* set up the window layout */
2785         win->id = id;
2786         win->ws = ws;
2787         win->s = r->s;  /* this never changes */
2788         TAILQ_INSERT_TAIL(&ws->winlist, win, entry);
2789
2790         win->g.w = win->wa.width;
2791         win->g.h = win->wa.height;
2792         win->g.x = win->wa.x;
2793         win->g.y = win->wa.y;
2794
2795         /* Set window properties so we can remember this after reincarnation */
2796         if (ws_idx_atom && prop == NULL &&
2797             snprintf(ws_idx_str, SWM_PROPLEN, "%d", ws->idx) < SWM_PROPLEN) {
2798                 DNPRINTF(SWM_D_PROP, "setting property _SWM_WS to %s\n",
2799                     ws_idx_str);
2800                 XChangeProperty(display, win->id, ws_idx_atom, XA_STRING, 8,
2801                     PropModeReplace, ws_idx_str, SWM_PROPLEN);
2802         }
2803         XFree(prop);
2804
2805         if (XGetClassHint(display, win->id, &win->ch)) {
2806                 DNPRINTF(SWM_D_CLASS, "class: %s name: %s\n",
2807                     win->ch.res_class, win->ch.res_name);
2808                 for (i = 0; i < quirks_length; i++){
2809                         if (!strcmp(win->ch.res_class, quirks[i].class) &&
2810                             !strcmp(win->ch.res_name, quirks[i].name)) {
2811                                 DNPRINTF(SWM_D_CLASS, "found: %s name: %s\n",
2812                                     win->ch.res_class, win->ch.res_name);
2813                                 if (quirks[i].quirk & SWM_Q_FLOAT)
2814                                         win->floating = 1;
2815                                 win->quirks = quirks[i].quirk;
2816                         }
2817                 }
2818         }
2819
2820         /* alter window position if quirky */
2821         if (win->quirks & SWM_Q_ANYWHERE) {
2822                 win->manual = 1; /* don't center the quirky windows */
2823                 bzero(&wc, sizeof wc);
2824                 mask = 0;
2825                 if (win->g.y < bar_height) {
2826                         win->g.y = wc.y = bar_height;
2827                         mask |= CWY;
2828                 }
2829                 if (win->g.w + win->g.x > WIDTH(r)) {
2830                         win->g.x = wc.x = WIDTH(win->ws->r) - win->g.w - 2;
2831                         mask |= CWX;
2832                 }
2833                 wc.border_width = 1;
2834                 mask |= CWBorderWidth;
2835                 XConfigureWindow(display, win->id, mask, &wc);
2836         }
2837
2838         /* Reset font sizes (the bruteforce way; no default keybinding). */
2839         if (win->quirks & SWM_Q_XTERM_FONTADJ) {
2840                 for (i = 0; i < SWM_MAX_FONT_STEPS; i++)
2841                         fake_keypress(win, XK_KP_Subtract, ShiftMask);
2842                 for (i = 0; i < SWM_MAX_FONT_STEPS; i++)
2843                         fake_keypress(win, XK_KP_Add, ShiftMask);
2844         }
2845
2846         XSelectInput(display, id, EnterWindowMask | FocusChangeMask |
2847             PropertyChangeMask | StructureNotifyMask);
2848
2849         set_win_state(win, NormalState);
2850
2851         /* floaters need to be mapped if they are in the current workspace */
2852         if (win->floating && (ws->idx == r->ws->idx))
2853                 XMapRaised(display, win->id);
2854
2855         /* make new win focused */
2856         focus_win(win);
2857
2858         return (win);
2859 }
2860
2861 void
2862 unmanage_window(struct ws_win *win)
2863 {
2864         struct workspace        *ws;
2865
2866         if (win == NULL)
2867                 return;
2868
2869         DNPRINTF(SWM_D_MISC, "unmanage_window:  %lu\n", win->id);
2870
2871         /* don't unmanage if we are switching workspaces */
2872         ws = win->ws;
2873         if (ws->restack)
2874                 return;
2875
2876         /* find a window to focus */
2877         if (ws->focus == win)
2878                 ws->focus = TAILQ_PREV(win, ws_win_list, entry);
2879         if (ws->focus == NULL)
2880                 ws->focus = TAILQ_FIRST(&ws->winlist);
2881         if (ws->focus == NULL || ws->focus == win) {
2882                 ws->focus = NULL;
2883                 unfocus_win(win);
2884         } else
2885                 focus_win(ws->focus);
2886         if (ws->focus_prev == win)
2887                 ws->focus_prev = NULL;
2888
2889         TAILQ_REMOVE(&win->ws->winlist, win, entry);
2890         set_win_state(win, WithdrawnState);
2891         if (win->ch.res_class)
2892                 XFree(win->ch.res_class);
2893         if (win->ch.res_name)
2894                 XFree(win->ch.res_name);
2895         free(win);
2896 }
2897
2898 void
2899 configurerequest(XEvent *e)
2900 {
2901         XConfigureRequestEvent  *ev = &e->xconfigurerequest;
2902         struct ws_win           *win;
2903         int                     new = 0;
2904         XWindowChanges          wc;
2905
2906         if ((win = find_window(ev->window)) == NULL)
2907                 new = 1;
2908
2909         if (new) {
2910                 DNPRINTF(SWM_D_EVENT, "configurerequest: new window: %lu\n",
2911                     ev->window);
2912                 bzero(&wc, sizeof wc);
2913                 wc.x = ev->x;
2914                 wc.y = ev->y;
2915                 wc.width = ev->width;
2916                 wc.height = ev->height;
2917                 wc.border_width = ev->border_width;
2918                 wc.sibling = ev->above;
2919                 wc.stack_mode = ev->detail;
2920                 XConfigureWindow(display, ev->window, ev->value_mask, &wc);
2921         } else {
2922                 DNPRINTF(SWM_D_EVENT, "configurerequest: change window: %lu\n",
2923                     ev->window);
2924                 if (win->floating) {
2925                         if (ev->value_mask & CWX)
2926                                 win->g.x = ev->x;
2927                         if (ev->value_mask & CWY)
2928                                 win->g.y = ev->y;
2929                         if (ev->value_mask & CWWidth)
2930                                 win->g.w = ev->width;
2931                         if (ev->value_mask & CWHeight)
2932                                 win->g.h = ev->height;
2933                         if (win->ws->r != NULL) {
2934                                 /* this seems to be full screen */
2935                                 if (win->g.w >= WIDTH(win->ws->r)) {
2936                                         win->g.x = 0;
2937                                         win->g.w = WIDTH(win->ws->r);
2938                                         ev->value_mask |= CWX | CWWidth;
2939                                 }
2940                                 if (win->g.h >= HEIGHT(win->ws->r)) {
2941                                         /* kill border */
2942                                         win->g.y = 0;
2943                                         win->g.h = HEIGHT(win->ws->r);
2944                                         ev->value_mask |= CWY | CWHeight;
2945                                 }
2946                         }
2947                         if ((ev->value_mask & (CWX | CWY)) &&
2948                             !(ev->value_mask & (CWWidth | CWHeight)))
2949                                 config_win(win);
2950                         XMoveResizeWindow(display, win->id,
2951                             win->g.x, win->g.y, win->g.w, win->g.h);
2952                 } else
2953                         config_win(win);
2954         }
2955 }
2956
2957 void
2958 configurenotify(XEvent *e)
2959 {
2960         struct ws_win           *win;
2961         long                    mask;
2962
2963         DNPRINTF(SWM_D_EVENT, "configurenotify: window: %lu\n",
2964             e->xconfigure.window);
2965
2966         XMapWindow(display, e->xconfigure.window);
2967         win = find_window(e->xconfigure.window);
2968         if (win) {
2969                 XGetWMNormalHints(display, win->id, &win->sh, &mask);
2970                 adjust_font(win);
2971                 XMapWindow(display, win->id);
2972                 if (font_adjusted)
2973                         stack();
2974         }
2975 }
2976
2977 void
2978 destroynotify(XEvent *e)
2979 {
2980         struct ws_win           *win;
2981         XDestroyWindowEvent     *ev = &e->xdestroywindow;
2982
2983         DNPRINTF(SWM_D_EVENT, "destroynotify: window %lu\n", ev->window);
2984
2985         if ((win = find_window(ev->window)) != NULL) {
2986                 unmanage_window(win);
2987                 stack();
2988         }
2989 }
2990
2991 void
2992 enternotify(XEvent *e)
2993 {
2994         XCrossingEvent          *ev = &e->xcrossing;
2995         struct ws_win           *win;
2996
2997         DNPRINTF(SWM_D_EVENT, "enternotify: window: %lu\n", ev->window);
2998
2999         if (ignore_enter) {
3000                 /* eat event(r) to prevent autofocus */
3001                 ignore_enter--;
3002                 return;
3003         }
3004
3005         if ((win = find_window(ev->window)) != NULL)
3006                 focus_win(win);
3007 }
3008
3009 void
3010 focusin(XEvent *e)
3011 {
3012         DNPRINTF(SWM_D_EVENT, "focusin: window: %lu\n", e->xfocus.window);
3013 }
3014
3015 void
3016 focusout(XEvent *e)
3017 {
3018         DNPRINTF(SWM_D_EVENT, "focusout: window: %lu\n", e->xfocus.window);
3019
3020         if (cur_focus && cur_focus->ws->r &&
3021             cur_focus->id == e->xfocus.window) {
3022                 struct swm_screen       *s = cur_focus->ws->r->s;
3023                 Window                  rr, cr;
3024                 int                     x, y, wx, wy;
3025                 unsigned int            mask;
3026
3027                 /* Try to detect synergy hiding the cursor.  */
3028                 if (XQueryPointer(display, cur_focus->id, 
3029                     &rr, &cr, &x, &y, &wx, &wy, &mask) != False &&
3030                     cr == 0 && !mask &&
3031                     x == DisplayWidth(display, s->idx)/2 &&
3032                     y == DisplayHeight(display, s->idx)/2) {
3033                         unfocus_win(cur_focus);
3034                 }
3035         }
3036 }
3037
3038 void
3039 mappingnotify(XEvent *e)
3040 {
3041         XMappingEvent           *ev = &e->xmapping;
3042
3043         DNPRINTF(SWM_D_EVENT, "mappingnotify: window: %lu\n", ev->window);
3044
3045         XRefreshKeyboardMapping(ev);
3046         if (ev->request == MappingKeyboard)
3047                 grabkeys();
3048 }
3049
3050 void
3051 maprequest(XEvent *e)
3052 {
3053         XMapRequestEvent        *ev = &e->xmaprequest;
3054         XWindowAttributes       wa;
3055
3056         DNPRINTF(SWM_D_EVENT, "maprequest: window: %lu\n",
3057             e->xmaprequest.window);
3058
3059         if (!XGetWindowAttributes(display, ev->window, &wa))
3060                 return;
3061         if (wa.override_redirect)
3062                 return;
3063         manage_window(e->xmaprequest.window);
3064
3065         stack();
3066 }
3067
3068 void
3069 propertynotify(XEvent *e)
3070 {
3071         struct ws_win           *win;
3072         XPropertyEvent          *ev = &e->xproperty;
3073
3074         DNPRINTF(SWM_D_EVENT, "propertynotify: window: %lu\n",
3075             ev->window);
3076
3077         if (ev->state == PropertyDelete)
3078                 return; /* ignore */
3079         win = find_window(ev->window);
3080         if (win == NULL)
3081                 return;
3082
3083         switch (ev->atom) {
3084         case XA_WM_NORMAL_HINTS:
3085 #if 0
3086                 long            mask;
3087                 XGetWMNormalHints(display, win->id, &win->sh, &mask);
3088                 fprintf(stderr, "normal hints: flag 0x%x\n", win->sh.flags);
3089                 if (win->sh.flags & PMinSize) {
3090                         win->g.w = win->sh.min_width;
3091                         win->g.h = win->sh.min_height;
3092                         fprintf(stderr, "min %d %d\n", win->g.w, win->g.h);
3093                 }
3094                 XMoveResizeWindow(display, win->id,
3095                     win->g.x, win->g.y, win->g.w, win->g.h);
3096 #endif
3097                 break;
3098         default:
3099                 break;
3100         }
3101 }
3102
3103 void
3104 unmapnotify(XEvent *e)
3105 {
3106         XDestroyWindowEvent     *ev = &e->xdestroywindow;
3107         struct ws_win           *win;
3108
3109         DNPRINTF(SWM_D_EVENT, "unmapnotify: window: %lu\n", e->xunmap.window);
3110
3111         if ((win = find_window(ev->window)) != NULL)
3112                 if (win->transient)
3113                         unmanage_window(win);
3114 }
3115
3116 void
3117 visibilitynotify(XEvent *e)
3118 {
3119         int                     i;
3120         struct swm_region       *r;
3121
3122         DNPRINTF(SWM_D_EVENT, "visibilitynotify: window: %lu\n",
3123             e->xvisibility.window);
3124         if (e->xvisibility.state == VisibilityUnobscured)
3125                 for (i = 0; i < ScreenCount(display); i++) 
3126                         TAILQ_FOREACH(r, &screens[i].rl, entry)
3127                                 if (e->xvisibility.window == r->bar_window)
3128                                         bar_update();
3129 }
3130
3131 int
3132 xerror_start(Display *d, XErrorEvent *ee)
3133 {
3134         other_wm = 1;
3135         return (-1);
3136 }
3137
3138 int
3139 xerror(Display *d, XErrorEvent *ee)
3140 {
3141         /* fprintf(stderr, "error: %p %p\n", display, ee); */
3142         return (-1);
3143 }
3144
3145 int
3146 active_wm(void)
3147 {
3148         other_wm = 0;
3149         xerrorxlib = XSetErrorHandler(xerror_start);
3150
3151         /* this causes an error if some other window manager is running */
3152         XSelectInput(display, DefaultRootWindow(display),
3153             SubstructureRedirectMask);
3154         XSync(display, False);
3155         if (other_wm)
3156                 return (1);
3157
3158         XSetErrorHandler(xerror);
3159         XSync(display, False);
3160         return (0);
3161 }
3162
3163 long
3164 getstate(Window w)
3165 {
3166         int                     format, status;
3167         long                    result = -1;
3168         unsigned char           *p = NULL;
3169         unsigned long           n, extra;
3170         Atom                    real;
3171
3172         status = XGetWindowProperty(display, w, astate, 0L, 2L, False, astate,
3173             &real, &format, &n, &extra, (unsigned char **)&p);
3174         if (status != Success)
3175                 return (-1);
3176         if (n != 0)
3177                 result = *((long *)p);
3178         XFree(p);
3179         return (result);
3180 }
3181
3182 void
3183 new_region(struct swm_screen *s, int x, int y, int w, int h)
3184 {
3185         struct swm_region       *r, *n;
3186         struct workspace        *ws = NULL;
3187         int                     i;
3188
3189         DNPRINTF(SWM_D_MISC, "new region: screen[%d]:%dx%d+%d+%d\n",
3190              s->idx, w, h, x, y);
3191
3192         /* remove any conflicting regions */
3193         n = TAILQ_FIRST(&s->rl);
3194         while (n) {
3195                 r = n;
3196                 n = TAILQ_NEXT(r, entry);
3197                 if (X(r) < (x + w) &&
3198                     (X(r) + WIDTH(r)) > x &&
3199                     Y(r) < (y + h) &&
3200                     (Y(r) + HEIGHT(r)) > y) {
3201                         XDestroyWindow(display, r->bar_window);
3202                         TAILQ_REMOVE(&s->rl, r, entry);
3203                         TAILQ_INSERT_TAIL(&s->orl, r, entry);
3204                 }
3205         }
3206
3207         /* search old regions for one to reuse */
3208
3209         /* size + location match */
3210         TAILQ_FOREACH(r, &s->orl, entry)
3211                 if (X(r) == x && Y(r) == y &&
3212                     HEIGHT(r) == h && WIDTH(r) == w)
3213                         break;
3214
3215         /* size match */
3216         TAILQ_FOREACH(r, &s->orl, entry)
3217                 if (HEIGHT(r) == h && WIDTH(r) == w)
3218                         break;
3219
3220         if (r != NULL) {
3221                 TAILQ_REMOVE(&s->orl, r, entry);
3222                 /* try to use old region's workspace */
3223                 if (r->ws->r == NULL)
3224                         ws = r->ws;
3225         } else
3226                 if ((r = calloc(1, sizeof(struct swm_region))) == NULL)
3227                         errx(1, "calloc: failed to allocate memory for screen");
3228
3229         /* if we don't have a workspace already, find one */
3230         if (ws == NULL) {
3231                 for (i = 0; i < SWM_WS_MAX; i++)
3232                         if (s->ws[i].r == NULL) {
3233                                 ws = &s->ws[i];
3234                                 break;
3235                         }
3236         }
3237
3238         if (ws == NULL)
3239                 errx(1, "no free workspaces\n");
3240
3241         X(r) = x;
3242         Y(r) = y;
3243         WIDTH(r) = w;
3244         HEIGHT(r) = h;
3245         r->s = s;
3246         r->ws = ws;
3247         ws->r = r;
3248         TAILQ_INSERT_TAIL(&s->rl, r, entry);
3249 }
3250
3251 void
3252 scan_xrandr(int i)
3253 {
3254 #ifdef SWM_XRR_HAS_CRTC
3255         XRRCrtcInfo             *ci;
3256         XRRScreenResources      *sr;
3257         int                     c;
3258         int                     ncrtc = 0;
3259 #endif /* SWM_XRR_HAS_CRTC */
3260         struct swm_region       *r;
3261
3262
3263         if (i >= ScreenCount(display))
3264                 errx(1, "invalid screen");
3265
3266         /* remove any old regions */
3267         while ((r = TAILQ_FIRST(&screens[i].rl)) != NULL) {
3268                 r->ws->r = NULL;
3269                 XDestroyWindow(display, r->bar_window);
3270                 TAILQ_REMOVE(&screens[i].rl, r, entry);
3271                 TAILQ_INSERT_TAIL(&screens[i].orl, r, entry);
3272         }
3273
3274         /* map virtual screens onto physical screens */
3275 #ifdef SWM_XRR_HAS_CRTC
3276         if (xrandr_support) {
3277                 sr = XRRGetScreenResources(display, screens[i].root);
3278                 if (sr == NULL)
3279                         new_region(&screens[i], 0, 0,
3280                             DisplayWidth(display, i),
3281                             DisplayHeight(display, i)); 
3282                 else 
3283                         ncrtc = sr->ncrtc;
3284
3285                 for (c = 0, ci = NULL; c < ncrtc; c++) {
3286                         ci = XRRGetCrtcInfo(display, sr, sr->crtcs[c]);
3287                         if (ci->noutput == 0)
3288                                 continue;
3289
3290                         if (ci != NULL && ci->mode == None)
3291                                 new_region(&screens[i], 0, 0,
3292                                     DisplayWidth(display, i),
3293                                     DisplayHeight(display, i)); 
3294                         else
3295                                 new_region(&screens[i],
3296                                     ci->x, ci->y, ci->width, ci->height);
3297                 }
3298                 if (ci)
3299                         XRRFreeCrtcInfo(ci);
3300                 XRRFreeScreenResources(sr);
3301         } else
3302 #endif /* SWM_XRR_HAS_CRTC */
3303         {
3304                 new_region(&screens[i], 0, 0, DisplayWidth(display, i),
3305                     DisplayHeight(display, i)); 
3306         }
3307 }
3308
3309 void
3310 screenchange(XEvent *e) {
3311         XRRScreenChangeNotifyEvent      *xe = (XRRScreenChangeNotifyEvent *)e;
3312         struct swm_region               *r;
3313         struct ws_win                   *win;
3314         int                             i;
3315
3316         DNPRINTF(SWM_D_EVENT, "screenchange: %lu\n", xe->root);
3317
3318         if (!XRRUpdateConfiguration(e))
3319                 return;
3320
3321         /* silly event doesn't include the screen index */
3322         for (i = 0; i < ScreenCount(display); i++)
3323                 if (screens[i].root == xe->root)
3324                         break;
3325         if (i >= ScreenCount(display))
3326                 errx(1, "screenchange: screen not found\n");
3327
3328         /* brute force for now, just re-enumerate the regions */
3329         scan_xrandr(i);
3330
3331         /* hide any windows that went away */
3332         TAILQ_FOREACH(r, &screens[i].rl, entry)
3333                 TAILQ_FOREACH(win, &r->ws->winlist, entry)
3334                         XUnmapWindow(display, win->id);
3335
3336         /* add bars to all regions */
3337         for (i = 0; i < ScreenCount(display); i++)
3338                 TAILQ_FOREACH(r, &screens[i].rl, entry)
3339                         bar_setup(r);
3340         stack();
3341 }
3342
3343 void
3344 setup_screens(void)
3345 {
3346         Window                  d1, d2, *wins = NULL;
3347         XWindowAttributes       wa;
3348         unsigned int            no;
3349         int                     i, j, k;
3350         int                     errorbase, major, minor;
3351         struct workspace        *ws;
3352         int                     ws_idx_atom;
3353
3354
3355         if ((screens = calloc(ScreenCount(display),
3356              sizeof(struct swm_screen))) == NULL)
3357                 errx(1, "calloc: screens");
3358
3359         ws_idx_atom = XInternAtom(display, "_SWM_WS", False);
3360
3361         /* initial Xrandr setup */
3362         xrandr_support = XRRQueryExtension(display,
3363             &xrandr_eventbase, &errorbase);
3364         if (xrandr_support)
3365                 if (XRRQueryVersion(display, &major, &minor) && major < 1)
3366                         xrandr_support = 0;
3367
3368         /* map physical screens */
3369         for (i = 0; i < ScreenCount(display); i++) {
3370                 DNPRINTF(SWM_D_WS, "setup_screens: init screen %d\n", i);
3371                 screens[i].idx = i;
3372                 TAILQ_INIT(&screens[i].rl);
3373                 TAILQ_INIT(&screens[i].orl);
3374                 screens[i].root = RootWindow(display, i);
3375
3376                 /* set default colors */
3377                 setscreencolor("red", i + 1, SWM_S_COLOR_FOCUS);
3378                 setscreencolor("rgb:88/88/88", i + 1, SWM_S_COLOR_UNFOCUS);
3379                 setscreencolor("rgb:00/80/80", i + 1, SWM_S_COLOR_BAR_BORDER);
3380                 setscreencolor("black", i + 1, SWM_S_COLOR_BAR);
3381                 setscreencolor("rgb:a0/a0/a0", i + 1, SWM_S_COLOR_BAR_FONT);
3382
3383                 /* init all workspaces */
3384                 /* XXX these should be dynamically allocated too */
3385                 for (j = 0; j < SWM_WS_MAX; j++) {
3386                         ws = &screens[i].ws[j];
3387                         ws->idx = j;
3388                         ws->restack = 1;
3389                         ws->focus = NULL;
3390                         ws->r = NULL;
3391                         TAILQ_INIT(&ws->winlist);
3392
3393                         for (k = 0; layouts[k].l_stack != NULL; k++)
3394                                 if (layouts[k].l_config != NULL)
3395                                         layouts[k].l_config(ws,
3396                                             SWM_ARG_ID_STACKINIT);
3397                         ws->cur_layout = &layouts[0];
3398                 }
3399                 /* grab existing windows (before we build the bars)*/
3400                 if (!XQueryTree(display, screens[i].root, &d1, &d2, &wins, &no))
3401                         continue;
3402
3403                 scan_xrandr(i);
3404
3405                 if (xrandr_support)
3406                         XRRSelectInput(display, screens[i].root,
3407                             RRScreenChangeNotifyMask);
3408
3409                 /* attach windows to a region */
3410                 /* normal windows */
3411                 for (j = 0; j < no; j++) {
3412                         XGetWindowAttributes(display, wins[j], &wa);
3413                         if (!XGetWindowAttributes(display, wins[j], &wa) ||
3414                             wa.override_redirect ||
3415                             XGetTransientForHint(display, wins[j], &d1))
3416                                 continue;
3417
3418                         if (wa.map_state == IsViewable ||
3419                             getstate(wins[j]) == NormalState)
3420                                 manage_window(wins[j]);
3421                 }
3422                 /* transient windows */
3423                 for (j = 0; j < no; j++) {
3424                         if (!XGetWindowAttributes(display, wins[j], &wa))
3425                                 continue;
3426
3427                         if (XGetTransientForHint(display, wins[j], &d1) &&
3428                             (wa.map_state == IsViewable || getstate(wins[j]) ==
3429                             NormalState))
3430                                 manage_window(wins[j]);
3431                 }
3432                 if (wins) {
3433                         XFree(wins);
3434                         wins = NULL;
3435                 }
3436         }
3437 }
3438
3439 void
3440 workaround(void)
3441 {
3442         int                     i;
3443         Atom                    netwmcheck, netwmname, utf8_string;
3444         Window                  root;
3445
3446         /* work around sun jdk bugs, code from wmname */
3447         netwmcheck = XInternAtom(display, "_NET_SUPPORTING_WM_CHECK", False);
3448         netwmname = XInternAtom(display, "_NET_WM_NAME", False);
3449         utf8_string = XInternAtom(display, "UTF8_STRING", False);
3450         for (i = 0; i < ScreenCount(display); i++) {
3451                 root = screens[i].root;
3452                 XChangeProperty(display, root, netwmcheck, XA_WINDOW, 32,
3453                     PropModeReplace, (unsigned char *)&root, 1);
3454                 XChangeProperty(display, root, netwmname, utf8_string, 8,
3455                     PropModeReplace, "LG3D", strlen("LG3D"));
3456         }
3457 }
3458
3459 int
3460 main(int argc, char *argv[])
3461 {
3462         struct passwd           *pwd;
3463         struct swm_region       *r;
3464         char                    conf[PATH_MAX], *cfile = NULL;
3465         struct stat             sb;
3466         XEvent                  e;
3467         int                     xfd, i;
3468         fd_set                  rd;
3469
3470         start_argv = argv;
3471         fprintf(stderr, "Welcome to scrotwm V%s cvs tag: %s\n",
3472             SWM_VERSION, cvstag);
3473         if (!setlocale(LC_CTYPE, "") || !XSupportsLocale())
3474                 warnx("no locale support");
3475
3476         if (!(display = XOpenDisplay(0)))
3477                 errx(1, "can not open display");
3478
3479         if (active_wm())
3480                 errx(1, "other wm running");
3481
3482         astate = XInternAtom(display, "WM_STATE", False);
3483         aprot = XInternAtom(display, "WM_PROTOCOLS", False);
3484         adelete = XInternAtom(display, "WM_DELETE_WINDOW", False);
3485
3486         /* look for local and global conf file */
3487         pwd = getpwuid(getuid());
3488         if (pwd == NULL)
3489                 errx(1, "invalid user %d", getuid());
3490
3491         setup_screens();
3492         setup_keys();
3493         setup_quirks();
3494
3495         snprintf(conf, sizeof conf, "%s/.%s", pwd->pw_dir, SWM_CONF_FILE);
3496         if (stat(conf, &sb) != -1) {
3497                 if (S_ISREG(sb.st_mode))
3498                         cfile = conf;
3499         } else {
3500                 /* try global conf file */
3501                 snprintf(conf, sizeof conf, "/etc/%s", SWM_CONF_FILE);
3502                 if (!stat(conf, &sb))
3503                         if (S_ISREG(sb.st_mode))
3504                                 cfile = conf;
3505         }
3506         if (cfile)
3507                 conf_load(cfile);
3508
3509         /* setup all bars */
3510         for (i = 0; i < ScreenCount(display); i++)
3511                 TAILQ_FOREACH(r, &screens[i].rl, entry)
3512                         bar_setup(r);
3513
3514         /* set some values to work around bad programs */
3515         workaround();
3516
3517         grabkeys();
3518         stack();
3519
3520         xfd = ConnectionNumber(display);
3521         while (running) {
3522                 FD_ZERO(&rd);
3523                 FD_SET(xfd, &rd);
3524                 if (select(xfd + 1, &rd, NULL, NULL, NULL) == -1)
3525                         if (errno != EINTR)
3526                                 errx(1, "select failed");
3527                 if (bar_alarm) {
3528                         bar_alarm = 0;
3529                         bar_update();
3530                 }
3531                 while (XPending(display)) {
3532                         XNextEvent(display, &e);
3533                         if (e.type < LASTEvent) {
3534                                 if (handler[e.type])
3535                                         handler[e.type](&e);
3536                                 else
3537                                         DNPRINTF(SWM_D_EVENT,
3538                                             "win: %lu unknown event: %d\n",
3539                                             e.xany.window, e.type);
3540                         } else {
3541                                 switch (e.type - xrandr_eventbase) {
3542                                 case RRScreenChangeNotify:
3543                                         screenchange(&e);
3544                                         break;
3545                                 default:
3546                                         DNPRINTF(SWM_D_EVENT,
3547                                             "win: %lu unknown xrandr event: "
3548                                             "%d\n", e.xany.window, e.type);
3549                                         break;
3550                                 }
3551                         }
3552                 }
3553         }
3554
3555         XCloseDisplay(display);
3556
3557         return (0);
3558 }