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