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