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