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