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