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