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