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