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