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