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