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