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