JasonWoof Got questions, comments, patches, etc.? Contact Jason Woofenden
oops! stackinit called too many times due to stray ;
[spectrwm.git] / scrotwm.c
1 /* $scrotwm$ */
2 /*
3  * Copyright (c) 2009-2010-2011 Marco Peereboom <marco@peereboom.us>
4  * Copyright (c) 2009-2010-2011 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  * Copyright (c) 2011 Jason L. Wright <jason@thought.net>
8  *
9  * Permission to use, copy, modify, and distribute this software for any
10  * purpose with or without fee is hereby granted, provided that the above
11  * copyright notice and this permission notice appear in all copies.
12  *
13  * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
14  * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
15  * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
16  * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
17  * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
18  * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
19  * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
20  */
21 /*
22  * Much code and ideas taken from dwm under the following license:
23  * MIT/X Consortium License
24  *
25  * 2006-2008 Anselm R Garbe <garbeam at gmail dot com>
26  * 2006-2007 Sander van Dijk <a dot h dot vandijk at gmail dot com>
27  * 2006-2007 Jukka Salmi <jukka at salmi dot ch>
28  * 2007 Premysl Hruby <dfenze at gmail dot com>
29  * 2007 Szabolcs Nagy <nszabolcs at gmail dot com>
30  * 2007 Christof Musik <christof at sendfax dot de>
31  * 2007-2008 Enno Gottox Boland <gottox at s01 dot de>
32  * 2007-2008 Peter Hartlich <sgkkr at hartlich dot com>
33  * 2008 Martin Hurton <martin dot hurton at gmail dot com>
34  *
35  * Permission is hereby granted, free of charge, to any person obtaining a
36  * copy of this software and associated documentation files (the "Software"),
37  * to deal in the Software without restriction, including without limitation
38  * the rights to use, copy, modify, merge, publish, distribute, sublicense,
39  * and/or sell copies of the Software, and to permit persons to whom the
40  * Software is furnished to do so, subject to the following conditions:
41  *
42  * The above copyright notice and this permission notice shall be included in
43  * all copies or substantial portions of the Software.
44  *
45  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
46  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
47  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
48  * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
49  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
50  * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
51  * DEALINGS IN THE SOFTWARE.
52  */
53
54 static const char       *cvstag =
55     "$scrotwm$";
56
57 #define SWM_VERSION     "0.9.30"
58
59 #include <stdio.h>
60 #include <stdlib.h>
61 #include <err.h>
62 #include <errno.h>
63 #include <fcntl.h>
64 #include <locale.h>
65 #include <unistd.h>
66 #include <time.h>
67 #include <signal.h>
68 #include <string.h>
69 #include <util.h>
70 #include <pwd.h>
71 #include <paths.h>
72 #include <ctype.h>
73
74 #include <sys/types.h>
75 #include <sys/time.h>
76 #include <sys/stat.h>
77 #include <sys/wait.h>
78 #include <sys/queue.h>
79 #include <sys/param.h>
80 #include <sys/select.h>
81
82 #include <X11/cursorfont.h>
83 #include <X11/keysym.h>
84 #include <X11/Xatom.h>
85 #include <X11/Xlib.h>
86 #include <X11/Xproto.h>
87 #include <X11/Xutil.h>
88 #include <X11/extensions/Xrandr.h>
89
90 #ifdef __OSX__
91 #include <osx.h>
92 #endif
93
94 #if RANDR_MAJOR < 1
95 #  error XRandR versions less than 1.0 are not supported
96 #endif
97
98 #if RANDR_MAJOR >= 1
99 #if RANDR_MINOR >= 2
100 #define SWM_XRR_HAS_CRTC
101 #endif
102 #endif
103
104 /*#define SWM_DEBUG*/
105 #ifdef SWM_DEBUG
106 #define DPRINTF(x...)           do { if (swm_debug) fprintf(stderr, x); } while (0)
107 #define DNPRINTF(n,x...)        do { if (swm_debug & n) fprintf(stderr, x); } while (0)
108 #define SWM_D_MISC              0x0001
109 #define SWM_D_EVENT             0x0002
110 #define SWM_D_WS                0x0004
111 #define SWM_D_FOCUS             0x0008
112 #define SWM_D_MOVE              0x0010
113 #define SWM_D_STACK             0x0020
114 #define SWM_D_MOUSE             0x0040
115 #define SWM_D_PROP              0x0080
116 #define SWM_D_CLASS             0x0100
117 #define SWM_D_KEY               0x0200
118 #define SWM_D_QUIRK             0x0400
119 #define SWM_D_SPAWN             0x0800
120 #define SWM_D_EVENTQ            0x1000
121 #define SWM_D_CONF              0x2000
122
123 u_int32_t               swm_debug = 0
124                             | SWM_D_MISC
125                             | SWM_D_EVENT
126                             | SWM_D_WS
127                             | SWM_D_FOCUS
128                             | SWM_D_MOVE
129                             | SWM_D_STACK
130                             | SWM_D_MOUSE
131                             | SWM_D_PROP
132                             | SWM_D_CLASS
133                             | SWM_D_KEY
134                             | SWM_D_QUIRK
135                             | SWM_D_SPAWN
136                             | SWM_D_EVENTQ
137                             | SWM_D_CONF
138                             ;
139 #else
140 #define DPRINTF(x...)
141 #define DNPRINTF(n,x...)
142 #endif
143
144 #define LENGTH(x)               (sizeof x / sizeof x[0])
145 #define MODKEY                  Mod1Mask
146 #define CLEANMASK(mask)         (mask & ~(numlockmask | LockMask))
147 #define BUTTONMASK              (ButtonPressMask|ButtonReleaseMask)
148 #define MOUSEMASK               (BUTTONMASK|PointerMotionMask)
149 #define SWM_PROPLEN             (16)
150 #define SWM_FUNCNAME_LEN        (32)
151 #define SWM_KEYS_LEN            (255)
152 #define SWM_QUIRK_LEN           (64)
153 #define X(r)                    (r)->g.x
154 #define Y(r)                    (r)->g.y
155 #define WIDTH(r)                (r)->g.w
156 #define HEIGHT(r)               (r)->g.h
157 #define SWM_MAX_FONT_STEPS      (3)
158 #define WINID(w)                (w ? w->id : 0)
159
160 #define SWM_FOCUS_DEFAULT       (0)
161 #define SWM_FOCUS_SYNERGY       (1)
162 #define SWM_FOCUS_FOLLOW        (2)
163
164 #ifndef SWM_LIB
165 #define SWM_LIB                 "/usr/local/lib/libswmhack.so"
166 #endif
167
168 char                    **start_argv;
169 Atom                    astate;
170 Atom                    aprot;
171 Atom                    adelete;
172 Atom                    takefocus;
173 Atom                    a_wmname;
174 Atom                    a_utf8_string;
175 Atom                    a_string;
176 Atom                    a_swm_iconic;
177 volatile sig_atomic_t   running = 1;
178 volatile sig_atomic_t   restart_wm = 0;
179 int                     outputs = 0;
180 int                     last_focus_event = FocusOut;
181 int                     (*xerrorxlib)(Display *, XErrorEvent *);
182 int                     other_wm;
183 int                     ss_enabled = 0;
184 int                     xrandr_support;
185 int                     xrandr_eventbase;
186 unsigned int            numlockmask = 0;
187 Display                 *display;
188
189 int                     cycle_empty = 0;
190 int                     cycle_visible = 0;
191 int                     term_width = 0;
192 int                     font_adjusted = 0;
193 unsigned int            mod_key = MODKEY;
194
195 /* dmenu search */
196 struct swm_region       *search_r;
197 int                     select_list_pipe[2];
198 int                     select_resp_pipe[2];
199 pid_t                   searchpid;
200 volatile sig_atomic_t   search_resp;
201
202 /* dialog windows */
203 double                  dialog_ratio = .6;
204 /* status bar */
205 #define SWM_BAR_MAX     (256)
206 char                    *bar_argv[] = { NULL, NULL };
207 int                     bar_pipe[2];
208 char                    bar_ext[SWM_BAR_MAX];
209 char                    bar_vertext[SWM_BAR_MAX];
210 int                     bar_version = 0;
211 sig_atomic_t            bar_alarm = 0;
212 int                     bar_delay = 30;
213 int                     bar_enabled = 1;
214 int                     bar_border_width = 1;
215 int                     bar_at_bottom = 0;
216 int                     bar_extra = 1;
217 int                     bar_extra_running = 0;
218 int                     bar_verbose = 1;
219 int                     bar_height = 0;
220 int                     stack_enabled = 1;
221 int                     clock_enabled = 1;
222 char                    *clock_format = NULL;
223 int                     title_name_enabled = 0;
224 int                     title_class_enabled = 0;
225 int                     window_name_enabled = 0;
226 int                     focus_mode = SWM_FOCUS_DEFAULT;
227 int                     disable_border = 0;
228 int                     border_width = 1;
229 pid_t                   bar_pid;
230 GC                      bar_gc;
231 XGCValues               bar_gcv;
232 int                     bar_fidx = 0;
233 XFontStruct             *bar_fs;
234 char                    *bar_fonts[] = { NULL, NULL, NULL, NULL };/* XXX Make fully dynamic */
235 char                    *spawn_term[] = { NULL, NULL };         /* XXX Make fully dynamic */
236
237 #define SWM_MENU_FN     (2)
238 #define SWM_MENU_NB     (4)
239 #define SWM_MENU_NF     (6)
240 #define SWM_MENU_SB     (8)
241 #define SWM_MENU_SF     (10)
242
243 /* layout manager data */
244 struct swm_geometry {
245         int                     x;
246         int                     y;
247         int                     w;
248         int                     h;
249 };
250
251 struct swm_screen;
252 struct workspace;
253
254 /* virtual "screens" */
255 struct swm_region {
256         TAILQ_ENTRY(swm_region) entry;
257         struct swm_geometry     g;
258         struct workspace        *ws;    /* current workspace on this region */
259         struct workspace        *ws_prior; /* prior workspace on this region */
260         struct swm_screen       *s;     /* screen idx */
261         Window                  bar_window;
262 };
263 TAILQ_HEAD(swm_region_list, swm_region);
264
265 struct ws_win {
266         TAILQ_ENTRY(ws_win)     entry;
267         Window                  id;
268         Window                  transient;
269         struct ws_win           *child_trans;   /* transient child window */
270         struct swm_geometry     g;              /* current geometry */
271         struct swm_geometry     g_float;        /* geometry when floating */
272         struct swm_geometry     rg_float;       /* region geom when floating */
273         int                     g_floatvalid;   /* flag: geometry in g_float is valid */
274         int                     floatmaxed;     /* flag: floater was maxed in max_stack */
275         int                     floating;
276         int                     manual;
277         int                     iconic;
278         unsigned int            ewmh_flags;
279         int                     font_size_boundary[SWM_MAX_FONT_STEPS];
280         int                     font_steps;
281         int                     last_inc;
282         int                     can_delete;
283         int                     take_focus;
284         int                     java;
285         unsigned long           quirks;
286         struct workspace        *ws;    /* always valid */
287         struct swm_screen       *s;     /* always valid, never changes */
288         XWindowAttributes       wa;
289         XSizeHints              sh;
290         XClassHint              ch;
291         XWMHints                *hints;
292 };
293 TAILQ_HEAD(ws_win_list, ws_win);
294
295 /* layout handlers */
296 void    stack(void);
297 void    vertical_config(struct workspace *, int);
298 void    vertical_stack(struct workspace *, struct swm_geometry *);
299 void    horizontal_config(struct workspace *, int);
300 void    horizontal_stack(struct workspace *, struct swm_geometry *);
301 void    max_stack(struct workspace *, struct swm_geometry *);
302
303 struct ws_win *find_window(Window);
304
305 void    grabbuttons(struct ws_win *, int);
306 void    new_region(struct swm_screen *, int, int, int, int);
307 void    unmanage_window(struct ws_win *);
308 long    getstate(Window);
309
310 struct layout {
311         void            (*l_stack)(struct workspace *, struct swm_geometry *);
312         void            (*l_config)(struct workspace *, int);
313         u_int32_t       flags;
314 #define SWM_L_FOCUSPREV         (1<<0)
315 #define SWM_L_MAPONFOCUS        (1<<1)
316         char            *name;
317 } layouts[] =  {
318         /* stack,               configure */
319         { vertical_stack,       vertical_config,        0,      "[|]" },
320         { horizontal_stack,     horizontal_config,      0,      "[-]" },
321         { max_stack,            NULL,
322           SWM_L_MAPONFOCUS | SWM_L_FOCUSPREV,                   "[ ]" },
323         { NULL,                 NULL,                   0,      NULL  },
324 };
325
326 /* position of max_stack mode in the layouts array */
327 #define SWM_MAX_STACK           2
328
329 #define SWM_H_SLICE             (32)
330 #define SWM_V_SLICE             (32)
331
332 /* define work spaces */
333 struct workspace {
334         int                     idx;            /* workspace index */
335         struct layout           *cur_layout;    /* current layout handlers */
336         struct ws_win           *focus;         /* may be NULL */
337         struct ws_win           *focus_prev;    /* may be NULL */
338         struct swm_region       *r;             /* may be NULL */
339         struct swm_region       *old_r;         /* may be NULL */
340         struct ws_win_list      winlist;        /* list of windows in ws */
341         struct ws_win_list      unmanagedlist;  /* list of dead 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)
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 /* args to functions */
376 union arg {
377         int                     id;
378 #define SWM_ARG_ID_FOCUSNEXT    (0)
379 #define SWM_ARG_ID_FOCUSPREV    (1)
380 #define SWM_ARG_ID_FOCUSMAIN    (2)
381 #define SWM_ARG_ID_FOCUSCUR     (4)
382 #define SWM_ARG_ID_SWAPNEXT     (10)
383 #define SWM_ARG_ID_SWAPPREV     (11)
384 #define SWM_ARG_ID_SWAPMAIN     (12)
385 #define SWM_ARG_ID_MOVELAST     (13)
386 #define SWM_ARG_ID_MASTERSHRINK (20)
387 #define SWM_ARG_ID_MASTERGROW   (21)
388 #define SWM_ARG_ID_MASTERADD    (22)
389 #define SWM_ARG_ID_MASTERDEL    (23)
390 #define SWM_ARG_ID_STACKRESET   (30)
391 #define SWM_ARG_ID_STACKINIT    (31)
392 #define SWM_ARG_ID_CYCLEWS_UP   (40)
393 #define SWM_ARG_ID_CYCLEWS_DOWN (41)
394 #define SWM_ARG_ID_CYCLESC_UP   (42)
395 #define SWM_ARG_ID_CYCLESC_DOWN (43)
396 #define SWM_ARG_ID_STACKINC     (50)
397 #define SWM_ARG_ID_STACKDEC     (51)
398 #define SWM_ARG_ID_SS_ALL       (60)
399 #define SWM_ARG_ID_SS_WINDOW    (61)
400 #define SWM_ARG_ID_DONTCENTER   (70)
401 #define SWM_ARG_ID_CENTER       (71)
402 #define SWM_ARG_ID_KILLWINDOW   (80)
403 #define SWM_ARG_ID_DELETEWINDOW (81)
404         char                    **argv;
405 };
406
407 void    focus(struct swm_region *, union arg *);
408 void    focus_magic(struct ws_win *);
409
410 /* quirks */
411 struct quirk {
412         char                    *class;
413         char                    *name;
414         unsigned long           quirk;
415 #define SWM_Q_FLOAT             (1<<0)  /* float this window */
416 #define SWM_Q_TRANSSZ           (1<<1)  /* transiend window size too small */
417 #define SWM_Q_ANYWHERE          (1<<2)  /* don't position this window */
418 #define SWM_Q_XTERM_FONTADJ     (1<<3)  /* adjust xterm fonts when resizing */
419 #define SWM_Q_FULLSCREEN        (1<<4)  /* remove border */
420 #define SWM_Q_FOCUSPREV         (1<<5)  /* focus on caller */
421 };
422 int                             quirks_size = 0, quirks_length = 0;
423 struct quirk                    *quirks = NULL;
424
425 /*
426  * Supported EWMH hints should be added to
427  * both the enum and the ewmh array
428  */
429 enum { _NET_ACTIVE_WINDOW, _NET_MOVERESIZE_WINDOW, _NET_CLOSE_WINDOW,
430     _NET_WM_WINDOW_TYPE, _NET_WM_WINDOW_TYPE_DOCK,
431     _NET_WM_WINDOW_TYPE_TOOLBAR, _NET_WM_WINDOW_TYPE_UTILITY,
432     _NET_WM_WINDOW_TYPE_SPLASH, _NET_WM_WINDOW_TYPE_DIALOG,
433     _NET_WM_WINDOW_TYPE_NORMAL, _NET_WM_STATE,
434     _NET_WM_STATE_MAXIMIZED_HORZ, _NET_WM_STATE_MAXIMIZED_VERT,
435     _NET_WM_STATE_SKIP_TASKBAR, _NET_WM_STATE_SKIP_PAGER,
436     _NET_WM_STATE_HIDDEN, _NET_WM_STATE_ABOVE, _SWM_WM_STATE_MANUAL,
437     _NET_WM_STATE_FULLSCREEN, _NET_WM_ALLOWED_ACTIONS, _NET_WM_ACTION_MOVE,
438     _NET_WM_ACTION_RESIZE, _NET_WM_ACTION_FULLSCREEN, _NET_WM_ACTION_CLOSE,
439     SWM_EWMH_HINT_MAX };
440
441 struct ewmh_hint {
442         char    *name;
443         Atom     atom;
444 } ewmh[SWM_EWMH_HINT_MAX] =     {
445     /* must be in same order as in the enum */
446     {"_NET_ACTIVE_WINDOW", None},
447     {"_NET_MOVERESIZE_WINDOW", None},
448     {"_NET_CLOSE_WINDOW", None},
449     {"_NET_WM_WINDOW_TYPE", None},
450     {"_NET_WM_WINDOW_TYPE_DOCK", None},
451     {"_NET_WM_WINDOW_TYPE_TOOLBAR", None},
452     {"_NET_WM_WINDOW_TYPE_UTILITY", None},
453     {"_NET_WM_WINDOW_TYPE_SPLASH", None},
454     {"_NET_WM_WINDOW_TYPE_DIALOG", None},
455     {"_NET_WM_WINDOW_TYPE_NORMAL", None},
456     {"_NET_WM_STATE", None},
457     {"_NET_WM_STATE_MAXIMIZED_HORZ", None},
458     {"_NET_WM_STATE_MAXIMIZED_VERT", None},
459     {"_NET_WM_STATE_SKIP_TASKBAR", None},
460     {"_NET_WM_STATE_SKIP_PAGER", None},
461     {"_NET_WM_STATE_HIDDEN", None},
462     {"_NET_WM_STATE_ABOVE", None},
463     {"_SWM_WM_STATE_MANUAL", None},
464     {"_NET_WM_STATE_FULLSCREEN", None},
465     {"_NET_WM_ALLOWED_ACTIONS", None},
466     {"_NET_WM_ACTION_MOVE", None},
467     {"_NET_WM_ACTION_RESIZE", None},
468     {"_NET_WM_ACTION_FULLSCREEN", None},
469     {"_NET_WM_ACTION_CLOSE", None},
470 };
471
472 void    store_float_geom(struct ws_win *win, struct swm_region *r);
473 int     floating_toggle_win(struct ws_win *win);
474 void    spawn_select(struct swm_region *, union arg *, char *, int *);
475
476 int
477 get_property(Window id, Atom atom, long count, Atom type,
478     unsigned long *n, unsigned char **data)
479 {
480         int                     format, status;
481         unsigned long           tmp, extra;
482         unsigned long           *nitems;
483         Atom                    real;
484
485         nitems = n != NULL ? n : &tmp;
486         status = XGetWindowProperty(display, id, atom, 0L, count, False, type,
487             &real, &format, nitems, &extra, data);
488
489         if (status != Success)
490                 return False;
491         if (real != type)
492                 return False;
493
494         return True;
495 }
496
497 void
498 update_iconic(struct ws_win *win, int newv)
499 {
500         int32_t v = newv;
501         Atom iprop;
502
503         win->iconic = newv;
504
505         iprop = XInternAtom(display, "_SWM_ICONIC", False);
506         if (!iprop)
507                 return;
508         if (newv)
509                 XChangeProperty(display, win->id, iprop, XA_INTEGER, 32,
510                     PropModeReplace, (unsigned char *)&v, 1);
511         else
512                 XDeleteProperty(display, win->id, iprop);
513 }
514
515 int
516 get_iconic(struct ws_win *win)
517 {
518         int32_t v = 0;
519         int retfmt, status;
520         Atom iprop, rettype;
521         unsigned long nitems, extra;
522         unsigned char *prop = NULL;
523
524         iprop = XInternAtom(display, "_SWM_ICONIC", False);
525         if (!iprop)
526                 goto out;
527         status = XGetWindowProperty(display, win->id, iprop, 0L, 1L,
528             False, XA_INTEGER, &rettype, &retfmt, &nitems, &extra, &prop);
529         if (status != Success)
530                 goto out;
531         if (rettype != XA_INTEGER || retfmt != 32)
532                 goto out;
533         if (nitems != 1)
534                 goto out;
535         v = *((int32_t *)prop);
536
537 out:
538         if (prop != NULL)
539                 XFree(prop);
540         return (v);
541 }
542
543 void
544 setup_ewmh(void)
545 {
546         int                     i,j;
547         Atom                    sup_list;
548
549         sup_list = XInternAtom(display, "_NET_SUPPORTED", False);
550
551         for (i = 0; i < LENGTH(ewmh); i++)
552                 ewmh[i].atom = XInternAtom(display, ewmh[i].name, False);
553
554         for (i = 0; i < ScreenCount(display); i++) {
555                 /* Support check window will be created by workaround(). */
556
557                 /* Report supported atoms */
558                 XDeleteProperty(display, screens[i].root, sup_list);
559                 for (j = 0; j < LENGTH(ewmh); j++)
560                         XChangeProperty(display, screens[i].root,
561                             sup_list, XA_ATOM, 32,
562                             PropModeAppend, (unsigned char *)&ewmh[j].atom,1);
563         }
564 }
565
566 void
567 teardown_ewmh(void)
568 {
569         int                     i, success;
570         unsigned char           *data = NULL;
571         unsigned long           n;
572         Atom                    sup_check, sup_list;
573         Window                  id;
574
575         sup_check = XInternAtom(display, "_NET_SUPPORTING_WM_CHECK", False);
576         sup_list = XInternAtom(display, "_NET_SUPPORTED", False);
577
578         for (i = 0; i < ScreenCount(display); i++) {
579                 /* Get the support check window and destroy it */
580                 success = get_property(screens[i].root, sup_check, 1, XA_WINDOW,
581                     &n, &data);
582
583                 if (success) {
584                         id = data[0];
585                         XDestroyWindow(display, id);
586                         XDeleteProperty(display, screens[i].root, sup_check);
587                         XDeleteProperty(display, screens[i].root, sup_list);
588                 }
589
590                 XFree(data);
591         }
592 }
593
594 void
595 ewmh_autoquirk(struct ws_win *win)
596 {
597         int                     success, i;
598         unsigned long           *data = NULL;
599         unsigned long           n;
600         Atom                    type;
601
602         success = get_property(win->id, ewmh[_NET_WM_WINDOW_TYPE].atom, (~0L),
603             XA_ATOM, &n, (unsigned char **)&data);
604
605         if (!success) {
606                 XFree(data);
607                 return;
608         }
609
610         for (i = 0; i < n; i++) {
611                 type = data[i];
612                 if (type == ewmh[_NET_WM_WINDOW_TYPE_NORMAL].atom)
613                         break;
614                 if (type == ewmh[_NET_WM_WINDOW_TYPE_DOCK].atom ||
615                     type == ewmh[_NET_WM_WINDOW_TYPE_TOOLBAR].atom ||
616                     type == ewmh[_NET_WM_WINDOW_TYPE_UTILITY].atom) {
617                         win->floating = 1;
618                         win->quirks = SWM_Q_FLOAT | SWM_Q_ANYWHERE;
619                         break;
620                 }
621                 if (type == ewmh[_NET_WM_WINDOW_TYPE_SPLASH].atom ||
622                     type == ewmh[_NET_WM_WINDOW_TYPE_DIALOG].atom) {
623                         win->floating = 1;
624                         win->quirks = SWM_Q_FLOAT;
625                         break;
626                 }
627         }
628
629         XFree(data);
630 }
631
632 #define SWM_EWMH_ACTION_COUNT_MAX       (6)
633 #define EWMH_F_FULLSCREEN               (1<<0)
634 #define EWMH_F_ABOVE                    (1<<1)
635 #define EWMH_F_HIDDEN                   (1<<2)
636 #define EWMH_F_SKIP_PAGER               (1<<3)
637 #define EWMH_F_SKIP_TASKBAR             (1<<4)
638 #define SWM_F_MANUAL                    (1<<5)
639
640 int
641 ewmh_set_win_fullscreen(struct ws_win *win, int fs)
642 {
643         struct swm_geometry     rg;
644
645         if (!win->ws->r)
646                 return 0;
647
648         if (!win->floating)
649                 return 0;
650
651         DNPRINTF(SWM_D_MISC, "ewmh_set_win_fullscreen: win 0x%lx fs: %d\n",
652             win->id, fs);
653
654         rg = win->ws->r->g;
655
656         if (fs) {
657                 store_float_geom(win, win->ws->r);
658
659                 win->g.x = rg.x;
660                 win->g.y = rg.y;
661                 win->g.w = rg.w;
662                 win->g.h = rg.h;
663         } else {
664                 if (win->g_floatvalid) {
665                         /* refloat at last floating relative position */
666                         win->g.x = win->g_float.x - win->rg_float.x + rg.x;
667                         win->g.y = win->g_float.y - win->rg_float.y + rg.y;
668                         win->g.w = win->g_float.w;
669                         win->g.h = win->g_float.h;
670                 }
671         }
672
673         return 1;
674 }
675
676 void
677 ewmh_update_actions(struct ws_win *win)
678 {
679         Atom                    actions[SWM_EWMH_ACTION_COUNT_MAX];
680         int                     n = 0;
681
682         if (win == NULL)
683                 return;
684
685         actions[n++] = ewmh[_NET_WM_ACTION_CLOSE].atom;
686
687         if (win->floating) {
688                 actions[n++] = ewmh[_NET_WM_ACTION_MOVE].atom;
689                 actions[n++] = ewmh[_NET_WM_ACTION_RESIZE].atom;
690         }
691
692         XChangeProperty(display, win->id, ewmh[_NET_WM_ALLOWED_ACTIONS].atom,
693             XA_ATOM, 32, PropModeReplace, (unsigned char *)actions, n);
694 }
695
696 #define _NET_WM_STATE_REMOVE    0    /* remove/unset property */
697 #define _NET_WM_STATE_ADD       1    /* add/set property */
698 #define _NET_WM_STATE_TOGGLE    2    /* toggle property */
699
700 void
701 ewmh_update_win_state(struct ws_win *win, long state, long action)
702 {
703         unsigned int            mask = 0;
704         unsigned int            changed = 0;
705         unsigned int            orig_flags;
706
707         if (win == NULL)
708                 return;
709
710         if (state == ewmh[_NET_WM_STATE_FULLSCREEN].atom)
711                 mask = EWMH_F_FULLSCREEN;
712         if (state == ewmh[_NET_WM_STATE_ABOVE].atom)
713                 mask = EWMH_F_ABOVE;
714         if (state == ewmh[_SWM_WM_STATE_MANUAL].atom)
715                 mask = SWM_F_MANUAL;
716         if (state == ewmh[_NET_WM_STATE_SKIP_PAGER].atom)
717                 mask = EWMH_F_SKIP_PAGER;
718         if (state == ewmh[_NET_WM_STATE_SKIP_TASKBAR].atom)
719                 mask = EWMH_F_SKIP_TASKBAR;
720
721
722         orig_flags = win->ewmh_flags;
723
724         switch (action) {
725         case _NET_WM_STATE_REMOVE:
726                 win->ewmh_flags &= ~mask;
727                 break;
728         case _NET_WM_STATE_ADD:
729                 win->ewmh_flags |= mask;
730                 break;
731         case _NET_WM_STATE_TOGGLE:
732                 win->ewmh_flags ^= mask;
733                 break;
734         }
735
736         changed = (win->ewmh_flags & mask) ^ (orig_flags & mask) ? 1 : 0;
737
738         if (state == ewmh[_NET_WM_STATE_ABOVE].atom)
739                 if (changed)
740                         if (!floating_toggle_win(win))
741                                 win->ewmh_flags = orig_flags; /* revert */
742         if (state == ewmh[_SWM_WM_STATE_MANUAL].atom)
743                 if (changed)
744                         win->manual = (win->ewmh_flags & SWM_F_MANUAL) != 0;
745         if (state == ewmh[_NET_WM_STATE_FULLSCREEN].atom)
746                 if (changed)
747                         if (!ewmh_set_win_fullscreen(win,
748                             win->ewmh_flags & EWMH_F_FULLSCREEN))
749                                 win->ewmh_flags = orig_flags; /* revert */
750
751         XDeleteProperty(display, win->id, ewmh[_NET_WM_STATE].atom);
752
753         if (win->ewmh_flags & EWMH_F_FULLSCREEN)
754                 XChangeProperty(display, win->id, ewmh[_NET_WM_STATE].atom,
755                     XA_ATOM, 32, PropModeAppend,
756                     (unsigned char *)&ewmh[_NET_WM_STATE_FULLSCREEN].atom, 1);
757         if (win->ewmh_flags & EWMH_F_SKIP_PAGER)
758                 XChangeProperty(display, win->id, ewmh[_NET_WM_STATE].atom,
759                     XA_ATOM, 32, PropModeAppend,
760                     (unsigned char *)&ewmh[_NET_WM_STATE_SKIP_PAGER].atom, 1);
761         if (win->ewmh_flags & EWMH_F_SKIP_TASKBAR)
762                 XChangeProperty(display, win->id, ewmh[_NET_WM_STATE].atom,
763                     XA_ATOM, 32, PropModeAppend,
764                     (unsigned char *)&ewmh[_NET_WM_STATE_SKIP_TASKBAR].atom, 1);
765         if (win->ewmh_flags & EWMH_F_ABOVE)
766                 XChangeProperty(display, win->id, ewmh[_NET_WM_STATE].atom,
767                     XA_ATOM, 32, PropModeAppend,
768                     (unsigned char *)&ewmh[_NET_WM_STATE_ABOVE].atom, 1);
769         if (win->ewmh_flags & SWM_F_MANUAL)
770                 XChangeProperty(display, win->id, ewmh[_NET_WM_STATE].atom,
771                     XA_ATOM, 32, PropModeAppend,
772                     (unsigned char *)&ewmh[_SWM_WM_STATE_MANUAL].atom, 1);
773 }
774
775 void
776 ewmh_get_win_state(struct ws_win *win)
777 {
778         int                     success, i;
779         unsigned long           n;
780         Atom                    *states;
781
782         if (win == NULL)
783                 return;
784
785         win->ewmh_flags = 0;
786         if (win->floating)
787                 win->ewmh_flags |= EWMH_F_ABOVE;
788         if (win->manual)
789                 win->ewmh_flags |= SWM_F_MANUAL;
790
791         success = get_property(win->id, ewmh[_NET_WM_STATE].atom,
792             (~0L), XA_ATOM, &n, (unsigned char **)&states);
793
794         if (!success)
795                 return;
796
797         for (i = 0; i < n; i++)
798                 ewmh_update_win_state(win, states[i], _NET_WM_STATE_ADD);
799
800         XFree(states);
801 }
802
803 /* events */
804 #ifdef SWM_DEBUG
805 void
806 dumpevent(XEvent *e)
807 {
808         char                    *name = NULL;
809
810         switch (e->type) {
811         case KeyPress:
812                 name = "KeyPress";
813                 break;
814         case KeyRelease:
815                 name = "KeyRelease";
816                 break;
817         case ButtonPress:
818                 name = "ButtonPress";
819                 break;
820         case ButtonRelease:
821                 name = "ButtonRelease";
822                 break;
823         case MotionNotify:
824                 name = "MotionNotify";
825                 break;
826         case EnterNotify:
827                 name = "EnterNotify";
828                 break;
829         case LeaveNotify:
830                 name = "LeaveNotify";
831                 break;
832         case FocusIn:
833                 name = "FocusIn";
834                 break;
835         case FocusOut:
836                 name = "FocusOut";
837                 break;
838         case KeymapNotify:
839                 name = "KeymapNotify";
840                 break;
841         case Expose:
842                 name = "Expose";
843                 break;
844         case GraphicsExpose:
845                 name = "GraphicsExpose";
846                 break;
847         case NoExpose:
848                 name = "NoExpose";
849                 break;
850         case VisibilityNotify:
851                 name = "VisibilityNotify";
852                 break;
853         case CreateNotify:
854                 name = "CreateNotify";
855                 break;
856         case DestroyNotify:
857                 name = "DestroyNotify";
858                 break;
859         case UnmapNotify:
860                 name = "UnmapNotify";
861                 break;
862         case MapNotify:
863                 name = "MapNotify";
864                 break;
865         case MapRequest:
866                 name = "MapRequest";
867                 break;
868         case ReparentNotify:
869                 name = "ReparentNotify";
870                 break;
871         case ConfigureNotify:
872                 name = "ConfigureNotify";
873                 break;
874         case ConfigureRequest:
875                 name = "ConfigureRequest";
876                 break;
877         case GravityNotify:
878                 name = "GravityNotify";
879                 break;
880         case ResizeRequest:
881                 name = "ResizeRequest";
882                 break;
883         case CirculateNotify:
884                 name = "CirculateNotify";
885                 break;
886         case CirculateRequest:
887                 name = "CirculateRequest";
888                 break;
889         case PropertyNotify:
890                 name = "PropertyNotify";
891                 break;
892         case SelectionClear:
893                 name = "SelectionClear";
894                 break;
895         case SelectionRequest:
896                 name = "SelectionRequest";
897                 break;
898         case SelectionNotify:
899                 name = "SelectionNotify";
900                 break;
901         case ColormapNotify:
902                 name = "ColormapNotify";
903                 break;
904         case ClientMessage:
905                 name = "ClientMessage";
906                 break;
907         case MappingNotify:
908                 name = "MappingNotify";
909                 break;
910         }
911
912         if (name)
913                 DNPRINTF(SWM_D_EVENTQ ,"window: %lu event: %s (%d), %d "
914                     "remaining\n",
915                     e->xany.window, name, e->type, QLength(display));
916         else
917                 DNPRINTF(SWM_D_EVENTQ, "window: %lu unknown event %d, %d "
918                     "remaining\n",
919                     e->xany.window, e->type, QLength(display));
920 }
921
922 void
923 dumpwins(struct swm_region *r, union arg *args)
924 {
925         struct ws_win           *win;
926         unsigned int            state;
927         XWindowAttributes       wa;
928
929         if (r->ws == NULL) {
930                 fprintf(stderr, "invalid workspace\n");
931                 return;
932         }
933
934         fprintf(stderr, "=== managed window list ws %02d ===\n", r->ws->idx);
935
936         TAILQ_FOREACH(win, &r->ws->winlist, entry) {
937                 state = getstate(win->id);
938                 if (!XGetWindowAttributes(display, win->id, &wa))
939                         fprintf(stderr, "window: %lu failed "
940                             "XGetWindowAttributes\n", win->id);
941                 fprintf(stderr, "window: %lu map_state: %d state: %d "
942                     "transient: %lu\n",
943                     win->id, wa.map_state, state, win->transient);
944         }
945
946         fprintf(stderr, "===== unmanaged window list =====\n");
947         TAILQ_FOREACH(win, &r->ws->unmanagedlist, entry) {
948                 state = getstate(win->id);
949                 if (!XGetWindowAttributes(display, win->id, &wa))
950                         fprintf(stderr, "window: %lu failed "
951                             "XGetWindowAttributes\n", win->id);
952                 fprintf(stderr, "window: %lu map_state: %d state: %d "
953                     "transient: %lu\n",
954                     win->id, wa.map_state, state, win->transient);
955         }
956
957         fprintf(stderr, "=================================\n");
958 }
959 #else
960 #define dumpevent(e)
961 void
962 dumpwins(struct swm_region *r, union arg *args)
963 {
964 }
965 #endif /* SWM_DEBUG */
966
967 void                    expose(XEvent *);
968 void                    keypress(XEvent *);
969 void                    buttonpress(XEvent *);
970 void                    configurerequest(XEvent *);
971 void                    configurenotify(XEvent *);
972 void                    destroynotify(XEvent *);
973 void                    enternotify(XEvent *);
974 void                    focusevent(XEvent *);
975 void                    mapnotify(XEvent *);
976 void                    mappingnotify(XEvent *);
977 void                    maprequest(XEvent *);
978 void                    propertynotify(XEvent *);
979 void                    unmapnotify(XEvent *);
980 void                    visibilitynotify(XEvent *);
981 void                    clientmessage(XEvent *);
982
983 void                    (*handler[LASTEvent])(XEvent *) = {
984                                 [Expose] = expose,
985                                 [KeyPress] = keypress,
986                                 [ButtonPress] = buttonpress,
987                                 [ConfigureRequest] = configurerequest,
988                                 [ConfigureNotify] = configurenotify,
989                                 [DestroyNotify] = destroynotify,
990                                 [EnterNotify] = enternotify,
991                                 [FocusIn] = focusevent,
992                                 [FocusOut] = focusevent,
993                                 [MapNotify] = mapnotify,
994                                 [MappingNotify] = mappingnotify,
995                                 [MapRequest] = maprequest,
996                                 [PropertyNotify] = propertynotify,
997                                 [UnmapNotify] = unmapnotify,
998                                 [VisibilityNotify] = visibilitynotify,
999                                 [ClientMessage] = clientmessage,
1000 };
1001
1002 void
1003 sighdlr(int sig)
1004 {
1005         int                     saved_errno, status;
1006         pid_t                   pid;
1007
1008         saved_errno = errno;
1009
1010         switch (sig) {
1011         case SIGCHLD:
1012                 while ((pid = waitpid(WAIT_ANY, &status, WNOHANG)) != 0) {
1013                         if (pid == -1) {
1014                                 if (errno == EINTR)
1015                                         continue;
1016 #ifdef SWM_DEBUG
1017                                 if (errno != ECHILD)
1018                                         warn("sighdlr: waitpid");
1019 #endif /* SWM_DEBUG */
1020                                 break;
1021                         }
1022                         if (pid == searchpid)
1023                                 search_resp = 1;
1024
1025 #ifdef SWM_DEBUG
1026                         if (WIFEXITED(status)) {
1027                                 if (WEXITSTATUS(status) != 0)
1028                                         warnx("sighdlr: child exit status: %d",
1029                                             WEXITSTATUS(status));
1030                         } else
1031                                 warnx("sighdlr: child is terminated "
1032                                     "abnormally");
1033 #endif /* SWM_DEBUG */
1034                 }
1035                 break;
1036
1037         case SIGHUP:
1038                 restart_wm = 1;
1039                 break;
1040         case SIGINT:
1041         case SIGTERM:
1042         case SIGQUIT:
1043                 running = 0;
1044                 break;
1045         }
1046
1047         errno = saved_errno;
1048 }
1049
1050 unsigned long
1051 name_to_color(char *colorname)
1052 {
1053         Colormap                cmap;
1054         Status                  status;
1055         XColor                  screen_def, exact_def;
1056         unsigned long           result = 0;
1057         char                    cname[32] = "#";
1058
1059         cmap = DefaultColormap(display, screens[0].idx);
1060         status = XAllocNamedColor(display, cmap, colorname,
1061             &screen_def, &exact_def);
1062         if (!status) {
1063                 strlcat(cname, colorname + 2, sizeof cname - 1);
1064                 status = XAllocNamedColor(display, cmap, cname, &screen_def,
1065                     &exact_def);
1066         }
1067         if (status)
1068                 result = screen_def.pixel;
1069         else
1070                 fprintf(stderr, "color '%s' not found.\n", colorname);
1071
1072         return (result);
1073 }
1074
1075 void
1076 setscreencolor(char *val, int i, int c)
1077 {
1078         if (i > 0 && i <= ScreenCount(display)) {
1079                 screens[i - 1].c[c].color = name_to_color(val);
1080                 free(screens[i - 1].c[c].name);
1081                 if ((screens[i - 1].c[c].name = strdup(val)) == NULL)
1082                         errx(1, "strdup");
1083         } else if (i == -1) {
1084                 for (i = 0; i < ScreenCount(display); i++) {
1085                         screens[i].c[c].color = name_to_color(val);
1086                         free(screens[i].c[c].name);
1087                         if ((screens[i].c[c].name = strdup(val)) == NULL)
1088                                 errx(1, "strdup");
1089                 }
1090         } else
1091                 errx(1, "invalid screen index: %d out of bounds (maximum %d)\n",
1092                     i, ScreenCount(display));
1093 }
1094
1095 void
1096 custom_region(char *val)
1097 {
1098         unsigned int                    sidx, x, y, w, h;
1099
1100         if (sscanf(val, "screen[%u]:%ux%u+%u+%u", &sidx, &w, &h, &x, &y) != 5)
1101                 errx(1, "invalid custom region, "
1102                     "should be 'screen[<n>]:<n>x<n>+<n>+<n>\n");
1103         if (sidx < 1 || sidx > ScreenCount(display))
1104                 errx(1, "invalid screen index: %d out of bounds (maximum %d)\n",
1105                     sidx, ScreenCount(display));
1106         sidx--;
1107
1108         if (w < 1 || h < 1)
1109                 errx(1, "region %ux%u+%u+%u too small\n", w, h, x, y);
1110
1111         if (x  < 0 || x > DisplayWidth(display, sidx) ||
1112             y < 0 || y > DisplayHeight(display, sidx) ||
1113             w + x > DisplayWidth(display, sidx) ||
1114             h + y > DisplayHeight(display, sidx)) {
1115                 fprintf(stderr, "ignoring region %ux%u+%u+%u "
1116                     "- not within screen boundaries "
1117                     "(%ux%u)\n", w, h, x, y,
1118                     DisplayWidth(display, sidx), DisplayHeight(display, sidx));
1119                 return;
1120         }
1121
1122         new_region(&screens[sidx], x, y, w, h);
1123 }
1124
1125 void
1126 socket_setnonblock(int fd)
1127 {
1128         int                     flags;
1129
1130         if ((flags = fcntl(fd, F_GETFL, 0)) == -1)
1131                 err(1, "fcntl F_GETFL");
1132         flags |= O_NONBLOCK;
1133         if ((flags = fcntl(fd, F_SETFL, flags)) == -1)
1134                 err(1, "fcntl F_SETFL");
1135 }
1136
1137 void
1138 bar_print(struct swm_region *r, char *s)
1139 {
1140         XClearWindow(display, r->bar_window);
1141         XSetForeground(display, bar_gc, r->s->c[SWM_S_COLOR_BAR_FONT].color);
1142         XDrawString(display, r->bar_window, bar_gc, 4, bar_fs->ascent, s,
1143             strlen(s));
1144 }
1145
1146 void
1147 bar_extra_stop(void)
1148 {
1149         if (bar_pipe[0]) {
1150                 close(bar_pipe[0]);
1151                 bzero(bar_pipe, sizeof bar_pipe);
1152         }
1153         if (bar_pid) {
1154                 kill(bar_pid, SIGTERM);
1155                 bar_pid = 0;
1156         }
1157         strlcpy(bar_ext, "", sizeof bar_ext);
1158         bar_extra = 0;
1159 }
1160
1161 void
1162 bar_class_name(char *s, ssize_t sz, struct ws_win *cur_focus)
1163 {
1164         int                     do_class, do_name;
1165         Status                  status;
1166         XClassHint              *xch = NULL;
1167
1168         if ((title_name_enabled == 1 || title_class_enabled == 1) &&
1169             cur_focus != NULL) {
1170                 if ((xch = XAllocClassHint()) == NULL)
1171                         goto out;
1172                 status = XGetClassHint(display, cur_focus->id, xch);
1173                 if (status == BadWindow || status == BadAlloc)
1174                         goto out;
1175                 do_class = (title_class_enabled && xch->res_class != NULL);
1176                 do_name = (title_name_enabled && xch->res_name != NULL);
1177                 if (do_class)
1178                         strlcat(s, xch->res_class, sz);
1179                 if (do_class && do_name)
1180                         strlcat(s, ":", sz);
1181                 if (do_name)
1182                         strlcat(s, xch->res_name, sz);
1183                 strlcat(s, "    ", sz);
1184         }
1185 out:
1186         if (xch)
1187                 XFree(xch);
1188 }
1189
1190 void
1191 bar_window_name(char *s, ssize_t sz, struct ws_win *cur_focus)
1192 {
1193         char                    *title;
1194
1195         if (window_name_enabled && cur_focus != NULL) {
1196                 XFetchName(display, cur_focus->id, &title);
1197                 if (title) {
1198                         if (cur_focus->floating)
1199                                 strlcat(s, "(f) ", sz);
1200                         strlcat(s, title, sz);
1201                         strlcat(s, " ", sz);
1202                         XFree(title);
1203                 }
1204         }
1205 }
1206
1207 void
1208 bar_update(void)
1209 {
1210         time_t                  tmt;
1211         struct tm               tm;
1212         struct swm_region       *r;
1213         int                     i, x;
1214         size_t                  len;
1215         char                    s[SWM_BAR_MAX];
1216         char                    cn[SWM_BAR_MAX];
1217         char                    loc[SWM_BAR_MAX];
1218         char                    *b;
1219         char                    *stack = "";
1220
1221         if (bar_enabled == 0)
1222                 return;
1223         if (bar_extra && bar_extra_running) {
1224                 /* ignore short reads; it'll correct itself */
1225                 while ((b = fgetln(stdin, &len)) != NULL)
1226                         if (b && b[len - 1] == '\n') {
1227                                 b[len - 1] = '\0';
1228                                 strlcpy(bar_ext, b, sizeof bar_ext);
1229                         }
1230                 if (b == NULL && errno != EAGAIN) {
1231                         fprintf(stderr, "bar_extra failed: errno: %d %s\n",
1232                             errno, strerror(errno));
1233                         bar_extra_stop();
1234                 }
1235         } else
1236                 strlcpy(bar_ext, "", sizeof bar_ext);
1237
1238         if (clock_enabled == 0)
1239                 strlcpy(s, "", sizeof s);
1240         else {
1241                 time(&tmt);
1242                 localtime_r(&tmt, &tm);
1243                 strftime(s, sizeof s, clock_format, &tm);
1244                 strlcat(s, "    ", sizeof s);
1245         }
1246
1247         for (i = 0; i < ScreenCount(display); i++) {
1248                 x = 1;
1249                 TAILQ_FOREACH(r, &screens[i].rl, entry) {
1250                         strlcpy(cn, "", sizeof cn);
1251                         if (r && r->ws) {
1252                                 bar_class_name(cn, sizeof cn, r->ws->focus);
1253                                 bar_window_name(cn, sizeof cn, r->ws->focus);
1254                         }
1255
1256                         if (stack_enabled)
1257                                 stack = r->ws->cur_layout->name;
1258
1259                         snprintf(loc, sizeof loc, "%d:%d %s   %s%s    %s    %s",
1260                             x++, r->ws->idx + 1, stack, s, cn, bar_ext,
1261                             bar_vertext);
1262                         bar_print(r, loc);
1263                 }
1264         }
1265         alarm(bar_delay);
1266 }
1267
1268 void
1269 bar_signal(int sig)
1270 {
1271         bar_alarm = 1;
1272 }
1273
1274 void
1275 bar_toggle(struct swm_region *r, union arg *args)
1276 {
1277         struct swm_region       *tmpr;
1278         int                     i, sc = ScreenCount(display);
1279
1280         DNPRINTF(SWM_D_MISC, "bar_toggle\n");
1281
1282         if (bar_enabled)
1283                 for (i = 0; i < sc; i++)
1284                         TAILQ_FOREACH(tmpr, &screens[i].rl, entry)
1285                                 XUnmapWindow(display, tmpr->bar_window);
1286         else
1287                 for (i = 0; i < sc; i++)
1288                         TAILQ_FOREACH(tmpr, &screens[i].rl, entry)
1289                                 XMapRaised(display, tmpr->bar_window);
1290
1291         bar_enabled = !bar_enabled;
1292
1293         stack();
1294         /* must be after stack */
1295         bar_update();
1296 }
1297
1298 void
1299 bar_refresh(void)
1300 {
1301         XSetWindowAttributes    wa;
1302         struct swm_region       *r;
1303         int                     i;
1304
1305         /* do this here because the conf file is in memory */
1306         if (bar_extra && bar_extra_running == 0 && bar_argv[0]) {
1307                 /* launch external status app */
1308                 bar_extra_running = 1;
1309                 if (pipe(bar_pipe) == -1)
1310                         err(1, "pipe error");
1311                 socket_setnonblock(bar_pipe[0]);
1312                 socket_setnonblock(bar_pipe[1]); /* XXX hmmm, really? */
1313                 if (dup2(bar_pipe[0], 0) == -1)
1314                         errx(1, "dup2");
1315                 if (dup2(bar_pipe[1], 1) == -1)
1316                         errx(1, "dup2");
1317                 if (signal(SIGPIPE, SIG_IGN) == SIG_ERR)
1318                         err(1, "could not disable SIGPIPE");
1319                 switch (bar_pid = fork()) {
1320                 case -1:
1321                         err(1, "cannot fork");
1322                         break;
1323                 case 0: /* child */
1324                         close(bar_pipe[0]);
1325                         execvp(bar_argv[0], bar_argv);
1326                         err(1, "%s external app failed", bar_argv[0]);
1327                         break;
1328                 default: /* parent */
1329                         close(bar_pipe[1]);
1330                         break;
1331                 }
1332         }
1333
1334         bzero(&wa, sizeof wa);
1335         for (i = 0; i < ScreenCount(display); i++)
1336                 TAILQ_FOREACH(r, &screens[i].rl, entry) {
1337                         wa.border_pixel =
1338                             screens[i].c[SWM_S_COLOR_BAR_BORDER].color;
1339                         wa.background_pixel =
1340                             screens[i].c[SWM_S_COLOR_BAR].color;
1341                         XChangeWindowAttributes(display, r->bar_window,
1342                             CWBackPixel | CWBorderPixel, &wa);
1343                 }
1344         bar_update();
1345 }
1346
1347 void
1348 bar_setup(struct swm_region *r)
1349 {
1350         int                     i, x, y;
1351
1352         if (bar_fs) {
1353                 XFreeFont(display, bar_fs);
1354                 bar_fs = NULL;
1355         }
1356
1357         for (i = 0; bar_fonts[i] != NULL; i++) {
1358                 bar_fs = XLoadQueryFont(display, bar_fonts[i]);
1359                 if (bar_fs) {
1360                         bar_fidx = i;
1361                         break;
1362                 }
1363         }
1364         if (bar_fonts[i] == NULL)
1365                         errx(1, "couldn't load font");
1366         if (bar_fs == NULL)
1367                 errx(1, "couldn't create font structure");
1368
1369         bar_height = bar_fs->ascent + bar_fs->descent + 1 +
1370             2 * bar_border_width;
1371         x = X(r);
1372         y = bar_at_bottom ? (Y(r) + HEIGHT(r) - bar_height) : Y(r);
1373
1374         r->bar_window = XCreateSimpleWindow(display,
1375             r->s->root, x, y, WIDTH(r) - 2 * bar_border_width,
1376             bar_height - 2 * bar_border_width,
1377             bar_border_width, r->s->c[SWM_S_COLOR_BAR_BORDER].color,
1378             r->s->c[SWM_S_COLOR_BAR].color);
1379         bar_gc = XCreateGC(display, r->bar_window, 0, &bar_gcv);
1380         XSetFont(display, bar_gc, bar_fs->fid);
1381         XSelectInput(display, r->bar_window, VisibilityChangeMask);
1382         if (bar_enabled)
1383                 XMapRaised(display, r->bar_window);
1384         DNPRINTF(SWM_D_MISC, "bar_setup: bar_window %lu\n", r->bar_window);
1385
1386         if (signal(SIGALRM, bar_signal) == SIG_ERR)
1387                 err(1, "could not install bar_signal");
1388         bar_refresh();
1389 }
1390
1391 void
1392 drain_enter_notify(void)
1393 {
1394         int                     i = 0;
1395         XEvent                  cne;
1396
1397         while (XCheckMaskEvent(display, EnterWindowMask, &cne))
1398                 i++;
1399
1400         DNPRINTF(SWM_D_MISC, "drain_enter_notify: drained %d\n", i);
1401 }
1402
1403 void
1404 set_win_state(struct ws_win *win, long state)
1405 {
1406         long                    data[] = {state, None};
1407
1408         DNPRINTF(SWM_D_EVENT, "set_win_state: window: %lu\n", win->id);
1409
1410         if (win == NULL)
1411                 return;
1412
1413         XChangeProperty(display, win->id, astate, astate, 32, PropModeReplace,
1414             (unsigned char *)data, 2);
1415 }
1416
1417 long
1418 getstate(Window w)
1419 {
1420         long                    result = -1;
1421         unsigned char           *p = NULL;
1422         unsigned long           n;
1423
1424         if (!get_property(w, astate, 2L, astate, &n, &p))
1425                 return (-1);
1426         if (n != 0)
1427                 result = *((long *)p);
1428         XFree(p);
1429         return (result);
1430 }
1431
1432 void
1433 version(struct swm_region *r, union arg *args)
1434 {
1435         bar_version = !bar_version;
1436         if (bar_version)
1437                 snprintf(bar_vertext, sizeof bar_vertext, "Version: %s CVS: %s",
1438                     SWM_VERSION, cvstag);
1439         else
1440                 strlcpy(bar_vertext, "", sizeof bar_vertext);
1441         bar_update();
1442 }
1443
1444 void
1445 client_msg(struct ws_win *win, Atom a)
1446 {
1447         XClientMessageEvent     cm;
1448
1449         if (win == NULL)
1450                 return;
1451
1452         bzero(&cm, sizeof cm);
1453         cm.type = ClientMessage;
1454         cm.window = win->id;
1455         cm.message_type = aprot;
1456         cm.format = 32;
1457         cm.data.l[0] = a;
1458         cm.data.l[1] = CurrentTime;
1459         XSendEvent(display, win->id, False, 0L, (XEvent *)&cm);
1460 }
1461
1462 void
1463 config_win(struct ws_win *win, XConfigureRequestEvent  *ev)
1464 {
1465         XConfigureEvent         ce;
1466
1467         if (win == NULL)
1468                 return;
1469
1470         if (ev == NULL) {
1471                 DNPRINTF(SWM_D_MISC,
1472                     "config_win: win %lu x %d y %d w %d h %d\n",
1473                     win->id, win->g.x, win->g.y, win->g.w, win->g.h);
1474
1475                 ce.type = ConfigureNotify;
1476                 ce.display = display;
1477                 ce.event = win->id;
1478                 ce.window = win->id;
1479                 ce.x = win->g.x;
1480                 ce.y = win->g.y;
1481                 ce.width = win->g.w;
1482                 ce.height = win->g.h;
1483                 ce.border_width = border_width;
1484                 ce.above = None;
1485                 ce.override_redirect = False;
1486         } else {
1487                 DNPRINTF(SWM_D_MISC,
1488                     "config_win: ev win %lu x %d y %d w %d h %d\n",
1489                     ev->window, ev->x, ev->y, ev->width, ev->height);
1490                 ce.type = ConfigureNotify;
1491                 ce.display = ev->display;
1492                 ce.event = ev->window;
1493                 ce.window = ev->window;
1494                 ce.x = ev->x;
1495                 ce.y = ev->y;
1496                 ce.width = ev->width;
1497                 ce.height = ev->height;
1498                 ce.border_width = ev->border_width;
1499                 ce.above = ev->above;
1500                 ce.override_redirect = False;
1501         }
1502
1503         XSendEvent(display, win->id, False, StructureNotifyMask, (XEvent *)&ce);
1504 }
1505
1506 int
1507 count_win(struct workspace *ws, int count_transient)
1508 {
1509         struct ws_win           *win;
1510         int                     count = 0;
1511
1512         TAILQ_FOREACH(win, &ws->winlist, entry) {
1513                 if (count_transient == 0 && win->floating)
1514                         continue;
1515                 if (count_transient == 0 && win->transient)
1516                         continue;
1517                 if (win->iconic)
1518                         continue;
1519                 count++;
1520         }
1521         DNPRINTF(SWM_D_MISC, "count_win: %d\n", count);
1522
1523         return (count);
1524 }
1525
1526 void
1527 quit(struct swm_region *r, union arg *args)
1528 {
1529         DNPRINTF(SWM_D_MISC, "quit\n");
1530         running = 0;
1531 }
1532
1533 void
1534 unmap_window(struct ws_win *win)
1535 {
1536         if (win == NULL)
1537                 return;
1538
1539         /* don't unmap again */
1540         if (getstate(win->id) == IconicState)
1541                 return;
1542
1543         set_win_state(win, IconicState);
1544
1545         XUnmapWindow(display, win->id);
1546         XSetWindowBorder(display, win->id,
1547             win->s->c[SWM_S_COLOR_UNFOCUS].color);
1548 }
1549
1550 void
1551 unmap_all(void)
1552 {
1553         struct ws_win           *win;
1554         int                     i, j;
1555
1556         for (i = 0; i < ScreenCount(display); i++)
1557                 for (j = 0; j < SWM_WS_MAX; j++)
1558                         TAILQ_FOREACH(win, &screens[i].ws[j].winlist, entry)
1559                                 unmap_window(win);
1560 }
1561
1562 void
1563 fake_keypress(struct ws_win *win, int keysym, int modifiers)
1564 {
1565         XKeyEvent event;
1566
1567         if (win == NULL)
1568                 return;
1569
1570         event.display = display;        /* Ignored, but what the hell */
1571         event.window = win->id;
1572         event.root = win->s->root;
1573         event.subwindow = None;
1574         event.time = CurrentTime;
1575         event.x = win->g.x;
1576         event.y = win->g.y;
1577         event.x_root = 1;
1578         event.y_root = 1;
1579         event.same_screen = True;
1580         event.keycode = XKeysymToKeycode(display, keysym);
1581         event.state = modifiers;
1582
1583         event.type = KeyPress;
1584         XSendEvent(event.display, event.window, True,
1585             KeyPressMask, (XEvent *)&event);
1586
1587         event.type = KeyRelease;
1588         XSendEvent(event.display, event.window, True,
1589             KeyPressMask, (XEvent *)&event);
1590
1591 }
1592
1593 void
1594 restart(struct swm_region *r, union arg *args)
1595 {
1596         DNPRINTF(SWM_D_MISC, "restart: %s\n", start_argv[0]);
1597
1598         /* disable alarm because the following code may not be interrupted */
1599         alarm(0);
1600         if (signal(SIGALRM, SIG_IGN) == SIG_ERR)
1601                 errx(1, "can't disable alarm");
1602
1603         bar_extra_stop();
1604         bar_extra = 1;
1605         unmap_all();
1606         XCloseDisplay(display);
1607         execvp(start_argv[0], start_argv);
1608         fprintf(stderr, "execvp failed\n");
1609         perror(" failed");
1610         quit(NULL, NULL);
1611 }
1612
1613 struct swm_region *
1614 root_to_region(Window root)
1615 {
1616         struct swm_region       *r = NULL;
1617         Window                  rr, cr;
1618         int                     i, x, y, wx, wy;
1619         unsigned int            mask;
1620
1621         for (i = 0; i < ScreenCount(display); i++)
1622                 if (screens[i].root == root)
1623                         break;
1624
1625         if (XQueryPointer(display, screens[i].root,
1626             &rr, &cr, &x, &y, &wx, &wy, &mask) != False) {
1627                 /* choose a region based on pointer location */
1628                 TAILQ_FOREACH(r, &screens[i].rl, entry)
1629                         if (x >= X(r) && x <= X(r) + WIDTH(r) &&
1630                             y >= Y(r) && y <= Y(r) + HEIGHT(r))
1631                                 break;
1632         }
1633
1634         if (r == NULL)
1635                 r = TAILQ_FIRST(&screens[i].rl);
1636
1637         return (r);
1638 }
1639
1640 struct ws_win *
1641 find_unmanaged_window(Window id)
1642 {
1643         struct ws_win           *win;
1644         int                     i, j;
1645
1646         for (i = 0; i < ScreenCount(display); i++)
1647                 for (j = 0; j < SWM_WS_MAX; j++)
1648                         TAILQ_FOREACH(win, &screens[i].ws[j].unmanagedlist,
1649                             entry)
1650                                 if (id == win->id)
1651                                         return (win);
1652         return (NULL);
1653 }
1654
1655 struct ws_win *
1656 find_window(Window id)
1657 {
1658         struct ws_win           *win;
1659         Window                  wrr, wpr, *wcr = NULL;
1660         int                     i, j;
1661         unsigned int            nc;
1662
1663         for (i = 0; i < ScreenCount(display); i++)
1664                 for (j = 0; j < SWM_WS_MAX; j++)
1665                         TAILQ_FOREACH(win, &screens[i].ws[j].winlist, entry)
1666                                 if (id == win->id)
1667                                         return (win);
1668
1669         /* if we were looking for the parent return that window instead */
1670         if (XQueryTree(display, id, &wrr, &wpr, &wcr, &nc) == 0)
1671                 return (NULL);
1672         if (wcr)
1673                 XFree(wcr);
1674
1675         /* ignore not found and root */
1676         if (wpr == 0 || wrr == wpr)
1677                 return (NULL);
1678
1679         /* look for parent */
1680         for (i = 0; i < ScreenCount(display); i++)
1681                 for (j = 0; j < SWM_WS_MAX; j++)
1682                         TAILQ_FOREACH(win, &screens[i].ws[j].winlist, entry)
1683                                 if (wpr == win->id)
1684                                         return (win);
1685
1686         return (NULL);
1687 }
1688
1689 void
1690 spawn(struct swm_region *r, union arg *args, int close_fd)
1691 {
1692         int                     fd;
1693         char                    *ret = NULL;
1694
1695         DNPRINTF(SWM_D_MISC, "spawn: %s\n", args->argv[0]);
1696
1697         if (display)
1698                 close(ConnectionNumber(display));
1699
1700         setenv("LD_PRELOAD", SWM_LIB, 1);
1701
1702         if (asprintf(&ret, "%d", r->ws->idx) == -1) {
1703                 perror("_SWM_WS");
1704                 _exit(1);
1705         }
1706         setenv("_SWM_WS", ret, 1);
1707         free(ret);
1708         ret = NULL;
1709
1710         if (asprintf(&ret, "%d", getpid()) == -1) {
1711                 perror("_SWM_PID");
1712                 _exit(1);
1713         }
1714         setenv("_SWM_PID", ret, 1);
1715         free(ret);
1716         ret = NULL;
1717
1718         if (setsid() == -1) {
1719                 perror("setsid");
1720                 _exit(1);
1721         }
1722
1723         if (close_fd) {
1724                 /*
1725                  * close stdin and stdout to prevent interaction between apps
1726                  * and the baraction script
1727                  * leave stderr open to record errors
1728                 */
1729                 if ((fd = open(_PATH_DEVNULL, O_RDWR, 0)) == -1) {
1730                         perror("open");
1731                         _exit(1);
1732                 }
1733                 dup2(fd, STDIN_FILENO);
1734                 dup2(fd, STDOUT_FILENO);
1735                 if (fd > 2)
1736                         close(fd);
1737         }
1738
1739         execvp(args->argv[0], args->argv);
1740
1741         perror("execvp");
1742         _exit(1);
1743 }
1744
1745 void
1746 spawnterm(struct swm_region *r, union arg *args)
1747 {
1748         DNPRINTF(SWM_D_MISC, "spawnterm\n");
1749
1750         if (term_width)
1751                 setenv("_SWM_XTERM_FONTADJ", "", 1);
1752         if (fork() == 0)
1753                 spawn(r, args, 1);
1754 }
1755
1756 void
1757 kill_refs(struct ws_win *win)
1758 {
1759         int                     i, x;
1760         struct swm_region       *r;
1761         struct workspace        *ws;
1762
1763         if (win == NULL)
1764                 return;
1765
1766         for (i = 0; i < ScreenCount(display); i++)
1767                 TAILQ_FOREACH(r, &screens[i].rl, entry)
1768                         for (x = 0; x < SWM_WS_MAX; x++) {
1769                                 ws = &r->s->ws[x];
1770                                 if (win == ws->focus)
1771                                         ws->focus = NULL;
1772                                 if (win == ws->focus_prev)
1773                                         ws->focus_prev = NULL;
1774                         }
1775 }
1776
1777 int
1778 validate_win(struct ws_win *testwin)
1779 {
1780         struct ws_win           *win;
1781         struct workspace        *ws;
1782         struct swm_region       *r;
1783         int                     i, x, foundit = 0;
1784
1785         if (testwin == NULL)
1786                 return (0);
1787
1788         for (i = 0, foundit = 0; i < ScreenCount(display); i++)
1789                 TAILQ_FOREACH(r, &screens[i].rl, entry)
1790                         for (x = 0; x < SWM_WS_MAX; x++) {
1791                                 ws = &r->s->ws[x];
1792                                 TAILQ_FOREACH(win, &ws->winlist, entry)
1793                                         if (win == testwin)
1794                                                 return (0);
1795                         }
1796         return (1);
1797 }
1798
1799 int
1800 validate_ws(struct workspace *testws)
1801 {
1802         struct swm_region       *r;
1803         struct workspace        *ws;
1804         int                     foundit, i, x;
1805
1806         /* validate all ws */
1807         for (i = 0, foundit = 0; i < ScreenCount(display); i++)
1808                 TAILQ_FOREACH(r, &screens[i].rl, entry)
1809                         for (x = 0; x < SWM_WS_MAX; x++) {
1810                                 ws = &r->s->ws[x];
1811                                 if (ws == testws)
1812                                         return (0);
1813                         }
1814         return (1);
1815 }
1816
1817 void
1818 unfocus_win(struct ws_win *win)
1819 {
1820         XEvent                  cne;
1821         Window                  none = None;
1822
1823         DNPRINTF(SWM_D_FOCUS, "unfocus_win: id: %lu\n", WINID(win));
1824
1825         if (win == NULL)
1826                 return;
1827         if (win->ws == NULL)
1828                 return;
1829
1830         if (validate_ws(win->ws))
1831                 return; /* XXX this gets hit with thunderbird, needs fixing */
1832
1833         if (win->ws->r == NULL)
1834                 return;
1835
1836         if (validate_win(win)) {
1837                 kill_refs(win);
1838                 return;
1839         }
1840
1841         if (win->ws->focus == win) {
1842                 win->ws->focus = NULL;
1843                 win->ws->focus_prev = win;
1844         }
1845
1846         if (validate_win(win->ws->focus)) {
1847                 kill_refs(win->ws->focus);
1848                 win->ws->focus = NULL;
1849         }
1850         if (validate_win(win->ws->focus_prev)) {
1851                 kill_refs(win->ws->focus_prev);
1852                 win->ws->focus_prev = NULL;
1853         }
1854
1855         /* drain all previous unfocus events */
1856         while (XCheckTypedEvent(display, FocusOut, &cne) == True)
1857                 ;
1858
1859         grabbuttons(win, 0);
1860         XSetWindowBorder(display, win->id,
1861             win->ws->r->s->c[SWM_S_COLOR_UNFOCUS].color);
1862
1863         XChangeProperty(display, win->s->root,
1864             ewmh[_NET_ACTIVE_WINDOW].atom, XA_WINDOW, 32,
1865             PropModeReplace, (unsigned char *)&none,1);
1866 }
1867
1868 void
1869 unfocus_all(void)
1870 {
1871         struct ws_win           *win;
1872         int                     i, j;
1873
1874         DNPRINTF(SWM_D_FOCUS, "unfocus_all\n");
1875
1876         for (i = 0; i < ScreenCount(display); i++)
1877                 for (j = 0; j < SWM_WS_MAX; j++)
1878                         TAILQ_FOREACH(win, &screens[i].ws[j].winlist, entry)
1879                                 unfocus_win(win);
1880 }
1881
1882 void
1883 focus_win(struct ws_win *win)
1884 {
1885         XEvent                  cne;
1886         Window                  cur_focus;
1887         int                     rr;
1888         struct ws_win           *cfw = NULL;
1889
1890
1891         DNPRINTF(SWM_D_FOCUS, "focus_win: id: %lu\n", win ? win->id : 0);
1892
1893         if (win == NULL)
1894                 return;
1895         if (win->ws == NULL)
1896                 return;
1897
1898         if (validate_ws(win->ws))
1899                 return; /* XXX this gets hit with thunderbird, needs fixing */
1900
1901         if (validate_win(win)) {
1902                 kill_refs(win);
1903                 return;
1904         }
1905
1906         if (validate_win(win)) {
1907                 kill_refs(win);
1908                 return;
1909         }
1910
1911         XGetInputFocus(display, &cur_focus, &rr);
1912         if ((cfw = find_window(cur_focus)) != NULL)
1913                 unfocus_win(cfw);
1914         else {
1915                 /* use larger hammer since the window was killed somehow */
1916                 TAILQ_FOREACH(cfw, &win->ws->winlist, entry)
1917                         if (cfw->ws && cfw->ws->r && cfw->ws->r->s)
1918                                 XSetWindowBorder(display, cfw->id,
1919                                     cfw->ws->r->s->c[SWM_S_COLOR_UNFOCUS].color);
1920         }
1921
1922         win->ws->focus = win;
1923
1924         if (win->ws->r != NULL) {
1925                 /* drain all previous focus events */
1926                 while (XCheckTypedEvent(display, FocusIn, &cne) == True)
1927                         ;
1928
1929                 if (win->java == 0)
1930                         XSetInputFocus(display, win->id,
1931                             RevertToParent, CurrentTime);
1932                 XMapRaised(display, win->id);
1933                 grabbuttons(win, 1);
1934                 XSetWindowBorder(display, win->id,
1935                     win->ws->r->s->c[SWM_S_COLOR_FOCUS].color);
1936                 if (win->ws->cur_layout->flags & SWM_L_MAPONFOCUS)
1937                         XMapRaised(display, win->id);
1938
1939                 XChangeProperty(display, win->s->root,
1940                     ewmh[_NET_ACTIVE_WINDOW].atom, XA_WINDOW, 32,
1941                     PropModeReplace, (unsigned char *)&win->id,1);
1942         }
1943
1944         if (window_name_enabled)
1945                 bar_update();
1946 }
1947
1948 void
1949 switchws(struct swm_region *r, union arg *args)
1950 {
1951         int                     wsid = args->id, unmap_old = 0;
1952         struct swm_region       *this_r, *other_r;
1953         struct ws_win           *win;
1954         struct workspace        *new_ws, *old_ws;
1955         union arg               a;
1956
1957         if (!(r && r->s))
1958                 return;
1959
1960         this_r = r;
1961         old_ws = this_r->ws;
1962         new_ws = &this_r->s->ws[wsid];
1963
1964         DNPRINTF(SWM_D_WS, "switchws screen[%d]:%dx%d+%d+%d: "
1965             "%d -> %d\n", r->s->idx, WIDTH(r), HEIGHT(r), X(r), Y(r),
1966             old_ws->idx, wsid);
1967
1968         if (new_ws == NULL || old_ws == NULL)
1969                 return;
1970         if (new_ws == old_ws)
1971                 return;
1972
1973         other_r = new_ws->r;
1974         if (other_r == NULL) {
1975                 /* the other workspace is hidden, hide this one */
1976                 old_ws->r = NULL;
1977                 unmap_old = 1;
1978         } else {
1979                 /* the other ws is visible in another region, exchange them */
1980                 other_r->ws_prior = new_ws;
1981                 other_r->ws = old_ws;
1982                 old_ws->r = other_r;
1983         }
1984         this_r->ws_prior = old_ws;
1985         this_r->ws = new_ws;
1986         new_ws->r = this_r;
1987
1988         /* this is needed so that we can click on a window after a restart */
1989         unfocus_all();
1990
1991         stack();
1992         a.id = SWM_ARG_ID_FOCUSCUR;
1993         focus(new_ws->r, &a);
1994
1995         bar_update();
1996
1997         /* unmap old windows */
1998         if (unmap_old)
1999                 TAILQ_FOREACH(win, &old_ws->winlist, entry)
2000                         unmap_window(win);
2001
2002         if (focus_mode == SWM_FOCUS_DEFAULT)
2003                 drain_enter_notify();
2004 }
2005
2006 void
2007 cyclews(struct swm_region *r, union arg *args)
2008 {
2009         union                   arg a;
2010         struct swm_screen       *s = r->s;
2011
2012         DNPRINTF(SWM_D_WS, "cyclews id %d "
2013             "in screen[%d]:%dx%d+%d+%d ws %d\n", args->id,
2014             r->s->idx, WIDTH(r), HEIGHT(r), X(r), Y(r), r->ws->idx);
2015
2016         a.id = r->ws->idx;
2017         do {
2018                 switch (args->id) {
2019                 case SWM_ARG_ID_CYCLEWS_UP:
2020                         if (a.id < SWM_WS_MAX - 1)
2021                                 a.id++;
2022                         else
2023                                 a.id = 0;
2024                         break;
2025                 case SWM_ARG_ID_CYCLEWS_DOWN:
2026                         if (a.id > 0)
2027                                 a.id--;
2028                         else
2029                                 a.id = SWM_WS_MAX - 1;
2030                         break;
2031                 default:
2032                         return;
2033                 };
2034
2035                 if (cycle_empty == 0 && TAILQ_EMPTY(&s->ws[a.id].winlist))
2036                         continue;
2037                 if (cycle_visible == 0 && s->ws[a.id].r != NULL)
2038                         continue;
2039
2040                 switchws(r, &a);
2041         } while (a.id != r->ws->idx);
2042 }
2043
2044 void
2045 priorws(struct swm_region *r, union arg *args)
2046 {
2047         union arg               a;
2048
2049         DNPRINTF(SWM_D_WS, "priorws id %d "
2050             "in screen[%d]:%dx%d+%d+%d ws %d\n", args->id,
2051             r->s->idx, WIDTH(r), HEIGHT(r), X(r), Y(r), r->ws->idx);
2052
2053         if (r->ws_prior == NULL)
2054                 return;
2055
2056         a.id = r->ws_prior->idx;
2057         switchws(r, &a);
2058 }
2059
2060 void
2061 cyclescr(struct swm_region *r, union arg *args)
2062 {
2063         struct swm_region       *rr = NULL;
2064         union arg               a;
2065         int                     i, x, y;
2066
2067         /* do nothing if we don't have more than one screen */
2068         if (!(ScreenCount(display) > 1 || outputs > 1))
2069                 return;
2070
2071         i = r->s->idx;
2072         switch (args->id) {
2073         case SWM_ARG_ID_CYCLESC_UP:
2074                 rr = TAILQ_NEXT(r, entry);
2075                 if (rr == NULL)
2076                         rr = TAILQ_FIRST(&screens[i].rl);
2077                 break;
2078         case SWM_ARG_ID_CYCLESC_DOWN:
2079                 rr = TAILQ_PREV(r, swm_region_list, entry);
2080                 if (rr == NULL)
2081                         rr = TAILQ_LAST(&screens[i].rl, swm_region_list);
2082                 break;
2083         default:
2084                 return;
2085         };
2086         if (rr == NULL)
2087                 return;
2088
2089         /* move mouse to region */
2090         x = rr->g.x + 1;
2091         y = rr->g.y + 1 + (bar_enabled ? bar_height : 0);
2092         XWarpPointer(display, None, rr->s[i].root, 0, 0, 0, 0, x, y);
2093
2094         a.id = SWM_ARG_ID_FOCUSCUR;
2095         focus(rr, &a);
2096
2097         if (rr->ws->focus) {
2098                 /* move to focus window */
2099                 x = rr->ws->focus->g.x + 1;
2100                 y = rr->ws->focus->g.y + 1;
2101                 XWarpPointer(display, None, rr->s[i].root, 0, 0, 0, 0, x, y);
2102         }
2103 }
2104
2105 void
2106 sort_windows(struct ws_win_list *wl)
2107 {
2108         struct ws_win           *win, *parent, *nxt;
2109
2110         if (wl == NULL)
2111                 return;
2112
2113         for (win = TAILQ_FIRST(wl); win != TAILQ_END(wl); win = nxt) {
2114                 nxt = TAILQ_NEXT(win, entry);
2115                 if (win->transient) {
2116                         parent = find_window(win->transient);
2117                         if (parent == NULL) {
2118                                 fprintf(stderr, "not possible bug\n");
2119                                 continue;
2120                         }
2121                         TAILQ_REMOVE(wl, win, entry);
2122                         TAILQ_INSERT_AFTER(wl, parent, win, entry);
2123                 }
2124         }
2125
2126 }
2127
2128 void
2129 swapwin(struct swm_region *r, union arg *args)
2130 {
2131         struct ws_win           *target, *source;
2132         struct ws_win           *cur_focus;
2133         struct ws_win_list      *wl;
2134
2135
2136         DNPRINTF(SWM_D_WS, "swapwin id %d "
2137             "in screen %d region %dx%d+%d+%d ws %d\n", args->id,
2138             r->s->idx, WIDTH(r), HEIGHT(r), X(r), Y(r), r->ws->idx);
2139
2140         cur_focus = r->ws->focus;
2141         if (cur_focus == NULL)
2142                 return;
2143
2144         source = cur_focus;
2145         wl = &source->ws->winlist;
2146
2147         switch (args->id) {
2148         case SWM_ARG_ID_SWAPPREV:
2149                 if (source->transient)
2150                         source = find_window(source->transient);
2151                 target = TAILQ_PREV(source, ws_win_list, entry);
2152                 if (target && target->transient)
2153                         target = find_window(target->transient);
2154                 TAILQ_REMOVE(wl, source, entry);
2155                 if (target == NULL)
2156                         TAILQ_INSERT_TAIL(wl, source, entry);
2157                 else
2158                         TAILQ_INSERT_BEFORE(target, source, entry);
2159                 break;
2160         case SWM_ARG_ID_SWAPNEXT:
2161                 target = TAILQ_NEXT(source, entry);
2162                 /* move the parent and let the sort handle the move */
2163                 if (source->transient)
2164                         source = find_window(source->transient);
2165                 TAILQ_REMOVE(wl, source, entry);
2166                 if (target == NULL)
2167                         TAILQ_INSERT_HEAD(wl, source, entry);
2168                 else
2169                         TAILQ_INSERT_AFTER(wl, target, source, entry);
2170                 break;
2171         case SWM_ARG_ID_SWAPMAIN:
2172                 target = TAILQ_FIRST(wl);
2173                 if (target == source) {
2174                         if (source->ws->focus_prev != NULL &&
2175                             source->ws->focus_prev != target)
2176
2177                                 source = source->ws->focus_prev;
2178                         else
2179                                 return;
2180                 }
2181                 if (target == NULL || source == NULL)
2182                         return;
2183                 source->ws->focus_prev = target;
2184                 TAILQ_REMOVE(wl, target, entry);
2185                 TAILQ_INSERT_BEFORE(source, target, entry);
2186                 TAILQ_REMOVE(wl, source, entry);
2187                 TAILQ_INSERT_HEAD(wl, source, entry);
2188                 break;
2189         case SWM_ARG_ID_MOVELAST:
2190                 TAILQ_REMOVE(wl, source, entry);
2191                 TAILQ_INSERT_TAIL(wl, source, entry);
2192                 break;
2193         default:
2194                 DNPRINTF(SWM_D_MOVE, "invalid id: %d\n", args->id);
2195                 return;
2196         }
2197
2198         sort_windows(wl);
2199
2200         stack();
2201 }
2202
2203 void
2204 focus_prev(struct ws_win *win)
2205 {
2206         struct ws_win           *winfocus = NULL, *winlostfocus = NULL;
2207         struct ws_win           *cur_focus = NULL;
2208         struct ws_win_list      *wl = NULL;
2209         struct workspace        *ws = NULL;
2210
2211         DNPRINTF(SWM_D_FOCUS, "focus_prev: id %lu\n", WINID(win));
2212
2213         if (!(win && win->ws))
2214                 return;
2215
2216         ws = win->ws;
2217         wl = &ws->winlist;
2218         cur_focus = ws->focus;
2219         winlostfocus = cur_focus;
2220
2221         /* pickle, just focus on whatever */
2222         if (cur_focus == NULL) {
2223                 /* use prev_focus if valid */
2224                 if (ws->focus_prev && ws->focus_prev != cur_focus &&
2225                     find_window(WINID(ws->focus_prev)))
2226                         winfocus = ws->focus_prev;
2227                 if (winfocus == NULL)
2228                         winfocus = TAILQ_FIRST(wl);
2229                 goto done;
2230         }
2231
2232         /* if transient focus on parent */
2233         if (cur_focus->transient) {
2234                 winfocus = find_window(cur_focus->transient);
2235                 goto done;
2236         }
2237
2238         /* if in max_stack try harder */
2239         if ((win->quirks & SWM_Q_FOCUSPREV) ||
2240             (ws->cur_layout->flags & SWM_L_FOCUSPREV)) {
2241                 if (cur_focus != ws->focus_prev)
2242                         winfocus = ws->focus_prev;
2243                 else if (cur_focus != ws->focus)
2244                         winfocus = ws->focus;
2245                 else
2246                         winfocus = TAILQ_PREV(win, ws_win_list, entry);
2247                 if (winfocus)
2248                         goto done;
2249         }
2250
2251         if (cur_focus == win)
2252                 winfocus = TAILQ_PREV(win, ws_win_list, entry);
2253         if (winfocus == NULL)
2254                 winfocus = TAILQ_LAST(wl, ws_win_list);
2255         if (winfocus == NULL || winfocus == win)
2256                 winfocus = TAILQ_NEXT(cur_focus, entry);
2257 done:
2258         if (winfocus == winlostfocus || winfocus == NULL)
2259                 return;
2260
2261         focus_magic(winfocus);
2262 }
2263
2264 void
2265 focus(struct swm_region *r, union arg *args)
2266 {
2267         struct ws_win           *winfocus = NULL, *winlostfocus = NULL, *head;
2268         struct ws_win           *cur_focus = NULL;
2269         struct ws_win_list      *wl = NULL;
2270         struct workspace        *ws = NULL;
2271
2272         if (!(r && r->ws))
2273                 return;
2274
2275         DNPRINTF(SWM_D_FOCUS, "focus: id %d\n", args->id);
2276
2277         /* treat FOCUS_CUR special */
2278         if (args->id == SWM_ARG_ID_FOCUSCUR) {
2279                 if (r->ws->focus && r->ws->focus->iconic == 0)
2280                         winfocus = r->ws->focus;
2281                 else if (r->ws->focus_prev && r->ws->focus_prev->iconic == 0)
2282                         winfocus = r->ws->focus_prev;
2283                 else
2284                         TAILQ_FOREACH(winfocus, &r->ws->winlist, entry)
2285                                 if (winfocus->iconic == 0)
2286                                         break;
2287
2288                 focus_magic(winfocus);
2289                 return;
2290         }
2291
2292         if ((cur_focus = r->ws->focus) == NULL)
2293                 return;
2294         ws = r->ws;
2295         wl = &ws->winlist;
2296
2297         winlostfocus = cur_focus;
2298
2299         switch (args->id) {
2300         case SWM_ARG_ID_FOCUSPREV:
2301                 head = TAILQ_PREV(cur_focus, ws_win_list, entry);
2302                 if (head == NULL)
2303                         head = TAILQ_LAST(wl, ws_win_list);
2304                 winfocus = head;
2305                 if (WINID(winfocus) == cur_focus->transient) {
2306                         head = TAILQ_PREV(winfocus, ws_win_list, entry);
2307                         if (head == NULL)
2308                                 head = TAILQ_LAST(wl, ws_win_list);
2309                         winfocus = head;
2310                 }
2311
2312                 /* skip iconics */
2313                 if (winfocus && winfocus->iconic) {
2314                         TAILQ_FOREACH_REVERSE(winfocus, wl, ws_win_list, entry)
2315                                 if (winfocus->iconic == 0)
2316                                         break;
2317                 }
2318                 break;
2319
2320         case SWM_ARG_ID_FOCUSNEXT:
2321                 head = TAILQ_NEXT(cur_focus, entry);
2322                 if (head == NULL)
2323                         head = TAILQ_FIRST(wl);
2324                 winfocus = head;
2325
2326                 /* skip iconics */
2327                 if (winfocus && winfocus->iconic) {
2328                         TAILQ_FOREACH(winfocus, wl, entry)
2329                                 if (winfocus->iconic == 0)
2330                                         break;
2331                 }
2332                 break;
2333
2334         case SWM_ARG_ID_FOCUSMAIN:
2335                 winfocus = TAILQ_FIRST(wl);
2336                 if (winfocus == cur_focus)
2337                         winfocus = cur_focus->ws->focus_prev;
2338                 break;
2339
2340         default:
2341                 return;
2342         }
2343         if (winfocus == winlostfocus || winfocus == NULL)
2344                 return;
2345
2346         focus_magic(winfocus);
2347 }
2348
2349 void
2350 cycle_layout(struct swm_region *r, union arg *args)
2351 {
2352         struct workspace        *ws = r->ws;
2353         struct ws_win           *winfocus;
2354         union arg               a;
2355
2356         DNPRINTF(SWM_D_EVENT, "cycle_layout: workspace: %d\n", ws->idx);
2357
2358         winfocus = ws->focus;
2359
2360         ws->cur_layout++;
2361         if (ws->cur_layout->l_stack == NULL)
2362                 ws->cur_layout = &layouts[0];
2363
2364         stack();
2365         if (focus_mode == SWM_FOCUS_DEFAULT)
2366                 drain_enter_notify();
2367         a.id = SWM_ARG_ID_FOCUSCUR;
2368         focus(r, &a);
2369         bar_update();
2370 }
2371
2372 void
2373 stack_config(struct swm_region *r, union arg *args)
2374 {
2375         struct workspace        *ws = r->ws;
2376
2377         DNPRINTF(SWM_D_STACK, "stack_config for workspace %d (id %d\n",
2378             args->id, ws->idx);
2379
2380         if (ws->cur_layout->l_config != NULL)
2381                 ws->cur_layout->l_config(ws, args->id);
2382
2383         if (args->id != SWM_ARG_ID_STACKINIT)
2384                 stack();
2385 }
2386
2387 void
2388 stack(void) {
2389         struct swm_geometry     g;
2390         struct swm_region       *r;
2391         int                     i, j;
2392
2393         DNPRINTF(SWM_D_STACK, "stack\n");
2394
2395         for (i = 0; i < ScreenCount(display); i++) {
2396                 j = 0;
2397                 TAILQ_FOREACH(r, &screens[i].rl, entry) {
2398                         DNPRINTF(SWM_D_STACK, "stacking workspace %d "
2399                             "(screen %d, region %d)\n", r->ws->idx, i, j++);
2400
2401                         /* start with screen geometry, adjust for bar */
2402                         g = r->g;
2403                         g.w -= 2 * border_width;
2404                         g.h -= 2 * border_width;
2405                         if (bar_enabled) {
2406                                 if (!bar_at_bottom)
2407                                         g.y += bar_height;
2408                                 g.h -= bar_height;
2409                         }
2410                         r->ws->cur_layout->l_stack(r->ws, &g);
2411                         /* save r so we can track region changes */
2412                         r->ws->old_r = r;
2413                 }
2414         }
2415         if (font_adjusted)
2416                 font_adjusted--;
2417
2418         if (focus_mode == SWM_FOCUS_DEFAULT)
2419                 drain_enter_notify();
2420 }
2421
2422 void
2423 store_float_geom(struct ws_win *win, struct swm_region *r)
2424 {
2425         /* retain window geom and region geom */
2426         win->g_float.x = win->g.x;
2427         win->g_float.y = win->g.y;
2428         win->g_float.w = win->g.w;
2429         win->g_float.h = win->g.h;
2430         win->rg_float.x = r->g.x;
2431         win->rg_float.y = r->g.y;
2432         win->rg_float.w = r->g.w;
2433         win->rg_float.h = r->g.h;
2434         win->g_floatvalid = 1;
2435 }
2436
2437 void
2438 stack_floater(struct ws_win *win, struct swm_region *r)
2439 {
2440         unsigned int            mask;
2441         XWindowChanges          wc;
2442
2443         if (win == NULL)
2444                 return;
2445
2446         bzero(&wc, sizeof wc);
2447         mask = CWX | CWY | CWBorderWidth | CWWidth | CWHeight;
2448
2449         /*
2450          * to allow windows to change their size (e.g. mplayer fs) only retrieve
2451          * geom on ws switches or return from max mode
2452          */
2453
2454         if (win->floatmaxed || (r != r->ws->old_r && win->g_floatvalid
2455             && !(win->ewmh_flags & EWMH_F_FULLSCREEN))) {
2456                 /*
2457                  * use stored g and rg to set relative position and size
2458                  * as in old region or before max stack mode
2459                  */
2460                 win->g.x = win->g_float.x - win->rg_float.x + r->g.x;
2461                 win->g.y = win->g_float.y - win->rg_float.y + r->g.y;
2462                 win->g.w = win->g_float.w;
2463                 win->g.h = win->g_float.h;
2464                 win->g_floatvalid = 0;
2465         }
2466
2467         win->floatmaxed = 0;
2468
2469         if ((win->quirks & SWM_Q_FULLSCREEN) && (win->g.w >= WIDTH(r)) &&
2470             (win->g.h >= HEIGHT(r)))
2471                 wc.border_width = 0;
2472         else
2473                 wc.border_width = border_width;
2474         if (win->transient && (win->quirks & SWM_Q_TRANSSZ)) {
2475                 win->g.w = (double)WIDTH(r) * dialog_ratio;
2476                 win->g.h = (double)HEIGHT(r) * dialog_ratio;
2477         }
2478
2479         if (!win->manual) {
2480                 /*
2481                  * floaters and transients are auto-centred unless moved
2482                  * or resized
2483                  */
2484                 win->g.x = r->g.x + (WIDTH(r) - win->g.w) /
2485                     2 - wc.border_width;
2486                 win->g.y = r->g.y + (HEIGHT(r) - win->g.h) /
2487                     2 - wc.border_width;
2488         }
2489
2490         /* win can be outside r if new r smaller than old r */
2491         /* Ensure top left corner inside r (move probs otherwise) */
2492         if (win->g.x < r->g.x - wc.border_width)
2493                 win->g.x = r->g.x - wc.border_width;
2494         if (win->g.x > r->g.x + r->g.w - 1)
2495                 win->g.x = (win->g.w > r->g.w) ? r->g.x :
2496                     (r->g.x + r->g.w - win->g.w - 2 * wc.border_width);
2497         if (win->g.y < r->g.y - wc.border_width)
2498                 win->g.y = r->g.y - wc.border_width;
2499         if (win->g.y > r->g.y + r->g.h - 1)
2500                 win->g.y = (win->g.h > r->g.h) ? r->g.y :
2501                     (r->g.y + r->g.h - win->g.h - 2 * wc.border_width);
2502
2503         wc.x = win->g.x;
2504         wc.y = win->g.y;
2505         wc.width = win->g.w;
2506         wc.height = win->g.h;
2507
2508         /*
2509          * Retain floater and transient geometry for correct positioning
2510          * when ws changes region
2511          */
2512         if (!(win->ewmh_flags & EWMH_F_FULLSCREEN))
2513                 store_float_geom(win, r);
2514
2515         DNPRINTF(SWM_D_MISC, "stack_floater: win %lu x %d y %d w %d h %d\n",
2516             win->id, wc.x, wc.y, wc.width, wc.height);
2517
2518         XConfigureWindow(display, win->id, mask, &wc);
2519 }
2520
2521 /*
2522  * Send keystrokes to terminal to decrease/increase the font size as the
2523  * window size changes.
2524  */
2525 void
2526 adjust_font(struct ws_win *win)
2527 {
2528         if (!(win->quirks & SWM_Q_XTERM_FONTADJ) ||
2529             win->floating || win->transient)
2530                 return;
2531
2532         if (win->sh.width_inc && win->last_inc != win->sh.width_inc &&
2533             win->g.w / win->sh.width_inc < term_width &&
2534             win->font_steps < SWM_MAX_FONT_STEPS) {
2535                 win->font_size_boundary[win->font_steps] =
2536                     (win->sh.width_inc * term_width) + win->sh.base_width;
2537                 win->font_steps++;
2538                 font_adjusted++;
2539                 win->last_inc = win->sh.width_inc;
2540                 fake_keypress(win, XK_KP_Subtract, ShiftMask);
2541         } else if (win->font_steps && win->last_inc != win->sh.width_inc &&
2542             win->g.w > win->font_size_boundary[win->font_steps - 1]) {
2543                 win->font_steps--;
2544                 font_adjusted++;
2545                 win->last_inc = win->sh.width_inc;
2546                 fake_keypress(win, XK_KP_Add, ShiftMask);
2547         }
2548 }
2549
2550 #define SWAPXY(g)       do {                            \
2551         int tmp;                                        \
2552         tmp = (g)->y; (g)->y = (g)->x; (g)->x = tmp;    \
2553         tmp = (g)->h; (g)->h = (g)->w; (g)->w = tmp;    \
2554 } while (0)
2555 void
2556 stack_master(struct workspace *ws, struct swm_geometry *g, int rot, int flip)
2557 {
2558         XWindowChanges          wc;
2559         XWindowAttributes       wa;
2560         struct swm_geometry     win_g, r_g = *g;
2561         struct ws_win           *win, *fs_win = 0;
2562         int                     i, j, s, stacks;
2563         int                     w_inc = 1, h_inc, w_base = 1, h_base;
2564         int                     hrh, extra = 0, h_slice, last_h = 0;
2565         int                     split, colno, winno, mwin, msize, mscale;
2566         int                     remain, missing, v_slice, reconfigure;
2567         unsigned int            mask;
2568
2569         DNPRINTF(SWM_D_STACK, "stack_master: workspace: %d\n rot=%s flip=%s",
2570             ws->idx, rot ? "yes" : "no", flip ? "yes" : "no");
2571
2572         winno = count_win(ws, 0);
2573         if (winno == 0 && count_win(ws, 1) == 0)
2574                 return;
2575
2576         TAILQ_FOREACH(win, &ws->winlist, entry)
2577                 if (win->transient == 0 && win->floating == 0
2578                     && win->iconic == 0)
2579                         break;
2580
2581         if (win == NULL)
2582                 goto notiles;
2583
2584         if (rot) {
2585                 w_inc = win->sh.width_inc;
2586                 w_base = win->sh.base_width;
2587                 mwin = ws->l_state.horizontal_mwin;
2588                 mscale = ws->l_state.horizontal_msize;
2589                 stacks = ws->l_state.horizontal_stacks;
2590                 SWAPXY(&r_g);
2591         } else {
2592                 w_inc = win->sh.height_inc;
2593                 w_base = win->sh.base_height;
2594                 mwin = ws->l_state.vertical_mwin;
2595                 mscale = ws->l_state.vertical_msize;
2596                 stacks = ws->l_state.vertical_stacks;
2597         }
2598         win_g = r_g;
2599
2600         if (stacks > winno - mwin)
2601                 stacks = winno - mwin;
2602         if (stacks < 1)
2603                 stacks = 1;
2604
2605         h_slice = r_g.h / SWM_H_SLICE;
2606         if (mwin && winno > mwin) {
2607                 v_slice = r_g.w / SWM_V_SLICE;
2608
2609                 split = mwin;
2610                 colno = split;
2611                 win_g.w = v_slice * mscale;
2612
2613                 if (w_inc > 1 && w_inc < v_slice) {
2614                         /* adjust for window's requested size increment */
2615                         remain = (win_g.w - w_base) % w_inc;
2616                         missing = w_inc - remain;
2617                         win_g.w -= remain;
2618                         extra += remain;
2619                 }
2620
2621                 msize = win_g.w;
2622                 if (flip)
2623                         win_g.x += r_g.w - msize;
2624         } else {
2625                 msize = -2;
2626                 colno = split = winno / stacks;
2627                 win_g.w = ((r_g.w - (stacks * 2 * border_width) +
2628                     2 * border_width) / stacks);
2629         }
2630         hrh = r_g.h / colno;
2631         extra = r_g.h - (colno * hrh);
2632         win_g.h = hrh - 2 * border_width;
2633
2634         /*  stack all the tiled windows */
2635         i = j = 0, s = stacks;
2636         TAILQ_FOREACH(win, &ws->winlist, entry) {
2637                 if (win->transient != 0 || win->floating != 0)
2638                         continue;
2639                 if (win->iconic != 0)
2640                         continue;
2641
2642                 if (win->ewmh_flags & EWMH_F_FULLSCREEN) {
2643                         fs_win = win;
2644                         continue;
2645                 }
2646
2647                 if (split && i == split) {
2648                         colno = (winno - mwin) / stacks;
2649                         if (s <= (winno - mwin) % stacks)
2650                                 colno++;
2651                         split = split + colno;
2652                         hrh = (r_g.h / colno);
2653                         extra = r_g.h - (colno * hrh);
2654                         if (flip)
2655                                 win_g.x = r_g.x;
2656                         else
2657                                 win_g.x += win_g.w + 2 * border_width;
2658                         win_g.w = (r_g.w - msize -
2659                             (stacks * 2 * border_width)) / stacks;
2660                         if (s == 1)
2661                                 win_g.w += (r_g.w - msize -
2662                                     (stacks * 2 * border_width)) % stacks;
2663                         s--;
2664                         j = 0;
2665                 }
2666                 win_g.h = hrh - 2 * border_width;
2667                 if (rot) {
2668                         h_inc = win->sh.width_inc;
2669                         h_base = win->sh.base_width;
2670                 } else {
2671                         h_inc = win->sh.height_inc;
2672                         h_base = win->sh.base_height;
2673                 }
2674                 if (j == colno - 1) {
2675                         win_g.h = hrh + extra;
2676                 } else if (h_inc > 1 && h_inc < h_slice) {
2677                         /* adjust for window's requested size increment */
2678                         remain = (win_g.h - h_base) % h_inc;
2679                         missing = h_inc - remain;
2680
2681                         if (missing <= extra || j == 0) {
2682                                 extra -= missing;
2683                                 win_g.h += missing;
2684                         } else {
2685                                 win_g.h -= remain;
2686                                 extra += remain;
2687                         }
2688                 }
2689
2690                 if (j == 0)
2691                         win_g.y = r_g.y;
2692                 else
2693                         win_g.y += last_h + 2 * border_width;
2694
2695                 bzero(&wc, sizeof wc);
2696                 if (disable_border && bar_enabled == 0 && winno == 1){
2697                         wc.border_width = 0;
2698                         win_g.w += 2 * border_width;
2699                         win_g.h += 2 * border_width;
2700                 } else
2701                         wc.border_width = border_width;
2702                 reconfigure = 0;
2703                 if (rot) {
2704                         if (win->g.x != win_g.y || win->g.y != win_g.x ||
2705                             win->g.w != win_g.h || win->g.h != win_g.w) {
2706                                 reconfigure = 1;
2707                                 win->g.x = wc.x = win_g.y;
2708                                 win->g.y = wc.y = win_g.x;
2709                                 win->g.w = wc.width = win_g.h;
2710                                 win->g.h = wc.height = win_g.w;
2711                         }
2712                 } else {
2713                         if (win->g.x != win_g.x || win->g.y != win_g.y ||
2714                             win->g.w != win_g.w || win->g.h != win_g.h) {
2715                                 reconfigure = 1;
2716                                 win->g.x = wc.x = win_g.x;
2717                                 win->g.y = wc.y = win_g.y;
2718                                 win->g.w = wc.width = win_g.w;
2719                                 win->g.h = wc.height = win_g.h;
2720                         }
2721                 }
2722                 if (reconfigure) {
2723                         adjust_font(win);
2724                         mask = CWX | CWY | CWWidth | CWHeight | CWBorderWidth;
2725                         XConfigureWindow(display, win->id, mask, &wc);
2726                 }
2727
2728                 if (XGetWindowAttributes(display, win->id, &wa))
2729                         if (wa.map_state == IsUnmapped)
2730                                 XMapRaised(display, win->id);
2731
2732                 last_h = win_g.h;
2733                 i++;
2734                 j++;
2735         }
2736
2737 notiles:
2738         /* now, stack all the floaters and transients */
2739         TAILQ_FOREACH(win, &ws->winlist, entry) {
2740                 if (win->transient == 0 && win->floating == 0)
2741                         continue;
2742                 if (win->iconic == 1)
2743                         continue;
2744                 if (win->ewmh_flags & EWMH_F_FULLSCREEN) {
2745                         fs_win = win;
2746                         continue;
2747                 }
2748
2749                 stack_floater(win, ws->r);
2750                 XMapRaised(display, win->id);
2751         }
2752
2753         if (fs_win) {
2754                 stack_floater(fs_win, ws->r);
2755                 XMapRaised(display, fs_win->id);
2756         }
2757 }
2758
2759 void
2760 vertical_config(struct workspace *ws, int id)
2761 {
2762         DNPRINTF(SWM_D_STACK, "vertical_resize: workspace: %d\n", ws->idx);
2763
2764         switch (id) {
2765         case SWM_ARG_ID_STACKRESET:
2766         case SWM_ARG_ID_STACKINIT:
2767                 ws->l_state.vertical_msize = SWM_V_SLICE / 2;
2768                 ws->l_state.vertical_mwin = 1;
2769                 ws->l_state.vertical_stacks = 1;
2770                 break;
2771         case SWM_ARG_ID_MASTERSHRINK:
2772                 if (ws->l_state.vertical_msize > 1)
2773                         ws->l_state.vertical_msize--;
2774                 break;
2775         case SWM_ARG_ID_MASTERGROW:
2776                 if (ws->l_state.vertical_msize < SWM_V_SLICE - 1)
2777                         ws->l_state.vertical_msize++;
2778                 break;
2779         case SWM_ARG_ID_MASTERADD:
2780                 ws->l_state.vertical_mwin++;
2781                 break;
2782         case SWM_ARG_ID_MASTERDEL:
2783                 if (ws->l_state.vertical_mwin > 0)
2784                         ws->l_state.vertical_mwin--;
2785                 break;
2786         case SWM_ARG_ID_STACKINC:
2787                 ws->l_state.vertical_stacks++;
2788                 break;
2789         case SWM_ARG_ID_STACKDEC:
2790                 if (ws->l_state.vertical_stacks > 1)
2791                         ws->l_state.vertical_stacks--;
2792                 break;
2793         default:
2794                 return;
2795         }
2796 }
2797
2798 void
2799 vertical_stack(struct workspace *ws, struct swm_geometry *g)
2800 {
2801         DNPRINTF(SWM_D_STACK, "vertical_stack: workspace: %d\n", ws->idx);
2802
2803         stack_master(ws, g, 0, 0);
2804 }
2805
2806 void
2807 horizontal_config(struct workspace *ws, int id)
2808 {
2809         DNPRINTF(SWM_D_STACK, "horizontal_config: workspace: %d\n", ws->idx);
2810
2811         switch (id) {
2812         case SWM_ARG_ID_STACKRESET:
2813         case SWM_ARG_ID_STACKINIT:
2814                 ws->l_state.horizontal_mwin = 1;
2815                 ws->l_state.horizontal_msize = SWM_H_SLICE / 2;
2816                 ws->l_state.horizontal_stacks = 1;
2817                 break;
2818         case SWM_ARG_ID_MASTERSHRINK:
2819                 if (ws->l_state.horizontal_msize > 1)
2820                         ws->l_state.horizontal_msize--;
2821                 break;
2822         case SWM_ARG_ID_MASTERGROW:
2823                 if (ws->l_state.horizontal_msize < SWM_H_SLICE - 1)
2824                         ws->l_state.horizontal_msize++;
2825                 break;
2826         case SWM_ARG_ID_MASTERADD:
2827                 ws->l_state.horizontal_mwin++;
2828                 break;
2829         case SWM_ARG_ID_MASTERDEL:
2830                 if (ws->l_state.horizontal_mwin > 0)
2831                         ws->l_state.horizontal_mwin--;
2832                 break;
2833         case SWM_ARG_ID_STACKINC:
2834                 ws->l_state.horizontal_stacks++;
2835                 break;
2836         case SWM_ARG_ID_STACKDEC:
2837                 if (ws->l_state.horizontal_stacks > 1)
2838                         ws->l_state.horizontal_stacks--;
2839                 break;
2840         default:
2841                 return;
2842         }
2843 }
2844
2845 void
2846 horizontal_stack(struct workspace *ws, struct swm_geometry *g)
2847 {
2848         DNPRINTF(SWM_D_STACK, "horizontal_stack: workspace: %d\n", ws->idx);
2849
2850         stack_master(ws, g, 1, 0);
2851 }
2852
2853 /* fullscreen view */
2854 void
2855 max_stack(struct workspace *ws, struct swm_geometry *g)
2856 {
2857         XWindowChanges          wc;
2858         struct swm_geometry     gg = *g;
2859         struct ws_win           *win, *wintrans = NULL, *parent = NULL;
2860         unsigned int            mask;
2861         int                     winno;
2862
2863         DNPRINTF(SWM_D_STACK, "max_stack: workspace: %d\n", ws->idx);
2864
2865         if (ws == NULL)
2866                 return;
2867
2868         winno = count_win(ws, 0);
2869         if (winno == 0 && count_win(ws, 1) == 0)
2870                 return;
2871
2872         TAILQ_FOREACH(win, &ws->winlist, entry) {
2873                 if (win->transient) {
2874                         wintrans = win;
2875                         parent = find_window(win->transient);
2876                         continue;
2877                 }
2878
2879                 if (win->floating && win->floatmaxed == 0 ) {
2880                         /*
2881                          * retain geometry for retrieval on exit from
2882                          * max_stack mode
2883                          */
2884                         store_float_geom(win, ws->r);
2885                         win->floatmaxed = 1;
2886                 }
2887
2888                 /* only reconfigure if necessary */
2889                 if (win->g.x != gg.x || win->g.y != gg.y || win->g.w != gg.w ||
2890                     win->g.h != gg.h) {
2891                         bzero(&wc, sizeof wc);
2892                         win->g.x = wc.x = gg.x;
2893                         win->g.y = wc.y = gg.y;
2894                         if (bar_enabled){
2895                                 wc.border_width = border_width;
2896                                 win->g.w = wc.width = gg.w;
2897                                 win->g.h = wc.height = gg.h;
2898                         } else {
2899                                 wc.border_width = 0;
2900                                 win->g.w = wc.width = gg.w + 2 * border_width;
2901                                 win->g.h = wc.height = gg.h + 2 * border_width;
2902                         }
2903                         mask = CWX | CWY | CWWidth | CWHeight | CWBorderWidth;
2904                         XConfigureWindow(display, win->id, mask, &wc);
2905                 }
2906                 /* unmap only if we don't have multi screen */
2907                 if (win != ws->focus)
2908                         if (!(ScreenCount(display) > 1 || outputs > 1))
2909                                 unmap_window(win);
2910         }
2911
2912         /* put the last transient on top */
2913         if (wintrans) {
2914                 if (parent)
2915                         XMapRaised(display, parent->id);
2916                 stack_floater(wintrans, ws->r);
2917                 focus_magic(wintrans);
2918         }
2919 }
2920
2921 void
2922 send_to_ws(struct swm_region *r, union arg *args)
2923 {
2924         int                     wsid = args->id;
2925         struct ws_win           *win = NULL, *parent;
2926         struct workspace        *ws, *nws;
2927         Atom                    ws_idx_atom = 0;
2928         unsigned char           ws_idx_str[SWM_PROPLEN];
2929         union arg               a;
2930
2931         if (r && r->ws)
2932                 win = r->ws->focus;
2933         else
2934                 return;
2935         if (win == NULL)
2936                 return;
2937         if (win->ws->idx == wsid)
2938                 return;
2939
2940         DNPRINTF(SWM_D_MOVE, "send_to_ws: win: %lu\n", win->id);
2941
2942         ws = win->ws;
2943         nws = &win->s->ws[wsid];
2944
2945         a.id = SWM_ARG_ID_FOCUSPREV;
2946         focus(r, &a);
2947         if (win->transient) {
2948                 parent = find_window(win->transient);
2949                 if (parent) {
2950                         unmap_window(parent);
2951                         TAILQ_REMOVE(&ws->winlist, parent, entry);
2952                         TAILQ_INSERT_TAIL(&nws->winlist, parent, entry);
2953                         parent->ws = nws;
2954                 }
2955         }
2956         unmap_window(win);
2957         TAILQ_REMOVE(&ws->winlist, win, entry);
2958         TAILQ_INSERT_TAIL(&nws->winlist, win, entry);
2959         win->ws = nws;
2960
2961         /* Try to update the window's workspace property */
2962         ws_idx_atom = XInternAtom(display, "_SWM_WS", False);
2963         if (ws_idx_atom &&
2964             snprintf(ws_idx_str, SWM_PROPLEN, "%d", nws->idx) < SWM_PROPLEN) {
2965                 DNPRINTF(SWM_D_PROP, "setting property _SWM_WS to %s\n",
2966                     ws_idx_str);
2967                 XChangeProperty(display, win->id, ws_idx_atom, XA_STRING, 8,
2968                     PropModeReplace, ws_idx_str, SWM_PROPLEN);
2969         }
2970
2971         stack();
2972 }
2973
2974 void
2975 iconify(struct swm_region *r, union arg *args)
2976 {
2977         union arg a;
2978
2979         if (r->ws->focus == NULL)
2980                 return;
2981         unmap_window(r->ws->focus);
2982         update_iconic(r->ws->focus, 1);
2983         stack();
2984         if (focus_mode == SWM_FOCUS_DEFAULT)
2985                 drain_enter_notify();
2986         r->ws->focus = NULL;
2987         a.id = SWM_ARG_ID_FOCUSCUR;
2988         focus(r, &a);
2989 }
2990
2991 unsigned char *
2992 get_win_name(Display *dpy, Window win, Atom wname, Atom stype,
2993     unsigned long *slen)
2994 {
2995         int                     status, retfmt;
2996         unsigned long           nitems, nbytes, nextra;
2997         unsigned char           *prop = NULL;
2998         Atom                    rettype;
2999
3000         status = XGetWindowProperty(dpy, win, wname, 0L, 0L, False, stype,
3001             &rettype, &retfmt,  &nitems, &nbytes, &prop);
3002         if (status != Success)
3003                 return (NULL);
3004         XFree(prop);
3005
3006         status = XGetWindowProperty(dpy, win, wname, 0L, nbytes, False,
3007             stype, &rettype, &retfmt, &nitems, &nextra, &prop);
3008         if (status != Success) {
3009                 XFree(prop);
3010                 return (NULL);
3011         }
3012         if (rettype != stype) {
3013                 XFree(prop);
3014                 return (NULL);
3015         }
3016         *slen = nitems;
3017         return (prop);
3018 }
3019
3020 void
3021 uniconify(struct swm_region *r, union arg *args)
3022 {
3023         struct ws_win           *win;
3024         FILE                    *lfile;
3025         char                    *name;
3026         int                     count = 0;
3027         unsigned long           len;
3028
3029         DNPRINTF(SWM_D_MISC, "uniconify\n");
3030
3031         if (r && r->ws == NULL)
3032                 return;
3033
3034         /* make sure we have anything to uniconify */
3035         TAILQ_FOREACH(win, &r->ws->winlist, entry) {
3036                 if (win->ws == NULL)
3037                         continue; /* should never happen */
3038                 if (win->iconic == 0)
3039                         continue;
3040                 count++;
3041         }
3042         if (count == 0)
3043                 return;
3044
3045         search_r = r;
3046
3047         spawn_select(r, args, "uniconify", &searchpid);
3048
3049         if ((lfile = fdopen(select_list_pipe[1], "w")) == NULL)
3050                 return;
3051
3052         TAILQ_FOREACH(win, &r->ws->winlist, entry) {
3053                 if (win->ws == NULL)
3054                         continue; /* should never happen */
3055                 if (win->iconic == 0)
3056                         continue;
3057
3058                 name = get_win_name(display, win->id, a_wmname, a_string,
3059                     &len);
3060                 if (name == NULL)
3061                         continue;
3062                 fprintf(lfile, "%s.%lu\n", name, win->id);
3063                 XFree(name);
3064         }
3065
3066         fclose(lfile);
3067 }
3068
3069 #define MAX_RESP_LEN    1024
3070
3071 void
3072 search_do_resp(void)
3073 {
3074         ssize_t                 rbytes;
3075         struct ws_win           *win;
3076         char                    *name, *resp, *s;
3077         unsigned long           len;
3078
3079         DNPRINTF(SWM_D_MISC, "search_do_resp:\n");
3080
3081         search_resp = 0;
3082         searchpid = 0;
3083
3084         if ((resp = calloc(1, MAX_RESP_LEN + 1)) == NULL) {
3085                 fprintf(stderr, "search: calloc\n");
3086                 return;
3087         }
3088
3089         rbytes = read(select_resp_pipe[0], resp, MAX_RESP_LEN);
3090         if (rbytes <= 0) {
3091                 fprintf(stderr, "search: read error: %s\n", strerror(errno));
3092                 goto done;
3093         }
3094         resp[rbytes] = '\0';
3095         len = strlen(resp);
3096
3097         DNPRINTF(SWM_D_MISC, "search_do_resp: resp %s\n", resp);
3098         TAILQ_FOREACH(win, &search_r->ws->winlist, entry) {
3099                 if (win->iconic == 0)
3100                         continue;
3101                 name = get_win_name(display, win->id, a_wmname, a_string, &len);
3102                 if (name == NULL)
3103                         continue;
3104                 if (asprintf(&s, "%s.%lu", name, win->id) == -1) {
3105                         XFree(name);
3106                         continue;
3107                 }
3108                 XFree(name);
3109                 if (strncmp(s, resp, len) == 0) {
3110                         /* XXX this should be a callback to generalize */
3111                         update_iconic(win, 0);
3112                         free(s);
3113                         break;
3114                 }
3115                 free(s);
3116         }
3117 done:
3118         free(resp);
3119 }
3120
3121 void
3122 wkill(struct swm_region *r, union arg *args)
3123 {
3124         DNPRINTF(SWM_D_MISC, "wkill %d\n", args->id);
3125
3126         if (r->ws->focus == NULL)
3127                 return;
3128
3129         if (args->id == SWM_ARG_ID_KILLWINDOW)
3130                 XKillClient(display, r->ws->focus->id);
3131         else
3132                 if (r->ws->focus->can_delete)
3133                         client_msg(r->ws->focus, adelete);
3134 }
3135
3136
3137 int
3138 floating_toggle_win(struct ws_win *win)
3139 {
3140         struct swm_region       *r;
3141
3142         if (win == NULL)
3143                 return 0;
3144
3145         if (!win->ws->r)
3146                 return 0;
3147
3148         r = win->ws->r;
3149
3150         /* reject floating toggles in max stack mode */
3151         if (win->ws->cur_layout == &layouts[SWM_MAX_STACK])
3152                 return 0;
3153
3154         if (win->floating) {
3155                 if (!win->floatmaxed) {
3156                         /* retain position for refloat */
3157                         store_float_geom(win, r);
3158                 }
3159                 win->floating = 0;
3160         } else {
3161                 if (win->g_floatvalid) {
3162                         /* refloat at last floating relative position */
3163                         win->g.x = win->g_float.x - win->rg_float.x + r->g.x;
3164                         win->g.y = win->g_float.y - win->rg_float.y + r->g.y;
3165                         win->g.w = win->g_float.w;
3166                         win->g.h = win->g_float.h;
3167                 }
3168                 win->floating = 1;
3169         }
3170
3171         ewmh_update_actions(win);
3172
3173         return 1;
3174 }
3175
3176 void
3177 floating_toggle(struct swm_region *r, union arg *args)
3178 {
3179         struct ws_win           *win = r->ws->focus;
3180         union arg               a;
3181
3182         if (win == NULL)
3183                 return;
3184
3185         ewmh_update_win_state(win, ewmh[_NET_WM_STATE_ABOVE].atom,
3186             _NET_WM_STATE_TOGGLE);
3187
3188         stack();
3189         if (focus_mode == SWM_FOCUS_DEFAULT)
3190                 drain_enter_notify();
3191
3192         if (win == win->ws->focus) {
3193                 a.id = SWM_ARG_ID_FOCUSCUR;
3194                 focus(win->ws->r, &a);
3195         }
3196 }
3197
3198 void
3199 resize_window(struct ws_win *win, int center)
3200 {
3201         unsigned int            mask;
3202         XWindowChanges          wc;
3203         struct swm_region       *r;
3204
3205         r = root_to_region(win->wa.root);
3206         bzero(&wc, sizeof wc);
3207         mask = CWBorderWidth | CWWidth | CWHeight;
3208         wc.border_width = border_width;
3209         wc.width = win->g.w;
3210         wc.height = win->g.h;
3211         if (center == SWM_ARG_ID_CENTER) {
3212                 wc.x = (WIDTH(r) - win->g.w) / 2 - border_width;
3213                 wc.y = (HEIGHT(r) - win->g.h) / 2 - border_width;
3214                 mask |= CWX | CWY;
3215         }
3216
3217         DNPRINTF(SWM_D_STACK, "resize_window: win %lu x %d y %d w %d h %d\n",
3218             win->id, wc.x, wc.y, wc.width, wc.height);
3219
3220         XConfigureWindow(display, win->id, mask, &wc);
3221 }
3222
3223 void
3224 resize(struct ws_win *win, union arg *args)
3225 {
3226         XEvent                  ev;
3227         Time                    time = 0;
3228         struct swm_region       *r = win->ws->r;
3229         int                     relx, rely;
3230
3231
3232         DNPRINTF(SWM_D_MOUSE, "resize: win %lu floating %d trans %lu\n",
3233             win->id, win->floating, win->transient);
3234
3235         if (!(win->transient != 0 || win->floating != 0))
3236                 return;
3237
3238         /* reject resizes in max mode for floaters (transient ok) */
3239         if (win->floatmaxed)
3240                 return;
3241
3242         win->manual = 1;
3243         ewmh_update_win_state(win, ewmh[_SWM_WM_STATE_MANUAL].atom,
3244             _NET_WM_STATE_ADD);
3245
3246         stack();
3247         if (focus_mode == SWM_FOCUS_DEFAULT)
3248                 drain_enter_notify();
3249
3250         if (XGrabPointer(display, win->id, False, MOUSEMASK, GrabModeAsync,
3251             GrabModeAsync, None, None /* cursor */, CurrentTime) != GrabSuccess)
3252                 return;
3253
3254         /* place pointer at bottom left corner or nearest point inside r */
3255         if ( win->g.x + win->g.w < r->g.x + r->g.w - 1)
3256                 relx = win->g.w - 1;
3257         else
3258                 relx = r->g.x + r->g.w - win->g.x - 1;
3259
3260         if ( win->g.y + win->g.h < r->g.y + r->g.h - 1)
3261                 rely = win->g.h - 1;
3262         else
3263                 rely = r->g.y + r->g.h - win->g.y - 1;
3264
3265         XWarpPointer(display, None, win->id, 0, 0, 0, 0, relx, rely);
3266         do {
3267                 XMaskEvent(display, MOUSEMASK | ExposureMask |
3268                     SubstructureRedirectMask, &ev);
3269                 switch (ev.type) {
3270                 case ConfigureRequest:
3271                 case Expose:
3272                 case MapRequest:
3273                         handler[ev.type](&ev);
3274                         break;
3275                 case MotionNotify:
3276                         /* do not allow resize outside of region */
3277                         if (    ev.xmotion.x_root < r->g.x ||
3278                                 ev.xmotion.x_root > r->g.x + r->g.w - 1 ||
3279                                 ev.xmotion.y_root < r->g.y ||
3280                                 ev.xmotion.y_root > r->g.y + r->g.h - 1)
3281                                 continue;
3282
3283                         if (ev.xmotion.x <= 1)
3284                                 ev.xmotion.x = 1;
3285                         if (ev.xmotion.y <= 1)
3286                                 ev.xmotion.y = 1;
3287                         win->g.w = ev.xmotion.x + 1;
3288                         win->g.h = ev.xmotion.y + 1;
3289
3290                         /* not free, don't sync more than 120 times / second */
3291                         if ((ev.xmotion.time - time) > (1000 / 120) ) {
3292                                 time = ev.xmotion.time;
3293                                 XSync(display, False);
3294                                 resize_window(win, args->id);
3295                         }
3296                         break;
3297                 }
3298         } while (ev.type != ButtonRelease);
3299         if (time) {
3300                 XSync(display, False);
3301                 resize_window(win, args->id);
3302         }
3303         store_float_geom(win,r);
3304
3305         XWarpPointer(display, None, win->id, 0, 0, 0, 0, win->g.w - 1,
3306             win->g.h - 1);
3307         XUngrabPointer(display, CurrentTime);
3308
3309         /* drain events */
3310         drain_enter_notify();
3311 }
3312
3313 void
3314 move_window(struct ws_win *win)
3315 {
3316         unsigned int            mask;
3317         XWindowChanges          wc;
3318         struct swm_region       *r;
3319
3320         r = root_to_region(win->wa.root);
3321         bzero(&wc, sizeof wc);
3322         mask = CWX | CWY;
3323         wc.x = win->g.x;
3324         wc.y = win->g.y;
3325         wc.border_width = border_width;
3326
3327         DNPRINTF(SWM_D_STACK, "move_window: win %lu x %d y %d w %d h %d\n",
3328             win->id, wc.x, wc.y, wc.width, wc.height);
3329
3330         XConfigureWindow(display, win->id, mask, &wc);
3331 }
3332
3333 void
3334 move(struct ws_win *win, union arg *args)
3335 {
3336         XEvent                  ev;
3337         Time                    time = 0;
3338         struct swm_region       *r = win->ws->r;
3339
3340         DNPRINTF(SWM_D_MOUSE, "move: win %lu floating %d trans %lu\n",
3341             win->id, win->floating, win->transient);
3342
3343         /* in max_stack mode should only move transients */
3344         if (win->ws->cur_layout == &layouts[SWM_MAX_STACK] && !win->transient)
3345                 return;
3346
3347         win->manual = 1;
3348         if (win->floating == 0 && !win->transient) {
3349                 ewmh_update_win_state(win, ewmh[_NET_WM_STATE_ABOVE].atom,
3350                     _NET_WM_STATE_ADD);
3351         }
3352         ewmh_update_win_state(win, ewmh[_SWM_WM_STATE_MANUAL].atom,
3353             _NET_WM_STATE_ADD);
3354
3355         stack();
3356
3357         if (XGrabPointer(display, win->id, False, MOUSEMASK, GrabModeAsync,
3358             GrabModeAsync, None, None /* cursor */, CurrentTime) != GrabSuccess)
3359                 return;
3360         XWarpPointer(display, None, win->id, 0, 0, 0, 0, 0, 0);
3361         do {
3362                 XMaskEvent(display, MOUSEMASK | ExposureMask |
3363                     SubstructureRedirectMask, &ev);
3364                 switch (ev.type) {
3365                 case ConfigureRequest:
3366                 case Expose:
3367                 case MapRequest:
3368                         handler[ev.type](&ev);
3369                         break;
3370                 case MotionNotify:
3371                         /* don't allow to move window origin out of region */
3372                         if (    ev.xmotion.x_root < r->g.x ||
3373                                 ev.xmotion.x_root > r->g.x + r->g.w - 1 ||
3374                                 ev.xmotion.y_root < r->g.y ||
3375                                 ev.xmotion.y_root > r->g.y + r->g.h - 1)
3376                                 continue;
3377
3378                         win->g.x = ev.xmotion.x_root - border_width;
3379                         win->g.y = ev.xmotion.y_root - border_width;
3380
3381                         /* not free, don't sync more than 120 times / second */
3382                         if ((ev.xmotion.time - time) > (1000 / 120) ) {
3383                                 time = ev.xmotion.time;
3384                                 XSync(display, False);
3385                                 move_window(win);
3386                         }
3387                         break;
3388                 }
3389         } while (ev.type != ButtonRelease);
3390         if (time) {
3391                 XSync(display, False);
3392                 move_window(win);
3393         }
3394         store_float_geom(win,r);
3395         XWarpPointer(display, None, win->id, 0, 0, 0, 0, 0, 0);
3396         XUngrabPointer(display, CurrentTime);
3397
3398         /* drain events */
3399         drain_enter_notify();
3400 }
3401
3402 /* user/key callable function IDs */
3403 enum keyfuncid {
3404         kf_cycle_layout,
3405         kf_stack_reset,
3406         kf_master_shrink,
3407         kf_master_grow,
3408         kf_master_add,
3409         kf_master_del,
3410         kf_stack_inc,
3411         kf_stack_dec,
3412         kf_swap_main,
3413         kf_focus_next,
3414         kf_focus_prev,
3415         kf_swap_next,
3416         kf_swap_prev,
3417         kf_spawn_term,
3418         kf_spawn_menu,
3419         kf_quit,
3420         kf_restart,
3421         kf_focus_main,
3422         kf_ws_1,
3423         kf_ws_2,
3424         kf_ws_3,
3425         kf_ws_4,
3426         kf_ws_5,
3427         kf_ws_6,
3428         kf_ws_7,
3429         kf_ws_8,
3430         kf_ws_9,
3431         kf_ws_10,
3432         kf_ws_next,
3433         kf_ws_prev,
3434         kf_ws_prior,
3435         kf_screen_next,
3436         kf_screen_prev,
3437         kf_mvws_1,
3438         kf_mvws_2,
3439         kf_mvws_3,
3440         kf_mvws_4,
3441         kf_mvws_5,
3442         kf_mvws_6,
3443         kf_mvws_7,
3444         kf_mvws_8,
3445         kf_mvws_9,
3446         kf_mvws_10,
3447         kf_bar_toggle,
3448         kf_wind_kill,
3449         kf_wind_del,
3450         kf_screenshot_all,
3451         kf_screenshot_wind,
3452         kf_float_toggle,
3453         kf_version,
3454         kf_spawn_lock,
3455         kf_spawn_initscr,
3456         kf_spawn_custom,
3457         kf_iconify,
3458         kf_uniconify,
3459         kf_dumpwins, /* MUST BE LAST */
3460         kf_invalid
3461 };
3462
3463 /* key definitions */
3464 void
3465 dummykeyfunc(struct swm_region *r, union arg *args)
3466 {
3467 };
3468
3469 void
3470 legacyfunc(struct swm_region *r, union arg *args)
3471 {
3472 };
3473
3474 struct keyfunc {
3475         char                    name[SWM_FUNCNAME_LEN];
3476         void                    (*func)(struct swm_region *r, union arg *);
3477         union arg               args;
3478 } keyfuncs[kf_invalid + 1] = {
3479         /* name                 function        argument */
3480         { "cycle_layout",       cycle_layout,   {0} },
3481         { "stack_reset",        stack_config,   {.id = SWM_ARG_ID_STACKRESET} },
3482         { "master_shrink",      stack_config,   {.id = SWM_ARG_ID_MASTERSHRINK} },
3483         { "master_grow",        stack_config,   {.id = SWM_ARG_ID_MASTERGROW} },
3484         { "master_add",         stack_config,   {.id = SWM_ARG_ID_MASTERADD} },
3485         { "master_del",         stack_config,   {.id = SWM_ARG_ID_MASTERDEL} },
3486         { "stack_inc",          stack_config,   {.id = SWM_ARG_ID_STACKINC} },
3487         { "stack_dec",          stack_config,   {.id = SWM_ARG_ID_STACKDEC} },
3488         { "swap_main",          swapwin,        {.id = SWM_ARG_ID_SWAPMAIN} },
3489         { "focus_next",         focus,          {.id = SWM_ARG_ID_FOCUSNEXT} },
3490         { "focus_prev",         focus,          {.id = SWM_ARG_ID_FOCUSPREV} },
3491         { "swap_next",          swapwin,        {.id = SWM_ARG_ID_SWAPNEXT} },
3492         { "swap_prev",          swapwin,        {.id = SWM_ARG_ID_SWAPPREV} },
3493         { "spawn_term",         spawnterm,      {.argv = spawn_term} },
3494         { "spawn_menu",         legacyfunc,     {0} },
3495         { "quit",               quit,           {0} },
3496         { "restart",            restart,        {0} },
3497         { "focus_main",         focus,          {.id = SWM_ARG_ID_FOCUSMAIN} },
3498         { "ws_1",               switchws,       {.id = 0} },
3499         { "ws_2",               switchws,       {.id = 1} },
3500         { "ws_3",               switchws,       {.id = 2} },
3501         { "ws_4",               switchws,       {.id = 3} },
3502         { "ws_5",               switchws,       {.id = 4} },
3503         { "ws_6",               switchws,       {.id = 5} },
3504         { "ws_7",               switchws,       {.id = 6} },
3505         { "ws_8",               switchws,       {.id = 7} },
3506         { "ws_9",               switchws,       {.id = 8} },
3507         { "ws_10",              switchws,       {.id = 9} },
3508         { "ws_next",            cyclews,        {.id = SWM_ARG_ID_CYCLEWS_UP} },
3509         { "ws_prev",            cyclews,        {.id = SWM_ARG_ID_CYCLEWS_DOWN} },
3510         { "ws_prior",           priorws,        {0} },
3511         { "screen_next",        cyclescr,       {.id = SWM_ARG_ID_CYCLESC_UP} },
3512         { "screen_prev",        cyclescr,       {.id = SWM_ARG_ID_CYCLESC_DOWN} },
3513         { "mvws_1",             send_to_ws,     {.id = 0} },
3514         { "mvws_2",             send_to_ws,     {.id = 1} },
3515         { "mvws_3",             send_to_ws,     {.id = 2} },
3516         { "mvws_4",             send_to_ws,     {.id = 3} },
3517         { "mvws_5",             send_to_ws,     {.id = 4} },
3518         { "mvws_6",             send_to_ws,     {.id = 5} },
3519         { "mvws_7",             send_to_ws,     {.id = 6} },
3520         { "mvws_8",             send_to_ws,     {.id = 7} },
3521         { "mvws_9",             send_to_ws,     {.id = 8} },
3522         { "mvws_10",            send_to_ws,     {.id = 9} },
3523         { "bar_toggle",         bar_toggle,     {0} },
3524         { "wind_kill",          wkill,          {.id = SWM_ARG_ID_KILLWINDOW} },
3525         { "wind_del",           wkill,          {.id = SWM_ARG_ID_DELETEWINDOW} },
3526         { "screenshot_all",     legacyfunc,     {0} },
3527         { "screenshot_wind",    legacyfunc,     {0} },
3528         { "float_toggle",       floating_toggle,{0} },
3529         { "version",            version,        {0} },
3530         { "spawn_lock",         legacyfunc,     {0} },
3531         { "spawn_initscr",      legacyfunc,     {0} },
3532         { "spawn_custom",       dummykeyfunc,   {0} },
3533         { "iconify",            iconify,        {0} },
3534         { "uniconify",          uniconify,      {0} },
3535         { "dumpwins",           dumpwins,       {0} }, /* MUST BE LAST */
3536         { "invalid key func",   NULL,           {0} },
3537 };
3538 struct key {
3539         unsigned int            mod;
3540         KeySym                  keysym;
3541         enum keyfuncid          funcid;
3542         char                    *spawn_name;
3543 };
3544 int                             keys_size = 0, keys_length = 0;
3545 struct key                      *keys = NULL;
3546
3547 /* mouse */
3548 enum { client_click, root_click };
3549 struct button {
3550         unsigned int            action;
3551         unsigned int            mask;
3552         unsigned int            button;
3553         void                    (*func)(struct ws_win *, union arg *);
3554         union arg               args;
3555 } buttons[] = {
3556           /* action     key             mouse button    func    args */
3557         { client_click, MODKEY,         Button3,        resize, {.id = SWM_ARG_ID_DONTCENTER} },
3558         { client_click, MODKEY | ShiftMask, Button3,    resize, {.id = SWM_ARG_ID_CENTER} },
3559         { client_click, MODKEY,         Button1,        move,   {0} },
3560 };
3561
3562 void
3563 update_modkey(unsigned int mod)
3564 {
3565         int                     i;
3566
3567         mod_key = mod;
3568         for (i = 0; i < keys_length; i++)
3569                 if (keys[i].mod & ShiftMask)
3570                         keys[i].mod = mod | ShiftMask;
3571                 else
3572                         keys[i].mod = mod;
3573
3574         for (i = 0; i < LENGTH(buttons); i++)
3575                 if (buttons[i].mask & ShiftMask)
3576                         buttons[i].mask = mod | ShiftMask;
3577                 else
3578                         buttons[i].mask = mod;
3579 }
3580
3581 /* spawn */
3582 struct spawn_prog {
3583         char                    *name;
3584         int                     argc;
3585         char                    **argv;
3586 };
3587
3588 int                             spawns_size = 0, spawns_length = 0;
3589 struct spawn_prog               *spawns = NULL;
3590
3591 int
3592 spawn_expand(struct swm_region *r, union arg *args, char *spawn_name,
3593     char ***ret_args)
3594 {
3595         struct spawn_prog       *prog = NULL;
3596         int                     i;
3597         char                    *ap, **real_args;
3598
3599         DNPRINTF(SWM_D_SPAWN, "spawn_expand %s\n", spawn_name);
3600
3601         /* find program */
3602         for (i = 0; i < spawns_length; i++) {
3603                 if (!strcasecmp(spawn_name, spawns[i].name))
3604                         prog = &spawns[i];
3605         }
3606         if (prog == NULL) {
3607                 fprintf(stderr, "spawn_custom: program %s not found\n",
3608                     spawn_name);
3609                 return (-1);
3610         }
3611
3612         /* make room for expanded args */
3613         if ((real_args = calloc(prog->argc + 1, sizeof(char *))) == NULL)
3614                 err(1, "spawn_custom: calloc real_args");
3615
3616         /* expand spawn_args into real_args */
3617         for (i = 0; i < prog->argc; i++) {
3618                 ap = prog->argv[i];
3619                 DNPRINTF(SWM_D_SPAWN, "spawn_custom: raw arg = %s\n", ap);
3620                 if (!strcasecmp(ap, "$bar_border")) {
3621                         if ((real_args[i] =
3622                             strdup(r->s->c[SWM_S_COLOR_BAR_BORDER].name))
3623                             == NULL)
3624                                 err(1,  "spawn_custom border color");
3625                 } else if (!strcasecmp(ap, "$bar_color")) {
3626                         if ((real_args[i] =
3627                             strdup(r->s->c[SWM_S_COLOR_BAR].name))
3628                             == NULL)
3629                                 err(1, "spawn_custom bar color");
3630                 } else if (!strcasecmp(ap, "$bar_font")) {
3631                         if ((real_args[i] = strdup(bar_fonts[bar_fidx]))
3632                             == NULL)
3633                                 err(1, "spawn_custom bar fonts");
3634                 } else if (!strcasecmp(ap, "$bar_font_color")) {
3635                         if ((real_args[i] =
3636                             strdup(r->s->c[SWM_S_COLOR_BAR_FONT].name))
3637                             == NULL)
3638                                 err(1, "spawn_custom color font");
3639                 } else if (!strcasecmp(ap, "$color_focus")) {
3640                         if ((real_args[i] =
3641                             strdup(r->s->c[SWM_S_COLOR_FOCUS].name))
3642                             == NULL)
3643                                 err(1, "spawn_custom color focus");
3644                 } else if (!strcasecmp(ap, "$color_unfocus")) {
3645                         if ((real_args[i] =
3646                             strdup(r->s->c[SWM_S_COLOR_UNFOCUS].name))
3647                             == NULL)
3648                                 err(1, "spawn_custom color unfocus");
3649                 } else {
3650                         /* no match --> copy as is */
3651                         if ((real_args[i] = strdup(ap)) == NULL)
3652                                 err(1, "spawn_custom strdup(ap)");
3653                 }
3654                 DNPRINTF(SWM_D_SPAWN, "spawn_custom: cooked arg = %s\n",
3655                     real_args[i]);
3656         }
3657
3658 #ifdef SWM_DEBUG
3659         if ((swm_debug & SWM_D_SPAWN) != 0) {
3660                 fprintf(stderr, "spawn_custom: result = ");
3661                 for (i = 0; i < prog->argc; i++)
3662                         fprintf(stderr, "\"%s\" ", real_args[i]);
3663                 fprintf(stderr, "\n");
3664         }
3665 #endif
3666         *ret_args = real_args;
3667         return (prog->argc);
3668 }
3669
3670 void
3671 spawn_custom(struct swm_region *r, union arg *args, char *spawn_name)
3672 {
3673         union arg               a;
3674         char                    **real_args;
3675         int                     spawn_argc, i;
3676
3677         if ((spawn_argc = spawn_expand(r, args, spawn_name, &real_args)) < 0)
3678                 return;
3679         a.argv = real_args;
3680         if (fork() == 0)
3681                 spawn(r, &a, 1);
3682
3683         for (i = 0; i < spawn_argc; i++)
3684                 free(real_args[i]);
3685         free(real_args);
3686 }
3687
3688 void
3689 spawn_select(struct swm_region *r, union arg *args, char *spawn_name, int *pid)
3690 {
3691         union arg               a;
3692         char                    **real_args;
3693         int                     i, spawn_argc;
3694
3695         if ((spawn_argc = spawn_expand(r, args, spawn_name, &real_args)) < 0)
3696                 return;
3697         a.argv = real_args;
3698
3699         if (pipe(select_list_pipe) == -1)
3700                 err(1, "pipe error");
3701         if (pipe(select_resp_pipe) == -1)
3702                 err(1, "pipe error");
3703
3704         if (signal(SIGPIPE, SIG_IGN) == SIG_ERR)
3705                 err(1, "could not disable SIGPIPE");
3706         switch (*pid = fork()) {
3707         case -1:
3708                 err(1, "cannot fork");
3709                 break;
3710         case 0: /* child */
3711                 if (dup2(select_list_pipe[0], 0) == -1)
3712                         errx(1, "dup2");
3713                 if (dup2(select_resp_pipe[1], 1) == -1)
3714                         errx(1, "dup2");
3715                 close(select_list_pipe[1]);
3716                 close(select_resp_pipe[0]);
3717                 spawn(r, &a, 0);
3718                 break;
3719         default: /* parent */
3720                 close(select_list_pipe[0]);
3721                 close(select_resp_pipe[1]);
3722                 break;
3723         }
3724
3725         for (i = 0; i < spawn_argc; i++)
3726                 free(real_args[i]);
3727         free(real_args);
3728 }
3729
3730 void
3731 setspawn(struct spawn_prog *prog)
3732 {
3733         int                     i, j;
3734
3735         if (prog == NULL || prog->name == NULL)
3736                 return;
3737
3738         /* find existing */
3739         for (i = 0; i < spawns_length; i++) {
3740                 if (!strcmp(spawns[i].name, prog->name)) {
3741                         /* found */
3742                         if (prog->argv == NULL) {
3743                                 /* delete */
3744                                 DNPRINTF(SWM_D_SPAWN,
3745                                     "setspawn: delete #%d %s\n",
3746                                     i, spawns[i].name);
3747                                 free(spawns[i].name);
3748                                 for (j = 0; j < spawns[i].argc; j++)
3749                                         free(spawns[i].argv[j]);
3750                                 free(spawns[i].argv);
3751                                 j = spawns_length - 1;
3752                                 if (i < j)
3753                                         spawns[i] = spawns[j];
3754                                 spawns_length--;
3755                                 free(prog->name);
3756                         } else {
3757                                 /* replace */
3758                                 DNPRINTF(SWM_D_SPAWN,
3759                                     "setspawn: replace #%d %s\n",
3760                                     i, spawns[i].name);
3761                                 free(spawns[i].name);
3762                                 for (j = 0; j < spawns[i].argc; j++)
3763                                         free(spawns[i].argv[j]);
3764                                 free(spawns[i].argv);
3765                                 spawns[i] = *prog;
3766                         }
3767                         /* found case handled */
3768                         free(prog);
3769                         return;
3770                 }
3771         }
3772
3773         if (prog->argv == NULL) {
3774                 fprintf(stderr,
3775                     "error: setspawn: cannot find program %s", prog->name);
3776                 free(prog);
3777                 return;
3778         }
3779
3780         /* not found: add */
3781         if (spawns_size == 0 || spawns == NULL) {
3782                 spawns_size = 4;
3783                 DNPRINTF(SWM_D_SPAWN, "setspawn: init list %d\n", spawns_size);
3784                 spawns = malloc((size_t)spawns_size *
3785                     sizeof(struct spawn_prog));
3786                 if (spawns == NULL) {
3787                         fprintf(stderr, "setspawn: malloc failed\n");
3788                         perror(" failed");
3789                         quit(NULL, NULL);
3790                 }
3791         } else if (spawns_length == spawns_size) {
3792                 spawns_size *= 2;
3793                 DNPRINTF(SWM_D_SPAWN, "setspawn: grow list %d\n", spawns_size);
3794                 spawns = realloc(spawns, (size_t)spawns_size *
3795                     sizeof(struct spawn_prog));
3796                 if (spawns == NULL) {
3797                         fprintf(stderr, "setspawn: realloc failed\n");
3798                         perror(" failed");
3799                         quit(NULL, NULL);
3800                 }
3801         }
3802
3803         if (spawns_length < spawns_size) {
3804                 DNPRINTF(SWM_D_SPAWN, "setspawn: add #%d %s\n",
3805                     spawns_length, prog->name);
3806                 i = spawns_length++;
3807                 spawns[i] = *prog;
3808         } else {
3809                 fprintf(stderr, "spawns array problem?\n");
3810                 if (spawns == NULL) {
3811                         fprintf(stderr, "spawns array is NULL!\n");
3812                         quit(NULL, NULL);
3813                 }
3814         }
3815         free(prog);
3816 }
3817
3818 int
3819 setconfspawn(char *selector, char *value, int flags)
3820 {
3821         struct spawn_prog       *prog;
3822         char                    *vp, *cp, *word;
3823
3824         DNPRINTF(SWM_D_SPAWN, "setconfspawn: [%s] [%s]\n", selector, value);
3825         if ((prog = calloc(1, sizeof *prog)) == NULL)
3826                 err(1, "setconfspawn: calloc prog");
3827         prog->name = strdup(selector);
3828         if (prog->name == NULL)
3829                 err(1, "setconfspawn prog->name");
3830         if ((cp = vp = strdup(value)) == NULL)
3831                 err(1, "setconfspawn: strdup(value) ");
3832         while ((word = strsep(&cp, " \t")) != NULL) {
3833                 DNPRINTF(SWM_D_SPAWN, "setconfspawn: arg [%s]\n", word);
3834                 if (cp)
3835                         cp += (long)strspn(cp, " \t");
3836                 if (strlen(word) > 0) {
3837                         prog->argc++;
3838                         prog->argv = realloc(prog->argv,
3839                             prog->argc * sizeof(char *));
3840                         if ((prog->argv[prog->argc - 1] = strdup(word)) == NULL)
3841                                 err(1, "setconfspawn: strdup");
3842                 }
3843         }
3844         free(vp);
3845
3846         setspawn(prog);
3847
3848         DNPRINTF(SWM_D_SPAWN, "setconfspawn: done\n");
3849         return (0);
3850 }
3851
3852 void
3853 setup_spawn(void)
3854 {
3855         setconfspawn("term",            "xterm",                0);
3856         setconfspawn("screenshot_all",  "screenshot.sh full",   0);
3857         setconfspawn("screenshot_wind", "screenshot.sh window", 0);
3858         setconfspawn("lock",            "xlock",                0);
3859         setconfspawn("initscr",         "initscreen.sh",        0);
3860         setconfspawn("menu",            "dmenu_run"
3861                                         " -fn $bar_font"
3862                                         " -nb $bar_color"
3863                                         " -nf $bar_font_color"
3864                                         " -sb $bar_border"
3865                                         " -sf $bar_color",      0);
3866         setconfspawn("uniconify",       "dmenu"
3867                                         " -i"
3868                                         " -fn $bar_font"
3869                                         " -nb $bar_color"
3870                                         " -nf $bar_font_color"
3871                                         " -sb $bar_border"
3872                                         " -sf $bar_color",      0);
3873 }
3874
3875 /* key bindings */
3876 #define SWM_MODNAME_SIZE        32
3877 #define SWM_KEY_WS              "\n+ \t"
3878 int
3879 parsekeys(char *keystr, unsigned int currmod, unsigned int *mod, KeySym *ks)
3880 {
3881         char                    *cp, *name;
3882         KeySym                  uks;
3883         DNPRINTF(SWM_D_KEY, "parsekeys: enter [%s]\n", keystr);
3884         if (mod == NULL || ks == NULL) {
3885                 DNPRINTF(SWM_D_KEY, "parsekeys: no mod or key vars\n");
3886                 return (1);
3887         }
3888         if (keystr == NULL || strlen(keystr) == 0) {
3889                 DNPRINTF(SWM_D_KEY, "parsekeys: no keystr\n");
3890                 return (1);
3891         }
3892         cp = keystr;
3893         *ks = NoSymbol;
3894         *mod = 0;
3895         while ((name = strsep(&cp, SWM_KEY_WS)) != NULL) {
3896                 DNPRINTF(SWM_D_KEY, "parsekeys: key [%s]\n", name);
3897                 if (cp)
3898                         cp += (long)strspn(cp, SWM_KEY_WS);
3899                 if (strncasecmp(name, "MOD", SWM_MODNAME_SIZE) == 0)
3900                         *mod |= currmod;
3901                 else if (!strncasecmp(name, "Mod1", SWM_MODNAME_SIZE))
3902                         *mod |= Mod1Mask;
3903                 else if (!strncasecmp(name, "Mod2", SWM_MODNAME_SIZE))
3904                         *mod += Mod2Mask;
3905                 else if (!strncmp(name, "Mod3", SWM_MODNAME_SIZE))
3906                         *mod |= Mod3Mask;
3907                 else if (!strncmp(name, "Mod4", SWM_MODNAME_SIZE))
3908                         *mod |= Mod4Mask;
3909                 else if (strncasecmp(name, "SHIFT", SWM_MODNAME_SIZE) == 0)
3910                         *mod |= ShiftMask;
3911                 else if (strncasecmp(name, "CONTROL", SWM_MODNAME_SIZE) == 0)
3912                         *mod |= ControlMask;
3913                 else {
3914                         *ks = XStringToKeysym(name);
3915                         XConvertCase(*ks, ks, &uks);
3916                         if (ks == NoSymbol) {
3917                                 DNPRINTF(SWM_D_KEY,
3918                                     "parsekeys: invalid key %s\n",
3919                                     name);
3920                                 return (1);
3921                         }
3922                 }
3923         }
3924         DNPRINTF(SWM_D_KEY, "parsekeys: leave ok\n");
3925         return (0);
3926 }
3927
3928 char *
3929 strdupsafe(char *str)
3930 {
3931         if (str == NULL)
3932                 return (NULL);
3933         else
3934                 return (strdup(str));
3935 }
3936
3937 void
3938 setkeybinding(unsigned int mod, KeySym ks, enum keyfuncid kfid,
3939     char *spawn_name)
3940 {
3941         int                     i, j;
3942         DNPRINTF(SWM_D_KEY, "setkeybinding: enter %s [%s]\n",
3943             keyfuncs[kfid].name, spawn_name);
3944         /* find existing */
3945         for (i = 0; i < keys_length; i++) {
3946                 if (keys[i].mod == mod && keys[i].keysym == ks) {
3947                         if (kfid == kf_invalid) {
3948                                 /* found: delete */
3949                                 DNPRINTF(SWM_D_KEY,
3950                                     "setkeybinding: delete #%d %s\n",
3951                                     i, keyfuncs[keys[i].funcid].name);
3952                                 free(keys[i].spawn_name);
3953                                 j = keys_length - 1;
3954                                 if (i < j)
3955                                         keys[i] = keys[j];
3956                                 keys_length--;
3957                                 DNPRINTF(SWM_D_KEY, "setkeybinding: leave\n");
3958                                 return;
3959                         } else {
3960                                 /* found: replace */
3961                                 DNPRINTF(SWM_D_KEY,
3962                                     "setkeybinding: replace #%d %s %s\n",
3963                                     i, keyfuncs[keys[i].funcid].name,
3964                                     spawn_name);
3965                                 free(keys[i].spawn_name);
3966                                 keys[i].mod = mod;
3967                                 keys[i].keysym = ks;
3968                                 keys[i].funcid = kfid;
3969                                 keys[i].spawn_name = strdupsafe(spawn_name);
3970                                 DNPRINTF(SWM_D_KEY, "setkeybinding: leave\n");
3971                                 return;
3972                         }
3973                 }
3974         }
3975         if (kfid == kf_invalid) {
3976                 fprintf(stderr,
3977                     "error: setkeybinding: cannot find mod/key combination");
3978                 DNPRINTF(SWM_D_KEY, "setkeybinding: leave\n");
3979                 return;
3980         }
3981         /* not found: add */
3982         if (keys_size == 0 || keys == NULL) {
3983                 keys_size = 4;
3984                 DNPRINTF(SWM_D_KEY, "setkeybinding: init list %d\n", keys_size);
3985                 keys = malloc((size_t)keys_size * sizeof(struct key));
3986                 if (!keys) {
3987                         fprintf(stderr, "malloc failed\n");
3988                         perror(" failed");
3989                         quit(NULL, NULL);
3990                 }
3991         } else if (keys_length == keys_size) {
3992                 keys_size *= 2;
3993                 DNPRINTF(SWM_D_KEY, "setkeybinding: grow list %d\n", keys_size);
3994                 keys = realloc(keys, (size_t)keys_size * sizeof(struct key));
3995                 if (!keys) {
3996                         fprintf(stderr, "realloc failed\n");
3997                         perror(" failed");
3998                         quit(NULL, NULL);
3999                 }
4000         }
4001         if (keys_length < keys_size) {
4002                 j = keys_length++;
4003                 DNPRINTF(SWM_D_KEY, "setkeybinding: add #%d %s %s\n",
4004                     j, keyfuncs[kfid].name, spawn_name);
4005                 keys[j].mod = mod;
4006                 keys[j].keysym = ks;
4007                 keys[j].funcid = kfid;
4008                 keys[j].spawn_name = strdupsafe(spawn_name);
4009         } else {
4010                 fprintf(stderr, "keys array problem?\n");
4011                 if (!keys) {
4012                         fprintf(stderr, "keys array problem\n");
4013                         quit(NULL, NULL);
4014                 }
4015         }
4016         DNPRINTF(SWM_D_KEY, "setkeybinding: leave\n");
4017 }
4018
4019 int
4020 setconfbinding(char *selector, char *value, int flags)
4021 {
4022         enum keyfuncid          kfid;
4023         unsigned int            mod;
4024         KeySym                  ks;
4025         int                     i;
4026         DNPRINTF(SWM_D_KEY, "setconfbinding: enter\n");
4027         if (selector == NULL) {
4028                 DNPRINTF(SWM_D_KEY, "setconfbinding: unbind %s\n", value);
4029                 if (parsekeys(value, mod_key, &mod, &ks) == 0) {
4030                         kfid = kf_invalid;
4031                         setkeybinding(mod, ks, kfid, NULL);
4032                         return (0);
4033                 } else
4034                         return (1);
4035         }
4036         /* search by key function name */
4037         for (kfid = 0; kfid < kf_invalid; (kfid)++) {
4038                 if (strncasecmp(selector, keyfuncs[kfid].name,
4039                     SWM_FUNCNAME_LEN) == 0) {
4040                         DNPRINTF(SWM_D_KEY, "setconfbinding: %s: match\n",
4041                             selector);
4042                         if (parsekeys(value, mod_key, &mod, &ks) == 0) {
4043                                 setkeybinding(mod, ks, kfid, NULL);
4044                                 return (0);
4045                         } else
4046                                 return (1);
4047                 }
4048         }
4049         /* search by custom spawn name */
4050         for (i = 0; i < spawns_length; i++) {
4051                 if (strcasecmp(selector, spawns[i].name) == 0) {
4052                         DNPRINTF(SWM_D_KEY, "setconfbinding: %s: match\n",
4053                             selector);
4054                         if (parsekeys(value, mod_key, &mod, &ks) == 0) {
4055                                 setkeybinding(mod, ks, kf_spawn_custom,
4056                                     spawns[i].name);
4057                                 return (0);
4058                         } else
4059                                 return (1);
4060                 }
4061         }
4062         DNPRINTF(SWM_D_KEY, "setconfbinding: no match\n");
4063         return (1);
4064 }
4065
4066 void
4067 setup_keys(void)
4068 {
4069         setkeybinding(MODKEY,           XK_space,       kf_cycle_layout,NULL);
4070         setkeybinding(MODKEY|ShiftMask, XK_space,       kf_stack_reset, NULL);
4071         setkeybinding(MODKEY,           XK_h,           kf_master_shrink,NULL);
4072         setkeybinding(MODKEY,           XK_l,           kf_master_grow, NULL);
4073         setkeybinding(MODKEY,           XK_comma,       kf_master_add,  NULL);
4074         setkeybinding(MODKEY,           XK_period,      kf_master_del,  NULL);
4075         setkeybinding(MODKEY|ShiftMask, XK_comma,       kf_stack_inc,   NULL);
4076         setkeybinding(MODKEY|ShiftMask, XK_period,      kf_stack_dec,   NULL);
4077         setkeybinding(MODKEY,           XK_Return,      kf_swap_main,   NULL);
4078         setkeybinding(MODKEY,           XK_j,           kf_focus_next,  NULL);
4079         setkeybinding(MODKEY,           XK_k,           kf_focus_prev,  NULL);
4080         setkeybinding(MODKEY|ShiftMask, XK_j,           kf_swap_next,   NULL);
4081         setkeybinding(MODKEY|ShiftMask, XK_k,           kf_swap_prev,   NULL);
4082         setkeybinding(MODKEY|ShiftMask, XK_Return,      kf_spawn_term,  NULL);
4083         setkeybinding(MODKEY,           XK_p,           kf_spawn_custom,        "menu");
4084         setkeybinding(MODKEY|ShiftMask, XK_q,           kf_quit,        NULL);
4085         setkeybinding(MODKEY,           XK_q,           kf_restart,     NULL);
4086         setkeybinding(MODKEY,           XK_m,           kf_focus_main,  NULL);
4087         setkeybinding(MODKEY,           XK_1,           kf_ws_1,        NULL);
4088         setkeybinding(MODKEY,           XK_2,           kf_ws_2,        NULL);
4089         setkeybinding(MODKEY,           XK_3,           kf_ws_3,        NULL);
4090         setkeybinding(MODKEY,           XK_4,           kf_ws_4,        NULL);
4091         setkeybinding(MODKEY,           XK_5,           kf_ws_5,        NULL);
4092         setkeybinding(MODKEY,           XK_6,           kf_ws_6,        NULL);
4093         setkeybinding(MODKEY,           XK_7,           kf_ws_7,        NULL);
4094         setkeybinding(MODKEY,           XK_8,           kf_ws_8,        NULL);
4095         setkeybinding(MODKEY,           XK_9,           kf_ws_9,        NULL);
4096         setkeybinding(MODKEY,           XK_0,           kf_ws_10,       NULL);
4097         setkeybinding(MODKEY,           XK_Right,       kf_ws_next,     NULL);
4098         setkeybinding(MODKEY,           XK_Left,        kf_ws_prev,     NULL);
4099         setkeybinding(MODKEY,           XK_a,           kf_ws_prior,    NULL);
4100         setkeybinding(MODKEY|ShiftMask, XK_Right,       kf_screen_next, NULL);
4101         setkeybinding(MODKEY|ShiftMask, XK_Left,        kf_screen_prev, NULL);
4102         setkeybinding(MODKEY|ShiftMask, XK_1,           kf_mvws_1,      NULL);
4103         setkeybinding(MODKEY|ShiftMask, XK_2,           kf_mvws_2,      NULL);
4104         setkeybinding(MODKEY|ShiftMask, XK_3,           kf_mvws_3,      NULL);
4105         setkeybinding(MODKEY|ShiftMask, XK_4,           kf_mvws_4,      NULL);
4106         setkeybinding(MODKEY|ShiftMask, XK_5,           kf_mvws_5,      NULL);
4107         setkeybinding(MODKEY|ShiftMask, XK_6,           kf_mvws_6,      NULL);
4108         setkeybinding(MODKEY|ShiftMask, XK_7,           kf_mvws_7,      NULL);
4109         setkeybinding(MODKEY|ShiftMask, XK_8,           kf_mvws_8,      NULL);
4110         setkeybinding(MODKEY|ShiftMask, XK_9,           kf_mvws_9,      NULL);
4111         setkeybinding(MODKEY|ShiftMask, XK_0,           kf_mvws_10,     NULL);
4112         setkeybinding(MODKEY,           XK_b,           kf_bar_toggle,  NULL);
4113         setkeybinding(MODKEY,           XK_Tab,         kf_focus_next,  NULL);
4114         setkeybinding(MODKEY|ShiftMask, XK_Tab,         kf_focus_prev,  NULL);
4115         setkeybinding(MODKEY|ShiftMask, XK_x,           kf_wind_kill,   NULL);
4116         setkeybinding(MODKEY,           XK_x,           kf_wind_del,    NULL);
4117         setkeybinding(MODKEY,           XK_s,           kf_spawn_custom,        "screenshot_all");
4118         setkeybinding(MODKEY|ShiftMask, XK_s,           kf_spawn_custom,        "screenshot_wind");
4119         setkeybinding(MODKEY,           XK_t,           kf_float_toggle,NULL);
4120         setkeybinding(MODKEY|ShiftMask, XK_v,           kf_version,     NULL);
4121         setkeybinding(MODKEY|ShiftMask, XK_Delete,      kf_spawn_custom,        "lock");
4122         setkeybinding(MODKEY|ShiftMask, XK_i,           kf_spawn_custom,        "initscr");
4123         setkeybinding(MODKEY,           XK_w,           kf_iconify,     NULL);
4124         setkeybinding(MODKEY|ShiftMask, XK_w,           kf_uniconify,   NULL);
4125 #ifdef SWM_DEBUG
4126         setkeybinding(MODKEY|ShiftMask, XK_d,           kf_dumpwins,    NULL);
4127 #endif
4128 }
4129
4130 void
4131 updatenumlockmask(void)
4132 {
4133         unsigned int            i, j;
4134         XModifierKeymap         *modmap;
4135
4136         DNPRINTF(SWM_D_MISC, "updatenumlockmask\n");
4137         numlockmask = 0;
4138         modmap = XGetModifierMapping(display);
4139         for (i = 0; i < 8; i++)
4140                 for (j = 0; j < modmap->max_keypermod; j++)
4141                         if (modmap->modifiermap[i * modmap->max_keypermod + j]
4142                             == XKeysymToKeycode(display, XK_Num_Lock))
4143                                 numlockmask = (1 << i);
4144
4145         XFreeModifiermap(modmap);
4146 }
4147
4148 void
4149 grabkeys(void)
4150 {
4151         unsigned int            i, j, k;
4152         KeyCode                 code;
4153         unsigned int            modifiers[] =
4154             { 0, LockMask, numlockmask, numlockmask | LockMask };
4155
4156         DNPRINTF(SWM_D_MISC, "grabkeys\n");
4157         updatenumlockmask();
4158
4159         for (k = 0; k < ScreenCount(display); k++) {
4160                 if (TAILQ_EMPTY(&screens[k].rl))
4161                         continue;
4162                 XUngrabKey(display, AnyKey, AnyModifier, screens[k].root);
4163                 for (i = 0; i < keys_length; i++) {
4164                         if ((code = XKeysymToKeycode(display, keys[i].keysym)))
4165                                 for (j = 0; j < LENGTH(modifiers); j++)
4166                                         XGrabKey(display, code,
4167                                             keys[i].mod | modifiers[j],
4168                                             screens[k].root, True,
4169                                             GrabModeAsync, GrabModeAsync);
4170                 }
4171         }
4172 }
4173
4174 void
4175 grabbuttons(struct ws_win *win, int focused)
4176 {
4177         unsigned int            i, j;
4178         unsigned int            modifiers[] =
4179             { 0, LockMask, numlockmask, numlockmask|LockMask };
4180
4181         updatenumlockmask();
4182         XUngrabButton(display, AnyButton, AnyModifier, win->id);
4183         if (focused) {
4184                 for (i = 0; i < LENGTH(buttons); i++)
4185                         if (buttons[i].action == client_click)
4186                                 for (j = 0; j < LENGTH(modifiers); j++)
4187                                         XGrabButton(display, buttons[i].button,
4188                                             buttons[i].mask | modifiers[j],
4189                                             win->id, False, BUTTONMASK,
4190                                             GrabModeAsync, GrabModeSync, None,
4191                                             None);
4192         } else
4193                 XGrabButton(display, AnyButton, AnyModifier, win->id, False,
4194                     BUTTONMASK, GrabModeAsync, GrabModeSync, None, None);
4195 }
4196
4197 const char *quirkname[] = {
4198         "NONE",         /* config string for "no value" */
4199         "FLOAT",
4200         "TRANSSZ",
4201         "ANYWHERE",
4202         "XTERM_FONTADJ",
4203         "FULLSCREEN",
4204         "FOCUSPREV",
4205 };
4206
4207 /* SWM_Q_WS: retain '|' for back compat for now (2009-08-11) */
4208 #define SWM_Q_WS                "\n|+ \t"
4209 int
4210 parsequirks(char *qstr, unsigned long *quirk)
4211 {
4212         char                    *cp, *name;
4213         int                     i;
4214
4215         if (quirk == NULL)
4216                 return (1);
4217
4218         cp = qstr;
4219         *quirk = 0;
4220         while ((name = strsep(&cp, SWM_Q_WS)) != NULL) {
4221                 if (cp)
4222                         cp += (long)strspn(cp, SWM_Q_WS);
4223                 for (i = 0; i < LENGTH(quirkname); i++) {
4224                         if (!strncasecmp(name, quirkname[i], SWM_QUIRK_LEN)) {
4225                                 DNPRINTF(SWM_D_QUIRK,
4226                                     "parsequirks: %s\n", name);
4227                                 if (i == 0) {
4228                                         *quirk = 0;
4229                                         return (0);
4230                                 }
4231                                 *quirk |= 1 << (i-1);
4232                                 break;
4233                         }
4234                 }
4235                 if (i >= LENGTH(quirkname)) {
4236                         DNPRINTF(SWM_D_QUIRK,
4237                             "parsequirks: invalid quirk [%s]\n", name);
4238                         return (1);
4239                 }
4240         }
4241         return (0);
4242 }
4243
4244 void
4245 setquirk(const char *class, const char *name, const int quirk)
4246 {
4247         int                     i, j;
4248
4249         /* find existing */
4250         for (i = 0; i < quirks_length; i++) {
4251                 if (!strcmp(quirks[i].class, class) &&
4252                     !strcmp(quirks[i].name, name)) {
4253                         if (!quirk) {
4254                                 /* found: delete */
4255                                 DNPRINTF(SWM_D_QUIRK,
4256                                     "setquirk: delete #%d %s:%s\n",
4257                                     i, quirks[i].class, quirks[i].name);
4258                                 free(quirks[i].class);
4259                                 free(quirks[i].name);
4260                                 j = quirks_length - 1;
4261                                 if (i < j)
4262                                         quirks[i] = quirks[j];
4263                                 quirks_length--;
4264                                 return;
4265                         } else {
4266                                 /* found: replace */
4267                                 DNPRINTF(SWM_D_QUIRK,
4268                                     "setquirk: replace #%d %s:%s\n",
4269                                     i, quirks[i].class, quirks[i].name);
4270                                 free(quirks[i].class);
4271                                 free(quirks[i].name);
4272                                 quirks[i].class = strdup(class);
4273                                 quirks[i].name = strdup(name);
4274                                 quirks[i].quirk = quirk;
4275                                 return;
4276                         }
4277                 }
4278         }
4279         if (!quirk) {
4280                 fprintf(stderr,
4281                     "error: setquirk: cannot find class/name combination");
4282                 return;
4283         }
4284         /* not found: add */
4285         if (quirks_size == 0 || quirks == NULL) {
4286                 quirks_size = 4;
4287                 DNPRINTF(SWM_D_QUIRK, "setquirk: init list %d\n", quirks_size);
4288                 quirks = malloc((size_t)quirks_size * sizeof(struct quirk));
4289                 if (!quirks) {
4290                         fprintf(stderr, "setquirk: malloc failed\n");
4291                         perror(" failed");
4292                         quit(NULL, NULL);
4293                 }
4294         } else if (quirks_length == quirks_size) {
4295                 quirks_size *= 2;
4296                 DNPRINTF(SWM_D_QUIRK, "setquirk: grow list %d\n", quirks_size);
4297                 quirks = realloc(quirks,
4298                     (size_t)quirks_size * sizeof(struct quirk));
4299                 if (!quirks) {
4300                         fprintf(stderr, "setquirk: realloc failed\n");
4301                         perror(" failed");
4302                         quit(NULL, NULL);
4303                 }
4304         }
4305         if (quirks_length < quirks_size) {
4306                 DNPRINTF(SWM_D_QUIRK, "setquirk: add %d\n", quirks_length);
4307                 j = quirks_length++;
4308                 quirks[j].class = strdup(class);
4309                 quirks[j].name = strdup(name);
4310                 quirks[j].quirk = quirk;
4311         } else {
4312                 fprintf(stderr, "quirks array problem?\n");
4313                 if (!quirks) {
4314                         fprintf(stderr, "quirks array problem!\n");
4315                         quit(NULL, NULL);
4316                 }
4317         }
4318 }
4319
4320 int
4321 setconfquirk(char *selector, char *value, int flags)
4322 {
4323         char                    *cp, *class, *name;
4324         int                     retval;
4325         unsigned long           quirks;
4326         if (selector == NULL)
4327                 return (0);
4328         if ((cp = strchr(selector, ':')) == NULL)
4329                 return (0);
4330         *cp = '\0';
4331         class = selector;
4332         name = cp + 1;
4333         if ((retval = parsequirks(value, &quirks)) == 0)
4334                 setquirk(class, name, quirks);
4335         return (retval);
4336 }
4337
4338 void
4339 setup_quirks(void)
4340 {
4341         setquirk("MPlayer",             "xv",           SWM_Q_FLOAT | SWM_Q_FULLSCREEN | SWM_Q_FOCUSPREV);
4342         setquirk("OpenOffice.org 3.2",  "VCLSalFrame",  SWM_Q_FLOAT);
4343         setquirk("Firefox-bin",         "firefox-bin",  SWM_Q_TRANSSZ);
4344         setquirk("Firefox",             "Dialog",       SWM_Q_FLOAT);
4345         setquirk("Gimp",                "gimp",         SWM_Q_FLOAT | SWM_Q_ANYWHERE);
4346         setquirk("XTerm",               "xterm",        SWM_Q_XTERM_FONTADJ);
4347         setquirk("xine",                "Xine Window",  SWM_Q_FLOAT | SWM_Q_ANYWHERE);
4348         setquirk("Xitk",                "Xitk Combo",   SWM_Q_FLOAT | SWM_Q_ANYWHERE);
4349         setquirk("xine",                "xine Panel",   SWM_Q_FLOAT | SWM_Q_ANYWHERE);
4350         setquirk("Xitk",                "Xine Window",  SWM_Q_FLOAT | SWM_Q_ANYWHERE);
4351         setquirk("xine",                "xine Video Fullscreen Window", SWM_Q_FULLSCREEN | SWM_Q_FLOAT);
4352         setquirk("pcb",                 "pcb",          SWM_Q_FLOAT);
4353         setquirk("SDL_App",             "SDL_App",      SWM_Q_FLOAT | SWM_Q_FULLSCREEN);
4354 }
4355
4356 /* conf file stuff */
4357 #define SWM_CONF_FILE   "scrotwm.conf"
4358
4359 enum    { SWM_S_BAR_DELAY, SWM_S_BAR_ENABLED, SWM_S_BAR_BORDER_WIDTH,
4360           SWM_S_STACK_ENABLED, SWM_S_CLOCK_ENABLED, SWM_S_CLOCK_FORMAT,
4361           SWM_S_CYCLE_EMPTY, SWM_S_CYCLE_VISIBLE, SWM_S_SS_ENABLED,
4362           SWM_S_TERM_WIDTH, SWM_S_TITLE_CLASS_ENABLED,
4363           SWM_S_TITLE_NAME_ENABLED, SWM_S_WINDOW_NAME_ENABLED,
4364           SWM_S_FOCUS_MODE, SWM_S_DISABLE_BORDER, SWM_S_BORDER_WIDTH,
4365           SWM_S_BAR_FONT, SWM_S_BAR_ACTION, SWM_S_SPAWN_TERM,
4366           SWM_S_SS_APP, SWM_S_DIALOG_RATIO, SWM_S_BAR_AT_BOTTOM
4367         };
4368
4369 int
4370 setconfvalue(char *selector, char *value, int flags)
4371 {
4372         switch (flags) {
4373         case SWM_S_BAR_DELAY:
4374                 bar_delay = atoi(value);
4375                 break;
4376         case SWM_S_BAR_ENABLED:
4377                 bar_enabled = atoi(value);
4378                 break;
4379         case SWM_S_BAR_BORDER_WIDTH:
4380                 bar_border_width = atoi(value);
4381                 break;
4382         case SWM_S_BAR_AT_BOTTOM:
4383                 bar_at_bottom = atoi(value);
4384                 break;
4385         case SWM_S_STACK_ENABLED:
4386                 stack_enabled = atoi(value);
4387                 break;
4388         case SWM_S_CLOCK_ENABLED:
4389                 clock_enabled = atoi(value);
4390                 break;
4391         case SWM_S_CLOCK_FORMAT:
4392 #ifndef SWM_DENY_CLOCK_FORMAT
4393                 free(clock_format);
4394                 if ((clock_format = strdup(value)) == NULL)
4395                         err(1, "setconfvalue: clock_format");
4396 #endif
4397                 break;
4398         case SWM_S_CYCLE_EMPTY:
4399                 cycle_empty = atoi(value);
4400                 break;
4401         case SWM_S_CYCLE_VISIBLE:
4402                 cycle_visible = atoi(value);
4403                 break;
4404         case SWM_S_SS_ENABLED:
4405                 ss_enabled = atoi(value);
4406                 break;
4407         case SWM_S_TERM_WIDTH:
4408                 term_width = atoi(value);
4409                 break;
4410         case SWM_S_TITLE_CLASS_ENABLED:
4411                 title_class_enabled = atoi(value);
4412                 break;
4413         case SWM_S_WINDOW_NAME_ENABLED:
4414                 window_name_enabled = atoi(value);
4415                 break;
4416         case SWM_S_TITLE_NAME_ENABLED:
4417                 title_name_enabled = atoi(value);
4418                 break;
4419         case SWM_S_FOCUS_MODE:
4420                 if (!strcmp(value, "default"))
4421                         focus_mode = SWM_FOCUS_DEFAULT;
4422                 else if (!strcmp(value, "follow_cursor"))
4423                         focus_mode = SWM_FOCUS_FOLLOW;
4424                 else if (!strcmp(value, "synergy"))
4425                         focus_mode = SWM_FOCUS_SYNERGY;
4426                 else
4427                         err(1, "focus_mode");
4428                 break;
4429         case SWM_S_DISABLE_BORDER:
4430                 disable_border = atoi(value);
4431                 break;
4432         case SWM_S_BORDER_WIDTH:
4433                 border_width = atoi(value);
4434                 break;
4435         case SWM_S_BAR_FONT:
4436                 free(bar_fonts[0]);
4437                 if ((bar_fonts[0] = strdup(value)) == NULL)
4438                         err(1, "setconfvalue: bar_font");
4439                 break;
4440         case SWM_S_BAR_ACTION:
4441                 free(bar_argv[0]);
4442                 if ((bar_argv[0] = strdup(value)) == NULL)
4443                         err(1, "setconfvalue: bar_action");
4444                 break;
4445         case SWM_S_SPAWN_TERM:
4446                 free(spawn_term[0]);
4447                 if ((spawn_term[0] = strdup(value)) == NULL)
4448                         err(1, "setconfvalue: spawn_term");
4449                 break;
4450         case SWM_S_SS_APP:
4451                 break;
4452         case SWM_S_DIALOG_RATIO:
4453                 dialog_ratio = atof(value);
4454                 if (dialog_ratio > 1.0 || dialog_ratio <= .3)
4455                         dialog_ratio = .6;
4456                 break;
4457         default:
4458                 return (1);
4459         }
4460         return (0);
4461 }
4462
4463 int
4464 setconfmodkey(char *selector, char *value, int flags)
4465 {
4466         if (!strncasecmp(value, "Mod1", strlen("Mod1")))
4467                 update_modkey(Mod1Mask);
4468         else if (!strncasecmp(value, "Mod2", strlen("Mod2")))
4469                 update_modkey(Mod2Mask);
4470         else if (!strncasecmp(value, "Mod3", strlen("Mod3")))
4471                 update_modkey(Mod3Mask);
4472         else if (!strncasecmp(value, "Mod4", strlen("Mod4")))
4473                 update_modkey(Mod4Mask);
4474         else
4475                 return (1);
4476         return (0);
4477 }
4478
4479 int
4480 setconfcolor(char *selector, char *value, int flags)
4481 {
4482         setscreencolor(value, ((selector == NULL)?-1:atoi(selector)), flags);
4483         return (0);
4484 }
4485
4486 int
4487 setconfregion(char *selector, char *value, int flags)
4488 {
4489         custom_region(value);
4490         return (0);
4491 }
4492
4493 /* config options */
4494 struct config_option {
4495         char                    *optname;
4496         int (*func)(char*, char*, int);
4497         int funcflags;
4498 };
4499 struct config_option configopt[] = {
4500         { "bar_enabled",                setconfvalue,   SWM_S_BAR_ENABLED },
4501         { "bar_at_bottom",              setconfvalue,   SWM_S_BAR_AT_BOTTOM },
4502         { "bar_border",                 setconfcolor,   SWM_S_COLOR_BAR_BORDER },
4503         { "bar_border_width",                   setconfvalue,   SWM_S_BAR_BORDER_WIDTH },
4504         { "bar_color",                  setconfcolor,   SWM_S_COLOR_BAR },
4505         { "bar_font_color",             setconfcolor,   SWM_S_COLOR_BAR_FONT },
4506         { "bar_font",                   setconfvalue,   SWM_S_BAR_FONT },
4507         { "bar_action",                 setconfvalue,   SWM_S_BAR_ACTION },
4508         { "bar_delay",                  setconfvalue,   SWM_S_BAR_DELAY },
4509         { "bind",                       setconfbinding, 0 },
4510         { "stack_enabled",              setconfvalue,   SWM_S_STACK_ENABLED },
4511         { "clock_enabled",              setconfvalue,   SWM_S_CLOCK_ENABLED },
4512         { "clock_format",               setconfvalue,   SWM_S_CLOCK_FORMAT },
4513         { "color_focus",                setconfcolor,   SWM_S_COLOR_FOCUS },
4514         { "color_unfocus",              setconfcolor,   SWM_S_COLOR_UNFOCUS },
4515         { "cycle_empty",                setconfvalue,   SWM_S_CYCLE_EMPTY },
4516         { "cycle_visible",              setconfvalue,   SWM_S_CYCLE_VISIBLE },
4517         { "dialog_ratio",               setconfvalue,   SWM_S_DIALOG_RATIO },
4518         { "modkey",                     setconfmodkey,  0 },
4519         { "program",                    setconfspawn,   0 },
4520         { "quirk",                      setconfquirk,   0 },
4521         { "region",                     setconfregion,  0 },
4522         { "spawn_term",                 setconfvalue,   SWM_S_SPAWN_TERM },
4523         { "screenshot_enabled",         setconfvalue,   SWM_S_SS_ENABLED },
4524         { "screenshot_app",             setconfvalue,   SWM_S_SS_APP },
4525         { "window_name_enabled",        setconfvalue,   SWM_S_WINDOW_NAME_ENABLED },
4526         { "term_width",                 setconfvalue,   SWM_S_TERM_WIDTH },
4527         { "title_class_enabled",        setconfvalue,   SWM_S_TITLE_CLASS_ENABLED },
4528         { "title_name_enabled",         setconfvalue,   SWM_S_TITLE_NAME_ENABLED },
4529         { "focus_mode",                 setconfvalue,   SWM_S_FOCUS_MODE },
4530         { "disable_border",             setconfvalue,   SWM_S_DISABLE_BORDER },
4531         { "border_width",               setconfvalue,   SWM_S_BORDER_WIDTH },
4532 };
4533
4534
4535 int
4536 conf_load(char *filename)
4537 {
4538         FILE                    *config;
4539         char                    *line, *cp, *optsub, *optval;
4540         size_t                  linelen, lineno = 0;
4541         int                     wordlen, i, optind;
4542         struct config_option    *opt;
4543
4544         DNPRINTF(SWM_D_CONF, "conf_load begin\n");
4545
4546         if (filename == NULL) {
4547                 fprintf(stderr, "conf_load: no filename\n");
4548                 return (1);
4549         }
4550         if ((config = fopen(filename, "r")) == NULL) {
4551                 warn("conf_load: fopen");
4552                 return (1);
4553         }
4554
4555         while (!feof(config)) {
4556                 if ((line = fparseln(config, &linelen, &lineno, NULL, 0))
4557                     == NULL) {
4558                         if (ferror(config))
4559                                 err(1, "%s", filename);
4560                         else
4561                                 continue;
4562                 }
4563                 cp = line;
4564                 cp += strspn(cp, " \t\n"); /* eat whitespace */
4565                 if (cp[0] == '\0') {
4566                         /* empty line */
4567                         free(line);
4568                         continue;
4569                 }
4570                 /* get config option */
4571                 wordlen = strcspn(cp, "=[ \t\n");
4572                 if (wordlen == 0) {
4573                         warnx("%s: line %zd: no option found",
4574                             filename, lineno);
4575                         return (1);
4576                 }
4577                 optind = -1;
4578                 for (i = 0; i < LENGTH(configopt); i++) {
4579                         opt = &configopt[i];
4580                         if (!strncasecmp(cp, opt->optname, wordlen) &&
4581                             strlen(opt->optname) == wordlen) {
4582                                 optind = i;
4583                                 break;
4584                         }
4585                 }
4586                 if (optind == -1) {
4587                         warnx("%s: line %zd: unknown option %.*s",
4588                             filename, lineno, wordlen, cp);
4589                         return (1);
4590                 }
4591                 cp += wordlen;
4592                 cp += strspn(cp, " \t\n"); /* eat whitespace */
4593                 /* get [selector] if any */
4594                 optsub = NULL;
4595                 if (*cp == '[') {
4596                         cp++;
4597                         wordlen = strcspn(cp, "]");
4598                         if (*cp != ']') {
4599                                 if (wordlen == 0) {
4600                                         warnx("%s: line %zd: syntax error",
4601                                             filename, lineno);
4602                                         return (1);
4603                                 }
4604                                 asprintf(&optsub, "%.*s", wordlen, cp);
4605                         }
4606                         cp += wordlen;
4607                         cp += strspn(cp, "] \t\n"); /* eat trailing */
4608                 }
4609                 cp += strspn(cp, "= \t\n"); /* eat trailing */
4610                 /* get RHS value */
4611                 optval = strdup(cp);
4612                 /* call function to deal with it all */
4613                 if (configopt[optind].func(optsub, optval,
4614                     configopt[optind].funcflags) != 0) {
4615                         fprintf(stderr, "%s line %zd: %s\n",
4616                             filename, lineno, line);
4617                         errx(1, "%s: line %zd: invalid data for %s",
4618                             filename, lineno, configopt[optind].optname);
4619                 }
4620                 free(optval);
4621                 free(optsub);
4622                 free(line);
4623         }
4624
4625         fclose(config);
4626         DNPRINTF(SWM_D_CONF, "conf_load end\n");
4627
4628         return (0);
4629 }
4630
4631 void
4632 set_child_transient(struct ws_win *win, Window *trans)
4633 {
4634         struct ws_win           *parent, *w;
4635         XWMHints                *wmh = NULL;
4636         struct swm_region       *r;
4637         struct workspace        *ws;
4638
4639         parent = find_window(win->transient);
4640         if (parent)
4641                 parent->child_trans = win;
4642         else {
4643                 DNPRINTF(SWM_D_MISC, "set_child_transient: parent doesn't exist"
4644                     " for %lu trans %lu\n", win->id, win->transient);
4645
4646                 if (win->hints == NULL) {
4647                         fprintf(stderr, "no hints for %lu\n", win->id);
4648                         return;
4649                 }
4650
4651                 r = root_to_region(win->wa.root);
4652                 ws = r->ws;
4653                 /* parent doen't exist in our window list */
4654                 TAILQ_FOREACH(w, &ws->winlist, entry) {
4655                         if (wmh)
4656                                 XFree(wmh);
4657
4658                         if ((wmh = XGetWMHints(display, w->id)) == NULL) {
4659                                 fprintf(stderr, "can't get hints for %lu\n",
4660                                     w->id);
4661                                 continue;
4662                         }
4663
4664                         if (win->hints->window_group != wmh->window_group)
4665                                 continue;
4666
4667                         w->child_trans = win;
4668                         win->transient = w->id;
4669                         *trans = w->id;
4670                         DNPRINTF(SWM_D_MISC, "set_child_transient: asjusting "
4671                             "transient to %lu\n", win->transient);
4672                         break;
4673                 }
4674         }
4675
4676         if (wmh)
4677                 XFree(wmh);
4678 }
4679
4680 struct ws_win *
4681 manage_window(Window id)
4682 {
4683         Window                  trans = 0;
4684         struct workspace        *ws;
4685         struct ws_win           *win, *ww;
4686         int                     format, i, ws_idx, n, border_me = 0;
4687         unsigned long           nitems, bytes;
4688         Atom                    ws_idx_atom = 0, type;
4689         Atom                    *prot = NULL, *pp;
4690         unsigned char           ws_idx_str[SWM_PROPLEN], *prop = NULL;
4691         struct swm_region       *r;
4692         long                    mask;
4693         const char              *errstr;
4694         XWindowChanges          wc;
4695
4696         if ((win = find_window(id)) != NULL)
4697                 return (win);   /* already being managed */
4698
4699         /* see if we are on the unmanaged list */
4700         if ((win = find_unmanaged_window(id)) != NULL) {
4701                 DNPRINTF(SWM_D_MISC, "manage previously unmanaged window "
4702                     "%lu\n", win->id);
4703                 TAILQ_REMOVE(&win->ws->unmanagedlist, win, entry);
4704                 if (win->transient) {
4705                         set_child_transient(win, &trans);
4706                 } if (trans && (ww = find_window(trans)))
4707                         TAILQ_INSERT_AFTER(&win->ws->winlist, ww, win, entry);
4708                 else
4709                         TAILQ_INSERT_TAIL(&win->ws->winlist, win, entry);
4710                 ewmh_update_actions(win);
4711                 return (win);
4712         }
4713
4714         if ((win = calloc(1, sizeof(struct ws_win))) == NULL)
4715                 errx(1, "calloc: failed to allocate memory for new window");
4716
4717         win->id = id;
4718
4719         /* Get all the window data in one shot */
4720         ws_idx_atom = XInternAtom(display, "_SWM_WS", False);
4721         if (ws_idx_atom)
4722                 XGetWindowProperty(display, id, ws_idx_atom, 0, SWM_PROPLEN,
4723                     False, XA_STRING, &type, &format, &nitems, &bytes, &prop);
4724         XGetWindowAttributes(display, id, &win->wa);
4725         XGetWMNormalHints(display, id, &win->sh, &mask);
4726         win->hints = XGetWMHints(display, id);
4727         XGetTransientForHint(display, id, &trans);
4728         if (trans) {
4729                 win->transient = trans;
4730                 set_child_transient(win, &trans);
4731                 DNPRINTF(SWM_D_MISC, "manage_window: win %lu transient %lu\n",
4732                     win->id, win->transient);
4733         }
4734
4735         /* get supported protocols */
4736         if (XGetWMProtocols(display, id, &prot, &n)) {
4737                 for (i = 0, pp = prot; i < n; i++, pp++) {
4738                         if (*pp == takefocus)
4739                                 win->take_focus = 1;
4740                         if (*pp == adelete)
4741                                 win->can_delete = 1;
4742                 }
4743                 if (prot)
4744                         XFree(prot);
4745         }
4746
4747         win->iconic = get_iconic(win);
4748
4749         /*
4750          * Figure out where to put the window. If it was previously assigned to
4751          * a workspace (either by spawn() or manually moving), and isn't
4752          * transient, * put it in the same workspace
4753          */
4754         r = root_to_region(win->wa.root);
4755         if (prop && win->transient == 0) {
4756                 DNPRINTF(SWM_D_PROP, "got property _SWM_WS=%s\n", prop);
4757                 ws_idx = strtonum(prop, 0, 9, &errstr);
4758                 if (errstr) {
4759                         DNPRINTF(SWM_D_EVENT, "window idx is %s: %s",
4760                             errstr, prop);
4761                 }
4762                 ws = &r->s->ws[ws_idx];
4763         } else {
4764                 ws = r->ws;
4765                 /* this should launch transients in the same ws as parent */
4766                 if (id && trans)
4767                         if ((ww = find_window(trans)) != NULL)
4768                                 if (ws->r) {
4769                                         ws = ww->ws;
4770                                         if (ww->ws->r)
4771                                                 r = ww->ws->r;
4772                                         else
4773                                                 fprintf(stderr,
4774                                                     "fix this bug mcbride\n");
4775                                         border_me = 1;
4776                                 }
4777         }
4778
4779         /* set up the window layout */
4780         win->id = id;
4781         win->ws = ws;
4782         win->s = r->s;  /* this never changes */
4783         if (trans && (ww = find_window(trans)))
4784                 TAILQ_INSERT_AFTER(&ws->winlist, ww, win, entry);
4785         else
4786                 TAILQ_INSERT_TAIL(&ws->winlist, win, entry);
4787
4788         win->g.w = win->wa.width;
4789         win->g.h = win->wa.height;
4790         win->g.x = win->wa.x;
4791         win->g.y = win->wa.y;
4792         win->g_floatvalid = 0;
4793         win->floatmaxed = 0;
4794         win->ewmh_flags = 0;
4795
4796         /* Set window properties so we can remember this after reincarnation */
4797         if (ws_idx_atom && prop == NULL &&
4798             snprintf(ws_idx_str, SWM_PROPLEN, "%d", ws->idx) < SWM_PROPLEN) {
4799                 DNPRINTF(SWM_D_PROP, "setting property _SWM_WS to %s\n",
4800                     ws_idx_str);
4801                 XChangeProperty(display, win->id, ws_idx_atom, XA_STRING, 8,
4802                     PropModeReplace, ws_idx_str, SWM_PROPLEN);
4803         }
4804         if (prop)
4805                 XFree(prop);
4806
4807         ewmh_autoquirk(win);
4808
4809         if (XGetClassHint(display, win->id, &win->ch)) {
4810                 DNPRINTF(SWM_D_CLASS, "class: %s name: %s\n",
4811                     win->ch.res_class, win->ch.res_name);
4812
4813                 /* java is retarded so treat it special */
4814                 if (strstr(win->ch.res_name, "sun-awt")) {
4815                         win->java = 1;
4816                         border_me = 1;
4817                 }
4818
4819                 for (i = 0; i < quirks_length; i++){
4820                         if (!strcmp(win->ch.res_class, quirks[i].class) &&
4821                             !strcmp(win->ch.res_name, quirks[i].name)) {
4822                                 DNPRINTF(SWM_D_CLASS, "found: %s name: %s\n",
4823                                     win->ch.res_class, win->ch.res_name);
4824                                 if (quirks[i].quirk & SWM_Q_FLOAT) {
4825                                         win->floating = 1;
4826                                         border_me = 1;
4827                                 }
4828                                 win->quirks = quirks[i].quirk;
4829                         }
4830                 }
4831         }
4832
4833         /* alter window position if quirky */
4834         if (win->quirks & SWM_Q_ANYWHERE) {
4835                 win->manual = 1; /* don't center the quirky windows */
4836                 bzero(&wc, sizeof wc);
4837                 mask = 0;
4838                 if (bar_enabled && win->g.y < bar_height) {
4839                         win->g.y = wc.y = bar_height;
4840                         mask |= CWY;
4841                 }
4842                 if (win->g.w + win->g.x > WIDTH(r)) {
4843                         win->g.x = wc.x = WIDTH(r) - win->g.w - 2;
4844                         mask |= CWX;
4845                 }
4846                 border_me = 1;
4847         }
4848
4849         /* Reset font sizes (the bruteforce way; no default keybinding). */
4850         if (win->quirks & SWM_Q_XTERM_FONTADJ) {
4851                 for (i = 0; i < SWM_MAX_FONT_STEPS; i++)
4852                         fake_keypress(win, XK_KP_Subtract, ShiftMask);
4853                 for (i = 0; i < SWM_MAX_FONT_STEPS; i++)
4854                         fake_keypress(win, XK_KP_Add, ShiftMask);
4855         }
4856
4857         ewmh_get_win_state(win);
4858         ewmh_update_actions(win);
4859         ewmh_update_win_state(win, None, _NET_WM_STATE_REMOVE);
4860
4861         /* border me */
4862         if (border_me) {
4863                 bzero(&wc, sizeof wc);
4864                 wc.border_width = border_width;
4865                 mask = CWBorderWidth;
4866                 XConfigureWindow(display, win->id, mask, &wc);
4867         }
4868
4869         XSelectInput(display, id, EnterWindowMask | FocusChangeMask |
4870             PropertyChangeMask | StructureNotifyMask);
4871
4872         /* floaters need to be mapped if they are in the current workspace */
4873         if ((win->floating || win->transient) && (ws->idx == r->ws->idx))
4874                 XMapRaised(display, win->id);
4875
4876         return (win);
4877 }
4878
4879 void
4880 free_window(struct ws_win *win)
4881 {
4882         DNPRINTF(SWM_D_MISC, "free_window:  %lu\n", win->id);
4883
4884         if (win == NULL)
4885                 return;
4886
4887         /* needed for restart wm */
4888         set_win_state(win, WithdrawnState);
4889
4890         TAILQ_REMOVE(&win->ws->unmanagedlist, win, entry);
4891
4892         if (win->ch.res_class)
4893                 XFree(win->ch.res_class);
4894         if (win->ch.res_name)
4895                 XFree(win->ch.res_name);
4896
4897         kill_refs(win);
4898
4899         /* paint memory */
4900         memset(win, 0xff, sizeof *win); /* XXX kill later */
4901
4902         free(win);
4903 }
4904
4905 void
4906 unmanage_window(struct ws_win *win)
4907 {
4908         struct ws_win           *parent;
4909
4910         if (win == NULL)
4911                 return;
4912
4913         DNPRINTF(SWM_D_MISC, "unmanage_window:  %lu\n", win->id);
4914
4915         if (win->transient) {
4916                 parent = find_window(win->transient);
4917                 if (parent)
4918                         parent->child_trans = NULL;
4919         }
4920
4921         /* focus on root just in case */
4922         XSetInputFocus(display, PointerRoot, PointerRoot, CurrentTime);
4923
4924         focus_prev(win);
4925
4926         TAILQ_REMOVE(&win->ws->winlist, win, entry);
4927         TAILQ_INSERT_TAIL(&win->ws->unmanagedlist, win, entry);
4928
4929         kill_refs(win);
4930 }
4931
4932 void
4933 focus_magic(struct ws_win *win)
4934 {
4935         DNPRINTF(SWM_D_FOCUS, "focus_magic: %lu\n", WINID(win));
4936
4937         if (win == NULL)
4938                 return;
4939
4940         if (win->child_trans) {
4941                 /* win = parent & has a transient so focus on that */
4942                 if (win->java) {
4943                         focus_win(win->child_trans);
4944                         if (win->child_trans->take_focus)
4945                                 client_msg(win, takefocus);
4946                 } else {
4947                         /* make sure transient hasn't dissapeared */
4948                         if (validate_win(win->child_trans) == 0) {
4949                                 focus_win(win->child_trans);
4950                                 if (win->child_trans->take_focus)
4951                                         client_msg(win->child_trans, takefocus);
4952                         } else {
4953                                 win->child_trans = NULL;
4954                                 focus_win(win);
4955                                 if (win->take_focus)
4956                                         client_msg(win, takefocus);
4957                         }
4958                 }
4959         } else {
4960                 /* regular focus */
4961                 focus_win(win);
4962                 if (win->take_focus)
4963                         client_msg(win, takefocus);
4964         }
4965 }
4966
4967 void
4968 expose(XEvent *e)
4969 {
4970         DNPRINTF(SWM_D_EVENT, "expose: window: %lu\n", e->xexpose.window);
4971 }
4972
4973 void
4974 keypress(XEvent *e)
4975 {
4976         unsigned int            i;
4977         KeySym                  keysym;
4978         XKeyEvent               *ev = &e->xkey;
4979
4980         DNPRINTF(SWM_D_EVENT, "keypress: window: %lu\n", ev->window);
4981
4982         keysym = XKeycodeToKeysym(display, (KeyCode)ev->keycode, 0);
4983         for (i = 0; i < keys_length; i++)
4984                 if (keysym == keys[i].keysym
4985                     && CLEANMASK(keys[i].mod) == CLEANMASK(ev->state)
4986                     && keyfuncs[keys[i].funcid].func) {
4987                         if (keys[i].funcid == kf_spawn_custom)
4988                                 spawn_custom(
4989                                     root_to_region(ev->root),
4990                                     &(keyfuncs[keys[i].funcid].args),
4991                                     keys[i].spawn_name
4992                                     );
4993                         else
4994                                 keyfuncs[keys[i].funcid].func(
4995                                     root_to_region(ev->root),
4996                                     &(keyfuncs[keys[i].funcid].args)
4997                                     );
4998                 }
4999 }
5000
5001 void
5002 buttonpress(XEvent *e)
5003 {
5004         struct ws_win           *win;
5005         int                     i, action;
5006         XButtonPressedEvent     *ev = &e->xbutton;
5007
5008         DNPRINTF(SWM_D_EVENT, "buttonpress: window: %lu\n", ev->window);
5009
5010         action = root_click;
5011         if ((win = find_window(ev->window)) == NULL)
5012                 return;
5013
5014         focus_magic(win);
5015         action = client_click;
5016
5017         for (i = 0; i < LENGTH(buttons); i++)
5018                 if (action == buttons[i].action && buttons[i].func &&
5019                     buttons[i].button == ev->button &&
5020                     CLEANMASK(buttons[i].mask) == CLEANMASK(ev->state))
5021                         buttons[i].func(win, &buttons[i].args);
5022 }
5023
5024 void
5025 configurerequest(XEvent *e)
5026 {
5027         XConfigureRequestEvent  *ev = &e->xconfigurerequest;
5028         struct ws_win           *win;
5029         int                     new = 0;
5030         XWindowChanges          wc;
5031
5032         if ((win = find_window(ev->window)) == NULL)
5033                 if ((win = find_unmanaged_window(ev->window)) == NULL)
5034                         new = 1;
5035
5036         if (new) {
5037                 DNPRINTF(SWM_D_EVENT, "configurerequest: new window: %lu\n",
5038                     ev->window);
5039                 bzero(&wc, sizeof wc);
5040                 wc.x = ev->x;
5041                 wc.y = ev->y;
5042                 wc.width = ev->width;
5043                 wc.height = ev->height;
5044                 wc.border_width = ev->border_width;
5045                 wc.sibling = ev->above;
5046                 wc.stack_mode = ev->detail;
5047                 XConfigureWindow(display, ev->window, ev->value_mask, &wc);
5048         } else {
5049                 DNPRINTF(SWM_D_EVENT, "configurerequest: change window: %lu\n",
5050                     ev->window);
5051                 config_win(win, ev);
5052         }
5053 }
5054
5055 void
5056 configurenotify(XEvent *e)
5057 {
5058         struct ws_win           *win;
5059         long                    mask;
5060
5061         DNPRINTF(SWM_D_EVENT, "configurenotify: window: %lu\n",
5062             e->xconfigure.window);
5063
5064         win = find_window(e->xconfigure.window);
5065         if (win) {
5066                 XGetWMNormalHints(display, win->id, &win->sh, &mask);
5067                 adjust_font(win);
5068                 if (font_adjusted)
5069                         stack();
5070                 if (focus_mode == SWM_FOCUS_DEFAULT)
5071                         drain_enter_notify();
5072         }
5073 }
5074
5075 void
5076 destroynotify(XEvent *e)
5077 {
5078         struct ws_win           *win;
5079         XDestroyWindowEvent     *ev = &e->xdestroywindow;
5080
5081         DNPRINTF(SWM_D_EVENT, "destroynotify: window %lu\n", ev->window);
5082
5083         if ((win = find_window(ev->window)) == NULL) {
5084                 if ((win = find_unmanaged_window(ev->window)) == NULL)
5085                         return;
5086                 free_window(win);
5087                 return;
5088         }
5089
5090         /* make sure we focus on something */
5091         win->floating = 0;
5092
5093         unmanage_window(win);
5094         stack();
5095         if (focus_mode == SWM_FOCUS_DEFAULT)
5096                 drain_enter_notify();
5097         free_window(win);
5098 }
5099
5100 void
5101 enternotify(XEvent *e)
5102 {
5103         XCrossingEvent          *ev = &e->xcrossing;
5104         XEvent                  cne;
5105         struct ws_win           *win;
5106 #if 0
5107         struct ws_win           *w;
5108         Window                  focus_return;
5109         int                     revert_to_return;
5110 #endif
5111         DNPRINTF(SWM_D_FOCUS, "enternotify: window: %lu mode %d detail %d root "
5112             "%lu subwindow %lu same_screen %d focus %d state %d\n",
5113             ev->window, ev->mode, ev->detail, ev->root, ev->subwindow,
5114             ev->same_screen, ev->focus, ev->state);
5115
5116         switch (focus_mode) {
5117         case SWM_FOCUS_DEFAULT:
5118                 break;
5119         case SWM_FOCUS_FOLLOW:
5120                 break;
5121         case SWM_FOCUS_SYNERGY:
5122 #if 0
5123         /*
5124          * all these checks need to be in this order because the
5125          * XCheckTypedWindowEvent relies on weeding out the previous events
5126          *
5127          * making this code an option would enable a follow mouse for focus
5128          * feature
5129          */
5130
5131         /*
5132          * state is set when we are switching workspaces and focus is set when
5133          * the window or a subwindow already has focus (occurs during restart).
5134          *
5135          * Only honor the focus flag if last_focus_event is not FocusOut,
5136          * this allows scrotwm to continue to control focus when another
5137          * program is also playing with it.
5138          */
5139         if (ev->state || (ev->focus && last_focus_event != FocusOut)) {
5140                 DNPRINTF(SWM_D_EVENT, "ignoring enternotify: focus\n");
5141                 return;
5142         }
5143
5144         /*
5145          * happens when a window is created or destroyed and the border
5146          * crosses the mouse pointer and when switching ws
5147          *
5148          * we need the subwindow test to see if we came from root in order
5149          * to give focus to floaters
5150          */
5151         if (ev->mode == NotifyNormal && ev->detail == NotifyVirtual &&
5152             ev->subwindow == 0) {
5153                 DNPRINTF(SWM_D_EVENT, "ignoring enternotify: NotifyVirtual\n");
5154                 return;
5155         }
5156
5157         /* this window already has focus */
5158         if (ev->mode == NotifyNormal && ev->detail == NotifyInferior) {
5159                 DNPRINTF(SWM_D_EVENT, "ignoring enternotify: win has focus\n");
5160                 return;
5161         }
5162
5163         /* this window is being deleted or moved to another ws */
5164         if (XCheckTypedWindowEvent(display, ev->window, ConfigureNotify,
5165             &cne) == True) {
5166                 DNPRINTF(SWM_D_EVENT, "ignoring enternotify: configurenotify\n");
5167                 XPutBackEvent(display, &cne);
5168                 return;
5169         }
5170
5171         if ((win = find_window(ev->window)) == NULL) {
5172                 DNPRINTF(SWM_D_EVENT, "ignoring enternotify: win == NULL\n");
5173                 return;
5174         }
5175
5176         /*
5177          * In fullstack kill all enters unless they come from a different ws
5178          * (i.e. another region) or focus has been grabbed externally.
5179          */
5180         if (win->ws->cur_layout->flags & SWM_L_FOCUSPREV &&
5181             last_focus_event != FocusOut) {
5182                 XGetInputFocus(display, &focus_return, &revert_to_return);
5183                 if ((w = find_window(focus_return)) == NULL ||
5184                     w->ws == win->ws) {
5185                         DNPRINTF(SWM_D_EVENT, "ignoring event: fullstack\n");
5186                         return;
5187                 }
5188         }
5189 #endif
5190                 break;
5191         }
5192
5193         if ((win = find_window(ev->window)) == NULL) {
5194                 DNPRINTF(SWM_D_EVENT, "ignoring enternotify: win == NULL\n");
5195                 return;
5196         }
5197
5198         /*
5199          * if we have more enternotifies let them handle it in due time
5200          */
5201         if (XCheckTypedEvent(display, EnterNotify, &cne) == True) {
5202                 DNPRINTF(SWM_D_EVENT,
5203                     "ignoring enternotify: got more enternotify\n");
5204                 XPutBackEvent(display, &cne);
5205                 return;
5206         }
5207
5208         focus_magic(win);
5209 }
5210
5211 /* lets us use one switch statement for arbitrary mode/detail combinations */
5212 #define MERGE_MEMBERS(a,b)      (((a & 0xffff) << 16) | (b & 0xffff))
5213
5214 void
5215 focusevent(XEvent *e)
5216 {
5217 #if 0
5218         struct ws_win           *win;
5219         u_int32_t               mode_detail;
5220         XFocusChangeEvent       *ev = &e->xfocus;
5221
5222         DNPRINTF(SWM_D_EVENT, "focusevent: %s window: %lu mode %d detail %d\n",
5223             ev->type == FocusIn ? "entering" : "leaving",
5224             ev->window, ev->mode, ev->detail);
5225
5226         if (last_focus_event == ev->type) {
5227                 DNPRINTF(SWM_D_FOCUS, "ignoring focusevent: bad ordering\n");
5228                 return;
5229         }
5230
5231         last_focus_event = ev->type;
5232         mode_detail = MERGE_MEMBERS(ev->mode, ev->detail);
5233
5234         switch (mode_detail) {
5235         /* synergy client focus operations */
5236         case MERGE_MEMBERS(NotifyNormal, NotifyNonlinear):
5237         case MERGE_MEMBERS(NotifyNormal, NotifyNonlinearVirtual):
5238
5239         /* synergy server focus operations */
5240         case MERGE_MEMBERS(NotifyWhileGrabbed, NotifyNonlinear):
5241
5242         /* Entering applications like rdesktop that mangle the pointer */
5243         case MERGE_MEMBERS(NotifyNormal, NotifyPointer):
5244
5245                 if ((win = find_window(e->xfocus.window)) != NULL && win->ws->r)
5246                         XSetWindowBorder(display, win->id,
5247                             win->ws->r->s->c[ev->type == FocusIn ?
5248                             SWM_S_COLOR_FOCUS : SWM_S_COLOR_UNFOCUS].color);
5249                 break;
5250         default:
5251                 fprintf(stderr, "ignoring focusevent\n");
5252                 DNPRINTF(SWM_D_FOCUS, "ignoring focusevent\n");
5253                 break;
5254         }
5255 #endif
5256 }
5257
5258 void
5259 mapnotify(XEvent *e)
5260 {
5261         struct ws_win           *win;
5262         XMapEvent               *ev = &e->xmap;
5263
5264         DNPRINTF(SWM_D_EVENT, "mapnotify: window: %lu\n", ev->window);
5265
5266         win = manage_window(ev->window);
5267         if (win)
5268                 set_win_state(win, NormalState);
5269 }
5270
5271 void
5272 mappingnotify(XEvent *e)
5273 {
5274         XMappingEvent           *ev = &e->xmapping;
5275
5276         XRefreshKeyboardMapping(ev);
5277         if (ev->request == MappingKeyboard)
5278                 grabkeys();
5279 }
5280
5281 void
5282 maprequest(XEvent *e)
5283 {
5284         struct ws_win           *win;
5285         struct swm_region       *r;
5286         XWindowAttributes       wa;
5287         XMapRequestEvent        *ev = &e->xmaprequest;
5288
5289         DNPRINTF(SWM_D_EVENT, "maprequest: window: %lu\n",
5290             e->xmaprequest.window);
5291
5292         if (!XGetWindowAttributes(display, ev->window, &wa))
5293                 return;
5294         if (wa.override_redirect)
5295                 return;
5296
5297         win = manage_window(e->xmaprequest.window);
5298         if (win == NULL)
5299                 return; /* can't happen */
5300
5301         stack();
5302
5303         /* make new win focused */
5304         r = root_to_region(win->wa.root);
5305         if (win->ws == r->ws)
5306                 focus_magic(win);
5307 }
5308
5309 void
5310 propertynotify(XEvent *e)
5311 {
5312         struct ws_win           *win;
5313         XPropertyEvent          *ev = &e->xproperty;
5314
5315         DNPRINTF(SWM_D_EVENT, "propertynotify: window: %lu\n",
5316             ev->window);
5317
5318         win = find_window(ev->window);
5319         if (win == NULL)
5320                 return;
5321
5322         if (ev->state == PropertyDelete && ev->atom == a_swm_iconic) {
5323                 update_iconic(win, 0);
5324                 XMapRaised(display, win->id);
5325                 stack();
5326                 focus_win(win);
5327                 return;
5328         }
5329
5330         switch (ev->atom) {
5331         case XA_WM_NORMAL_HINTS:
5332 #if 0
5333                 long            mask;
5334                 XGetWMNormalHints(display, win->id, &win->sh, &mask);
5335                 fprintf(stderr, "normal hints: flag 0x%x\n", win->sh.flags);
5336                 if (win->sh.flags & PMinSize) {
5337                         win->g.w = win->sh.min_width;
5338                         win->g.h = win->sh.min_height;
5339                         fprintf(stderr, "min %d %d\n", win->g.w, win->g.h);
5340                 }
5341                 XMoveResizeWindow(display, win->id,
5342                     win->g.x, win->g.y, win->g.w, win->g.h);
5343 #endif
5344                 if (window_name_enabled)
5345                         bar_update();
5346                 break;
5347         default:
5348                 break;
5349         }
5350 }
5351
5352 void
5353 unmapnotify(XEvent *e)
5354 {
5355         struct ws_win           *win;
5356
5357         DNPRINTF(SWM_D_EVENT, "unmapnotify: window: %lu\n", e->xunmap.window);
5358
5359         /* determine if we need to help unmanage this window */
5360         win = find_window(e->xunmap.window);
5361         if (win == NULL)
5362                 return;
5363
5364         if (getstate(e->xunmap.window) == NormalState) {
5365                 unmanage_window(win);
5366                 stack();
5367
5368                 /* giant hack for apps that don't destroy transient windows */
5369                 /* eat a bunch of events to prevent remanaging the window */
5370                 XEvent                  cne;
5371                 while (XCheckWindowEvent(display, e->xunmap.window,
5372                     EnterWindowMask, &cne))
5373                         ;
5374                 while (XCheckWindowEvent(display, e->xunmap.window,
5375                     StructureNotifyMask, &cne))
5376                         ;
5377                 while (XCheckWindowEvent(display, e->xunmap.window,
5378                     SubstructureNotifyMask, &cne))
5379                         ;
5380                 /* resend unmap because we ated it */
5381                 XUnmapWindow(display, e->xunmap.window);
5382         }
5383
5384         if (focus_mode == SWM_FOCUS_DEFAULT)
5385                 drain_enter_notify();
5386 }
5387
5388 void
5389 visibilitynotify(XEvent *e)
5390 {
5391         int                     i;
5392         struct swm_region       *r;
5393
5394         DNPRINTF(SWM_D_EVENT, "visibilitynotify: window: %lu\n",
5395             e->xvisibility.window);
5396         if (e->xvisibility.state == VisibilityUnobscured)
5397                 for (i = 0; i < ScreenCount(display); i++)
5398                         TAILQ_FOREACH(r, &screens[i].rl, entry)
5399                                 if (e->xvisibility.window == r->bar_window)
5400                                         bar_update();
5401 }
5402
5403 void
5404 clientmessage(XEvent *e)
5405 {
5406         XClientMessageEvent *ev;
5407         struct ws_win *win;
5408
5409         ev = &e->xclient;
5410
5411         win = find_window(ev->window);
5412         if (win == NULL)
5413                 return;
5414
5415         DNPRINTF(SWM_D_EVENT, "clientmessage: window: 0x%lx type: %ld \n",
5416             ev->window, ev->message_type);
5417
5418         if (ev->message_type == ewmh[_NET_ACTIVE_WINDOW].atom) {
5419                 DNPRINTF(SWM_D_EVENT, "clientmessage: _NET_ACTIVE_WINDOW \n");
5420                 focus_win(win);
5421         }
5422         if (ev->message_type == ewmh[_NET_CLOSE_WINDOW].atom) {
5423                 DNPRINTF(SWM_D_EVENT, "clientmessage: _NET_CLOSE_WINDOW \n");
5424                 if (win->can_delete)
5425                         client_msg(win, adelete);
5426                 else
5427                         XKillClient(display, win->id);
5428         }
5429         if (ev->message_type == ewmh[_NET_MOVERESIZE_WINDOW].atom) {
5430                 DNPRINTF(SWM_D_EVENT,
5431                     "clientmessage: _NET_MOVERESIZE_WINDOW \n");
5432                 if (win->floating) {
5433                         if (ev->data.l[0] & (1<<8)) /* x */
5434                                 win->g.x = ev->data.l[1];
5435                         if (ev->data.l[0] & (1<<9)) /* y */
5436                                 win->g.y = ev->data.l[2];
5437                         if (ev->data.l[0] & (1<<10)) /* width */
5438                                 win->g.w = ev->data.l[3];
5439                         if (ev->data.l[0] & (1<<11)) /* height */
5440                                 win->g.h = ev->data.l[4];
5441                 }
5442                 else {
5443                         /* TODO: Change stack sizes */
5444                 }
5445                 config_win(win, NULL);
5446         }
5447         if (ev->message_type == ewmh[_NET_WM_STATE].atom) {
5448                 DNPRINTF(SWM_D_EVENT, "clientmessage: _NET_WM_STATE \n");
5449                 ewmh_update_win_state(win, ev->data.l[1], ev->data.l[0]);
5450                 if (ev->data.l[2])
5451                         ewmh_update_win_state(win, ev->data.l[2],
5452                             ev->data.l[0]);
5453
5454                 stack();
5455         }
5456 }
5457
5458 int
5459 xerror_start(Display *d, XErrorEvent *ee)
5460 {
5461         other_wm = 1;
5462         return (-1);
5463 }
5464
5465 int
5466 xerror(Display *d, XErrorEvent *ee)
5467 {
5468         /* fprintf(stderr, "error: %p %p\n", display, ee); */
5469         return (-1);
5470 }
5471
5472 int
5473 active_wm(void)
5474 {
5475         other_wm = 0;
5476         xerrorxlib = XSetErrorHandler(xerror_start);
5477
5478         /* this causes an error if some other window manager is running */
5479         XSelectInput(display, DefaultRootWindow(display),
5480             SubstructureRedirectMask);
5481         XSync(display, False);
5482         if (other_wm)
5483                 return (1);
5484
5485         XSetErrorHandler(xerror);
5486         XSync(display, False);
5487         return (0);
5488 }
5489
5490 void
5491 new_region(struct swm_screen *s, int x, int y, int w, int h)
5492 {
5493         struct swm_region       *r, *n;
5494         struct workspace        *ws = NULL;
5495         int                     i;
5496
5497         DNPRINTF(SWM_D_MISC, "new region: screen[%d]:%dx%d+%d+%d\n",
5498              s->idx, w, h, x, y);
5499
5500         /* remove any conflicting regions */
5501         n = TAILQ_FIRST(&s->rl);
5502         while (n) {
5503                 r = n;
5504                 n = TAILQ_NEXT(r, entry);
5505                 if (X(r) < (x + w) &&
5506                     (X(r) + WIDTH(r)) > x &&
5507                     Y(r) < (y + h) &&
5508                     (Y(r) + HEIGHT(r)) > y) {
5509                         if (r->ws->r != NULL)
5510                                 r->ws->old_r = r->ws->r;
5511                         r->ws->r = NULL;
5512                         XDestroyWindow(display, r->bar_window);
5513                         TAILQ_REMOVE(&s->rl, r, entry);
5514                         TAILQ_INSERT_TAIL(&s->orl, r, entry);
5515                 }
5516         }
5517
5518         /* search old regions for one to reuse */
5519
5520         /* size + location match */
5521         TAILQ_FOREACH(r, &s->orl, entry)
5522                 if (X(r) == x && Y(r) == y &&
5523                     HEIGHT(r) == h && WIDTH(r) == w)
5524                         break;
5525
5526         /* size match */
5527         TAILQ_FOREACH(r, &s->orl, entry)
5528                 if (HEIGHT(r) == h && WIDTH(r) == w)
5529                         break;
5530
5531         if (r != NULL) {
5532                 TAILQ_REMOVE(&s->orl, r, entry);
5533                 /* try to use old region's workspace */
5534                 if (r->ws->r == NULL)
5535                         ws = r->ws;
5536         } else
5537                 if ((r = calloc(1, sizeof(struct swm_region))) == NULL)
5538                         errx(1, "calloc: failed to allocate memory for screen");
5539
5540         /* if we don't have a workspace already, find one */
5541         if (ws == NULL) {
5542                 for (i = 0; i < SWM_WS_MAX; i++)
5543                         if (s->ws[i].r == NULL) {
5544                                 ws = &s->ws[i];
5545                                 break;
5546                         }
5547         }
5548
5549         if (ws == NULL)
5550                 errx(1, "no free workspaces\n");
5551
5552         X(r) = x;
5553         Y(r) = y;
5554         WIDTH(r) = w;
5555         HEIGHT(r) = h;
5556         r->s = s;
5557         r->ws = ws;
5558         r->ws_prior = NULL;
5559         ws->r = r;
5560         outputs++;
5561         TAILQ_INSERT_TAIL(&s->rl, r, entry);
5562 }
5563
5564 void
5565 scan_xrandr(int i)
5566 {
5567 #ifdef SWM_XRR_HAS_CRTC
5568         XRRCrtcInfo             *ci;
5569         XRRScreenResources      *sr;
5570         int                     c;
5571         int                     ncrtc = 0;
5572 #endif /* SWM_XRR_HAS_CRTC */
5573         struct swm_region       *r;
5574
5575
5576         if (i >= ScreenCount(display))
5577                 errx(1, "invalid screen");
5578
5579         /* remove any old regions */
5580         while ((r = TAILQ_FIRST(&screens[i].rl)) != NULL) {
5581                 r->ws->old_r = r->ws->r = NULL;
5582                 XDestroyWindow(display, r->bar_window);
5583                 TAILQ_REMOVE(&screens[i].rl, r, entry);
5584                 TAILQ_INSERT_TAIL(&screens[i].orl, r, entry);
5585         }
5586         outputs = 0;
5587
5588         /* map virtual screens onto physical screens */
5589 #ifdef SWM_XRR_HAS_CRTC
5590         if (xrandr_support) {
5591                 sr = XRRGetScreenResources(display, screens[i].root);
5592                 if (sr == NULL)
5593                         new_region(&screens[i], 0, 0,
5594                             DisplayWidth(display, i),
5595                             DisplayHeight(display, i));
5596                 else
5597                         ncrtc = sr->ncrtc;
5598
5599                 for (c = 0, ci = NULL; c < ncrtc; c++) {
5600                         ci = XRRGetCrtcInfo(display, sr, sr->crtcs[c]);
5601                         if (ci->noutput == 0)
5602                                 continue;
5603
5604                         if (ci != NULL && ci->mode == None)
5605                                 new_region(&screens[i], 0, 0,
5606                                     DisplayWidth(display, i),
5607                                     DisplayHeight(display, i));
5608                         else
5609                                 new_region(&screens[i],
5610                                     ci->x, ci->y, ci->width, ci->height);
5611                 }
5612                 if (ci)
5613                         XRRFreeCrtcInfo(ci);
5614                 XRRFreeScreenResources(sr);
5615         } else
5616 #endif /* SWM_XRR_HAS_CRTC */
5617         {
5618                 new_region(&screens[i], 0, 0, DisplayWidth(display, i),
5619                     DisplayHeight(display, i));
5620         }
5621 }
5622
5623 void
5624 screenchange(XEvent *e) {
5625         XRRScreenChangeNotifyEvent      *xe = (XRRScreenChangeNotifyEvent *)e;
5626         struct swm_region               *r;
5627         int                             i;
5628
5629         DNPRINTF(SWM_D_EVENT, "screenchange: %lu\n", xe->root);
5630
5631         if (!XRRUpdateConfiguration(e))
5632                 return;
5633
5634         /* silly event doesn't include the screen index */
5635         for (i = 0; i < ScreenCount(display); i++)
5636                 if (screens[i].root == xe->root)
5637                         break;
5638         if (i >= ScreenCount(display))
5639                 errx(1, "screenchange: screen not found\n");
5640
5641         /* brute force for now, just re-enumerate the regions */
5642         scan_xrandr(i);
5643
5644         /* add bars to all regions */
5645         for (i = 0; i < ScreenCount(display); i++)
5646                 TAILQ_FOREACH(r, &screens[i].rl, entry)
5647                         bar_setup(r);
5648         stack();
5649         if (focus_mode == SWM_FOCUS_DEFAULT)
5650                 drain_enter_notify();
5651 }
5652
5653 void
5654 grab_windows(void)
5655 {
5656         Window                  d1, d2, *wins = NULL;
5657         XWindowAttributes       wa;
5658         unsigned int            no;
5659         int                     i, j;
5660         long                    state, manage;
5661
5662         for (i = 0; i < ScreenCount(display); i++) {
5663                 if (!XQueryTree(display, screens[i].root, &d1, &d2, &wins, &no))
5664                         continue;
5665
5666                 /* attach windows to a region */
5667                 /* normal windows */
5668                 for (j = 0; j < no; j++) {
5669                         if (!XGetWindowAttributes(display, wins[j], &wa) ||
5670                             wa.override_redirect ||
5671                             XGetTransientForHint(display, wins[j], &d1))
5672                                 continue;
5673
5674                         state = getstate(wins[j]);
5675                         manage = state == IconicState;
5676                         if (wa.map_state == IsViewable || manage)
5677                                 manage_window(wins[j]);
5678                 }
5679                 /* transient windows */
5680                 for (j = 0; j < no; j++) {
5681                         if (!XGetWindowAttributes(display, wins[j], &wa) ||
5682                             wa.override_redirect)
5683                                 continue;
5684
5685                         state = getstate(wins[j]);
5686                         manage = state == IconicState;
5687                         if (XGetTransientForHint(display, wins[j], &d1) &&
5688                             manage)
5689                                 manage_window(wins[j]);
5690                 }
5691                 if (wins) {
5692                         XFree(wins);
5693                         wins = NULL;
5694                 }
5695         }
5696 }
5697
5698 void
5699 setup_screens(void)
5700 {
5701         int                     i, j, k;
5702         int                     errorbase, major, minor;
5703         struct workspace        *ws;
5704         int                     ws_idx_atom;
5705
5706         if ((screens = calloc(ScreenCount(display),
5707              sizeof(struct swm_screen))) == NULL)
5708                 errx(1, "calloc: screens");
5709
5710         ws_idx_atom = XInternAtom(display, "_SWM_WS", False);
5711
5712         /* initial Xrandr setup */
5713         xrandr_support = XRRQueryExtension(display,
5714             &xrandr_eventbase, &errorbase);
5715         if (xrandr_support)
5716                 if (XRRQueryVersion(display, &major, &minor) && major < 1)
5717                         xrandr_support = 0;
5718
5719         /* map physical screens */
5720         for (i = 0; i < ScreenCount(display); i++) {
5721                 DNPRINTF(SWM_D_WS, "setup_screens: init screen %d\n", i);
5722                 screens[i].idx = i;
5723                 TAILQ_INIT(&screens[i].rl);
5724                 TAILQ_INIT(&screens[i].orl);
5725                 screens[i].root = RootWindow(display, i);
5726
5727                 /* set default colors */
5728                 setscreencolor("red", i + 1, SWM_S_COLOR_FOCUS);
5729                 setscreencolor("rgb:88/88/88", i + 1, SWM_S_COLOR_UNFOCUS);
5730                 setscreencolor("rgb:00/80/80", i + 1, SWM_S_COLOR_BAR_BORDER);
5731                 setscreencolor("black", i + 1, SWM_S_COLOR_BAR);
5732                 setscreencolor("rgb:a0/a0/a0", i + 1, SWM_S_COLOR_BAR_FONT);
5733
5734                 /* set default cursor */
5735                 XDefineCursor(display, screens[i].root,
5736                     XCreateFontCursor(display, XC_left_ptr));
5737
5738                 /* init all workspaces */
5739                 /* XXX these should be dynamically allocated too */
5740                 for (j = 0; j < SWM_WS_MAX; j++) {
5741                         ws = &screens[i].ws[j];
5742                         ws->idx = j;
5743                         ws->focus = NULL;
5744                         ws->r = NULL;
5745                         ws->old_r = NULL;
5746                         TAILQ_INIT(&ws->winlist);
5747                         TAILQ_INIT(&ws->unmanagedlist);
5748
5749                         for (k = 0; layouts[k].l_stack != NULL; k++)
5750                                 if (layouts[k].l_config != NULL)
5751                                         layouts[k].l_config(ws,
5752                                             SWM_ARG_ID_STACKINIT);
5753                         ws->cur_layout = &layouts[0];
5754                 }
5755
5756                 scan_xrandr(i);
5757
5758                 if (xrandr_support)
5759                         XRRSelectInput(display, screens[i].root,
5760                             RRScreenChangeNotifyMask);
5761         }
5762 }
5763
5764 void
5765 setup_globals(void)
5766 {
5767         if ((bar_fonts[0] = strdup("-*-terminus-medium-*-*-*-*-*-*-*-*-*-*-*"))
5768             == NULL)
5769                 err(1, "setup_globals: strdup");
5770         if ((bar_fonts[1] = strdup("-*-times-medium-r-*-*-*-*-*-*-*-*-*-*"))
5771             == NULL)
5772                 err(1, "setup_globals: strdup");
5773         if ((bar_fonts[2] = strdup("-misc-fixed-medium-r-*-*-*-*-*-*-*-*-*-*"))
5774             == NULL)
5775                 err(1, "setup_globals: strdup");
5776         if ((spawn_term[0] = strdup("xterm")) == NULL)
5777                 err(1, "setup_globals: strdup");
5778         if ((clock_format = strdup("%a %b %d %R %Z %Y")) == NULL)
5779                 errx(1, "strdup");
5780 }
5781
5782 void
5783 workaround(void)
5784 {
5785         int                     i;
5786         Atom                    netwmcheck, netwmname, utf8_string;
5787         Window                  root, win;
5788
5789         /* work around sun jdk bugs, code from wmname */
5790         netwmcheck = XInternAtom(display, "_NET_SUPPORTING_WM_CHECK", False);
5791         netwmname = XInternAtom(display, "_NET_WM_NAME", False);
5792         utf8_string = XInternAtom(display, "UTF8_STRING", False);
5793         for (i = 0; i < ScreenCount(display); i++) {
5794                 root = screens[i].root;
5795                 win = XCreateSimpleWindow(display,root, 0, 0, 1, 1, 0,
5796                     screens[i].c[SWM_S_COLOR_UNFOCUS].color,
5797                     screens[i].c[SWM_S_COLOR_UNFOCUS].color);
5798
5799                 XChangeProperty(display, root, netwmcheck, XA_WINDOW, 32,
5800                     PropModeReplace, (unsigned char *)&win,1);
5801                 XChangeProperty(display, win, netwmcheck, XA_WINDOW, 32,
5802                     PropModeReplace, (unsigned char *)&win,1);
5803                 XChangeProperty(display, win, netwmname, utf8_string, 8,
5804                     PropModeReplace, (unsigned char*)"LG3D", strlen("LG3D"));
5805         }
5806 }
5807
5808 int
5809 main(int argc, char *argv[])
5810 {
5811         struct passwd           *pwd;
5812         struct swm_region       *r, *rr;
5813         struct ws_win           *winfocus = NULL;
5814         struct timeval          tv;
5815         union arg               a;
5816         char                    conf[PATH_MAX], *cfile = NULL;
5817         struct stat             sb;
5818         XEvent                  e;
5819         int                     xfd, i;
5820         fd_set                  rd;
5821         struct sigaction        sact;
5822
5823         start_argv = argv;
5824         fprintf(stderr, "Welcome to scrotwm V%s cvs tag: %s\n",
5825             SWM_VERSION, cvstag);
5826         if (!setlocale(LC_CTYPE, "") || !XSupportsLocale())
5827                 warnx("no locale support");
5828
5829         if (!(display = XOpenDisplay(0)))
5830                 errx(1, "can not open display");
5831
5832         if (active_wm())
5833                 errx(1, "other wm running");
5834
5835         /* handle some signals */
5836         bzero(&sact, sizeof(sact));
5837         sigemptyset(&sact.sa_mask);
5838         sact.sa_flags = 0;
5839         sact.sa_handler = sighdlr;
5840         sigaction(SIGINT, &sact, NULL);
5841         sigaction(SIGQUIT, &sact, NULL);
5842         sigaction(SIGTERM, &sact, NULL);
5843         sigaction(SIGHUP, &sact, NULL);
5844
5845         sact.sa_handler = sighdlr;
5846         sact.sa_flags = SA_NOCLDSTOP;
5847         sigaction(SIGCHLD, &sact, NULL);
5848
5849         astate = XInternAtom(display, "WM_STATE", False);
5850         aprot = XInternAtom(display, "WM_PROTOCOLS", False);
5851         adelete = XInternAtom(display, "WM_DELETE_WINDOW", False);
5852         takefocus = XInternAtom(display, "WM_TAKE_FOCUS", False);
5853         a_wmname = XInternAtom(display, "WM_NAME", False);
5854         a_utf8_string = XInternAtom(display, "UTF8_STRING", False);
5855         a_string = XInternAtom(display, "STRING", False);
5856         a_swm_iconic = XInternAtom(display, "_SWM_ICONIC", False);
5857
5858         /* look for local and global conf file */
5859         pwd = getpwuid(getuid());
5860         if (pwd == NULL)
5861                 errx(1, "invalid user %d", getuid());
5862
5863         setup_screens();
5864         setup_globals();
5865         setup_keys();
5866         setup_quirks();
5867         setup_spawn();
5868
5869         /* load config */
5870         snprintf(conf, sizeof conf, "%s/.%s", pwd->pw_dir, SWM_CONF_FILE);
5871         if (stat(conf, &sb) != -1) {
5872                 if (S_ISREG(sb.st_mode))
5873                         cfile = conf;
5874         } else {
5875                 /* try global conf file */
5876                 snprintf(conf, sizeof conf, "/etc/%s", SWM_CONF_FILE);
5877                 if (!stat(conf, &sb))
5878                         if (S_ISREG(sb.st_mode))
5879                                 cfile = conf;
5880         }
5881         if (cfile)
5882                 conf_load(cfile);
5883
5884         setup_ewmh();
5885         /* set some values to work around bad programs */
5886         workaround();
5887
5888         /* grab existing windows (before we build the bars) */
5889         grab_windows();
5890
5891         /* setup all bars */
5892         for (i = 0; i < ScreenCount(display); i++)
5893                 TAILQ_FOREACH(r, &screens[i].rl, entry) {
5894                         if (winfocus == NULL)
5895                                 winfocus = TAILQ_FIRST(&r->ws->winlist);
5896                         bar_setup(r);
5897                 }
5898
5899         unfocus_all();
5900
5901         grabkeys();
5902         stack();
5903         if (focus_mode == SWM_FOCUS_DEFAULT)
5904                 drain_enter_notify();
5905
5906         xfd = ConnectionNumber(display);
5907         while (running) {
5908                 while (XPending(display)) {
5909                         XNextEvent(display, &e);
5910                         if (running == 0)
5911                                 goto done;
5912                         if (e.type < LASTEvent) {
5913                                 dumpevent(&e);
5914                                 if (handler[e.type])
5915                                         handler[e.type](&e);
5916                                 else
5917                                         DNPRINTF(SWM_D_EVENT,
5918                                             "win: %lu unknown event: %d\n",
5919                                             e.xany.window, e.type);
5920                         } else {
5921                                 switch (e.type - xrandr_eventbase) {
5922                                 case RRScreenChangeNotify:
5923                                         screenchange(&e);
5924                                         break;
5925                                 default:
5926                                         DNPRINTF(SWM_D_EVENT,
5927                                             "win: %lu unknown xrandr event: "
5928                                             "%d\n", e.xany.window, e.type);
5929                                         break;
5930                                 }
5931                         }
5932                 }
5933
5934                 /* if we are being restarted go focus on first window */
5935                 if (winfocus) {
5936                         rr = winfocus->ws->r;
5937                         if (rr == NULL) {
5938                                 /* not a visible window */
5939                                 winfocus = NULL;
5940                                 continue;
5941                         }
5942                         /* move pointer to first screen if multi screen */
5943                         if (ScreenCount(display) > 1 || outputs > 1)
5944                                 XWarpPointer(display, None, rr->s[0].root,
5945                                     0, 0, 0, 0, rr->g.x,
5946                                     rr->g.y + (bar_enabled ? bar_height : 0));
5947
5948                         a.id = SWM_ARG_ID_FOCUSCUR;
5949                         focus(rr, &a);
5950                         winfocus = NULL;
5951                         continue;
5952                 }
5953
5954                 FD_ZERO(&rd);
5955                 FD_SET(xfd, &rd);
5956                 tv.tv_sec = 1;
5957                 tv.tv_usec = 0;
5958                 if (select(xfd + 1, &rd, NULL, NULL, &tv) == -1)
5959                         if (errno != EINTR)
5960                                 DNPRINTF(SWM_D_MISC, "select failed");
5961                 if (restart_wm == 1)
5962                         restart(NULL, NULL);
5963                 if (search_resp == 1)
5964                         search_do_resp();
5965                 if (running == 0)
5966                         goto done;
5967                 if (bar_alarm) {
5968                         bar_alarm = 0;
5969                         bar_update();
5970                 }
5971         }
5972 done:
5973         teardown_ewmh();
5974         bar_extra_stop();
5975         XFreeGC(display, bar_gc);
5976         XCloseDisplay(display);
5977
5978         return (0);
5979 }