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