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