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