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