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