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