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