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