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