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