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