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