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