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