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