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