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