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