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