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