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