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