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