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