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