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