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