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