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