JasonWoof Got questions, comments, patches, etc.? Contact Jason Woofenden
Refresh status-bar after moving a window.
[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         bar_update();
2286
2287         /* unmap old windows */
2288         if (unmap_old)
2289                 TAILQ_FOREACH(win, &old_ws->winlist, entry)
2290                         unmap_window(win);
2291
2292         if (focus_mode == SWM_FOCUS_DEFAULT)
2293                 drain_enter_notify();
2294 }
2295
2296 void
2297 cyclews(struct swm_region *r, union arg *args)
2298 {
2299         union                   arg a;
2300         struct swm_screen       *s = r->s;
2301         int                     cycle_all = 0;
2302
2303         DNPRINTF(SWM_D_WS, "cyclews: id: %d, screen[%d]:%dx%d+%d+%d, ws: %d\n",
2304             args->id, r->s->idx, WIDTH(r), HEIGHT(r), X(r), Y(r), r->ws->idx);
2305
2306         a.id = r->ws->idx;
2307         do {
2308                 switch (args->id) {
2309                 case SWM_ARG_ID_CYCLEWS_UP_ALL:
2310                         cycle_all = 1;
2311                         /* FALLTHROUGH */
2312                 case SWM_ARG_ID_CYCLEWS_UP:
2313                         if (a.id < workspace_limit - 1)
2314                                 a.id++;
2315                         else
2316                                 a.id = 0;
2317                         break;
2318                 case SWM_ARG_ID_CYCLEWS_DOWN_ALL:
2319                         cycle_all = 1;
2320                         /* FALLTHROUGH */
2321                 case SWM_ARG_ID_CYCLEWS_DOWN:
2322                         if (a.id > 0)
2323                                 a.id--;
2324                         else
2325                                 a.id = workspace_limit - 1;
2326                         break;
2327                 default:
2328                         return;
2329                 };
2330
2331                 if (!cycle_all &&
2332                     (cycle_empty == 0 && TAILQ_EMPTY(&s->ws[a.id].winlist)))
2333                         continue;
2334                 if (cycle_visible == 0 && s->ws[a.id].r != NULL)
2335                         continue;
2336
2337                 switchws(r, &a);
2338         } while (a.id != r->ws->idx);
2339 }
2340
2341 void
2342 priorws(struct swm_region *r, union arg *args)
2343 {
2344         union arg               a;
2345
2346         DNPRINTF(SWM_D_WS, "priorws: id: %d, screen[%d]:%dx%d+%d+%d, ws: %d\n",
2347             args->id, r->s->idx, WIDTH(r), HEIGHT(r), X(r), Y(r), r->ws->idx);
2348
2349         if (r->ws_prior == NULL)
2350                 return;
2351
2352         a.id = r->ws_prior->idx;
2353         switchws(r, &a);
2354 }
2355
2356 void
2357 cyclescr(struct swm_region *r, union arg *args)
2358 {
2359         struct swm_region       *rr = NULL;
2360         union arg               a;
2361         int                     i, x, y;
2362
2363         /* do nothing if we don't have more than one screen */
2364         if (!(ScreenCount(display) > 1 || outputs > 1))
2365                 return;
2366
2367         i = r->s->idx;
2368         switch (args->id) {
2369         case SWM_ARG_ID_CYCLESC_UP:
2370                 rr = TAILQ_NEXT(r, entry);
2371                 if (rr == NULL)
2372                         rr = TAILQ_FIRST(&screens[i].rl);
2373                 break;
2374         case SWM_ARG_ID_CYCLESC_DOWN:
2375                 rr = TAILQ_PREV(r, swm_region_list, entry);
2376                 if (rr == NULL)
2377                         rr = TAILQ_LAST(&screens[i].rl, swm_region_list);
2378                 break;
2379         default:
2380                 return;
2381         };
2382         if (rr == NULL)
2383                 return;
2384
2385         /* move mouse to region */
2386         x = X(rr) + 1;
2387         y = Y(rr) + 1 + (bar_enabled ? bar_height : 0);
2388         XWarpPointer(display, None, rr->s[i].root, 0, 0, 0, 0, x, y);
2389
2390         a.id = SWM_ARG_ID_FOCUSCUR;
2391         focus(rr, &a);
2392
2393         if (rr->ws->focus) {
2394                 /* move to focus window */
2395                 x = X(rr->ws->focus) + 1;
2396                 y = Y(rr->ws->focus) + 1;
2397                 XWarpPointer(display, None, rr->s[i].root, 0, 0, 0, 0, x, y);
2398         }
2399 }
2400
2401 void
2402 sort_windows(struct ws_win_list *wl)
2403 {
2404         struct ws_win           *win, *parent, *nxt;
2405
2406         if (wl == NULL)
2407                 return;
2408
2409         for (win = TAILQ_FIRST(wl); win != TAILQ_END(wl); win = nxt) {
2410                 nxt = TAILQ_NEXT(win, entry);
2411                 if (win->transient) {
2412                         parent = find_window(win->transient);
2413                         if (parent == NULL) {
2414                                 warnx("not possible bug");
2415                                 continue;
2416                         }
2417                         TAILQ_REMOVE(wl, win, entry);
2418                         TAILQ_INSERT_AFTER(wl, parent, win, entry);
2419                 }
2420         }
2421
2422 }
2423
2424 void
2425 swapwin(struct swm_region *r, union arg *args)
2426 {
2427         struct ws_win           *target, *source;
2428         struct ws_win           *cur_focus;
2429         struct ws_win_list      *wl;
2430
2431
2432         DNPRINTF(SWM_D_WS, "swapwin: id: %d, screen[%d]:%dx%d+%d+%d, ws: %d\n",
2433             args->id, r->s->idx, WIDTH(r), HEIGHT(r), X(r), Y(r), r->ws->idx);
2434
2435         cur_focus = r->ws->focus;
2436         if (cur_focus == NULL)
2437                 return;
2438
2439         source = cur_focus;
2440         wl = &source->ws->winlist;
2441
2442         switch (args->id) {
2443         case SWM_ARG_ID_SWAPPREV:
2444                 if (source->transient)
2445                         source = find_window(source->transient);
2446                 target = TAILQ_PREV(source, ws_win_list, entry);
2447                 if (target && target->transient)
2448                         target = find_window(target->transient);
2449                 TAILQ_REMOVE(wl, source, entry);
2450                 if (target == NULL)
2451                         TAILQ_INSERT_TAIL(wl, source, entry);
2452                 else
2453                         TAILQ_INSERT_BEFORE(target, source, entry);
2454                 break;
2455         case SWM_ARG_ID_SWAPNEXT:
2456                 target = TAILQ_NEXT(source, entry);
2457                 /* move the parent and let the sort handle the move */
2458                 if (source->transient)
2459                         source = find_window(source->transient);
2460                 TAILQ_REMOVE(wl, source, entry);
2461                 if (target == NULL)
2462                         TAILQ_INSERT_HEAD(wl, source, entry);
2463                 else
2464                         TAILQ_INSERT_AFTER(wl, target, source, entry);
2465                 break;
2466         case SWM_ARG_ID_SWAPMAIN:
2467                 target = TAILQ_FIRST(wl);
2468                 if (target == source) {
2469                         if (source->ws->focus_prev != NULL &&
2470                             source->ws->focus_prev != target)
2471                                 source = source->ws->focus_prev;
2472                         else
2473                                 return;
2474                 }
2475                 if (target == NULL || source == NULL)
2476                         return;
2477                 source->ws->focus_prev = target;
2478                 TAILQ_REMOVE(wl, target, entry);
2479                 TAILQ_INSERT_BEFORE(source, target, entry);
2480                 TAILQ_REMOVE(wl, source, entry);
2481                 TAILQ_INSERT_HEAD(wl, source, entry);
2482                 break;
2483         case SWM_ARG_ID_MOVELAST:
2484                 TAILQ_REMOVE(wl, source, entry);
2485                 TAILQ_INSERT_TAIL(wl, source, entry);
2486                 break;
2487         default:
2488                 DNPRINTF(SWM_D_MOVE, "swapwin: invalid id: %d\n", args->id);
2489                 return;
2490         }
2491
2492         sort_windows(wl);
2493
2494         stack();
2495 }
2496
2497 void
2498 focus_prev(struct ws_win *win)
2499 {
2500         struct ws_win           *winfocus = NULL;
2501         struct ws_win           *cur_focus = NULL;
2502         struct ws_win_list      *wl = NULL;
2503         struct workspace        *ws = NULL;
2504
2505         if (!(win && win->ws))
2506                 return;
2507
2508         ws = win->ws;
2509         wl = &ws->winlist;
2510         cur_focus = ws->focus;
2511
2512         DNPRINTF(SWM_D_FOCUS, "focus_prev: window: 0x%lx, cur_focus: 0x%lx\n",
2513             WINID(win), WINID(cur_focus));
2514
2515         /* pickle, just focus on whatever */
2516         if (cur_focus == NULL) {
2517                 /* use prev_focus if valid */
2518                 if (ws->focus_prev && ws->focus_prev != cur_focus &&
2519                     find_window(WINID(ws->focus_prev)))
2520                         winfocus = ws->focus_prev;
2521                 goto done;
2522         }
2523
2524         /* if transient focus on parent */
2525         if (cur_focus->transient) {
2526                 winfocus = find_window(cur_focus->transient);
2527                 goto done;
2528         }
2529
2530         /* if in max_stack try harder */
2531         if ((win->quirks & SWM_Q_FOCUSPREV) ||
2532             (ws->cur_layout->flags & SWM_L_FOCUSPREV)) {
2533                 if (cur_focus != ws->focus_prev)
2534                         winfocus = ws->focus_prev;
2535                 else
2536                         winfocus = TAILQ_PREV(win, ws_win_list, entry);
2537                 if (winfocus)
2538                         goto done;
2539         }
2540
2541         DNPRINTF(SWM_D_FOCUS, "focus_prev: focus_close: %d\n", focus_close);
2542
2543         if (winfocus == NULL || winfocus == win) {
2544                 switch (focus_close) {
2545                 case SWM_STACK_BOTTOM:
2546                         winfocus = TAILQ_FIRST(wl);
2547                         break;
2548                 case SWM_STACK_TOP:
2549                         winfocus = TAILQ_LAST(wl, ws_win_list);
2550                         break;
2551                 case SWM_STACK_ABOVE:
2552                         if ((winfocus = TAILQ_NEXT(cur_focus, entry)) == NULL) {
2553                                 if (focus_close_wrap)
2554                                         winfocus = TAILQ_FIRST(wl);
2555                                 else
2556                                         winfocus = TAILQ_PREV(cur_focus,
2557                                             ws_win_list, entry);
2558                         }
2559                         break;
2560                 case SWM_STACK_BELOW:
2561                         if ((winfocus = TAILQ_PREV(cur_focus, ws_win_list,
2562                             entry)) == NULL) {
2563                                 if (focus_close_wrap)
2564                                         winfocus = TAILQ_LAST(wl, ws_win_list);
2565                                 else
2566                                         winfocus = TAILQ_NEXT(cur_focus, entry);
2567                         }
2568                         break;
2569                 }
2570         }
2571 done:
2572         if (winfocus == NULL) {
2573                 if (focus_default == SWM_STACK_TOP)
2574                         winfocus = TAILQ_LAST(wl, ws_win_list);
2575                 else
2576                         winfocus = TAILQ_FIRST(wl);
2577         }
2578
2579         kill_refs(win);
2580         focus_magic(winfocus);
2581 }
2582
2583 void
2584 focus(struct swm_region *r, union arg *args)
2585 {
2586         struct ws_win           *winfocus = NULL, *head;
2587         struct ws_win           *cur_focus = NULL;
2588         struct ws_win_list      *wl = NULL;
2589         struct workspace        *ws = NULL;
2590         int                     all_iconics;
2591
2592         if (!(r && r->ws))
2593                 return;
2594
2595         DNPRINTF(SWM_D_FOCUS, "focus: id: %d\n", args->id);
2596
2597         /* treat FOCUS_CUR special */
2598         if (args->id == SWM_ARG_ID_FOCUSCUR) {
2599                 if (r->ws->focus && r->ws->focus->iconic == 0)
2600                         winfocus = r->ws->focus;
2601                 else if (r->ws->focus_prev && r->ws->focus_prev->iconic == 0)
2602                         winfocus = r->ws->focus_prev;
2603                 else
2604                         TAILQ_FOREACH(winfocus, &r->ws->winlist, entry)
2605                                 if (winfocus->iconic == 0)
2606                                         break;
2607
2608                 focus_magic(winfocus);
2609                 return;
2610         }
2611
2612         if ((cur_focus = r->ws->focus) == NULL)
2613                 return;
2614         ws = r->ws;
2615         wl = &ws->winlist;
2616         if (TAILQ_EMPTY(wl))
2617                 return;
2618         /* make sure there is at least one uniconified window */
2619         all_iconics = 1;
2620         TAILQ_FOREACH(winfocus, wl, entry)
2621                 if (winfocus->iconic == 0) {
2622                         all_iconics = 0;
2623                         break;
2624                 }
2625         if (all_iconics)
2626                 return;
2627
2628         switch (args->id) {
2629         case SWM_ARG_ID_FOCUSPREV:
2630                 head = TAILQ_PREV(cur_focus, ws_win_list, entry);
2631                 if (head == NULL)
2632                         head = TAILQ_LAST(wl, ws_win_list);
2633                 winfocus = head;
2634                 if (WINID(winfocus) == cur_focus->transient) {
2635                         head = TAILQ_PREV(winfocus, ws_win_list, entry);
2636                         if (head == NULL)
2637                                 head = TAILQ_LAST(wl, ws_win_list);
2638                         winfocus = head;
2639                 }
2640
2641                 /* skip iconics */
2642                 if (winfocus && winfocus->iconic) {
2643                         while (winfocus != cur_focus) {
2644                                 if (winfocus == NULL)
2645                                         winfocus = TAILQ_LAST(wl, ws_win_list);
2646                                 if (winfocus->iconic == 0)
2647                                         break;
2648                                 winfocus = TAILQ_PREV(winfocus, ws_win_list,
2649                                     entry);
2650                         }
2651                 }
2652                 break;
2653
2654         case SWM_ARG_ID_FOCUSNEXT:
2655                 head = TAILQ_NEXT(cur_focus, entry);
2656                 if (head == NULL)
2657                         head = TAILQ_FIRST(wl);
2658                 winfocus = head;
2659
2660                 /* skip iconics */
2661                 if (winfocus && winfocus->iconic) {
2662                         while (winfocus != cur_focus) {
2663                                 if (winfocus == NULL)
2664                                         winfocus = TAILQ_FIRST(wl);
2665                                 if (winfocus->iconic == 0)
2666                                         break;
2667                                 winfocus = TAILQ_NEXT(winfocus, entry);
2668                         }
2669                 }
2670                 break;
2671
2672         case SWM_ARG_ID_FOCUSMAIN:
2673                 winfocus = TAILQ_FIRST(wl);
2674                 if (winfocus == cur_focus)
2675                         winfocus = cur_focus->ws->focus_prev;
2676                 break;
2677
2678         default:
2679                 return;
2680         }
2681
2682         focus_magic(winfocus);
2683 }
2684
2685 void
2686 cycle_layout(struct swm_region *r, union arg *args)
2687 {
2688         struct workspace        *ws = r->ws;
2689         union arg               a;
2690
2691         DNPRINTF(SWM_D_EVENT, "cycle_layout: workspace: %d\n", ws->idx);
2692
2693         ws->cur_layout++;
2694         if (ws->cur_layout->l_stack == NULL)
2695                 ws->cur_layout = &layouts[0];
2696
2697         stack();
2698         if (focus_mode == SWM_FOCUS_DEFAULT)
2699                 drain_enter_notify();
2700         a.id = SWM_ARG_ID_FOCUSCUR;
2701         focus(r, &a);
2702         bar_update();
2703 }
2704
2705 void
2706 stack_config(struct swm_region *r, union arg *args)
2707 {
2708         struct workspace        *ws = r->ws;
2709
2710         DNPRINTF(SWM_D_STACK, "stack_config: id: %d workspace: %d\n",
2711             args->id, ws->idx);
2712
2713         if (ws->cur_layout->l_config != NULL)
2714                 ws->cur_layout->l_config(ws, args->id);
2715
2716         if (args->id != SWM_ARG_ID_STACKINIT)
2717                 stack();
2718         bar_update();
2719 }
2720
2721 void
2722 stack(void) {
2723         struct swm_geometry     g;
2724         struct swm_region       *r;
2725         int                     i;
2726 #ifdef SWM_DEBUG
2727         int j;
2728 #endif
2729
2730         DNPRINTF(SWM_D_STACK, "stack: begin\n");
2731
2732         for (i = 0; i < ScreenCount(display); i++) {
2733 #ifdef SWM_DEBUG
2734                 j = 0;
2735 #endif
2736                 TAILQ_FOREACH(r, &screens[i].rl, entry) {
2737                         DNPRINTF(SWM_D_STACK, "stack: workspace: %d "
2738                             "(screen: %d, region: %d)\n", r->ws->idx, i, j++);
2739
2740                         /* start with screen geometry, adjust for bar */
2741                         g = r->g;
2742                         g.w -= 2 * border_width;
2743                         g.h -= 2 * border_width;
2744                         if (bar_enabled) {
2745                                 if (!bar_at_bottom)
2746                                         g.y += bar_height;
2747                                 g.h -= bar_height;
2748                         }
2749                         r->ws->cur_layout->l_stack(r->ws, &g);
2750                         r->ws->cur_layout->l_string(r->ws);
2751                         /* save r so we can track region changes */
2752                         r->ws->old_r = r;
2753                 }
2754         }
2755         if (font_adjusted)
2756                 font_adjusted--;
2757
2758         if (focus_mode == SWM_FOCUS_DEFAULT)
2759                 drain_enter_notify();
2760
2761         DNPRINTF(SWM_D_STACK, "stack: end\n");
2762 }
2763
2764 void
2765 store_float_geom(struct ws_win *win, struct swm_region *r)
2766 {
2767         /* retain window geom and region geom */
2768         win->g_float = win->g;
2769         win->rg_float = r->g;
2770         win->g_floatvalid = 1;
2771 }
2772
2773 void
2774 stack_floater(struct ws_win *win, struct swm_region *r)
2775 {
2776         unsigned int            mask;
2777         XWindowChanges          wc;
2778
2779         if (win == NULL)
2780                 return;
2781
2782         bzero(&wc, sizeof wc);
2783         mask = CWX | CWY | CWBorderWidth | CWWidth | CWHeight;
2784
2785         /*
2786          * to allow windows to change their size (e.g. mplayer fs) only retrieve
2787          * geom on ws switches or return from max mode
2788          */
2789         if (win->floatmaxed || (r != r->ws->old_r && win->g_floatvalid
2790             && !(win->ewmh_flags & EWMH_F_FULLSCREEN))) {
2791                 /*
2792                  * use stored g and rg to set relative position and size
2793                  * as in old region or before max stack mode
2794                  */
2795                 X(win) = win->g_float.x - win->rg_float.x + X(r);
2796                 Y(win) = win->g_float.y - win->rg_float.y + Y(r);
2797                 WIDTH(win) = win->g_float.w;
2798                 HEIGHT(win) = win->g_float.h;
2799                 win->g_floatvalid = 0;
2800         }
2801
2802         win->floatmaxed = 0;
2803
2804         if ((win->quirks & SWM_Q_FULLSCREEN) && (WIDTH(win) >= WIDTH(r)) &&
2805             (HEIGHT(win) >= HEIGHT(r)))
2806                 wc.border_width = 0;
2807         else
2808                 wc.border_width = border_width;
2809         if (win->transient && (win->quirks & SWM_Q_TRANSSZ)) {
2810                 WIDTH(win) = (double)WIDTH(r) * dialog_ratio;
2811                 HEIGHT(win) = (double)HEIGHT(r) * dialog_ratio;
2812         }
2813
2814         if (!win->manual) {
2815                 /*
2816                  * floaters and transients are auto-centred unless moved
2817                  * or resized
2818                  */
2819                 X(win) = X(r) + (WIDTH(r) - WIDTH(win)) /  2 - wc.border_width;
2820                 Y(win) = Y(r) + (HEIGHT(r) - HEIGHT(win)) / 2 - wc.border_width;
2821         }
2822
2823         /* win can be outside r if new r smaller than old r */
2824         /* Ensure top left corner inside r (move probs otherwise) */
2825         if (X(win) < X(r) - wc.border_width)
2826                 X(win) = X(r) - wc.border_width;
2827         if (X(win) > X(r) + WIDTH(r) - 1)
2828                 X(win) = (WIDTH(win) > WIDTH(r)) ? X(r) :
2829                     (X(r) + WIDTH(r) - WIDTH(win) - 2 * wc.border_width);
2830         if (Y(win) < Y(r) - wc.border_width)
2831                 Y(win) = Y(r) - wc.border_width;
2832         if (Y(win) > Y(r) + HEIGHT(r) - 1)
2833                 Y(win) = (HEIGHT(win) > HEIGHT(r)) ? Y(r) :
2834                     (Y(r) + HEIGHT(r) - HEIGHT(win) - 2 * wc.border_width);
2835
2836         wc.x = X(win);
2837         wc.y = Y(win);
2838         wc.width = WIDTH(win);
2839         wc.height = HEIGHT(win);
2840
2841         /*
2842          * Retain floater and transient geometry for correct positioning
2843          * when ws changes region
2844          */
2845         if (!(win->ewmh_flags & EWMH_F_FULLSCREEN))
2846                 store_float_geom(win, r);
2847
2848         DNPRINTF(SWM_D_MISC, "stack_floater: window: %lu, (x,y) w x h: (%d,%d) "
2849             "%d x %d\n", win->id, wc.x, wc.y, wc.width, wc.height);
2850
2851         XConfigureWindow(display, win->id, mask, &wc);
2852 }
2853
2854 /*
2855  * Send keystrokes to terminal to decrease/increase the font size as the
2856  * window size changes.
2857  */
2858 void
2859 adjust_font(struct ws_win *win)
2860 {
2861         if (!(win->quirks & SWM_Q_XTERM_FONTADJ) ||
2862             win->floating || win->transient)
2863                 return;
2864
2865         if (win->sh.width_inc && win->last_inc != win->sh.width_inc &&
2866             WIDTH(win) / win->sh.width_inc < term_width &&
2867             win->font_steps < SWM_MAX_FONT_STEPS) {
2868                 win->font_size_boundary[win->font_steps] =
2869                     (win->sh.width_inc * term_width) + win->sh.base_width;
2870                 win->font_steps++;
2871                 font_adjusted++;
2872                 win->last_inc = win->sh.width_inc;
2873                 fake_keypress(win, XK_KP_Subtract, ShiftMask);
2874         } else if (win->font_steps && win->last_inc != win->sh.width_inc &&
2875             WIDTH(win) > win->font_size_boundary[win->font_steps - 1]) {
2876                 win->font_steps--;
2877                 font_adjusted++;
2878                 win->last_inc = win->sh.width_inc;
2879                 fake_keypress(win, XK_KP_Add, ShiftMask);
2880         }
2881 }
2882
2883 #define SWAPXY(g)       do {                            \
2884         int tmp;                                        \
2885         tmp = (g)->y; (g)->y = (g)->x; (g)->x = tmp;    \
2886         tmp = (g)->h; (g)->h = (g)->w; (g)->w = tmp;    \
2887 } while (0)
2888 void
2889 stack_master(struct workspace *ws, struct swm_geometry *g, int rot, int flip)
2890 {
2891         XWindowChanges          wc;
2892         XWindowAttributes       wa;
2893         struct swm_geometry     win_g, r_g = *g;
2894         struct ws_win           *win, *fs_win = 0;
2895         int                     i, j, s, stacks;
2896         int                     w_inc = 1, h_inc, w_base = 1, h_base;
2897         int                     hrh, extra = 0, h_slice, last_h = 0;
2898         int                     split, colno, winno, mwin, msize, mscale;
2899         int                     remain, missing, v_slice, reconfigure;
2900         unsigned int            mask;
2901
2902         DNPRINTF(SWM_D_STACK, "stack_master: workspace: %d, rot: %s, "
2903             "flip: %s\n", ws->idx, YESNO(rot), YESNO(flip));
2904
2905         winno = count_win(ws, 0);
2906         if (winno == 0 && count_win(ws, 1) == 0)
2907                 return;
2908
2909         TAILQ_FOREACH(win, &ws->winlist, entry)
2910                 if (win->transient == 0 && win->floating == 0
2911                     && win->iconic == 0)
2912                         break;
2913
2914         if (win == NULL)
2915                 goto notiles;
2916
2917         if (rot) {
2918                 w_inc = win->sh.width_inc;
2919                 w_base = win->sh.base_width;
2920                 mwin = ws->l_state.horizontal_mwin;
2921                 mscale = ws->l_state.horizontal_msize;
2922                 stacks = ws->l_state.horizontal_stacks;
2923                 SWAPXY(&r_g);
2924         } else {
2925                 w_inc = win->sh.height_inc;
2926                 w_base = win->sh.base_height;
2927                 mwin = ws->l_state.vertical_mwin;
2928                 mscale = ws->l_state.vertical_msize;
2929                 stacks = ws->l_state.vertical_stacks;
2930         }
2931         win_g = r_g;
2932
2933         if (stacks > winno - mwin)
2934                 stacks = winno - mwin;
2935         if (stacks < 1)
2936                 stacks = 1;
2937
2938         h_slice = r_g.h / SWM_H_SLICE;
2939         if (mwin && winno > mwin) {
2940                 v_slice = r_g.w / SWM_V_SLICE;
2941
2942                 split = mwin;
2943                 colno = split;
2944                 win_g.w = v_slice * mscale;
2945
2946                 if (w_inc > 1 && w_inc < v_slice) {
2947                         /* adjust for window's requested size increment */
2948                         remain = (win_g.w - w_base) % w_inc;
2949                         win_g.w -= remain;
2950                 }
2951
2952                 msize = win_g.w;
2953                 if (flip)
2954                         win_g.x += r_g.w - msize;
2955         } else {
2956                 msize = -2;
2957                 colno = split = winno / stacks;
2958                 win_g.w = ((r_g.w - (stacks * 2 * border_width) +
2959                     2 * border_width) / stacks);
2960         }
2961         hrh = r_g.h / colno;
2962         extra = r_g.h - (colno * hrh);
2963         win_g.h = hrh - 2 * border_width;
2964
2965         /*  stack all the tiled windows */
2966         i = j = 0, s = stacks;
2967         TAILQ_FOREACH(win, &ws->winlist, entry) {
2968                 if (win->transient != 0 || win->floating != 0)
2969                         continue;
2970                 if (win->iconic != 0)
2971                         continue;
2972
2973                 if (win->ewmh_flags & EWMH_F_FULLSCREEN) {
2974                         fs_win = win;
2975                         continue;
2976                 }
2977
2978                 if (split && i == split) {
2979                         colno = (winno - mwin) / stacks;
2980                         if (s <= (winno - mwin) % stacks)
2981                                 colno++;
2982                         split = split + colno;
2983                         hrh = (r_g.h / colno);
2984                         extra = r_g.h - (colno * hrh);
2985                         if (flip)
2986                                 win_g.x = r_g.x;
2987                         else
2988                                 win_g.x += win_g.w + 2 * border_width;
2989                         win_g.w = (r_g.w - msize -
2990                             (stacks * 2 * border_width)) / stacks;
2991                         if (s == 1)
2992                                 win_g.w += (r_g.w - msize -
2993                                     (stacks * 2 * border_width)) % stacks;
2994                         s--;
2995                         j = 0;
2996                 }
2997                 win_g.h = hrh - 2 * border_width;
2998                 if (rot) {
2999                         h_inc = win->sh.width_inc;
3000                         h_base = win->sh.base_width;
3001                 } else {
3002                         h_inc = win->sh.height_inc;
3003                         h_base = win->sh.base_height;
3004                 }
3005                 if (j == colno - 1) {
3006                         win_g.h = hrh + extra;
3007                 } else if (h_inc > 1 && h_inc < h_slice) {
3008                         /* adjust for window's requested size increment */
3009                         remain = (win_g.h - h_base) % h_inc;
3010                         missing = h_inc - remain;
3011
3012                         if (missing <= extra || j == 0) {
3013                                 extra -= missing;
3014                                 win_g.h += missing;
3015                         } else {
3016                                 win_g.h -= remain;
3017                                 extra += remain;
3018                         }
3019                 }
3020
3021                 if (j == 0)
3022                         win_g.y = r_g.y;
3023                 else
3024                         win_g.y += last_h + 2 * border_width;
3025
3026                 bzero(&wc, sizeof wc);
3027                 if (disable_border && bar_enabled == 0 && winno == 1){
3028                         wc.border_width = 0;
3029                         win_g.w += 2 * border_width;
3030                         win_g.h += 2 * border_width;
3031                 } else
3032                         wc.border_width = border_width;
3033                 reconfigure = 0;
3034                 if (rot) {
3035                         if (X(win) != win_g.y || Y(win) != win_g.x ||
3036                             WIDTH(win) != win_g.h || HEIGHT(win) != win_g.w) {
3037                                 reconfigure = 1;
3038                                 X(win) = wc.x = win_g.y;
3039                                 Y(win) = wc.y = win_g.x;
3040                                 WIDTH(win) = wc.width = win_g.h;
3041                                 HEIGHT(win) = wc.height = win_g.w;
3042                         }
3043                 } else {
3044                         if (X(win) != win_g.x || Y(win) != win_g.y ||
3045                             WIDTH(win) != win_g.w || HEIGHT(win) != win_g.h) {
3046                                 reconfigure = 1;
3047                                 X(win) = wc.x = win_g.x;
3048                                 Y(win) = wc.y = win_g.y;
3049                                 WIDTH(win) = wc.width = win_g.w;
3050                                 HEIGHT(win) = wc.height = win_g.h;
3051                         }
3052                 }
3053                 if (reconfigure) {
3054                         adjust_font(win);
3055                         mask = CWX | CWY | CWWidth | CWHeight | CWBorderWidth;
3056                         XConfigureWindow(display, win->id, mask, &wc);
3057                 }
3058
3059                 if (XGetWindowAttributes(display, win->id, &wa))
3060                         if (wa.map_state == IsUnmapped)
3061                                 XMapRaised(display, win->id);
3062
3063                 last_h = win_g.h;
3064                 i++;
3065                 j++;
3066         }
3067
3068 notiles:
3069         /* now, stack all the floaters and transients */
3070         TAILQ_FOREACH(win, &ws->winlist, entry) {
3071                 if (win->transient == 0 && win->floating == 0)
3072                         continue;
3073                 if (win->iconic == 1)
3074                         continue;
3075                 if (win->ewmh_flags & EWMH_F_FULLSCREEN) {
3076                         fs_win = win;
3077                         continue;
3078                 }
3079
3080                 stack_floater(win, ws->r);
3081                 XMapRaised(display, win->id);
3082         }
3083
3084         if (fs_win) {
3085                 stack_floater(fs_win, ws->r);
3086                 XMapRaised(display, fs_win->id);
3087         }
3088 }
3089
3090 void
3091 vertical_config(struct workspace *ws, int id)
3092 {
3093         DNPRINTF(SWM_D_STACK, "vertical_config: id: %d, workspace: %d\n",
3094             id, ws->idx);
3095
3096         switch (id) {
3097         case SWM_ARG_ID_STACKRESET:
3098         case SWM_ARG_ID_STACKINIT:
3099                 ws->l_state.vertical_msize = SWM_V_SLICE / 2;
3100                 ws->l_state.vertical_mwin = 1;
3101                 ws->l_state.vertical_stacks = 1;
3102                 break;
3103         case SWM_ARG_ID_MASTERSHRINK:
3104                 if (ws->l_state.vertical_msize > 1)
3105                         ws->l_state.vertical_msize--;
3106                 break;
3107         case SWM_ARG_ID_MASTERGROW:
3108                 if (ws->l_state.vertical_msize < SWM_V_SLICE - 1)
3109                         ws->l_state.vertical_msize++;
3110                 break;
3111         case SWM_ARG_ID_MASTERADD:
3112                 ws->l_state.vertical_mwin++;
3113                 break;
3114         case SWM_ARG_ID_MASTERDEL:
3115                 if (ws->l_state.vertical_mwin > 0)
3116                         ws->l_state.vertical_mwin--;
3117                 break;
3118         case SWM_ARG_ID_STACKINC:
3119                 ws->l_state.vertical_stacks++;
3120                 break;
3121         case SWM_ARG_ID_STACKDEC:
3122                 if (ws->l_state.vertical_stacks > 1)
3123                         ws->l_state.vertical_stacks--;
3124                 break;
3125         case SWM_ARG_ID_FLIPLAYOUT:
3126                 ws->l_state.vertical_flip = !ws->l_state.vertical_flip;
3127                 break;
3128         default:
3129                 return;
3130         }
3131 }
3132
3133 void
3134 vertical_stack(struct workspace *ws, struct swm_geometry *g)
3135 {
3136         DNPRINTF(SWM_D_STACK, "vertical_stack: workspace: %d\n", ws->idx);
3137
3138         stack_master(ws, g, 0, ws->l_state.vertical_flip);
3139 }
3140
3141 void
3142 horizontal_config(struct workspace *ws, int id)
3143 {
3144         DNPRINTF(SWM_D_STACK, "horizontal_config: workspace: %d\n", ws->idx);
3145
3146         switch (id) {
3147         case SWM_ARG_ID_STACKRESET:
3148         case SWM_ARG_ID_STACKINIT:
3149                 ws->l_state.horizontal_mwin = 1;
3150                 ws->l_state.horizontal_msize = SWM_H_SLICE / 2;
3151                 ws->l_state.horizontal_stacks = 1;
3152                 break;
3153         case SWM_ARG_ID_MASTERSHRINK:
3154                 if (ws->l_state.horizontal_msize > 1)
3155                         ws->l_state.horizontal_msize--;
3156                 break;
3157         case SWM_ARG_ID_MASTERGROW:
3158                 if (ws->l_state.horizontal_msize < SWM_H_SLICE - 1)
3159                         ws->l_state.horizontal_msize++;
3160                 break;
3161         case SWM_ARG_ID_MASTERADD:
3162                 ws->l_state.horizontal_mwin++;
3163                 break;
3164         case SWM_ARG_ID_MASTERDEL:
3165                 if (ws->l_state.horizontal_mwin > 0)
3166                         ws->l_state.horizontal_mwin--;
3167                 break;
3168         case SWM_ARG_ID_STACKINC:
3169                 ws->l_state.horizontal_stacks++;
3170                 break;
3171         case SWM_ARG_ID_STACKDEC:
3172                 if (ws->l_state.horizontal_stacks > 1)
3173                         ws->l_state.horizontal_stacks--;
3174                 break;
3175         case SWM_ARG_ID_FLIPLAYOUT:
3176                 ws->l_state.horizontal_flip = !ws->l_state.horizontal_flip;
3177                 break;
3178         default:
3179                 return;
3180         }
3181 }
3182
3183 void
3184 horizontal_stack(struct workspace *ws, struct swm_geometry *g)
3185 {
3186         DNPRINTF(SWM_D_STACK, "horizontal_stack: workspace: %d\n", ws->idx);
3187
3188         stack_master(ws, g, 1, ws->l_state.horizontal_flip);
3189 }
3190
3191 /* fullscreen view */
3192 void
3193 max_stack(struct workspace *ws, struct swm_geometry *g)
3194 {
3195         XWindowChanges          wc;
3196         struct swm_geometry     gg = *g;
3197         struct ws_win           *win, *wintrans = NULL, *parent = NULL;
3198         unsigned int            mask;
3199         int                     winno;
3200
3201         DNPRINTF(SWM_D_STACK, "max_stack: workspace: %d\n", ws->idx);
3202
3203         if (ws == NULL)
3204                 return;
3205
3206         winno = count_win(ws, 0);
3207         if (winno == 0 && count_win(ws, 1) == 0)
3208                 return;
3209
3210         TAILQ_FOREACH(win, &ws->winlist, entry) {
3211                 if (win->transient) {
3212                         wintrans = win;
3213                         parent = find_window(win->transient);
3214                         continue;
3215                 }
3216
3217                 if (win->floating && win->floatmaxed == 0 ) {
3218                         /*
3219                          * retain geometry for retrieval on exit from
3220                          * max_stack mode
3221                          */
3222                         store_float_geom(win, ws->r);
3223                         win->floatmaxed = 1;
3224                 }
3225
3226                 /* only reconfigure if necessary */
3227                 if (X(win) != gg.x || Y(win) != gg.y || WIDTH(win) != gg.w ||
3228                     HEIGHT(win) != gg.h) {
3229                         bzero(&wc, sizeof wc);
3230                         X(win) = wc.x = gg.x;
3231                         Y(win) = wc.y = gg.y;
3232                         if (bar_enabled){
3233                                 wc.border_width = border_width;
3234                                 WIDTH(win) = wc.width = gg.w;
3235                                 HEIGHT(win) = wc.height = gg.h;
3236                         } else {
3237                                 wc.border_width = 0;
3238                                 WIDTH(win) = wc.width = gg.w + 2 * border_width;
3239                                 HEIGHT(win) = wc.height = gg.h +
3240                                     2 * border_width;
3241                         }
3242                         mask = CWX | CWY | CWWidth | CWHeight | CWBorderWidth;
3243                         XConfigureWindow(display, win->id, mask, &wc);
3244                 }
3245                 /* unmap only if we don't have multi screen */
3246                 if (win != ws->focus)
3247                         if (!(ScreenCount(display) > 1 || outputs > 1))
3248                                 unmap_window(win);
3249         }
3250
3251         /* put the last transient on top */
3252         if (wintrans) {
3253                 if (parent)
3254                         XMapRaised(display, parent->id);
3255                 stack_floater(wintrans, ws->r);
3256                 focus_magic(wintrans);
3257         }
3258 }
3259
3260 void
3261 send_to_ws(struct swm_region *r, union arg *args)
3262 {
3263         int                     wsid = args->id;
3264         struct ws_win           *win = NULL, *parent;
3265         struct workspace        *ws, *nws;
3266         Atom                    ws_idx_atom = 0;
3267         unsigned char           ws_idx_str[SWM_PROPLEN];
3268         union arg               a;
3269
3270         if (wsid >= workspace_limit)
3271                 return;
3272
3273         if (r && r->ws && r->ws->focus)
3274                 win = r->ws->focus;
3275         else
3276                 return;
3277         if (win == NULL)
3278                 return;
3279         if (win->ws->idx == wsid)
3280                 return;
3281
3282         DNPRINTF(SWM_D_MOVE, "send_to_ws: window: 0x%lx\n", win->id);
3283
3284         ws = win->ws;
3285         nws = &win->s->ws[wsid];
3286
3287         a.id = SWM_ARG_ID_FOCUSPREV;
3288         focus(r, &a);
3289         if (win->transient) {
3290                 parent = find_window(win->transient);
3291                 if (parent) {
3292                         unmap_window(parent);
3293                         TAILQ_REMOVE(&ws->winlist, parent, entry);
3294                         TAILQ_INSERT_TAIL(&nws->winlist, parent, entry);
3295                         parent->ws = nws;
3296                 }
3297         }
3298         unmap_window(win);
3299         TAILQ_REMOVE(&ws->winlist, win, entry);
3300         TAILQ_INSERT_TAIL(&nws->winlist, win, entry);
3301         if (TAILQ_EMPTY(&ws->winlist))
3302                 r->ws->focus = NULL;
3303         win->ws = nws;
3304
3305         /* Try to update the window's workspace property */
3306         ws_idx_atom = XInternAtom(display, "_SWM_WS", False);
3307         if (ws_idx_atom &&
3308             snprintf((char *)ws_idx_str, SWM_PROPLEN, "%d", nws->idx) <
3309                 SWM_PROPLEN) {
3310                 DNPRINTF(SWM_D_PROP, "send_to_ws: set property: _SWM_WS: %s\n",
3311                     ws_idx_str);
3312                 XChangeProperty(display, win->id, ws_idx_atom, XA_STRING, 8,
3313                     PropModeReplace, ws_idx_str, strlen((char *)ws_idx_str));
3314         }
3315
3316         stack();
3317         bar_update();
3318 }
3319
3320 void
3321 pressbutton(struct swm_region *r, union arg *args)
3322 {
3323         XTestFakeButtonEvent(display, args->id, True, CurrentTime);
3324         XTestFakeButtonEvent(display, args->id, False, CurrentTime);
3325 }
3326
3327 void
3328 raise_toggle(struct swm_region *r, union arg *args)
3329 {
3330         if (r == NULL || r->ws == NULL)
3331                 return;
3332
3333         r->ws->always_raise = !r->ws->always_raise;
3334
3335         /* bring floaters back to top */
3336         if (r->ws->always_raise == 0)
3337                 stack();
3338 }
3339
3340 void
3341 iconify(struct swm_region *r, union arg *args)
3342 {
3343         union arg a;
3344
3345         if (r->ws->focus == NULL)
3346                 return;
3347         unmap_window(r->ws->focus);
3348         update_iconic(r->ws->focus, 1);
3349         stack();
3350         if (focus_mode == SWM_FOCUS_DEFAULT)
3351                 drain_enter_notify();
3352         r->ws->focus = NULL;
3353         a.id = SWM_ARG_ID_FOCUSCUR;
3354         focus(r, &a);
3355 }
3356
3357 unsigned char *
3358 get_win_name(Window win)
3359 {
3360         unsigned char           *prop = NULL;
3361         unsigned long           nbytes, nitems;
3362
3363         /* try _NET_WM_NAME first */
3364         if (get_property(win, a_netwmname, 0L, a_utf8_string, NULL, &nbytes,
3365             &prop)) {
3366                 XFree(prop);
3367                 if (get_property(win, a_netwmname, nbytes, a_utf8_string,
3368                     &nitems, NULL, &prop))
3369                         return (prop);
3370         }
3371
3372         /* fallback to WM_NAME */
3373         if (!get_property(win, a_wmname, 0L, a_string, NULL, &nbytes, &prop))
3374                 return (NULL);
3375         XFree(prop);
3376         if (get_property(win, a_wmname, nbytes, a_string, &nitems, NULL, &prop))
3377                 return (prop);
3378
3379         return (NULL);
3380 }
3381
3382 void
3383 uniconify(struct swm_region *r, union arg *args)
3384 {
3385         struct ws_win           *win;
3386         FILE                    *lfile;
3387         unsigned char           *name;
3388         int                     count = 0;
3389
3390         DNPRINTF(SWM_D_MISC, "uniconify\n");
3391
3392         if (r == NULL || r->ws == NULL)
3393                 return;
3394
3395         /* make sure we have anything to uniconify */
3396         TAILQ_FOREACH(win, &r->ws->winlist, entry) {
3397                 if (win->ws == NULL)
3398                         continue; /* should never happen */
3399                 if (win->iconic == 0)
3400                         continue;
3401                 count++;
3402         }
3403         if (count == 0)
3404                 return;
3405
3406         search_r = r;
3407         search_resp_action = SWM_SEARCH_UNICONIFY;
3408
3409         spawn_select(r, args, "search", &searchpid);
3410
3411         if ((lfile = fdopen(select_list_pipe[1], "w")) == NULL)
3412                 return;
3413
3414         TAILQ_FOREACH(win, &r->ws->winlist, entry) {
3415                 if (win->ws == NULL)
3416                         continue; /* should never happen */
3417                 if (win->iconic == 0)
3418                         continue;
3419
3420                 name = get_win_name(win->id);
3421                 if (name == NULL)
3422                         continue;
3423                 fprintf(lfile, "%s.%lu\n", name, win->id);
3424                 XFree(name);
3425         }
3426
3427         fclose(lfile);
3428 }
3429
3430 void
3431 name_workspace(struct swm_region *r, union arg *args)
3432 {
3433         FILE                    *lfile;
3434
3435         DNPRINTF(SWM_D_MISC, "name_workspace\n");
3436
3437         if (r == NULL)
3438                 return;
3439
3440         search_r = r;
3441         search_resp_action = SWM_SEARCH_NAME_WORKSPACE;
3442
3443         spawn_select(r, args, "name_workspace", &searchpid);
3444
3445         if ((lfile = fdopen(select_list_pipe[1], "w")) == NULL)
3446                 return;
3447
3448         fprintf(lfile, "%s", "");
3449         fclose(lfile);
3450 }
3451
3452 void
3453 search_workspace(struct swm_region *r, union arg *args)
3454 {
3455         int                     i;
3456         struct workspace        *ws;
3457         FILE                    *lfile;
3458
3459         DNPRINTF(SWM_D_MISC, "search_workspace\n");
3460
3461         if (r == NULL)
3462                 return;
3463
3464         search_r = r;
3465         search_resp_action = SWM_SEARCH_SEARCH_WORKSPACE;
3466
3467         spawn_select(r, args, "search", &searchpid);
3468
3469         if ((lfile = fdopen(select_list_pipe[1], "w")) == NULL)
3470                 return;
3471
3472         for (i = 0; i < workspace_limit; i++) {
3473                 ws = &r->s->ws[i];
3474                 if (ws == NULL)
3475                         continue;
3476                 fprintf(lfile, "%d%s%s\n", ws->idx + 1,
3477                     (ws->name ? ":" : ""), (ws->name ? ws->name : ""));
3478         }
3479
3480         fclose(lfile);
3481 }
3482
3483 void
3484 search_win_cleanup(void)
3485 {
3486         struct search_window    *sw = NULL;
3487
3488         while ((sw = TAILQ_FIRST(&search_wl)) != NULL) {
3489                 XDestroyWindow(display, sw->indicator);
3490                 XFreeGC(display, sw->gc);
3491                 TAILQ_REMOVE(&search_wl, sw, entry);
3492                 free(sw);
3493         }
3494 }
3495
3496 void
3497 search_win(struct swm_region *r, union arg *args)
3498 {
3499         struct ws_win           *win = NULL;
3500         struct search_window    *sw = NULL;
3501         Window                  w;
3502         XGCValues               gcv;
3503         int                     i;
3504         char                    s[8];
3505         FILE                    *lfile;
3506         size_t                  len;
3507         XRectangle              ibox, lbox;
3508
3509         DNPRINTF(SWM_D_MISC, "search_win\n");
3510
3511         search_r = r;
3512         search_resp_action = SWM_SEARCH_SEARCH_WINDOW;
3513
3514         spawn_select(r, args, "search", &searchpid);
3515
3516         if ((lfile = fdopen(select_list_pipe[1], "w")) == NULL)
3517                 return;
3518
3519         TAILQ_INIT(&search_wl);
3520
3521         i = 1;
3522         TAILQ_FOREACH(win, &r->ws->winlist, entry) {
3523                 if (win->iconic == 1)
3524                         continue;
3525
3526                 sw = calloc(1, sizeof(struct search_window));
3527                 if (sw == NULL) {
3528                         warn("search_win: calloc");
3529                         fclose(lfile);
3530                         search_win_cleanup();
3531                         return;
3532                 }
3533                 sw->idx = i;
3534                 sw->win = win;
3535
3536                 snprintf(s, sizeof s, "%d", i);
3537                 len = strlen(s);
3538
3539                 XmbTextExtents(bar_fs, s, len, &ibox, &lbox);
3540
3541                 w = XCreateSimpleWindow(display,
3542                     win->id, 0, 0,lbox.width + 4,
3543                     bar_fs_extents->max_logical_extent.height, 1,
3544                     r->s->c[SWM_S_COLOR_UNFOCUS].color,
3545                     r->s->c[SWM_S_COLOR_FOCUS].color);
3546
3547                 sw->indicator = w;
3548                 TAILQ_INSERT_TAIL(&search_wl, sw, entry);
3549
3550                 sw->gc = XCreateGC(display, w, 0, &gcv);
3551                 XMapRaised(display, w);
3552                 XSetForeground(display, sw->gc, r->s->c[SWM_S_COLOR_BAR].color);
3553
3554                 DRAWSTRING(display, w, bar_fs, sw->gc, 2,
3555                     (bar_fs_extents->max_logical_extent.height -
3556                     lbox.height) / 2 - lbox.y, s, len);
3557
3558                 fprintf(lfile, "%d\n", i);
3559                 i++;
3560         }
3561
3562         fclose(lfile);
3563 }
3564
3565 void
3566 search_resp_uniconify(char *resp, unsigned long len)
3567 {
3568         unsigned char           *name;
3569         struct ws_win           *win;
3570         char                    *s;
3571
3572         DNPRINTF(SWM_D_MISC, "search_resp_uniconify: resp: %s\n", resp);
3573
3574         TAILQ_FOREACH(win, &search_r->ws->winlist, entry) {
3575                 if (win->iconic == 0)
3576                         continue;
3577                 name = get_win_name(win->id);
3578                 if (name == NULL)
3579                         continue;
3580                 if (asprintf(&s, "%s.%lu", name, win->id) == -1) {
3581                         XFree(name);
3582                         continue;
3583                 }
3584                 XFree(name);
3585                 if (strncmp(s, resp, len) == 0) {
3586                         /* XXX this should be a callback to generalize */
3587                         update_iconic(win, 0);
3588                         free(s);
3589                         break;
3590                 }
3591                 free(s);
3592         }
3593 }
3594
3595 void
3596 search_resp_name_workspace(char *resp, unsigned long len)
3597 {
3598         struct workspace        *ws;
3599
3600         DNPRINTF(SWM_D_MISC, "search_resp_name_workspace: resp: %s\n", resp);
3601
3602         if (search_r->ws == NULL)
3603                 return;
3604         ws = search_r->ws;
3605
3606         if (ws->name) {
3607                 free(search_r->ws->name);
3608                 search_r->ws->name = NULL;
3609         }
3610
3611         if (len > 1) {
3612                 ws->name = strdup(resp);
3613                 if (ws->name == NULL) {
3614                         DNPRINTF(SWM_D_MISC, "search_resp_name_workspace: "
3615                             "strdup: %s", strerror(errno));
3616                         return;
3617                 }
3618         }
3619 }
3620
3621 void
3622 search_resp_search_workspace(char *resp, unsigned long len)
3623 {
3624         char                    *p, *q;
3625         int                     ws_idx;
3626         const char              *errstr;
3627         union arg               a;
3628
3629         DNPRINTF(SWM_D_MISC, "search_resp_search_workspace: resp: %s\n", resp);
3630
3631         q = strdup(resp);
3632         if (!q) {
3633                 DNPRINTF(SWM_D_MISC, "search_resp_search_workspace: strdup: %s",
3634                     strerror(errno));
3635                 return;
3636         }
3637         p = strchr(q, ':');
3638         if (p != NULL)
3639                 *p = '\0';
3640         ws_idx = strtonum(q, 1, workspace_limit, &errstr);
3641         if (errstr) {
3642                 DNPRINTF(SWM_D_MISC, "workspace idx is %s: %s",
3643                     errstr, q);
3644                 free(q);
3645                 return;
3646         }
3647         free(q);
3648         a.id = ws_idx - 1;
3649         switchws(search_r, &a);
3650 }
3651
3652 void
3653 search_resp_search_window(char *resp, unsigned long len)
3654 {
3655         char                    *s;
3656         int                     idx;
3657         const char              *errstr;
3658         struct search_window    *sw;
3659
3660         DNPRINTF(SWM_D_MISC, "search_resp_search_window: resp: %s\n", resp);
3661
3662         s = strdup(resp);
3663         if (!s) {
3664                 DNPRINTF(SWM_D_MISC, "search_resp_search_window: strdup: %s",
3665                     strerror(errno));
3666                 return;
3667         }
3668
3669         idx = strtonum(s, 1, INT_MAX, &errstr);
3670         if (errstr) {
3671                 DNPRINTF(SWM_D_MISC, "window idx is %s: %s",
3672                     errstr, s);
3673                 free(s);
3674                 return;
3675         }
3676         free(s);
3677
3678         TAILQ_FOREACH(sw, &search_wl, entry)
3679                 if (idx == sw->idx) {
3680                         focus_win(sw->win);
3681                         break;
3682                 }
3683 }
3684
3685 #define MAX_RESP_LEN    1024
3686
3687 void
3688 search_do_resp(void)
3689 {
3690         ssize_t                 rbytes;
3691         char                    *resp;
3692         unsigned long           len;
3693
3694         DNPRINTF(SWM_D_MISC, "search_do_resp:\n");
3695
3696         search_resp = 0;
3697         searchpid = 0;
3698
3699         if ((resp = calloc(1, MAX_RESP_LEN + 1)) == NULL) {
3700                 warn("search: calloc");
3701                 goto done;
3702         }
3703
3704         rbytes = read(select_resp_pipe[0], resp, MAX_RESP_LEN);
3705         if (rbytes <= 0) {
3706                 warn("search: read error");
3707                 goto done;
3708         }
3709         resp[rbytes] = '\0';
3710
3711         /* XXX:
3712          * Older versions of dmenu (Atleast pre 4.4.1) do not send a
3713          * newline, so work around that by sanitizing the resp now.
3714          */
3715         resp[strcspn(resp, "\n")] = '\0';
3716         len = strlen(resp);
3717
3718         switch (search_resp_action) {
3719         case SWM_SEARCH_UNICONIFY:
3720                 search_resp_uniconify(resp, len);
3721                 break;
3722         case SWM_SEARCH_NAME_WORKSPACE:
3723                 search_resp_name_workspace(resp, len);
3724                 break;
3725         case SWM_SEARCH_SEARCH_WORKSPACE:
3726                 search_resp_search_workspace(resp, len);
3727                 break;
3728         case SWM_SEARCH_SEARCH_WINDOW:
3729                 search_resp_search_window(resp, len);
3730                 break;
3731         }
3732
3733 done:
3734         if (search_resp_action == SWM_SEARCH_SEARCH_WINDOW)
3735                 search_win_cleanup();
3736
3737         search_resp_action = SWM_SEARCH_NONE;
3738         close(select_resp_pipe[0]);
3739         free(resp);
3740 }
3741
3742 void
3743 wkill(struct swm_region *r, union arg *args)
3744 {
3745         DNPRINTF(SWM_D_MISC, "wkill: id: %d\n", args->id);
3746
3747         if (r->ws->focus == NULL)
3748                 return;
3749
3750         if (args->id == SWM_ARG_ID_KILLWINDOW)
3751                 XKillClient(display, r->ws->focus->id);
3752         else
3753                 if (r->ws->focus->can_delete)
3754                         client_msg(r->ws->focus, adelete);
3755 }
3756
3757
3758 int
3759 floating_toggle_win(struct ws_win *win)
3760 {
3761         struct swm_region       *r;
3762
3763         if (win == NULL)
3764                 return (0);
3765
3766         if (!win->ws->r)
3767                 return (0);
3768
3769         r = win->ws->r;
3770
3771         /* reject floating toggles in max stack mode */
3772         if (win->ws->cur_layout == &layouts[SWM_MAX_STACK])
3773                 return (0);
3774
3775         if (win->floating) {
3776                 if (!win->floatmaxed) {
3777                         /* retain position for refloat */
3778                         store_float_geom(win, r);
3779                 }
3780                 win->floating = 0;
3781         } else {
3782                 if (win->g_floatvalid) {
3783                         /* refloat at last floating relative position */
3784                         X(win) = win->g_float.x - win->rg_float.x + X(r);
3785                         Y(win) = win->g_float.y - win->rg_float.y + Y(r);
3786                         WIDTH(win) = win->g_float.w;
3787                         HEIGHT(win) = win->g_float.h;
3788                 }
3789                 win->floating = 1;
3790         }
3791
3792         ewmh_update_actions(win);
3793
3794         return (1);
3795 }
3796
3797 void
3798 floating_toggle(struct swm_region *r, union arg *args)
3799 {
3800         struct ws_win           *win = r->ws->focus;
3801         union arg               a;
3802
3803         if (win == NULL)
3804                 return;
3805
3806         ewmh_update_win_state(win, ewmh[_NET_WM_STATE_ABOVE].atom,
3807             _NET_WM_STATE_TOGGLE);
3808
3809         stack();
3810         if (focus_mode == SWM_FOCUS_DEFAULT)
3811                 drain_enter_notify();
3812
3813         if (win == win->ws->focus) {
3814                 a.id = SWM_ARG_ID_FOCUSCUR;
3815                 focus(win->ws->r, &a);
3816         }
3817 }
3818
3819 void
3820 constrain_window(struct ws_win *win, struct swm_region *r, int resizable)
3821 {
3822         if (X(win) + WIDTH(win) > X(r) + WIDTH(r) - border_width) {
3823                 if (resizable)
3824                         WIDTH(win) = X(r) + WIDTH(r) - X(win) - border_width;
3825                 else
3826                         X(win) = X(r) + WIDTH(r) - WIDTH(win) - border_width;
3827         }
3828
3829         if (X(win) < X(r) - border_width) {
3830                 if (resizable)
3831                         WIDTH(win) -= X(r) - X(win) - border_width;
3832
3833                 X(win) = X(r) - border_width;
3834         }
3835
3836         if (Y(win) + HEIGHT(win) > Y(r) + HEIGHT(r) - border_width) {
3837                 if (resizable)
3838                         HEIGHT(win) = Y(r) + HEIGHT(r) - Y(win) - border_width;
3839                 else
3840                         Y(win) = Y(r) + HEIGHT(r) - HEIGHT(win) - border_width;
3841         }
3842
3843         if (Y(win) < Y(r) - border_width) {
3844                 if (resizable)
3845                         HEIGHT(win) -= Y(r) - Y(win) - border_width;
3846
3847                 Y(win) = Y(r) - border_width;
3848         }
3849
3850         if (WIDTH(win) < 1)
3851                 WIDTH(win) = 1;
3852         if (HEIGHT(win) < 1)
3853                 HEIGHT(win) = 1;
3854 }
3855
3856 void
3857 update_window(struct ws_win *win)
3858 {
3859         unsigned int            mask;
3860         XWindowChanges          wc;
3861
3862         bzero(&wc, sizeof wc);
3863         mask = CWBorderWidth | CWWidth | CWHeight | CWX | CWY;
3864         wc.border_width = border_width;
3865         wc.x = X(win);
3866         wc.y = Y(win);
3867         wc.width = WIDTH(win);
3868         wc.height = HEIGHT(win);
3869
3870         DNPRINTF(SWM_D_MISC, "update_window: window: 0x%lx, (x,y) w x h: "
3871             "(%d,%d) %d x %d\n", win->id, wc.x, wc.y, wc.width, wc.height);
3872
3873         XConfigureWindow(display, win->id, mask, &wc);
3874 }
3875
3876 #define SWM_RESIZE_STEPS        (50)
3877
3878 void
3879 resize(struct ws_win *win, union arg *args)
3880 {
3881         XEvent                  ev;
3882         Time                    time = 0;
3883         struct swm_region       *r = NULL;
3884         int                     resize_step = 0;
3885         Window                  rr, cr;
3886         int                     x, y, wx, wy;
3887         unsigned int            mask;
3888         struct swm_geometry     g;
3889         int                     top = 0, left = 0;
3890         int                     dx, dy;
3891         Cursor                  cursor;
3892         unsigned int            shape; /* cursor style */
3893
3894         if (win == NULL)
3895                 return;
3896         r = win->ws->r;
3897
3898         DNPRINTF(SWM_D_MOUSE, "resize: window: 0x%lx, floating: %s, "
3899             "transient: 0x%lx\n", win->id, YESNO(win->floating),
3900             win->transient);
3901
3902         if (!(win->transient != 0 || win->floating != 0))
3903                 return;
3904
3905         /* reject resizes in max mode for floaters (transient ok) */
3906         if (win->floatmaxed)
3907                 return;
3908
3909         win->manual = 1;
3910         ewmh_update_win_state(win, ewmh[_SWM_WM_STATE_MANUAL].atom,
3911             _NET_WM_STATE_ADD);
3912
3913         stack();
3914
3915         switch (args->id) {
3916         case SWM_ARG_ID_WIDTHSHRINK:
3917                 WIDTH(win) -= SWM_RESIZE_STEPS;
3918                 resize_step = 1;
3919                 break;
3920         case SWM_ARG_ID_WIDTHGROW:
3921                 WIDTH(win) += SWM_RESIZE_STEPS;
3922                 resize_step = 1;
3923                 break;
3924         case SWM_ARG_ID_HEIGHTSHRINK:
3925                 HEIGHT(win) -= SWM_RESIZE_STEPS;
3926                 resize_step = 1;
3927                 break;
3928         case SWM_ARG_ID_HEIGHTGROW:
3929                 HEIGHT(win) += SWM_RESIZE_STEPS;
3930                 resize_step = 1;
3931                 break;
3932         default:
3933                 break;
3934         }
3935         if (resize_step) {
3936                 constrain_window(win, r, 1);
3937                 update_window(win);
3938                 store_float_geom(win,r);
3939                 return;
3940         }
3941
3942         if (focus_mode == SWM_FOCUS_DEFAULT)
3943                 drain_enter_notify();
3944
3945         /* get cursor offset from window root */
3946         if (!XQueryPointer(display, win->id, &rr, &cr, &x, &y, &wx, &wy, &mask))
3947             return;
3948
3949         g = win->g;
3950
3951         if (wx < WIDTH(win) / 2)
3952                 left = 1;
3953
3954         if (wy < HEIGHT(win) / 2)
3955                 top = 1;
3956
3957         if (args->id == SWM_ARG_ID_CENTER)
3958                 shape = XC_sizing;
3959         else if (top)
3960                 shape = (left) ? XC_top_left_corner : XC_top_right_corner;
3961         else
3962                 shape = (left) ? XC_bottom_left_corner : XC_bottom_right_corner;
3963
3964         cursor = XCreateFontCursor(display, shape);
3965
3966         if (XGrabPointer(display, win->id, False, MOUSEMASK, GrabModeAsync,
3967             GrabModeAsync, None, cursor, CurrentTime) != GrabSuccess) {
3968                 XFreeCursor(display, cursor);
3969                 return;
3970         }
3971
3972         do {
3973                 XMaskEvent(display, MOUSEMASK | ExposureMask |
3974                     SubstructureRedirectMask, &ev);
3975                 switch (ev.type) {
3976                 case ConfigureRequest:
3977                 case Expose:
3978                 case MapRequest:
3979                         handler[ev.type](&ev);
3980                         break;
3981                 case MotionNotify:
3982                         /* cursor offset/delta from start of the operation */
3983                         dx = ev.xmotion.x_root - x;
3984                         dy = ev.xmotion.y_root - y;
3985
3986                         /* vertical */
3987                         if (top)
3988                                 dy = -dy;
3989
3990                         if (args->id == SWM_ARG_ID_CENTER) {
3991                                 if (g.h / 2 + dy < 1)
3992                                         dy = 1 - g.h / 2;
3993
3994                                 Y(win) = g.y - dy;
3995                                 HEIGHT(win) = g.h + 2 * dy;
3996                         } else {
3997                                 if (g.h + dy < 1)
3998                                         dy = 1 - g.h;
3999
4000                                 if (top)
4001                                         Y(win) = g.y - dy;
4002
4003                                 HEIGHT(win) = g.h + dy;
4004                         }
4005
4006                         /* horizontal */
4007                         if (left)
4008                                 dx = -dx;
4009
4010                         if (args->id == SWM_ARG_ID_CENTER) {
4011                                 if (g.w / 2 + dx < 1)
4012                                         dx = 1 - g.w / 2;
4013
4014                                 X(win) = g.x - dx;
4015                                 WIDTH(win) = g.w + 2 * dx;
4016                         } else {
4017                                 if (g.w + dx < 1)
4018                                         dx = 1 - g.w;
4019
4020                                 if (left)
4021                                         X(win) = g.x - dx;
4022
4023                                 WIDTH(win) = g.w + dx;
4024                         }
4025
4026                         constrain_window(win, r, 1);
4027
4028                         /* not free, don't sync more than 120 times / second */
4029                         if ((ev.xmotion.time - time) > (1000 / 120) ) {
4030                                 time = ev.xmotion.time;
4031                                 XSync(display, False);
4032                                 update_window(win);
4033                         }
4034                         break;
4035                 }
4036         } while (ev.type != ButtonRelease);
4037         if (time) {
4038                 XSync(display, False);
4039                 update_window(win);
4040         }
4041         store_float_geom(win,r);
4042
4043         XUngrabPointer(display, CurrentTime);
4044         XFreeCursor(display, cursor);
4045
4046         /* drain events */
4047         drain_enter_notify();
4048 }
4049
4050 void
4051 resize_step(struct swm_region *r, union arg *args)
4052 {
4053         struct ws_win           *win = NULL;
4054
4055         if (r && r->ws && r->ws->focus)
4056                 win = r->ws->focus;
4057         else
4058                 return;
4059
4060         resize(win, args);
4061 }
4062
4063 #define SWM_MOVE_STEPS  (50)
4064
4065 void
4066 move(struct ws_win *win, union arg *args)
4067 {
4068         XEvent                  ev;
4069         Time                    time = 0;
4070         int                     move_step = 0;
4071         struct swm_region       *r = NULL;
4072
4073         Window                  rr, cr;
4074         int                     x, y, wx, wy;
4075         unsigned int            mask;
4076
4077         if (win == NULL)
4078                 return;
4079         r = win->ws->r;
4080
4081         DNPRINTF(SWM_D_MOUSE, "move: window: 0x%lx, floating: %s, transient: "
4082             "0x%lx\n", win->id, YESNO(win->floating), win->transient);
4083
4084         /* in max_stack mode should only move transients */
4085         if (win->ws->cur_layout == &layouts[SWM_MAX_STACK] && !win->transient)
4086                 return;
4087
4088         win->manual = 1;
4089         if (win->floating == 0 && !win->transient) {
4090                 store_float_geom(win,r);
4091                 ewmh_update_win_state(win, ewmh[_NET_WM_STATE_ABOVE].atom,
4092                     _NET_WM_STATE_ADD);
4093         }
4094         ewmh_update_win_state(win, ewmh[_SWM_WM_STATE_MANUAL].atom,
4095             _NET_WM_STATE_ADD);
4096
4097         stack();
4098
4099         move_step = 0;
4100         switch (args->id) {
4101         case SWM_ARG_ID_MOVELEFT:
4102                 X(win) -= (SWM_MOVE_STEPS - border_width);
4103                 move_step = 1;
4104                 break;
4105         case SWM_ARG_ID_MOVERIGHT:
4106                 X(win) += (SWM_MOVE_STEPS - border_width);
4107                 move_step = 1;
4108                 break;
4109         case SWM_ARG_ID_MOVEUP:
4110                 Y(win) -= (SWM_MOVE_STEPS - border_width);
4111                 move_step = 1;
4112                 break;
4113         case SWM_ARG_ID_MOVEDOWN:
4114                 Y(win) += (SWM_MOVE_STEPS - border_width);
4115                 move_step = 1;
4116                 break;
4117         default:
4118                 break;
4119         }
4120         if (move_step) {
4121                 constrain_window(win, r, 0);
4122                 update_window(win);
4123                 store_float_geom(win, r);
4124                 return;
4125         }
4126
4127         if (XGrabPointer(display, win->id, False, MOUSEMASK, GrabModeAsync,
4128             GrabModeAsync, None, XCreateFontCursor(display, XC_fleur),
4129             CurrentTime) != GrabSuccess)
4130                 return;
4131
4132         /* get cursor offset from window root */
4133         if (!XQueryPointer(display, win->id, &rr, &cr, &x, &y, &wx, &wy, &mask))
4134             return;
4135
4136         do {
4137                 XMaskEvent(display, MOUSEMASK | ExposureMask |
4138                     SubstructureRedirectMask, &ev);
4139                 switch (ev.type) {
4140                 case ConfigureRequest:
4141                 case Expose:
4142                 case MapRequest:
4143                         handler[ev.type](&ev);
4144                         break;
4145                 case MotionNotify:
4146                         X(win) = ev.xmotion.x_root - wx - border_width;
4147                         Y(win) = ev.xmotion.y_root - wy - border_width;
4148
4149                         constrain_window(win, r, 0);
4150
4151                         /* not free, don't sync more than 120 times / second */
4152                         if ((ev.xmotion.time - time) > (1000 / 120) ) {
4153                                 time = ev.xmotion.time;
4154                                 XSync(display, False);
4155                                 update_window(win);
4156                         }
4157                         break;
4158                 }
4159         } while (ev.type != ButtonRelease);
4160         if (time) {
4161                 XSync(display, False);
4162                 update_window(win);
4163         }
4164         store_float_geom(win,r);
4165         XUngrabPointer(display, CurrentTime);
4166
4167         /* drain events */
4168         drain_enter_notify();
4169 }
4170
4171 void
4172 move_step(struct swm_region *r, union arg *args)
4173 {
4174         struct ws_win           *win = NULL;
4175
4176         if (r && r->ws && r->ws->focus)
4177                 win = r->ws->focus;
4178         else
4179                 return;
4180
4181         if (!(win->transient != 0 || win->floating != 0))
4182                 return;
4183
4184         move(win, args);
4185 }
4186
4187
4188 /* user/key callable function IDs */
4189 enum keyfuncid {
4190         kf_cycle_layout,
4191         kf_flip_layout,
4192         kf_stack_reset,
4193         kf_master_shrink,
4194         kf_master_grow,
4195         kf_master_add,
4196         kf_master_del,
4197         kf_stack_inc,
4198         kf_stack_dec,
4199         kf_swap_main,
4200         kf_focus_next,
4201         kf_focus_prev,
4202         kf_swap_next,
4203         kf_swap_prev,
4204         kf_spawn_term,
4205         kf_spawn_menu,
4206         kf_quit,
4207         kf_restart,
4208         kf_focus_main,
4209         kf_ws_1,
4210         kf_ws_2,
4211         kf_ws_3,
4212         kf_ws_4,
4213         kf_ws_5,
4214         kf_ws_6,
4215         kf_ws_7,
4216         kf_ws_8,
4217         kf_ws_9,
4218         kf_ws_10,
4219         kf_ws_11,
4220         kf_ws_12,
4221         kf_ws_13,
4222         kf_ws_14,
4223         kf_ws_15,
4224         kf_ws_16,
4225         kf_ws_17,
4226         kf_ws_18,
4227         kf_ws_19,
4228         kf_ws_20,
4229         kf_ws_21,
4230         kf_ws_22,
4231         kf_ws_next,
4232         kf_ws_prev,
4233         kf_ws_next_all,
4234         kf_ws_prev_all,
4235         kf_ws_prior,
4236         kf_screen_next,
4237         kf_screen_prev,
4238         kf_mvws_1,
4239         kf_mvws_2,
4240         kf_mvws_3,
4241         kf_mvws_4,
4242         kf_mvws_5,
4243         kf_mvws_6,
4244         kf_mvws_7,
4245         kf_mvws_8,
4246         kf_mvws_9,
4247         kf_mvws_10,
4248         kf_mvws_11,
4249         kf_mvws_12,
4250         kf_mvws_13,
4251         kf_mvws_14,
4252         kf_mvws_15,
4253         kf_mvws_16,
4254         kf_mvws_17,
4255         kf_mvws_18,
4256         kf_mvws_19,
4257         kf_mvws_20,
4258         kf_mvws_21,
4259         kf_mvws_22,
4260         kf_bar_toggle,
4261         kf_wind_kill,
4262         kf_wind_del,
4263         kf_screenshot_all,
4264         kf_screenshot_wind,
4265         kf_float_toggle,
4266         kf_version,
4267         kf_spawn_lock,
4268         kf_spawn_initscr,
4269         kf_spawn_custom,
4270         kf_iconify,
4271         kf_uniconify,
4272         kf_raise_toggle,
4273         kf_button2,
4274         kf_width_shrink,
4275         kf_width_grow,
4276         kf_height_shrink,
4277         kf_height_grow,
4278         kf_move_left,
4279         kf_move_right,
4280         kf_move_up,
4281         kf_move_down,
4282         kf_name_workspace,
4283         kf_search_workspace,
4284         kf_search_win,
4285         kf_dumpwins, /* MUST BE LAST */
4286         kf_invalid
4287 };
4288
4289 /* key definitions */
4290 void
4291 dummykeyfunc(struct swm_region *r, union arg *args)
4292 {
4293 };
4294
4295 void
4296 legacyfunc(struct swm_region *r, union arg *args)
4297 {
4298 };
4299
4300 struct keyfunc {
4301         char                    name[SWM_FUNCNAME_LEN];
4302         void                    (*func)(struct swm_region *r, union arg *);
4303         union arg               args;
4304 } keyfuncs[kf_invalid + 1] = {
4305         /* name                 function        argument */
4306         { "cycle_layout",       cycle_layout,   {0} },
4307         { "flip_layout",        stack_config,   {.id = SWM_ARG_ID_FLIPLAYOUT} },
4308         { "stack_reset",        stack_config,   {.id = SWM_ARG_ID_STACKRESET} },
4309         { "master_shrink",      stack_config,   {.id = SWM_ARG_ID_MASTERSHRINK} },
4310         { "master_grow",        stack_config,   {.id = SWM_ARG_ID_MASTERGROW} },
4311         { "master_add",         stack_config,   {.id = SWM_ARG_ID_MASTERADD} },
4312         { "master_del",         stack_config,   {.id = SWM_ARG_ID_MASTERDEL} },
4313         { "stack_inc",          stack_config,   {.id = SWM_ARG_ID_STACKINC} },
4314         { "stack_dec",          stack_config,   {.id = SWM_ARG_ID_STACKDEC} },
4315         { "swap_main",          swapwin,        {.id = SWM_ARG_ID_SWAPMAIN} },
4316         { "focus_next",         focus,          {.id = SWM_ARG_ID_FOCUSNEXT} },
4317         { "focus_prev",         focus,          {.id = SWM_ARG_ID_FOCUSPREV} },
4318         { "swap_next",          swapwin,        {.id = SWM_ARG_ID_SWAPNEXT} },
4319         { "swap_prev",          swapwin,        {.id = SWM_ARG_ID_SWAPPREV} },
4320         { "spawn_term",         spawnterm,      {.argv = spawn_term} },
4321         { "spawn_menu",         legacyfunc,     {0} },
4322         { "quit",               quit,           {0} },
4323         { "restart",            restart,        {0} },
4324         { "focus_main",         focus,          {.id = SWM_ARG_ID_FOCUSMAIN} },
4325         { "ws_1",               switchws,       {.id = 0} },
4326         { "ws_2",               switchws,       {.id = 1} },
4327         { "ws_3",               switchws,       {.id = 2} },
4328         { "ws_4",               switchws,       {.id = 3} },
4329         { "ws_5",               switchws,       {.id = 4} },
4330         { "ws_6",               switchws,       {.id = 5} },
4331         { "ws_7",               switchws,       {.id = 6} },
4332         { "ws_8",               switchws,       {.id = 7} },
4333         { "ws_9",               switchws,       {.id = 8} },
4334         { "ws_10",              switchws,       {.id = 9} },
4335         { "ws_11",              switchws,       {.id = 10} },
4336         { "ws_12",              switchws,       {.id = 11} },
4337         { "ws_13",              switchws,       {.id = 12} },
4338         { "ws_14",              switchws,       {.id = 13} },
4339         { "ws_15",              switchws,       {.id = 14} },
4340         { "ws_16",              switchws,       {.id = 15} },
4341         { "ws_17",              switchws,       {.id = 16} },
4342         { "ws_18",              switchws,       {.id = 17} },
4343         { "ws_19",              switchws,       {.id = 18} },
4344         { "ws_20",              switchws,       {.id = 19} },
4345         { "ws_21",              switchws,       {.id = 20} },
4346         { "ws_22",              switchws,       {.id = 21} },
4347         { "ws_next",            cyclews,        {.id = SWM_ARG_ID_CYCLEWS_UP} },
4348         { "ws_prev",            cyclews,        {.id = SWM_ARG_ID_CYCLEWS_DOWN} },
4349         { "ws_next_all",        cyclews,        {.id = SWM_ARG_ID_CYCLEWS_UP_ALL} },
4350         { "ws_prev_all",        cyclews,        {.id = SWM_ARG_ID_CYCLEWS_DOWN_ALL} },
4351         { "ws_prior",           priorws,        {0} },
4352         { "screen_next",        cyclescr,       {.id = SWM_ARG_ID_CYCLESC_UP} },
4353         { "screen_prev",        cyclescr,       {.id = SWM_ARG_ID_CYCLESC_DOWN} },
4354         { "mvws_1",             send_to_ws,     {.id = 0} },
4355         { "mvws_2",             send_to_ws,     {.id = 1} },
4356         { "mvws_3",             send_to_ws,     {.id = 2} },
4357         { "mvws_4",             send_to_ws,     {.id = 3} },
4358         { "mvws_5",             send_to_ws,     {.id = 4} },
4359         { "mvws_6",             send_to_ws,     {.id = 5} },
4360         { "mvws_7",             send_to_ws,     {.id = 6} },
4361         { "mvws_8",             send_to_ws,     {.id = 7} },
4362         { "mvws_9",             send_to_ws,     {.id = 8} },
4363         { "mvws_10",            send_to_ws,     {.id = 9} },
4364         { "mvws_11",            send_to_ws,     {.id = 10} },
4365         { "mvws_12",            send_to_ws,     {.id = 11} },
4366         { "mvws_13",            send_to_ws,     {.id = 12} },
4367         { "mvws_14",            send_to_ws,     {.id = 13} },
4368         { "mvws_15",            send_to_ws,     {.id = 14} },
4369         { "mvws_16",            send_to_ws,     {.id = 15} },
4370         { "mvws_17",            send_to_ws,     {.id = 16} },
4371         { "mvws_18",            send_to_ws,     {.id = 17} },
4372         { "mvws_19",            send_to_ws,     {.id = 18} },
4373         { "mvws_20",            send_to_ws,     {.id = 19} },
4374         { "mvws_21",            send_to_ws,     {.id = 20} },
4375         { "mvws_22",            send_to_ws,     {.id = 21} },
4376         { "bar_toggle",         bar_toggle,     {0} },
4377         { "wind_kill",          wkill,          {.id = SWM_ARG_ID_KILLWINDOW} },
4378         { "wind_del",           wkill,          {.id = SWM_ARG_ID_DELETEWINDOW} },
4379         { "screenshot_all",     legacyfunc,     {0} },
4380         { "screenshot_wind",    legacyfunc,     {0} },
4381         { "float_toggle",       floating_toggle,{0} },
4382         { "version",            version,        {0} },
4383         { "spawn_lock",         legacyfunc,     {0} },
4384         { "spawn_initscr",      legacyfunc,     {0} },
4385         { "spawn_custom",       dummykeyfunc,   {0} },
4386         { "iconify",            iconify,        {0} },
4387         { "uniconify",          uniconify,      {0} },
4388         { "raise_toggle",       raise_toggle,   {0} },
4389         { "button2",            pressbutton,    {2} },
4390         { "width_shrink",       resize_step,    {.id = SWM_ARG_ID_WIDTHSHRINK} },
4391         { "width_grow",         resize_step,    {.id = SWM_ARG_ID_WIDTHGROW} },
4392         { "height_shrink",      resize_step,    {.id = SWM_ARG_ID_HEIGHTSHRINK} },
4393         { "height_grow",        resize_step,    {.id = SWM_ARG_ID_HEIGHTGROW} },
4394         { "move_left",          move_step,      {.id = SWM_ARG_ID_MOVELEFT} },
4395         { "move_right",         move_step,      {.id = SWM_ARG_ID_MOVERIGHT} },
4396         { "move_up",            move_step,      {.id = SWM_ARG_ID_MOVEUP} },
4397         { "move_down",          move_step,      {.id = SWM_ARG_ID_MOVEDOWN} },
4398         { "name_workspace",     name_workspace, {0} },
4399         { "search_workspace",   search_workspace,       {0} },
4400         { "search_win",         search_win,     {0} },
4401         { "dumpwins",           dumpwins,       {0} }, /* MUST BE LAST */
4402         { "invalid key func",   NULL,           {0} },
4403 };
4404 struct key {
4405         RB_ENTRY(key)           entry;
4406         unsigned int            mod;
4407         KeySym                  keysym;
4408         enum keyfuncid          funcid;
4409         char                    *spawn_name;
4410 };
4411 RB_HEAD(key_list, key);
4412
4413 int
4414 key_cmp(struct key *kp1, struct key *kp2)
4415 {
4416         if (kp1->keysym < kp2->keysym)
4417                 return (-1);
4418         if (kp1->keysym > kp2->keysym)
4419                 return (1);
4420
4421         if (kp1->mod < kp2->mod)
4422                 return (-1);
4423         if (kp1->mod > kp2->mod)
4424                 return (1);
4425
4426         return (0);
4427 }
4428
4429 RB_GENERATE_STATIC(key_list, key, entry, key_cmp);
4430 struct key_list                 keys;
4431
4432 /* mouse */
4433 enum { client_click, root_click };
4434 struct button {
4435         unsigned int            action;
4436         unsigned int            mask;
4437         unsigned int            button;
4438         void                    (*func)(struct ws_win *, union arg *);
4439         union arg               args;
4440 } buttons[] = {
4441           /* action     key             mouse button    func    args */
4442         { client_click, MODKEY,         Button3,        resize, {.id = SWM_ARG_ID_DONTCENTER} },
4443         { client_click, MODKEY | ShiftMask, Button3,    resize, {.id = SWM_ARG_ID_CENTER} },
4444         { client_click, MODKEY,         Button1,        move,   {0} },
4445 };
4446
4447 void
4448 update_modkey(unsigned int mod)
4449 {
4450         int                     i;
4451         struct key              *kp;
4452
4453         mod_key = mod;
4454         RB_FOREACH(kp, key_list, &keys)
4455                 if (kp->mod & ShiftMask)
4456                         kp->mod = mod | ShiftMask;
4457                 else
4458                         kp->mod = mod;
4459
4460         for (i = 0; i < LENGTH(buttons); i++)
4461                 if (buttons[i].mask & ShiftMask)
4462                         buttons[i].mask = mod | ShiftMask;
4463                 else
4464                         buttons[i].mask = mod;
4465 }
4466
4467 /* spawn */
4468 struct spawn_prog {
4469         TAILQ_ENTRY(spawn_prog) entry;
4470         char                    *name;
4471         int                     argc;
4472         char                    **argv;
4473 };
4474 TAILQ_HEAD(spawn_list, spawn_prog);
4475 struct spawn_list               spawns = TAILQ_HEAD_INITIALIZER(spawns);
4476
4477 int
4478 spawn_expand(struct swm_region *r, union arg *args, char *spawn_name,
4479     char ***ret_args)
4480 {
4481         struct spawn_prog       *prog = NULL;
4482         int                     i;
4483         char                    *ap, **real_args;
4484
4485         DNPRINTF(SWM_D_SPAWN, "spawn_expand: %s\n", spawn_name);
4486
4487         /* find program */
4488         TAILQ_FOREACH(prog, &spawns, entry) {
4489                 if (!strcasecmp(spawn_name, prog->name))
4490                         break;
4491         }
4492         if (prog == NULL) {
4493                 warnx("spawn_custom: program %s not found", spawn_name);
4494                 return (-1);
4495         }
4496
4497         /* make room for expanded args */
4498         if ((real_args = calloc(prog->argc + 1, sizeof(char *))) == NULL)
4499                 err(1, "spawn_custom: calloc real_args");
4500
4501         /* expand spawn_args into real_args */
4502         for (i = 0; i < prog->argc; i++) {
4503                 ap = prog->argv[i];
4504                 DNPRINTF(SWM_D_SPAWN, "spawn_custom: raw arg: %s\n", ap);
4505                 if (!strcasecmp(ap, "$bar_border")) {
4506                         if ((real_args[i] =
4507                             strdup(r->s->c[SWM_S_COLOR_BAR_BORDER].name))
4508                             == NULL)
4509                                 err(1,  "spawn_custom border color");
4510                 } else if (!strcasecmp(ap, "$bar_color")) {
4511                         if ((real_args[i] =
4512                             strdup(r->s->c[SWM_S_COLOR_BAR].name))
4513                             == NULL)
4514                                 err(1, "spawn_custom bar color");
4515                 } else if (!strcasecmp(ap, "$bar_font")) {
4516                         if ((real_args[i] = strdup(bar_fonts))
4517                             == NULL)
4518                                 err(1, "spawn_custom bar fonts");
4519                 } else if (!strcasecmp(ap, "$bar_font_color")) {
4520                         if ((real_args[i] =
4521                             strdup(r->s->c[SWM_S_COLOR_BAR_FONT].name))
4522                             == NULL)
4523                                 err(1, "spawn_custom color font");
4524                 } else if (!strcasecmp(ap, "$color_focus")) {
4525                         if ((real_args[i] =
4526                             strdup(r->s->c[SWM_S_COLOR_FOCUS].name))
4527                             == NULL)
4528                                 err(1, "spawn_custom color focus");
4529                 } else if (!strcasecmp(ap, "$color_unfocus")) {
4530                         if ((real_args[i] =
4531                             strdup(r->s->c[SWM_S_COLOR_UNFOCUS].name))
4532                             == NULL)
4533                                 err(1, "spawn_custom color unfocus");
4534                 } else {
4535                         /* no match --> copy as is */
4536                         if ((real_args[i] = strdup(ap)) == NULL)
4537                                 err(1, "spawn_custom strdup(ap)");
4538                 }
4539                 DNPRINTF(SWM_D_SPAWN, "spawn_custom: cooked arg: %s\n",
4540                     real_args[i]);
4541         }
4542
4543 #ifdef SWM_DEBUG
4544         DNPRINTF(SWM_D_SPAWN, "spawn_custom: result: ");
4545         for (i = 0; i < prog->argc; i++)
4546                 DNPRINTF(SWM_D_SPAWN, "\"%s\" ", real_args[i]);
4547         DNPRINTF(SWM_D_SPAWN, "\n");
4548 #endif
4549         *ret_args = real_args;
4550         return (prog->argc);
4551 }
4552
4553 void
4554 spawn_custom(struct swm_region *r, union arg *args, char *spawn_name)
4555 {
4556         union arg               a;
4557         char                    **real_args;
4558         int                     spawn_argc, i;
4559
4560         if ((spawn_argc = spawn_expand(r, args, spawn_name, &real_args)) < 0)
4561                 return;
4562         a.argv = real_args;
4563         if (fork() == 0)
4564                 spawn(r->ws->idx, &a, 1);
4565
4566         for (i = 0; i < spawn_argc; i++)
4567                 free(real_args[i]);
4568         free(real_args);
4569 }
4570
4571 void
4572 spawn_select(struct swm_region *r, union arg *args, char *spawn_name, int *pid)
4573 {
4574         union arg               a;
4575         char                    **real_args;
4576         int                     i, spawn_argc;
4577
4578         if ((spawn_argc = spawn_expand(r, args, spawn_name, &real_args)) < 0)
4579                 return;
4580         a.argv = real_args;
4581
4582         if (pipe(select_list_pipe) == -1)
4583                 err(1, "pipe error");
4584         if (pipe(select_resp_pipe) == -1)
4585                 err(1, "pipe error");
4586
4587         if (signal(SIGPIPE, SIG_IGN) == SIG_ERR)
4588                 err(1, "could not disable SIGPIPE");
4589         switch (*pid = fork()) {
4590         case -1:
4591                 err(1, "cannot fork");
4592                 break;
4593         case 0: /* child */
4594                 if (dup2(select_list_pipe[0], 0) == -1)
4595                         err(1, "dup2");
4596                 if (dup2(select_resp_pipe[1], 1) == -1)
4597                         err(1, "dup2");
4598                 close(select_list_pipe[1]);
4599                 close(select_resp_pipe[0]);
4600                 spawn(r->ws->idx, &a, 0);
4601                 break;
4602         default: /* parent */
4603                 close(select_list_pipe[0]);
4604                 close(select_resp_pipe[1]);
4605                 break;
4606         }
4607
4608         for (i = 0; i < spawn_argc; i++)
4609                 free(real_args[i]);
4610         free(real_args);
4611 }
4612
4613 void
4614 spawn_insert(char *name, char *args)
4615 {
4616         char                    *arg, *cp, *ptr;
4617         struct spawn_prog       *sp;
4618
4619         DNPRINTF(SWM_D_SPAWN, "spawn_insert: %s\n", name);
4620
4621         if ((sp = calloc(1, sizeof *sp)) == NULL)
4622                 err(1, "spawn_insert: malloc");
4623         if ((sp->name = strdup(name)) == NULL)
4624                 err(1, "spawn_insert: strdup");
4625
4626         /* convert the arguments to an argument list */
4627         if ((ptr = cp = strdup(args)) == NULL)
4628                 err(1, "spawn_insert: strdup");
4629         while ((arg = strsep(&ptr, " \t")) != NULL) {
4630                 /* empty field; skip it */
4631                 if (*arg == '\0')
4632                         continue;
4633
4634                 sp->argc++;
4635                 if ((sp->argv = realloc(sp->argv, sp->argc *
4636                     sizeof *sp->argv)) == NULL)
4637                         err(1, "spawn_insert: realloc");
4638                 if ((sp->argv[sp->argc - 1] = strdup(arg)) == NULL)
4639                         err(1, "spawn_insert: strdup");
4640         }
4641         free(cp);
4642
4643         TAILQ_INSERT_TAIL(&spawns, sp, entry);
4644         DNPRINTF(SWM_D_SPAWN, "spawn_insert: leave\n");
4645 }
4646
4647 void
4648 spawn_remove(struct spawn_prog *sp)
4649 {
4650         int                     i;
4651
4652         DNPRINTF(SWM_D_SPAWN, "spawn_remove: %s\n", sp->name);
4653
4654         TAILQ_REMOVE(&spawns, sp, entry);
4655         for (i = 0; i < sp->argc; i++)
4656                 free(sp->argv[i]);
4657         free(sp->argv);
4658         free(sp->name);
4659         free(sp);
4660
4661         DNPRINTF(SWM_D_SPAWN, "spawn_remove: leave\n");
4662 }
4663
4664 void
4665 spawn_replace(struct spawn_prog *sp, char *name, char *args)
4666 {
4667         DNPRINTF(SWM_D_SPAWN, "spawn_replace: %s [%s]\n", sp->name, name);
4668
4669         spawn_remove(sp);
4670         spawn_insert(name, args);
4671
4672         DNPRINTF(SWM_D_SPAWN, "spawn_replace: leave\n");
4673 }
4674
4675 void
4676 setspawn(char *name, char *args)
4677 {
4678         struct spawn_prog       *sp;
4679
4680         DNPRINTF(SWM_D_SPAWN, "setspawn: %s\n", name);
4681
4682         if (name == NULL)
4683                 return;
4684
4685         TAILQ_FOREACH(sp, &spawns, entry) {
4686                 if (!strcmp(sp->name, name)) {
4687                         if (*args == '\0')
4688                                 spawn_remove(sp);
4689                         else
4690                                 spawn_replace(sp, name, args);
4691                         DNPRINTF(SWM_D_SPAWN, "setspawn: leave\n");
4692                         return;
4693                 }
4694         }
4695         if (*args == '\0') {
4696                 warnx("error: setspawn: cannot find program: %s", name);
4697                 return;
4698         }
4699
4700         spawn_insert(name, args);
4701         DNPRINTF(SWM_D_SPAWN, "setspawn: leave\n");
4702 }
4703
4704 int
4705 setconfspawn(char *selector, char *value, int flags)
4706 {
4707         DNPRINTF(SWM_D_SPAWN, "setconfspawn: [%s] [%s]\n", selector, value);
4708
4709         setspawn(selector, value);
4710
4711         DNPRINTF(SWM_D_SPAWN, "setconfspawn: done\n");
4712         return (0);
4713 }
4714
4715 void
4716 setup_spawn(void)
4717 {
4718         setconfspawn("term",            "xterm",                0);
4719         setconfspawn("screenshot_all",  "screenshot.sh full",   0);
4720         setconfspawn("screenshot_wind", "screenshot.sh window", 0);
4721         setconfspawn("lock",            "xlock",                0);
4722         setconfspawn("initscr",         "initscreen.sh",        0);
4723         setconfspawn("menu",            "dmenu_run"
4724                                         " -fn $bar_font"
4725                                         " -nb $bar_color"
4726                                         " -nf $bar_font_color"
4727                                         " -sb $bar_border"
4728                                         " -sf $bar_color",      0);
4729         setconfspawn("search",          "dmenu"
4730                                         " -i"
4731                                         " -fn $bar_font"
4732                                         " -nb $bar_color"
4733                                         " -nf $bar_font_color"
4734                                         " -sb $bar_border"
4735                                         " -sf $bar_color",      0);
4736         setconfspawn("name_workspace",  "dmenu"
4737                                         " -p Workspace"
4738                                         " -fn $bar_font"
4739                                         " -nb $bar_color"
4740                                         " -nf $bar_font_color"
4741                                         " -sb $bar_border"
4742                                         " -sf $bar_color",      0);
4743 }
4744
4745 /* key bindings */
4746 #define SWM_MODNAME_SIZE        32
4747 #define SWM_KEY_WS              "\n+ \t"
4748 int
4749 parsekeys(char *keystr, unsigned int currmod, unsigned int *mod, KeySym *ks)
4750 {
4751         char                    *cp, *name;
4752         KeySym                  uks;
4753         DNPRINTF(SWM_D_KEY, "parsekeys: enter [%s]\n", keystr);
4754         if (mod == NULL || ks == NULL) {
4755                 DNPRINTF(SWM_D_KEY, "parsekeys: no mod or key vars\n");
4756                 return (1);
4757         }
4758         if (keystr == NULL || strlen(keystr) == 0) {
4759                 DNPRINTF(SWM_D_KEY, "parsekeys: no keystr\n");
4760                 return (1);
4761         }
4762         cp = keystr;
4763         *ks = NoSymbol;
4764         *mod = 0;
4765         while ((name = strsep(&cp, SWM_KEY_WS)) != NULL) {
4766                 DNPRINTF(SWM_D_KEY, "parsekeys: key [%s]\n", name);
4767                 if (cp)
4768                         cp += (long)strspn(cp, SWM_KEY_WS);
4769                 if (strncasecmp(name, "MOD", SWM_MODNAME_SIZE) == 0)
4770                         *mod |= currmod;
4771                 else if (!strncasecmp(name, "Mod1", SWM_MODNAME_SIZE))
4772                         *mod |= Mod1Mask;
4773                 else if (!strncasecmp(name, "Mod2", SWM_MODNAME_SIZE))
4774                         *mod += Mod2Mask;
4775                 else if (!strncmp(name, "Mod3", SWM_MODNAME_SIZE))
4776                         *mod |= Mod3Mask;
4777                 else if (!strncmp(name, "Mod4", SWM_MODNAME_SIZE))
4778                         *mod |= Mod4Mask;
4779                 else if (strncasecmp(name, "SHIFT", SWM_MODNAME_SIZE) == 0)
4780                         *mod |= ShiftMask;
4781                 else if (strncasecmp(name, "CONTROL", SWM_MODNAME_SIZE) == 0)
4782                         *mod |= ControlMask;
4783                 else {
4784                         *ks = XStringToKeysym(name);
4785                         XConvertCase(*ks, ks, &uks);
4786                         if (ks == NoSymbol) {
4787                                 DNPRINTF(SWM_D_KEY,
4788                                     "parsekeys: invalid key %s\n",
4789                                     name);
4790                                 return (1);
4791                         }
4792                 }
4793         }
4794         DNPRINTF(SWM_D_KEY, "parsekeys: leave ok\n");
4795         return (0);
4796 }
4797
4798 char *
4799 strdupsafe(char *str)
4800 {
4801         if (str == NULL)
4802                 return (NULL);
4803         else
4804                 return (strdup(str));
4805 }
4806
4807 void
4808 key_insert(unsigned int mod, KeySym ks, enum keyfuncid kfid, char *spawn_name)
4809 {
4810         struct key              *kp;
4811
4812         DNPRINTF(SWM_D_KEY, "key_insert: enter %s [%s]\n",
4813             keyfuncs[kfid].name, spawn_name);
4814
4815         if ((kp = malloc(sizeof *kp)) == NULL)
4816                 err(1, "key_insert: malloc");
4817
4818         kp->mod = mod;
4819         kp->keysym = ks;
4820         kp->funcid = kfid;
4821         kp->spawn_name = strdupsafe(spawn_name);
4822         RB_INSERT(key_list, &keys, kp);
4823
4824         DNPRINTF(SWM_D_KEY, "key_insert: leave\n");
4825 }
4826
4827 struct key *
4828 key_lookup(unsigned int mod, KeySym ks)
4829 {
4830         struct key              kp;
4831
4832         kp.keysym = ks;
4833         kp.mod = mod;
4834
4835         return (RB_FIND(key_list, &keys, &kp));
4836 }
4837
4838 void
4839 key_remove(struct key *kp)
4840 {
4841         DNPRINTF(SWM_D_KEY, "key_remove: %s\n", keyfuncs[kp->funcid].name);
4842
4843         RB_REMOVE(key_list, &keys, kp);
4844         free(kp->spawn_name);
4845         free(kp);
4846
4847         DNPRINTF(SWM_D_KEY, "key_remove: leave\n");
4848 }
4849
4850 void
4851 key_replace(struct key *kp, unsigned int mod, KeySym ks, enum keyfuncid kfid,
4852     char *spawn_name)
4853 {
4854         DNPRINTF(SWM_D_KEY, "key_replace: %s [%s]\n", keyfuncs[kp->funcid].name,
4855             spawn_name);
4856
4857         key_remove(kp);
4858         key_insert(mod, ks, kfid, spawn_name);
4859
4860         DNPRINTF(SWM_D_KEY, "key_replace: leave\n");
4861 }
4862
4863 void
4864 setkeybinding(unsigned int mod, KeySym ks, enum keyfuncid kfid,
4865     char *spawn_name)
4866 {
4867         struct key              *kp;
4868
4869         DNPRINTF(SWM_D_KEY, "setkeybinding: enter %s [%s]\n",
4870             keyfuncs[kfid].name, spawn_name);
4871
4872         if ((kp = key_lookup(mod, ks)) != NULL) {
4873                 if (kfid == kf_invalid)
4874                         key_remove(kp);
4875                 else
4876                         key_replace(kp, mod, ks, kfid, spawn_name);
4877                 DNPRINTF(SWM_D_KEY, "setkeybinding: leave\n");
4878                 return;
4879         }
4880         if (kfid == kf_invalid) {
4881                 warnx("error: setkeybinding: cannot find mod/key combination");
4882                 DNPRINTF(SWM_D_KEY, "setkeybinding: leave\n");
4883                 return;
4884         }
4885
4886         key_insert(mod, ks, kfid, spawn_name);
4887         DNPRINTF(SWM_D_KEY, "setkeybinding: leave\n");
4888 }
4889
4890 int
4891 setconfbinding(char *selector, char *value, int flags)
4892 {
4893         enum keyfuncid          kfid;
4894         unsigned int            mod;
4895         KeySym                  ks;
4896         struct spawn_prog       *sp;
4897         DNPRINTF(SWM_D_KEY, "setconfbinding: enter\n");
4898         if (selector == NULL) {
4899                 DNPRINTF(SWM_D_KEY, "setconfbinding: unbind %s\n", value);
4900                 if (parsekeys(value, mod_key, &mod, &ks) == 0) {
4901                         kfid = kf_invalid;
4902                         setkeybinding(mod, ks, kfid, NULL);
4903                         return (0);
4904                 } else
4905                         return (1);
4906         }
4907         /* search by key function name */
4908         for (kfid = 0; kfid < kf_invalid; (kfid)++) {
4909                 if (strncasecmp(selector, keyfuncs[kfid].name,
4910                     SWM_FUNCNAME_LEN) == 0) {
4911                         DNPRINTF(SWM_D_KEY, "setconfbinding: %s: match\n",
4912                             selector);
4913                         if (parsekeys(value, mod_key, &mod, &ks) == 0) {
4914                                 setkeybinding(mod, ks, kfid, NULL);
4915                                 return (0);
4916                         } else
4917                                 return (1);
4918                 }
4919         }
4920         /* search by custom spawn name */
4921         TAILQ_FOREACH(sp, &spawns, entry) {
4922                 if (strcasecmp(selector, sp->name) == 0) {
4923                         DNPRINTF(SWM_D_KEY, "setconfbinding: %s: match\n",
4924                             selector);
4925                         if (parsekeys(value, mod_key, &mod, &ks) == 0) {
4926                                 setkeybinding(mod, ks, kf_spawn_custom,
4927                                     sp->name);
4928                                 return (0);
4929                         } else
4930                                 return (1);
4931                 }
4932         }
4933         DNPRINTF(SWM_D_KEY, "setconfbinding: no match\n");
4934         return (1);
4935 }
4936
4937 void
4938 setup_keys(void)
4939 {
4940         setkeybinding(MODKEY,           XK_space,       kf_cycle_layout,NULL);
4941         setkeybinding(MODKEY|ShiftMask, XK_backslash,   kf_flip_layout, NULL);
4942         setkeybinding(MODKEY|ShiftMask, XK_space,       kf_stack_reset, NULL);
4943         setkeybinding(MODKEY,           XK_h,           kf_master_shrink,NULL);
4944         setkeybinding(MODKEY,           XK_l,           kf_master_grow, NULL);
4945         setkeybinding(MODKEY,           XK_comma,       kf_master_add,  NULL);
4946         setkeybinding(MODKEY,           XK_period,      kf_master_del,  NULL);
4947         setkeybinding(MODKEY|ShiftMask, XK_comma,       kf_stack_inc,   NULL);
4948         setkeybinding(MODKEY|ShiftMask, XK_period,      kf_stack_dec,   NULL);
4949         setkeybinding(MODKEY,           XK_Return,      kf_swap_main,   NULL);
4950         setkeybinding(MODKEY,           XK_j,           kf_focus_next,  NULL);
4951         setkeybinding(MODKEY,           XK_k,           kf_focus_prev,  NULL);
4952         setkeybinding(MODKEY|ShiftMask, XK_j,           kf_swap_next,   NULL);
4953         setkeybinding(MODKEY|ShiftMask, XK_k,           kf_swap_prev,   NULL);
4954         setkeybinding(MODKEY|ShiftMask, XK_Return,      kf_spawn_term,  NULL);
4955         setkeybinding(MODKEY,           XK_p,           kf_spawn_custom,"menu");
4956         setkeybinding(MODKEY|ShiftMask, XK_q,           kf_quit,        NULL);
4957         setkeybinding(MODKEY,           XK_q,           kf_restart,     NULL);
4958         setkeybinding(MODKEY,           XK_m,           kf_focus_main,  NULL);
4959         setkeybinding(MODKEY,           XK_1,           kf_ws_1,        NULL);
4960         setkeybinding(MODKEY,           XK_2,           kf_ws_2,        NULL);
4961         setkeybinding(MODKEY,           XK_3,           kf_ws_3,        NULL);
4962         setkeybinding(MODKEY,           XK_4,           kf_ws_4,        NULL);
4963         setkeybinding(MODKEY,           XK_5,           kf_ws_5,        NULL);
4964         setkeybinding(MODKEY,           XK_6,           kf_ws_6,        NULL);
4965         setkeybinding(MODKEY,           XK_7,           kf_ws_7,        NULL);
4966         setkeybinding(MODKEY,           XK_8,           kf_ws_8,        NULL);
4967         setkeybinding(MODKEY,           XK_9,           kf_ws_9,        NULL);
4968         setkeybinding(MODKEY,           XK_0,           kf_ws_10,       NULL);
4969         setkeybinding(MODKEY,           XK_F1,          kf_ws_11,       NULL);
4970         setkeybinding(MODKEY,           XK_F2,          kf_ws_12,       NULL);
4971         setkeybinding(MODKEY,           XK_F3,          kf_ws_13,       NULL);
4972         setkeybinding(MODKEY,           XK_F4,          kf_ws_14,       NULL);
4973         setkeybinding(MODKEY,           XK_F5,          kf_ws_15,       NULL);
4974         setkeybinding(MODKEY,           XK_F6,          kf_ws_16,       NULL);
4975         setkeybinding(MODKEY,           XK_F7,          kf_ws_17,       NULL);
4976         setkeybinding(MODKEY,           XK_F8,          kf_ws_18,       NULL);
4977         setkeybinding(MODKEY,           XK_F9,          kf_ws_19,       NULL);
4978         setkeybinding(MODKEY,           XK_F10,         kf_ws_20,       NULL);
4979         setkeybinding(MODKEY,           XK_F11,         kf_ws_21,       NULL);
4980         setkeybinding(MODKEY,           XK_F12,         kf_ws_22,       NULL);
4981         setkeybinding(MODKEY,           XK_Right,       kf_ws_next,     NULL);
4982         setkeybinding(MODKEY,           XK_Left,        kf_ws_prev,     NULL);
4983         setkeybinding(MODKEY,           XK_Up,          kf_ws_next_all, NULL);
4984         setkeybinding(MODKEY,           XK_Down,        kf_ws_prev_all, NULL);
4985         setkeybinding(MODKEY,           XK_a,           kf_ws_prior,    NULL);
4986         setkeybinding(MODKEY|ShiftMask, XK_Right,       kf_screen_next, NULL);
4987         setkeybinding(MODKEY|ShiftMask, XK_Left,        kf_screen_prev, NULL);
4988         setkeybinding(MODKEY|ShiftMask, XK_1,           kf_mvws_1,      NULL);
4989         setkeybinding(MODKEY|ShiftMask, XK_2,           kf_mvws_2,      NULL);
4990         setkeybinding(MODKEY|ShiftMask, XK_3,           kf_mvws_3,      NULL);
4991         setkeybinding(MODKEY|ShiftMask, XK_4,           kf_mvws_4,      NULL);
4992         setkeybinding(MODKEY|ShiftMask, XK_5,           kf_mvws_5,      NULL);
4993         setkeybinding(MODKEY|ShiftMask, XK_6,           kf_mvws_6,      NULL);
4994         setkeybinding(MODKEY|ShiftMask, XK_7,           kf_mvws_7,      NULL);
4995         setkeybinding(MODKEY|ShiftMask, XK_8,           kf_mvws_8,      NULL);
4996         setkeybinding(MODKEY|ShiftMask, XK_9,           kf_mvws_9,      NULL);
4997         setkeybinding(MODKEY|ShiftMask, XK_0,           kf_mvws_10,     NULL);
4998         setkeybinding(MODKEY|ShiftMask, XK_F1,          kf_mvws_11,     NULL);
4999         setkeybinding(MODKEY|ShiftMask, XK_F2,          kf_mvws_12,     NULL);
5000         setkeybinding(MODKEY|ShiftMask, XK_F3,          kf_mvws_13,     NULL);
5001         setkeybinding(MODKEY|ShiftMask, XK_F4,          kf_mvws_14,     NULL);
5002         setkeybinding(MODKEY|ShiftMask, XK_F5,          kf_mvws_15,     NULL);
5003         setkeybinding(MODKEY|ShiftMask, XK_F6,          kf_mvws_16,     NULL);
5004         setkeybinding(MODKEY|ShiftMask, XK_F7,          kf_mvws_17,     NULL);
5005         setkeybinding(MODKEY|ShiftMask, XK_F8,          kf_mvws_18,     NULL);
5006         setkeybinding(MODKEY|ShiftMask, XK_F9,          kf_mvws_19,     NULL);
5007         setkeybinding(MODKEY|ShiftMask, XK_F10,         kf_mvws_20,     NULL);
5008         setkeybinding(MODKEY|ShiftMask, XK_F11,         kf_mvws_21,     NULL);
5009         setkeybinding(MODKEY|ShiftMask, XK_F12,         kf_mvws_22,     NULL);
5010         setkeybinding(MODKEY,           XK_b,           kf_bar_toggle,  NULL);
5011         setkeybinding(MODKEY,           XK_Tab,         kf_focus_next,  NULL);
5012         setkeybinding(MODKEY|ShiftMask, XK_Tab,         kf_focus_prev,  NULL);
5013         setkeybinding(MODKEY|ShiftMask, XK_x,           kf_wind_kill,   NULL);
5014         setkeybinding(MODKEY,           XK_x,           kf_wind_del,    NULL);
5015         setkeybinding(MODKEY,           XK_s,           kf_spawn_custom,"screenshot_all");
5016         setkeybinding(MODKEY|ShiftMask, XK_s,           kf_spawn_custom,"screenshot_wind");
5017         setkeybinding(MODKEY,           XK_t,           kf_float_toggle,NULL);
5018         setkeybinding(MODKEY|ShiftMask, XK_v,           kf_version,     NULL);
5019         setkeybinding(MODKEY|ShiftMask, XK_Delete,      kf_spawn_custom,"lock");
5020         setkeybinding(MODKEY|ShiftMask, XK_i,           kf_spawn_custom,"initscr");
5021         setkeybinding(MODKEY,           XK_w,           kf_iconify,     NULL);
5022         setkeybinding(MODKEY|ShiftMask, XK_w,           kf_uniconify,   NULL);
5023         setkeybinding(MODKEY|ShiftMask, XK_r,           kf_raise_toggle,NULL);
5024         setkeybinding(MODKEY,           XK_v,           kf_button2,     NULL);
5025         setkeybinding(MODKEY,           XK_equal,       kf_width_grow,  NULL);
5026         setkeybinding(MODKEY,           XK_minus,       kf_width_shrink,NULL);
5027         setkeybinding(MODKEY|ShiftMask, XK_equal,       kf_height_grow, NULL);
5028         setkeybinding(MODKEY|ShiftMask, XK_minus,       kf_height_shrink,NULL);
5029         setkeybinding(MODKEY,           XK_bracketleft, kf_move_left,   NULL);
5030         setkeybinding(MODKEY,           XK_bracketright,kf_move_right,  NULL);
5031         setkeybinding(MODKEY|ShiftMask, XK_bracketleft, kf_move_up,     NULL);
5032         setkeybinding(MODKEY|ShiftMask, XK_bracketright,kf_move_down,   NULL);
5033         setkeybinding(MODKEY|ShiftMask, XK_slash,       kf_name_workspace,NULL);
5034         setkeybinding(MODKEY,           XK_slash,       kf_search_workspace,NULL);
5035         setkeybinding(MODKEY,           XK_f,           kf_search_win,  NULL);
5036 #ifdef SWM_DEBUG
5037         setkeybinding(MODKEY|ShiftMask, XK_d,           kf_dumpwins,    NULL);
5038 #endif
5039 }
5040
5041 void
5042 clear_keys(void)
5043 {
5044         struct key              *kp;
5045
5046         while (RB_EMPTY(&keys) == 0) {
5047                 kp = RB_ROOT(&keys);
5048                 key_remove(kp);
5049         }
5050 }
5051
5052 int
5053 setkeymapping(char *selector, char *value, int flags)
5054 {
5055         char                    keymapping_file[PATH_MAX];
5056         DNPRINTF(SWM_D_KEY, "setkeymapping: enter\n");
5057         if (value[0] == '~')
5058                 snprintf(keymapping_file, sizeof keymapping_file, "%s/%s",
5059                     pwd->pw_dir, &value[1]);
5060         else
5061                 strlcpy(keymapping_file, value, sizeof keymapping_file);
5062         clear_keys();
5063         /* load new key bindings; if it fails, revert to default bindings */
5064         if (conf_load(keymapping_file, SWM_CONF_KEYMAPPING)) {
5065                 clear_keys();
5066                 setup_keys();
5067         }
5068         DNPRINTF(SWM_D_KEY, "setkeymapping: leave\n");
5069         return (0);
5070 }
5071
5072 void
5073 updatenumlockmask(void)
5074 {
5075         unsigned int            i, j;
5076         XModifierKeymap         *modmap;
5077
5078         DNPRINTF(SWM_D_MISC, "updatenumlockmask\n");
5079         numlockmask = 0;
5080         modmap = XGetModifierMapping(display);
5081         for (i = 0; i < 8; i++)
5082                 for (j = 0; j < modmap->max_keypermod; j++)
5083                         if (modmap->modifiermap[i * modmap->max_keypermod + j]
5084                             == XKeysymToKeycode(display, XK_Num_Lock))
5085                                 numlockmask = (1 << i);
5086
5087         XFreeModifiermap(modmap);
5088 }
5089
5090 void
5091 grabkeys(void)
5092 {
5093         unsigned int            j, k;
5094         KeyCode                 code;
5095         unsigned int            modifiers[] =
5096             { 0, LockMask, numlockmask, numlockmask | LockMask };
5097         struct key              *kp;
5098
5099         DNPRINTF(SWM_D_MISC, "grabkeys\n");
5100         updatenumlockmask();
5101
5102         for (k = 0; k < ScreenCount(display); k++) {
5103                 if (TAILQ_EMPTY(&screens[k].rl))
5104                         continue;
5105                 XUngrabKey(display, AnyKey, AnyModifier, screens[k].root);
5106                 RB_FOREACH(kp, key_list, &keys) {
5107                         if ((code = XKeysymToKeycode(display, kp->keysym)))
5108                                 for (j = 0; j < LENGTH(modifiers); j++)
5109                                         XGrabKey(display, code,
5110                                             kp->mod | modifiers[j],
5111                                             screens[k].root, True,
5112                                             GrabModeAsync, GrabModeAsync);
5113                 }
5114         }
5115 }
5116
5117 void
5118 grabbuttons(struct ws_win *win, int focused)
5119 {
5120         unsigned int            i, j;
5121         unsigned int            modifiers[] =
5122             { 0, LockMask, numlockmask, numlockmask|LockMask };
5123
5124         updatenumlockmask();
5125         XUngrabButton(display, AnyButton, AnyModifier, win->id);
5126         if (focused) {
5127                 for (i = 0; i < LENGTH(buttons); i++)
5128                         if (buttons[i].action == client_click)
5129                                 for (j = 0; j < LENGTH(modifiers); j++)
5130                                         XGrabButton(display, buttons[i].button,
5131                                             buttons[i].mask | modifiers[j],
5132                                             win->id, False, BUTTONMASK,
5133                                             GrabModeAsync, GrabModeSync, None,
5134                                             None);
5135         } else
5136                 XGrabButton(display, AnyButton, AnyModifier, win->id, False,
5137                     BUTTONMASK, GrabModeAsync, GrabModeSync, None, None);
5138 }
5139
5140 const char *quirkname[] = {
5141         "NONE",         /* config string for "no value" */
5142         "FLOAT",
5143         "TRANSSZ",
5144         "ANYWHERE",
5145         "XTERM_FONTADJ",
5146         "FULLSCREEN",
5147         "FOCUSPREV",
5148 };
5149
5150 /* SWM_Q_WS: retain '|' for back compat for now (2009-08-11) */
5151 #define SWM_Q_WS                "\n|+ \t"
5152 int
5153 parsequirks(char *qstr, unsigned long *quirk)
5154 {
5155         char                    *cp, *name;
5156         int                     i;
5157
5158         if (quirk == NULL)
5159                 return (1);
5160
5161         cp = qstr;
5162         *quirk = 0;
5163         while ((name = strsep(&cp, SWM_Q_WS)) != NULL) {
5164                 if (cp)
5165                         cp += (long)strspn(cp, SWM_Q_WS);
5166                 for (i = 0; i < LENGTH(quirkname); i++) {
5167                         if (!strncasecmp(name, quirkname[i], SWM_QUIRK_LEN)) {
5168                                 DNPRINTF(SWM_D_QUIRK,
5169                                     "parsequirks: %s\n", name);
5170                                 if (i == 0) {
5171                                         *quirk = 0;
5172                                         return (0);
5173                                 }
5174                                 *quirk |= 1 << (i-1);
5175                                 break;
5176                         }
5177                 }
5178                 if (i >= LENGTH(quirkname)) {
5179                         DNPRINTF(SWM_D_QUIRK,
5180                             "parsequirks: invalid quirk [%s]\n", name);
5181                         return (1);
5182                 }
5183         }
5184         return (0);
5185 }
5186
5187 void
5188 quirk_insert(const char *class, const char *name, unsigned long quirk)
5189 {
5190         struct quirk            *qp;
5191
5192         DNPRINTF(SWM_D_QUIRK, "quirk_insert: %s:%s [%lu]\n", class, name,
5193             quirk);
5194
5195         if ((qp = malloc(sizeof *qp)) == NULL)
5196                 err(1, "quirk_insert: malloc");
5197         if ((qp->class = strdup(class)) == NULL)
5198                 err(1, "quirk_insert: strdup");
5199         if ((qp->name = strdup(name)) == NULL)
5200                 err(1, "quirk_insert: strdup");
5201
5202         qp->quirk = quirk;
5203         TAILQ_INSERT_TAIL(&quirks, qp, entry);
5204
5205         DNPRINTF(SWM_D_QUIRK, "quirk_insert: leave\n");
5206 }
5207
5208 void
5209 quirk_remove(struct quirk *qp)
5210 {
5211         DNPRINTF(SWM_D_QUIRK, "quirk_remove: %s:%s [%lu]\n", qp->class,
5212             qp->name, qp->quirk);
5213
5214         TAILQ_REMOVE(&quirks, qp, entry);
5215         free(qp->class);
5216         free(qp->name);
5217         free(qp);
5218
5219         DNPRINTF(SWM_D_QUIRK, "quirk_remove: leave\n");
5220 }
5221
5222 void
5223 quirk_replace(struct quirk *qp, const char *class, const char *name,
5224     unsigned long quirk)
5225 {
5226         DNPRINTF(SWM_D_QUIRK, "quirk_replace: %s:%s [%lu]\n", qp->class,
5227             qp->name, qp->quirk);
5228
5229         quirk_remove(qp);
5230         quirk_insert(class, name, quirk);
5231
5232         DNPRINTF(SWM_D_QUIRK, "quirk_replace: leave\n");
5233 }
5234
5235 void
5236 setquirk(const char *class, const char *name, unsigned long quirk)
5237 {
5238         struct quirk            *qp;
5239
5240         DNPRINTF(SWM_D_QUIRK, "setquirk: enter %s:%s [%lu]\n", class, name,
5241            quirk);
5242
5243         TAILQ_FOREACH(qp, &quirks, entry) {
5244                 if (!strcmp(qp->class, class) && !strcmp(qp->name, name)) {
5245                         if (!quirk)
5246                                 quirk_remove(qp);
5247                         else
5248                                 quirk_replace(qp, class, name, quirk);
5249                         DNPRINTF(SWM_D_QUIRK, "setquirk: leave\n");
5250                         return;
5251                 }
5252         }
5253         if (!quirk) {
5254                 warnx("error: setquirk: cannot find class/name combination");
5255                 return;
5256         }
5257
5258         quirk_insert(class, name, quirk);
5259         DNPRINTF(SWM_D_QUIRK, "setquirk: leave\n");
5260 }
5261
5262 int
5263 setconfquirk(char *selector, char *value, int flags)
5264 {
5265         char                    *cp, *class, *name;
5266         int                     retval;
5267         unsigned long           quirks;
5268         if (selector == NULL)
5269                 return (0);
5270         if ((cp = strchr(selector, ':')) == NULL)
5271                 return (0);
5272         *cp = '\0';
5273         class = selector;
5274         name = cp + 1;
5275         if ((retval = parsequirks(value, &quirks)) == 0)
5276                 setquirk(class, name, quirks);
5277         return (retval);
5278 }
5279
5280 void
5281 setup_quirks(void)
5282 {
5283         setquirk("MPlayer",             "xv",           SWM_Q_FLOAT | SWM_Q_FULLSCREEN | SWM_Q_FOCUSPREV);
5284         setquirk("OpenOffice.org 3.2",  "VCLSalFrame",  SWM_Q_FLOAT);
5285         setquirk("Firefox-bin",         "firefox-bin",  SWM_Q_TRANSSZ);
5286         setquirk("Firefox",             "Dialog",       SWM_Q_FLOAT);
5287         setquirk("Gimp",                "gimp",         SWM_Q_FLOAT | SWM_Q_ANYWHERE);
5288         setquirk("XTerm",               "xterm",        SWM_Q_XTERM_FONTADJ);
5289         setquirk("xine",                "Xine Window",  SWM_Q_FLOAT | SWM_Q_ANYWHERE);
5290         setquirk("Xitk",                "Xitk Combo",   SWM_Q_FLOAT | SWM_Q_ANYWHERE);
5291         setquirk("xine",                "xine Panel",   SWM_Q_FLOAT | SWM_Q_ANYWHERE);
5292         setquirk("Xitk",                "Xine Window",  SWM_Q_FLOAT | SWM_Q_ANYWHERE);
5293         setquirk("xine",                "xine Video Fullscreen Window", SWM_Q_FULLSCREEN | SWM_Q_FLOAT);
5294         setquirk("pcb",                 "pcb",          SWM_Q_FLOAT);
5295         setquirk("SDL_App",             "SDL_App",      SWM_Q_FLOAT | SWM_Q_FULLSCREEN);
5296 }
5297
5298 /* conf file stuff */
5299 #define SWM_CONF_FILE           "spectrwm.conf"
5300 #define SWM_CONF_FILE_OLD       "scrotwm.conf"
5301
5302 enum    { SWM_S_BAR_DELAY, SWM_S_BAR_ENABLED, SWM_S_BAR_BORDER_WIDTH,
5303           SWM_S_STACK_ENABLED, SWM_S_CLOCK_ENABLED, SWM_S_CLOCK_FORMAT,
5304           SWM_S_CYCLE_EMPTY, SWM_S_CYCLE_VISIBLE, SWM_S_WORKSPACE_LIMIT,
5305           SWM_S_SS_ENABLED, SWM_S_TERM_WIDTH, SWM_S_TITLE_CLASS_ENABLED,
5306           SWM_S_TITLE_NAME_ENABLED, SWM_S_WINDOW_NAME_ENABLED,
5307           SWM_S_URGENT_ENABLED, SWM_S_FOCUS_MODE, SWM_S_FOCUS_CLOSE,
5308           SWM_S_FOCUS_CLOSE_WRAP, SWM_S_FOCUS_DEFAULT, SWM_S_SPAWN_ORDER,
5309           SWM_S_DISABLE_BORDER, SWM_S_BORDER_WIDTH, SWM_S_BAR_FONT,
5310           SWM_S_BAR_ACTION, SWM_S_SPAWN_TERM, SWM_S_SS_APP, SWM_S_DIALOG_RATIO,
5311           SWM_S_BAR_AT_BOTTOM, SWM_S_VERBOSE_LAYOUT, SWM_S_BAR_JUSTIFY
5312         };
5313
5314 int
5315 setconfvalue(char *selector, char *value, int flags)
5316 {
5317         int     i;
5318         char    *b;
5319
5320         switch (flags) {
5321         case SWM_S_BAR_DELAY:
5322                 bar_delay = atoi(value);
5323                 break;
5324         case SWM_S_BAR_ENABLED:
5325                 bar_enabled = atoi(value);
5326                 break;
5327         case SWM_S_BAR_BORDER_WIDTH:
5328                 bar_border_width = atoi(value);
5329                 break;
5330         case SWM_S_BAR_AT_BOTTOM:
5331                 bar_at_bottom = atoi(value);
5332                 break;
5333         case SWM_S_BAR_JUSTIFY:
5334                 if (!strcmp(value, "left"))
5335                         bar_justify = SWM_BAR_JUSTIFY_LEFT;
5336                 else if (!strcmp(value, "center"))
5337                         bar_justify = SWM_BAR_JUSTIFY_CENTER;
5338                 else if (!strcmp(value, "right"))
5339                         bar_justify = SWM_BAR_JUSTIFY_RIGHT;
5340                 else
5341                         errx(1, "invalid bar_justify");
5342                 break;
5343         case SWM_S_STACK_ENABLED:
5344                 stack_enabled = atoi(value);
5345                 break;
5346         case SWM_S_CLOCK_ENABLED:
5347                 clock_enabled = atoi(value);
5348                 break;
5349         case SWM_S_CLOCK_FORMAT:
5350 #ifndef SWM_DENY_CLOCK_FORMAT
5351                 free(clock_format);
5352                 if ((clock_format = strdup(value)) == NULL)
5353                         err(1, "setconfvalue: clock_format");
5354 #endif
5355                 break;
5356         case SWM_S_CYCLE_EMPTY:
5357                 cycle_empty = atoi(value);
5358                 break;
5359         case SWM_S_CYCLE_VISIBLE:
5360                 cycle_visible = atoi(value);
5361                 break;
5362         case SWM_S_WORKSPACE_LIMIT:
5363                 workspace_limit = atoi(value);
5364                 if (workspace_limit > SWM_WS_MAX)
5365                         workspace_limit = SWM_WS_MAX;
5366                 else if (workspace_limit < 1)
5367                         workspace_limit = 1;
5368                 break;
5369         case SWM_S_SS_ENABLED:
5370                 ss_enabled = atoi(value);
5371                 break;
5372         case SWM_S_TERM_WIDTH:
5373                 term_width = atoi(value);
5374                 break;
5375         case SWM_S_TITLE_CLASS_ENABLED:
5376                 title_class_enabled = atoi(value);
5377                 break;
5378         case SWM_S_WINDOW_NAME_ENABLED:
5379                 window_name_enabled = atoi(value);
5380                 break;
5381         case SWM_S_TITLE_NAME_ENABLED:
5382                 title_name_enabled = atoi(value);
5383                 break;
5384         case SWM_S_URGENT_ENABLED:
5385                 urgent_enabled = atoi(value);
5386                 break;
5387         case SWM_S_FOCUS_MODE:
5388                 if (!strcmp(value, "default"))
5389                         focus_mode = SWM_FOCUS_DEFAULT;
5390                 else if (!strcmp(value, "follow_cursor"))
5391                         focus_mode = SWM_FOCUS_FOLLOW;
5392                 else if (!strcmp(value, "synergy"))
5393                         focus_mode = SWM_FOCUS_SYNERGY;
5394                 else
5395                         errx(1, "focus_mode");
5396                 break;
5397         case SWM_S_FOCUS_CLOSE:
5398                 if (!strcmp(value, "first"))
5399                         focus_close = SWM_STACK_BOTTOM;
5400                 else if (!strcmp(value, "last"))
5401                         focus_close = SWM_STACK_TOP;
5402                 else if (!strcmp(value, "next"))
5403                         focus_close = SWM_STACK_ABOVE;
5404                 else if (!strcmp(value, "previous"))
5405                         focus_close = SWM_STACK_BELOW;
5406                 else
5407                         errx(1, "focus_close");
5408                 break;
5409         case SWM_S_FOCUS_CLOSE_WRAP:
5410                 focus_close_wrap = atoi(value);
5411                 break;
5412         case SWM_S_FOCUS_DEFAULT:
5413                 if (!strcmp(value, "last"))
5414                         focus_default = SWM_STACK_TOP;
5415                 else if (!strcmp(value, "first"))
5416                         focus_default = SWM_STACK_BOTTOM;
5417                 else
5418                         errx(1, "focus_default");
5419                 break;
5420         case SWM_S_SPAWN_ORDER:
5421                 if (!strcmp(value, "first"))
5422                         spawn_position = SWM_STACK_BOTTOM;
5423                 else if (!strcmp(value, "last"))
5424                         spawn_position = SWM_STACK_TOP;
5425                 else if (!strcmp(value, "next"))
5426                         spawn_position = SWM_STACK_ABOVE;
5427                 else if (!strcmp(value, "previous"))
5428                         spawn_position = SWM_STACK_BELOW;
5429                 else
5430                         errx(1, "spawn_position");
5431                 break;
5432         case SWM_S_DISABLE_BORDER:
5433                 disable_border = atoi(value);
5434                 break;
5435         case SWM_S_BORDER_WIDTH:
5436                 border_width = atoi(value);
5437                 break;
5438         case SWM_S_BAR_FONT:
5439                 b = bar_fonts;
5440                 if (asprintf(&bar_fonts, "%s,%s", value, bar_fonts) == -1)
5441                         err(1, "setconfvalue: asprintf: failed to allocate "
5442                                 "memory for bar_fonts.");
5443
5444                 free(b);
5445                 break;
5446         case SWM_S_BAR_ACTION:
5447                 free(bar_argv[0]);
5448                 if ((bar_argv[0] = strdup(value)) == NULL)
5449                         err(1, "setconfvalue: bar_action");
5450                 break;
5451         case SWM_S_SPAWN_TERM:
5452                 free(spawn_term[0]);
5453                 if ((spawn_term[0] = strdup(value)) == NULL)
5454                         err(1, "setconfvalue: spawn_term");
5455                 break;
5456         case SWM_S_SS_APP:
5457                 break;
5458         case SWM_S_DIALOG_RATIO:
5459                 dialog_ratio = atof(value);
5460                 if (dialog_ratio > 1.0 || dialog_ratio <= .3)
5461                         dialog_ratio = .6;
5462                 break;
5463         case SWM_S_VERBOSE_LAYOUT:
5464                 verbose_layout = atoi(value);
5465                 for (i = 0; layouts[i].l_stack != NULL; i++) {
5466                         if (verbose_layout)
5467                                 layouts[i].l_string = fancy_stacker;
5468                         else
5469                                 layouts[i].l_string = plain_stacker;
5470                 }
5471                 break;
5472         default:
5473                 return (1);
5474         }
5475         return (0);
5476 }
5477
5478 int
5479 setconfmodkey(char *selector, char *value, int flags)
5480 {
5481         if (!strncasecmp(value, "Mod1", strlen("Mod1")))
5482                 update_modkey(Mod1Mask);
5483         else if (!strncasecmp(value, "Mod2", strlen("Mod2")))
5484                 update_modkey(Mod2Mask);
5485         else if (!strncasecmp(value, "Mod3", strlen("Mod3")))
5486                 update_modkey(Mod3Mask);
5487         else if (!strncasecmp(value, "Mod4", strlen("Mod4")))
5488                 update_modkey(Mod4Mask);
5489         else
5490                 return (1);
5491         return (0);
5492 }
5493
5494 int
5495 setconfcolor(char *selector, char *value, int flags)
5496 {
5497         setscreencolor(value, ((selector == NULL)?-1:atoi(selector)), flags);
5498         return (0);
5499 }
5500
5501 int
5502 setconfregion(char *selector, char *value, int flags)
5503 {
5504         custom_region(value);
5505         return (0);
5506 }
5507
5508 int
5509 setautorun(char *selector, char *value, int flags)
5510 {
5511         int                     ws_id;
5512         char                    s[1024];
5513         char                    *ap, *sp = s;
5514         union arg               a;
5515         int                     argc = 0;
5516         long                    pid;
5517         struct pid_e            *p;
5518
5519         if (getenv("SWM_STARTED"))
5520                 return (0);
5521
5522         bzero(s, sizeof s);
5523         if (sscanf(value, "ws[%d]:%1023c", &ws_id, s) != 2)
5524                 errx(1, "invalid autorun entry, should be 'ws[<idx>]:command'");
5525         ws_id--;
5526         if (ws_id < 0 || ws_id >= workspace_limit)
5527                 errx(1, "autorun: invalid workspace %d", ws_id + 1);
5528
5529         /*
5530          * This is a little intricate
5531          *
5532          * If the pid already exists we simply reuse it because it means it was
5533          * used before AND not claimed by manage_window.  We get away with
5534          * altering it in the parent after INSERT because this can not be a race
5535          */
5536         a.argv = NULL;
5537         while ((ap = strsep(&sp, " \t")) != NULL) {
5538                 if (*ap == '\0')
5539                         continue;
5540                 DNPRINTF(SWM_D_SPAWN, "setautorun: arg [%s]\n", ap);
5541                 argc++;
5542                 if ((a.argv = realloc(a.argv, argc * sizeof(char *))) == NULL)
5543                         err(1, "setautorun: realloc");
5544                 a.argv[argc - 1] = ap;
5545         }
5546
5547         if ((a.argv = realloc(a.argv, (argc + 1) * sizeof(char *))) == NULL)
5548                 err(1, "setautorun: realloc");
5549         a.argv[argc] = NULL;
5550
5551         if ((pid = fork()) == 0) {
5552                 spawn(ws_id, &a, 1);
5553                 /* NOTREACHED */
5554                 _exit(1);
5555         }
5556         free(a.argv);
5557
5558         /* parent */
5559         p = find_pid(pid);
5560         if (p == NULL) {
5561                 p = calloc(1, sizeof *p);
5562                 if (p == NULL)
5563                         return (1);
5564                 TAILQ_INSERT_TAIL(&pidlist, p, entry);
5565         }
5566
5567         p->pid = pid;
5568         p->ws = ws_id;
5569
5570         return (0);
5571 }
5572
5573 int
5574 setlayout(char *selector, char *value, int flags)
5575 {
5576         int                     ws_id, i, x, mg, ma, si, raise;
5577         int                     st = SWM_V_STACK;
5578         char                    s[1024];
5579         struct workspace        *ws;
5580
5581         if (getenv("SWM_STARTED"))
5582                 return (0);
5583
5584         bzero(s, sizeof s);
5585         if (sscanf(value, "ws[%d]:%d:%d:%d:%d:%1023c",
5586             &ws_id, &mg, &ma, &si, &raise, s) != 6)
5587                 errx(1, "invalid layout entry, should be 'ws[<idx>]:"
5588                     "<master_grow>:<master_add>:<stack_inc>:<always_raise>:"
5589                     "<type>'");
5590         ws_id--;
5591         if (ws_id < 0 || ws_id >= workspace_limit)
5592                 errx(1, "layout: invalid workspace %d", ws_id + 1);
5593
5594         if (!strcasecmp(s, "vertical"))
5595                 st = SWM_V_STACK;
5596         else if (!strcasecmp(s, "horizontal"))
5597                 st = SWM_H_STACK;
5598         else if (!strcasecmp(s, "fullscreen"))
5599                 st = SWM_MAX_STACK;
5600         else
5601                 errx(1, "invalid layout entry, should be 'ws[<idx>]:"
5602                     "<master_grow>:<master_add>:<stack_inc>:<always_raise>:"
5603                     "<type>'");
5604
5605         for (i = 0; i < ScreenCount(display); i++) {
5606                 ws = (struct workspace *)&screens[i].ws;
5607                 ws[ws_id].cur_layout = &layouts[st];
5608
5609                 ws[ws_id].always_raise = raise;
5610                 if (st == SWM_MAX_STACK)
5611                         continue;
5612
5613                 /* master grow */
5614                 for (x = 0; x < abs(mg); x++) {
5615                         ws[ws_id].cur_layout->l_config(&ws[ws_id],
5616                             mg >= 0 ?  SWM_ARG_ID_MASTERGROW :
5617                             SWM_ARG_ID_MASTERSHRINK);
5618                         stack();
5619                 }
5620                 /* master add */
5621                 for (x = 0; x < abs(ma); x++) {
5622                         ws[ws_id].cur_layout->l_config(&ws[ws_id],
5623                             ma >= 0 ?  SWM_ARG_ID_MASTERADD :
5624                             SWM_ARG_ID_MASTERDEL);
5625                         stack();
5626                 }
5627                 /* stack inc */
5628                 for (x = 0; x < abs(si); x++) {
5629                         ws[ws_id].cur_layout->l_config(&ws[ws_id],
5630                             si >= 0 ?  SWM_ARG_ID_STACKINC :
5631                             SWM_ARG_ID_STACKDEC);
5632                         stack();
5633                 }
5634         }
5635
5636         return (0);
5637 }
5638
5639 /* config options */
5640 struct config_option {
5641         char                    *optname;
5642         int                     (*func)(char*, char*, int);
5643         int                     funcflags;
5644 };
5645 struct config_option configopt[] = {
5646         { "bar_enabled",                setconfvalue,   SWM_S_BAR_ENABLED },
5647         { "bar_at_bottom",              setconfvalue,   SWM_S_BAR_AT_BOTTOM },
5648         { "bar_border",                 setconfcolor,   SWM_S_COLOR_BAR_BORDER },
5649         { "bar_border_width",           setconfvalue,   SWM_S_BAR_BORDER_WIDTH },
5650         { "bar_color",                  setconfcolor,   SWM_S_COLOR_BAR },
5651         { "bar_font_color",             setconfcolor,   SWM_S_COLOR_BAR_FONT },
5652         { "bar_font",                   setconfvalue,   SWM_S_BAR_FONT },
5653         { "bar_action",                 setconfvalue,   SWM_S_BAR_ACTION },
5654         { "bar_delay",                  setconfvalue,   SWM_S_BAR_DELAY },
5655         { "bar_justify",                setconfvalue,   SWM_S_BAR_JUSTIFY },
5656         { "keyboard_mapping",           setkeymapping,  0 },
5657         { "bind",                       setconfbinding, 0 },
5658         { "stack_enabled",              setconfvalue,   SWM_S_STACK_ENABLED },
5659         { "clock_enabled",              setconfvalue,   SWM_S_CLOCK_ENABLED },
5660         { "clock_format",               setconfvalue,   SWM_S_CLOCK_FORMAT },
5661         { "color_focus",                setconfcolor,   SWM_S_COLOR_FOCUS },
5662         { "color_unfocus",              setconfcolor,   SWM_S_COLOR_UNFOCUS },
5663         { "cycle_empty",                setconfvalue,   SWM_S_CYCLE_EMPTY },
5664         { "cycle_visible",              setconfvalue,   SWM_S_CYCLE_VISIBLE },
5665         { "workspace_limit",            setconfvalue,   SWM_S_WORKSPACE_LIMIT },
5666         { "dialog_ratio",               setconfvalue,   SWM_S_DIALOG_RATIO },
5667         { "verbose_layout",             setconfvalue,   SWM_S_VERBOSE_LAYOUT },
5668         { "modkey",                     setconfmodkey,  0 },
5669         { "program",                    setconfspawn,   0 },
5670         { "quirk",                      setconfquirk,   0 },
5671         { "region",                     setconfregion,  0 },
5672         { "spawn_term",                 setconfvalue,   SWM_S_SPAWN_TERM },
5673         { "screenshot_enabled",         setconfvalue,   SWM_S_SS_ENABLED },
5674         { "screenshot_app",             setconfvalue,   SWM_S_SS_APP },
5675         { "window_name_enabled",        setconfvalue,   SWM_S_WINDOW_NAME_ENABLED },
5676         { "urgent_enabled",             setconfvalue,   SWM_S_URGENT_ENABLED },
5677         { "term_width",                 setconfvalue,   SWM_S_TERM_WIDTH },
5678         { "title_class_enabled",        setconfvalue,   SWM_S_TITLE_CLASS_ENABLED },
5679         { "title_name_enabled",         setconfvalue,   SWM_S_TITLE_NAME_ENABLED },
5680         { "focus_mode",                 setconfvalue,   SWM_S_FOCUS_MODE },
5681         { "focus_close",                setconfvalue,   SWM_S_FOCUS_CLOSE },
5682         { "focus_close_wrap",           setconfvalue,   SWM_S_FOCUS_CLOSE_WRAP },
5683         { "focus_default",              setconfvalue,   SWM_S_FOCUS_DEFAULT },
5684         { "spawn_position",             setconfvalue,   SWM_S_SPAWN_ORDER },
5685         { "disable_border",             setconfvalue,   SWM_S_DISABLE_BORDER },
5686         { "border_width",               setconfvalue,   SWM_S_BORDER_WIDTH },
5687         { "autorun",                    setautorun,     0 },
5688         { "layout",                     setlayout,      0 },
5689 };
5690
5691
5692 int
5693 conf_load(char *filename, int keymapping)
5694 {
5695         FILE                    *config;
5696         char                    *line, *cp, *optsub, *optval;
5697         size_t                  linelen, lineno = 0;
5698         int                     wordlen, i, optind;
5699         struct config_option    *opt;
5700
5701         DNPRINTF(SWM_D_CONF, "conf_load: begin\n");
5702
5703         if (filename == NULL) {
5704                 warnx("conf_load: no filename");
5705                 return (1);
5706         }
5707         if ((config = fopen(filename, "r")) == NULL) {
5708                 warn("conf_load: fopen: %s", filename);
5709                 return (1);
5710         }
5711
5712         while (!feof(config)) {
5713                 if ((line = fparseln(config, &linelen, &lineno, NULL, 0))
5714                     == NULL) {
5715                         if (ferror(config))
5716                                 err(1, "%s", filename);
5717                         else
5718                                 continue;
5719                 }
5720                 cp = line;
5721                 cp += strspn(cp, " \t\n"); /* eat whitespace */
5722                 if (cp[0] == '\0') {
5723                         /* empty line */
5724                         free(line);
5725                         continue;
5726                 }
5727                 /* get config option */
5728                 wordlen = strcspn(cp, "=[ \t\n");
5729                 if (wordlen == 0) {
5730                         warnx("%s: line %zd: no option found",
5731                             filename, lineno);
5732                         goto out;
5733                 }
5734                 optind = -1;
5735                 for (i = 0; i < LENGTH(configopt); i++) {
5736                         opt = &configopt[i];
5737                         if (!strncasecmp(cp, opt->optname, wordlen) &&
5738                             strlen(opt->optname) == wordlen) {
5739                                 optind = i;
5740                                 break;
5741                         }
5742                 }
5743                 if (optind == -1) {
5744                         warnx("%s: line %zd: unknown option %.*s",
5745                             filename, lineno, wordlen, cp);
5746                         goto out;
5747                 }
5748                 if (keymapping && strcmp(opt->optname, "bind")) {
5749                         warnx("%s: line %zd: invalid option %.*s",
5750                             filename, lineno, wordlen, cp);
5751                         goto out;
5752                 }
5753                 cp += wordlen;
5754                 cp += strspn(cp, " \t\n"); /* eat whitespace */
5755                 /* get [selector] if any */
5756                 optsub = NULL;
5757                 if (*cp == '[') {
5758                         cp++;
5759                         wordlen = strcspn(cp, "]");
5760                         if (*cp != ']') {
5761                                 if (wordlen == 0) {
5762                                         warnx("%s: line %zd: syntax error",
5763                                             filename, lineno);
5764                                         goto out;
5765                                 }
5766
5767                                 if (asprintf(&optsub, "%.*s", wordlen, cp) ==
5768                                     -1) {
5769                                         warnx("%s: line %zd: unable to allocate"
5770                                             "memory for selector", filename,
5771                                             lineno);
5772                                         goto out;
5773                                 }
5774                         }
5775                         cp += wordlen;
5776                         cp += strspn(cp, "] \t\n"); /* eat trailing */
5777                 }
5778                 cp += strspn(cp, "= \t\n"); /* eat trailing */
5779                 /* get RHS value */
5780                 optval = strdup(cp);
5781                 /* call function to deal with it all */
5782                 if (configopt[optind].func(optsub, optval,
5783                     configopt[optind].funcflags) != 0)
5784                         errx(1, "%s: line %zd: invalid data for %s",
5785                             filename, lineno, configopt[optind].optname);
5786                 free(optval);
5787                 free(optsub);
5788                 free(line);
5789         }
5790
5791         fclose(config);
5792         DNPRINTF(SWM_D_CONF, "conf_load: end\n");
5793
5794         return (0);
5795
5796 out:
5797         free(line);
5798         fclose(config);
5799         DNPRINTF(SWM_D_CONF, "conf_load: end with error.\n");
5800
5801         return (1);
5802 }
5803
5804 void
5805 set_child_transient(struct ws_win *win, Window *trans)
5806 {
5807         struct ws_win           *parent, *w;
5808         XWMHints                *wmh = NULL;
5809         struct swm_region       *r;
5810         struct workspace        *ws;
5811
5812         parent = find_window(win->transient);
5813         if (parent)
5814                 parent->child_trans = win;
5815         else {
5816                 DNPRINTF(SWM_D_MISC, "set_child_transient: parent doesn't exist"
5817                     " for 0x%lx trans 0x%lx\n", win->id, win->transient);
5818
5819                 if (win->hints == NULL) {
5820                         warnx("no hints for 0x%lx", win->id);
5821                         return;
5822                 }
5823
5824                 r = root_to_region(win->wa.root);
5825                 ws = r->ws;
5826                 /* parent doen't exist in our window list */
5827                 TAILQ_FOREACH(w, &ws->winlist, entry) {
5828                         if (wmh)
5829                                 XFree(wmh);
5830
5831                         if ((wmh = XGetWMHints(display, w->id)) == NULL) {
5832                                 warnx("can't get hints for 0x%lx", w->id);
5833                                 continue;
5834                         }
5835
5836                         if (win->hints->window_group != wmh->window_group)
5837                                 continue;
5838
5839                         w->child_trans = win;
5840                         win->transient = w->id;
5841                         *trans = w->id;
5842                         DNPRINTF(SWM_D_MISC, "set_child_transient: asjusting "
5843                             "transient to 0x%lx\n", win->transient);
5844                         break;
5845                 }
5846         }
5847
5848         if (wmh)
5849                 XFree(wmh);
5850 }
5851
5852 long
5853 window_get_pid(Window win)
5854 {
5855         Atom                    actual_type_return;
5856         int                     actual_format_return = 0;
5857         unsigned long           nitems_return = 0;
5858         unsigned long           bytes_after_return = 0;
5859         long                    *pid = NULL;
5860         long                    ret = 0;
5861         const char              *errstr;
5862         unsigned char           *prop = NULL;
5863
5864         if (XGetWindowProperty(display, win,
5865             XInternAtom(display, "_NET_WM_PID", False), 0, 1, False,
5866             XA_CARDINAL, &actual_type_return, &actual_format_return,
5867             &nitems_return, &bytes_after_return,
5868             (unsigned char**)(void*)&pid) != Success)
5869                 goto tryharder;
5870         if (actual_type_return != XA_CARDINAL)
5871                 goto tryharder;
5872         if (pid == NULL)
5873                 goto tryharder;
5874
5875         ret = *pid;
5876         XFree(pid);
5877
5878         return (ret);
5879
5880 tryharder:
5881         if (XGetWindowProperty(display, win,
5882             XInternAtom(display, "_SWM_PID", False), 0, SWM_PROPLEN, False,
5883             XA_STRING, &actual_type_return, &actual_format_return,
5884             &nitems_return, &bytes_after_return, &prop) != Success)
5885                 return (0);
5886         if (actual_type_return != XA_STRING)
5887                 return (0);
5888         if (prop == NULL)
5889                 return (0);
5890
5891         ret = strtonum((const char *)prop, 0, UINT_MAX, &errstr);
5892         /* ignore error because strtonum returns 0 anyway */
5893         XFree(prop);
5894
5895         return (ret);
5896 }
5897
5898 struct ws_win *
5899 manage_window(Window id)
5900 {
5901         Window                  trans = 0;
5902         struct workspace        *ws;
5903         struct ws_win           *win, *ww;
5904         int                     format, i, ws_idx, n, border_me = 0;
5905         unsigned long           nitems, bytes;
5906         Atom                    ws_idx_atom = 0, type;
5907         Atom                    *prot = NULL, *pp;
5908         unsigned char           ws_idx_str[SWM_PROPLEN], *prop = NULL;
5909         struct swm_region       *r;
5910         long                    mask = 0;
5911         const char              *errstr;
5912         XWindowChanges          wc;
5913         struct pid_e            *p;
5914         struct quirk            *qp;
5915
5916         if ((win = find_window(id)) != NULL)
5917                 return (win);   /* already being managed */
5918
5919         /* see if we are on the unmanaged list */
5920         if ((win = find_unmanaged_window(id)) != NULL) {
5921                 DNPRINTF(SWM_D_MISC, "manage_window: previously unmanaged "
5922                     "window: 0x%lx\n", win->id);
5923                 TAILQ_REMOVE(&win->ws->unmanagedlist, win, entry);
5924                 if (win->transient)
5925                         set_child_transient(win, &trans);
5926
5927                 if (trans && (ww = find_window(trans)))
5928                         TAILQ_INSERT_AFTER(&win->ws->winlist, ww, win, entry);
5929                 else if ((ww = win->ws->focus) &&
5930                     spawn_position == SWM_STACK_ABOVE)
5931                         TAILQ_INSERT_AFTER(&win->ws->winlist, win->ws->focus, win, entry);
5932                 else if (ww && spawn_position == SWM_STACK_BELOW)
5933                         TAILQ_INSERT_AFTER(&win->ws->winlist, win->ws->focus, win, entry);
5934                 else switch (spawn_position) {
5935                 default:
5936                 case SWM_STACK_TOP:
5937                 case SWM_STACK_ABOVE:
5938                         TAILQ_INSERT_TAIL(&win->ws->winlist, win, entry);
5939                         break;
5940                 case SWM_STACK_BOTTOM:
5941                 case SWM_STACK_BELOW:
5942                         TAILQ_INSERT_HEAD(&win->ws->winlist, win, entry);
5943                 }
5944
5945                 ewmh_update_actions(win);
5946                 return (win);
5947         }
5948
5949         if ((win = calloc(1, sizeof(struct ws_win))) == NULL)
5950                 err(1, "manage_window: calloc: failed to allocate memory for "
5951                     "new window");
5952
5953         win->id = id;
5954
5955         /* see if we need to override the workspace */
5956         p = find_pid(window_get_pid(id));
5957
5958         /* Get all the window data in one shot */
5959         ws_idx_atom = XInternAtom(display, "_SWM_WS", False);
5960         if (ws_idx_atom) {
5961                 XGetWindowProperty(display, id, ws_idx_atom, 0, SWM_PROPLEN,
5962                     False, XA_STRING, &type, &format, &nitems, &bytes, &prop);
5963         }
5964         XGetWindowAttributes(display, id, &win->wa);
5965         XGetWMNormalHints(display, id, &win->sh, &win->sh_mask);
5966         win->hints = XGetWMHints(display, id);
5967         XGetTransientForHint(display, id, &trans);
5968         if (trans) {
5969                 win->transient = trans;
5970                 set_child_transient(win, &trans);
5971                 DNPRINTF(SWM_D_MISC, "manage_window: window: 0x%lx, "
5972                     "transient: 0x%lx\n", win->id, win->transient);
5973         }
5974
5975         /* get supported protocols */
5976         if (XGetWMProtocols(display, id, &prot, &n)) {
5977                 for (i = 0, pp = prot; i < n; i++, pp++) {
5978                         if (*pp == takefocus)
5979                                 win->take_focus = 1;
5980                         if (*pp == adelete)
5981                                 win->can_delete = 1;
5982                 }
5983                 if (prot)
5984                         XFree(prot);
5985         }
5986
5987         win->iconic = get_iconic(win);
5988
5989         /*
5990          * Figure out where to put the window. If it was previously assigned to
5991          * a workspace (either by spawn() or manually moving), and isn't
5992          * transient, * put it in the same workspace
5993          */
5994         r = root_to_region(win->wa.root);
5995         if (p) {
5996                 ws = &r->s->ws[p->ws];
5997                 TAILQ_REMOVE(&pidlist, p, entry);
5998                 free(p);
5999                 p = NULL;
6000         } else if (prop && win->transient == 0) {
6001                 DNPRINTF(SWM_D_PROP, "manage_window: get _SWM_WS: %s\n", prop);
6002                 ws_idx = strtonum((const char *)prop, 0, workspace_limit - 1,
6003                     &errstr);
6004                 if (errstr) {
6005                         DNPRINTF(SWM_D_EVENT, "manage_window: window: #%s: %s",
6006                             errstr, prop);
6007                 }
6008                 ws = &r->s->ws[ws_idx];
6009         } else {
6010                 ws = r->ws;
6011                 /* this should launch transients in the same ws as parent */
6012                 if (id && trans)
6013                         if ((ww = find_window(trans)) != NULL)
6014                                 if (ws->r) {
6015                                         ws = ww->ws;
6016                                         if (ww->ws->r)
6017                                                 r = ww->ws->r;
6018                                         else
6019                                                 warnx("manage_window: fix this "
6020                                                     "bug mcbride");
6021                                         border_me = 1;
6022                                 }
6023         }
6024
6025         /* set up the window layout */
6026         win->id = id;
6027         win->ws = ws;
6028         win->s = r->s;  /* this never changes */
6029         if (trans && (ww = find_window(trans)))
6030                 TAILQ_INSERT_AFTER(&ws->winlist, ww, win, entry);
6031         else if (spawn_position == SWM_STACK_ABOVE && win->ws->focus)
6032                 TAILQ_INSERT_AFTER(&win->ws->winlist, win->ws->focus, win, entry);
6033         else
6034                 TAILQ_INSERT_TAIL(&ws->winlist, win, entry);
6035
6036         WIDTH(win) = win->wa.width;
6037         HEIGHT(win) = win->wa.height;
6038         X(win) = win->wa.x;
6039         Y(win) = win->wa.y;
6040         win->g_floatvalid = 0;
6041         win->floatmaxed = 0;
6042         win->ewmh_flags = 0;
6043
6044         /* Set window properties so we can remember this after reincarnation */
6045         if (ws_idx_atom && prop == NULL &&
6046             snprintf((char *)ws_idx_str, SWM_PROPLEN, "%d", ws->idx) <
6047                 SWM_PROPLEN) {
6048                 DNPRINTF(SWM_D_PROP, "manage_window: set _SWM_WS: %s\n",
6049                     ws_idx_str);
6050                 XChangeProperty(display, win->id, ws_idx_atom, XA_STRING, 8,
6051                     PropModeReplace, ws_idx_str, strlen((char *)ws_idx_str));
6052         }
6053         if (prop)
6054                 XFree(prop);
6055
6056         ewmh_autoquirk(win);
6057
6058         if (XGetClassHint(display, win->id, &win->ch)) {
6059                 DNPRINTF(SWM_D_CLASS, "manage_window: class: %s, name: %s\n",
6060                     win->ch.res_class, win->ch.res_name);
6061
6062                 /* java is retarded so treat it special */
6063                 if (strstr(win->ch.res_name, "sun-awt")) {
6064                         win->java = 1;
6065                         border_me = 1;
6066                 }
6067
6068                 TAILQ_FOREACH(qp, &quirks, entry) {
6069                         if (!strcmp(win->ch.res_class, qp->class) &&
6070                             !strcmp(win->ch.res_name, qp->name)) {
6071                                 DNPRINTF(SWM_D_CLASS, "manage_window: found: "
6072                                     "class: %s, name: %s\n", win->ch.res_class,
6073                                     win->ch.res_name);
6074                                 if (qp->quirk & SWM_Q_FLOAT) {
6075                                         win->floating = 1;
6076                                         border_me = 1;
6077                                 }
6078                                 win->quirks = qp->quirk;
6079                         }
6080                 }
6081         }
6082
6083         /* alter window position if quirky */
6084         if (win->quirks & SWM_Q_ANYWHERE) {
6085                 win->manual = 1; /* don't center the quirky windows */
6086                 bzero(&wc, sizeof wc);
6087                 mask = 0;
6088                 if (bar_enabled && Y(win) < bar_height) {
6089                         Y(win) = wc.y = bar_height;
6090                         mask |= CWY;
6091                 }
6092                 if (WIDTH(win) + X(win) > WIDTH(r)) {
6093                         X(win) = wc.x = WIDTH(r) - WIDTH(win) - 2;
6094                         mask |= CWX;
6095                 }
6096                 border_me = 1;
6097         }
6098
6099         /* Reset font sizes (the bruteforce way; no default keybinding). */
6100         if (win->quirks & SWM_Q_XTERM_FONTADJ) {
6101                 for (i = 0; i < SWM_MAX_FONT_STEPS; i++)
6102                         fake_keypress(win, XK_KP_Subtract, ShiftMask);
6103                 for (i = 0; i < SWM_MAX_FONT_STEPS; i++)
6104                         fake_keypress(win, XK_KP_Add, ShiftMask);
6105         }
6106
6107         ewmh_get_win_state(win);
6108         ewmh_update_actions(win);
6109         ewmh_update_win_state(win, None, _NET_WM_STATE_REMOVE);
6110
6111         /* border me */
6112         if (border_me) {
6113                 bzero(&wc, sizeof wc);
6114                 wc.border_width = border_width;
6115                 mask |= CWBorderWidth;
6116                 XConfigureWindow(display, win->id, mask, &wc);
6117         }
6118
6119         XSelectInput(display, id, EnterWindowMask | FocusChangeMask |
6120             PropertyChangeMask | StructureNotifyMask);
6121
6122         /* floaters need to be mapped if they are in the current workspace */
6123         if ((win->floating || win->transient) && (ws->idx == r->ws->idx))
6124                 XMapRaised(display, win->id);
6125
6126         return (win);
6127 }
6128
6129 void
6130 free_window(struct ws_win *win)
6131 {
6132         DNPRINTF(SWM_D_MISC, "free_window: window: 0x%lx\n", win->id);
6133
6134         if (win == NULL)
6135                 return;
6136
6137         /* needed for restart wm */
6138         set_win_state(win, WithdrawnState);
6139
6140         TAILQ_REMOVE(&win->ws->unmanagedlist, win, entry);
6141
6142         if (win->ch.res_class)
6143                 XFree(win->ch.res_class);
6144         if (win->ch.res_name)
6145                 XFree(win->ch.res_name);
6146
6147         kill_refs(win);
6148
6149         /* paint memory */
6150         memset(win, 0xff, sizeof *win); /* XXX kill later */
6151
6152         free(win);
6153 }
6154
6155 void
6156 unmanage_window(struct ws_win *win)
6157 {
6158         struct ws_win           *parent;
6159
6160         if (win == NULL)
6161                 return;
6162
6163         DNPRINTF(SWM_D_MISC, "unmanage_window: window: 0x%lx\n", win->id);
6164
6165         if (win->transient) {
6166                 parent = find_window(win->transient);
6167                 if (parent)
6168                         parent->child_trans = NULL;
6169         }
6170
6171         /* focus on root just in case */
6172         XSetInputFocus(display, PointerRoot, PointerRoot, CurrentTime);
6173
6174         focus_prev(win);
6175
6176         if (win->hints) {
6177                 XFree(win->hints);
6178                 win->hints = NULL;
6179         }
6180
6181         TAILQ_REMOVE(&win->ws->winlist, win, entry);
6182         TAILQ_INSERT_TAIL(&win->ws->unmanagedlist, win, entry);
6183 }
6184
6185 void
6186 focus_magic(struct ws_win *win)
6187 {
6188         DNPRINTF(SWM_D_FOCUS, "focus_magic: window: 0x%lx\n", WINID(win));
6189
6190         if (win == NULL) {
6191                 /* if there are no windows clear the status-bar */
6192                 bar_update();
6193                 return;
6194         }
6195
6196         if (win->child_trans) {
6197                 /* win = parent & has a transient so focus on that */
6198                 if (win->java) {
6199                         focus_win(win->child_trans);
6200                         if (win->child_trans->take_focus)
6201                                 client_msg(win, takefocus);
6202                 } else {
6203                         /* make sure transient hasn't disappeared */
6204                         if (validate_win(win->child_trans) == 0) {
6205                                 focus_win(win->child_trans);
6206                                 if (win->child_trans->take_focus)
6207                                         client_msg(win->child_trans, takefocus);
6208                         } else {
6209                                 win->child_trans = NULL;
6210                                 focus_win(win);
6211                                 if (win->take_focus)
6212                                         client_msg(win, takefocus);
6213                         }
6214                 }
6215         } else {
6216                 /* regular focus */
6217                 focus_win(win);
6218                 if (win->take_focus)
6219                         client_msg(win, takefocus);
6220         }
6221 }
6222
6223 void
6224 expose(XEvent *e)
6225 {
6226         DNPRINTF(SWM_D_EVENT, "expose: window: 0x%lx\n", e->xexpose.window);
6227 }
6228
6229 void
6230 keypress(XEvent *e)
6231 {
6232         KeySym                  keysym;
6233         XKeyEvent               *ev = &e->xkey;
6234         struct key              *kp;
6235         struct swm_region       *r;
6236
6237         keysym = XkbKeycodeToKeysym(display, (KeyCode)ev->keycode, 0, 0);
6238         if ((kp = key_lookup(CLEANMASK(ev->state), keysym)) == NULL)
6239                 return;
6240         if (keyfuncs[kp->funcid].func == NULL)
6241                 return;
6242
6243         r = root_to_region(ev->root);
6244         if (kp->funcid == kf_spawn_custom)
6245                 spawn_custom(r, &(keyfuncs[kp->funcid].args), kp->spawn_name);
6246         else
6247                 keyfuncs[kp->funcid].func(r, &(keyfuncs[kp->funcid].args));
6248 }
6249
6250 void
6251 buttonpress(XEvent *e)
6252 {
6253         struct ws_win           *win;
6254         int                     i, action;
6255         XButtonPressedEvent     *ev = &e->xbutton;
6256
6257         if ((win = find_window(ev->window)) == NULL)
6258                 return;
6259
6260         focus_magic(win);
6261         action = client_click;
6262
6263         for (i = 0; i < LENGTH(buttons); i++)
6264                 if (action == buttons[i].action && buttons[i].func &&
6265                     buttons[i].button == ev->button &&
6266                     CLEANMASK(buttons[i].mask) == CLEANMASK(ev->state))
6267                         buttons[i].func(win, &buttons[i].args);
6268 }
6269
6270 void
6271 configurerequest(XEvent *e)
6272 {
6273         XConfigureRequestEvent  *ev = &e->xconfigurerequest;
6274         struct ws_win           *win;
6275         int                     new = 0;
6276         XWindowChanges          wc;
6277
6278         if ((win = find_window(ev->window)) == NULL)
6279                 if ((win = find_unmanaged_window(ev->window)) == NULL)
6280                         new = 1;
6281
6282         DNPRINTF(SWM_D_EVENT, "configurerequest: window: 0x%lx, new: %s\n",
6283             ev->window, YESNO(new));
6284
6285         if (new) {
6286                 bzero(&wc, sizeof wc);
6287                 wc.x = ev->x;
6288                 wc.y = ev->y;
6289                 wc.width = ev->width;
6290                 wc.height = ev->height;
6291                 wc.border_width = ev->border_width;
6292                 wc.sibling = ev->above;
6293                 wc.stack_mode = ev->detail;
6294                 XConfigureWindow(display, ev->window, ev->value_mask, &wc);
6295         } else
6296                 config_win(win, ev);
6297 }
6298
6299 void
6300 configurenotify(XEvent *e)
6301 {
6302         struct ws_win           *win;
6303
6304         DNPRINTF(SWM_D_EVENT, "configurenotify: window: 0x%lx\n",
6305             e->xconfigure.window);
6306
6307         win = find_window(e->xconfigure.window);
6308         if (win) {
6309                 XGetWMNormalHints(display, win->id, &win->sh, &win->sh_mask);
6310                 adjust_font(win);
6311                 if (font_adjusted)
6312                         stack();
6313                 if (focus_mode == SWM_FOCUS_DEFAULT)
6314                         drain_enter_notify();
6315         }
6316 }
6317
6318 void
6319 destroynotify(XEvent *e)
6320 {
6321         struct ws_win           *win;
6322         XDestroyWindowEvent     *ev = &e->xdestroywindow;
6323
6324         DNPRINTF(SWM_D_EVENT, "destroynotify: window: 0x%lx\n", ev->window);
6325
6326         if ((win = find_window(ev->window)) == NULL) {
6327                 if ((win = find_unmanaged_window(ev->window)) == NULL)
6328                         return;
6329                 free_window(win);
6330                 return;
6331         }
6332
6333         /* make sure we focus on something */
6334         win->floating = 0;
6335
6336         unmanage_window(win);
6337         stack();
6338         if (focus_mode == SWM_FOCUS_DEFAULT)
6339                 drain_enter_notify();
6340         free_window(win);
6341 }
6342
6343 void
6344 enternotify(XEvent *e)
6345 {
6346         XCrossingEvent          *ev = &e->xcrossing;
6347         XEvent                  cne;
6348         struct ws_win           *win;
6349 #if 0
6350         struct ws_win           *w;
6351         Window                  focus_return;
6352         int                     revert_to_return;
6353 #endif
6354         DNPRINTF(SWM_D_FOCUS, "enternotify: window: 0x%lx, mode: %d, detail: "
6355             "%d, root: 0x%lx, subwindow: 0x%lx, same_screen: %s, focus: %s, "
6356             "state: %d\n", ev->window, ev->mode, ev->detail, ev->root,
6357             ev->subwindow, YESNO(ev->same_screen), YESNO(ev->focus), ev->state);
6358
6359         if (ev->mode != NotifyNormal) {
6360                 DNPRINTF(SWM_D_EVENT, "skip enternotify: generated by "
6361                     "cursor grab.\n");
6362                 return;
6363         }
6364
6365         switch (focus_mode) {
6366         case SWM_FOCUS_DEFAULT:
6367                 break;
6368         case SWM_FOCUS_FOLLOW:
6369                 break;
6370         case SWM_FOCUS_SYNERGY:
6371 #if 0
6372         /*
6373          * all these checks need to be in this order because the
6374          * XCheckTypedWindowEvent relies on weeding out the previous events
6375          *
6376          * making this code an option would enable a follow mouse for focus
6377          * feature
6378          */
6379
6380         /*
6381          * state is set when we are switching workspaces and focus is set when
6382          * the window or a subwindow already has focus (occurs during restart).
6383          *
6384          * Only honor the focus flag if last_focus_event is not FocusOut,
6385          * this allows spectrwm to continue to control focus when another
6386          * program is also playing with it.
6387          */
6388         if (ev->state || (ev->focus && last_focus_event != FocusOut)) {
6389                 DNPRINTF(SWM_D_EVENT, "ignoring enternotify: focus\n");
6390                 return;
6391         }
6392
6393         /*
6394          * happens when a window is created or destroyed and the border
6395          * crosses the mouse pointer and when switching ws
6396          *
6397          * we need the subwindow test to see if we came from root in order
6398          * to give focus to floaters
6399          */
6400         if (ev->mode == NotifyNormal && ev->detail == NotifyVirtual &&
6401             ev->subwindow == 0) {
6402                 DNPRINTF(SWM_D_EVENT, "ignoring enternotify: NotifyVirtual\n");
6403                 return;
6404         }
6405
6406         /* this window already has focus */
6407         if (ev->mode == NotifyNormal && ev->detail == NotifyInferior) {
6408                 DNPRINTF(SWM_D_EVENT, "ignoring enternotify: win has focus\n");
6409                 return;
6410         }
6411
6412         /* this window is being deleted or moved to another ws */
6413         if (XCheckTypedWindowEvent(display, ev->window, ConfigureNotify,
6414             &cne) == True) {
6415                 DNPRINTF(SWM_D_EVENT, "ignoring enternotify: configurenotify\n");
6416                 XPutBackEvent(display, &cne);
6417                 return;
6418         }
6419
6420         if ((win = find_window(ev->window)) == NULL) {
6421                 DNPRINTF(SWM_D_EVENT, "ignoring enternotify: win == NULL\n");
6422                 return;
6423         }
6424
6425         /*
6426          * In fullstack kill all enters unless they come from a different ws
6427          * (i.e. another region) or focus has been grabbed externally.
6428          */
6429         if (win->ws->cur_layout->flags & SWM_L_FOCUSPREV &&
6430             last_focus_event != FocusOut) {
6431                 XGetInputFocus(display, &focus_return, &revert_to_return);
6432                 if ((w = find_window(focus_return)) == NULL ||
6433                     w->ws == win->ws) {
6434                         DNPRINTF(SWM_D_EVENT, "ignoring event: fullstack\n");
6435                         return;
6436                 }
6437         }
6438 #endif
6439                 break;
6440         }
6441
6442         if ((win = find_window(ev->window)) == NULL) {
6443                 DNPRINTF(SWM_D_EVENT, "skip enternotify: window is NULL\n");
6444                 return;
6445         }
6446
6447         /*
6448          * if we have more enternotifies let them handle it in due time
6449          */
6450         if (XCheckTypedEvent(display, EnterNotify, &cne) == True) {
6451                 DNPRINTF(SWM_D_EVENT,
6452                     "ignoring enternotify: got more enternotify\n");
6453                 XPutBackEvent(display, &cne);
6454                 return;
6455         }
6456
6457         focus_magic(win);
6458 }
6459
6460 /* lets us use one switch statement for arbitrary mode/detail combinations */
6461 #define MERGE_MEMBERS(a,b)      (((a & 0xffff) << 16) | (b & 0xffff))
6462
6463 void
6464 focusevent(XEvent *e)
6465 {
6466 #if 0
6467         struct ws_win           *win;
6468         u_int32_t               mode_detail;
6469         XFocusChangeEvent       *ev = &e->xfocus;
6470
6471         DNPRINTF(SWM_D_EVENT, "focusevent: %s window: 0x%lx mode: %d "
6472             "detail: %d\n", ev->type == FocusIn ? "entering" : "leaving",
6473             ev->window, ev->mode, ev->detail);
6474
6475         if (last_focus_event == ev->type) {
6476                 DNPRINTF(SWM_D_FOCUS, "ignoring focusevent: bad ordering\n");
6477                 return;
6478         }
6479
6480         last_focus_event = ev->type;
6481         mode_detail = MERGE_MEMBERS(ev->mode, ev->detail);
6482
6483         switch (mode_detail) {
6484         /* synergy client focus operations */
6485         case MERGE_MEMBERS(NotifyNormal, NotifyNonlinear):
6486         case MERGE_MEMBERS(NotifyNormal, NotifyNonlinearVirtual):
6487
6488         /* synergy server focus operations */
6489         case MERGE_MEMBERS(NotifyWhileGrabbed, NotifyNonlinear):
6490
6491         /* Entering applications like rdesktop that mangle the pointer */
6492         case MERGE_MEMBERS(NotifyNormal, NotifyPointer):
6493
6494                 if ((win = find_window(e->xfocus.window)) != NULL && win->ws->r)
6495                         XSetWindowBorder(display, win->id,
6496                             win->ws->r->s->c[ev->type == FocusIn ?
6497                             SWM_S_COLOR_FOCUS : SWM_S_COLOR_UNFOCUS].color);
6498                 break;
6499         default:
6500                 warnx("ignoring focusevent");
6501                 DNPRINTF(SWM_D_FOCUS, "ignoring focusevent\n");
6502                 break;
6503         }
6504 #endif
6505 }
6506
6507 void
6508 mapnotify(XEvent *e)
6509 {
6510         struct ws_win           *win;
6511         XMapEvent               *ev = &e->xmap;
6512
6513         DNPRINTF(SWM_D_EVENT, "mapnotify: window: 0x%lx\n", ev->window);
6514
6515         win = manage_window(ev->window);
6516         if (win)
6517                 set_win_state(win, NormalState);
6518
6519         /*
6520          * focus_win can only set input focus on a mapped window.
6521          * make sure the window really has focus since it is just being mapped.
6522          */
6523         if (win->ws->focus == win)
6524                 focus_win(win);
6525 }
6526
6527 void
6528 mappingnotify(XEvent *e)
6529 {
6530         XMappingEvent           *ev = &e->xmapping;
6531
6532         XRefreshKeyboardMapping(ev);
6533         if (ev->request == MappingKeyboard)
6534                 grabkeys();
6535 }
6536
6537 void
6538 maprequest(XEvent *e)
6539 {
6540         struct ws_win           *win;
6541         struct swm_region       *r;
6542         XWindowAttributes       wa;
6543         XMapRequestEvent        *ev = &e->xmaprequest;
6544
6545         DNPRINTF(SWM_D_EVENT, "maprequest: window: 0x%lx\n",
6546             e->xmaprequest.window);
6547
6548         if (!XGetWindowAttributes(display, ev->window, &wa))
6549                 return;
6550         if (wa.override_redirect)
6551                 return;
6552
6553         win = manage_window(e->xmaprequest.window);
6554         if (win == NULL)
6555                 return; /* can't happen */
6556
6557         stack();
6558
6559         /* make new win focused */
6560         r = root_to_region(win->wa.root);
6561         if (win->ws == r->ws)
6562                 focus_magic(win);
6563 }
6564
6565 void
6566 propertynotify(XEvent *e)
6567 {
6568         struct ws_win           *win;
6569         XPropertyEvent          *ev = &e->xproperty;
6570 #ifdef SWM_DEBUG
6571         char                    *name;
6572         name = XGetAtomName(display, ev->atom);
6573         DNPRINTF(SWM_D_EVENT, "propertynotify: window: 0x%lx, atom: %s\n",
6574             ev->window, name);
6575         XFree(name);
6576 #endif
6577
6578         win = find_window(ev->window);
6579         if (win == NULL)
6580                 return;
6581
6582         if (ev->state == PropertyDelete && ev->atom == a_swm_iconic) {
6583                 update_iconic(win, 0);
6584                 XMapRaised(display, win->id);
6585                 stack();
6586                 focus_win(win);
6587                 return;
6588         }
6589
6590         switch (ev->atom) {
6591 #if 0
6592         case XA_WM_NORMAL_HINTS:
6593                 long            mask;
6594                 XGetWMNormalHints(display, win->id, &win->sh, &mask);
6595                 warnx("normal hints: flag 0x%x", win->sh.flags);
6596                 if (win->sh.flags & PMinSize) {
6597                         WIDTH(win) = win->sh.min_width;
6598                         HEIGHT(win) = win->sh.min_height;
6599                         warnx("min %d %d", WIDTH(win), HEIGHT(win));
6600                 }
6601                 XMoveResizeWindow(display, win->id,
6602                     X(win), Y(win), WIDTH(win), HEIGHT(win));
6603 #endif
6604         case XA_WM_CLASS:
6605         case XA_WM_NAME:
6606                 bar_update();
6607                 break;
6608         default:
6609                 break;
6610         }
6611 }
6612
6613 void
6614 unmapnotify(XEvent *e)
6615 {
6616         struct ws_win           *win;
6617
6618         DNPRINTF(SWM_D_EVENT, "unmapnotify: window: 0x%lx\n", e->xunmap.window);
6619
6620         /* determine if we need to help unmanage this window */
6621         win = find_window(e->xunmap.window);
6622         if (win == NULL)
6623                 return;
6624
6625         if (getstate(e->xunmap.window) == NormalState) {
6626                 unmanage_window(win);
6627                 stack();
6628
6629                 /* giant hack for apps that don't destroy transient windows */
6630                 /* eat a bunch of events to prevent remanaging the window */
6631                 XEvent                  cne;
6632                 while (XCheckWindowEvent(display, e->xunmap.window,
6633                     EnterWindowMask, &cne))
6634                         ;
6635                 while (XCheckWindowEvent(display, e->xunmap.window,
6636                     StructureNotifyMask, &cne))
6637                         ;
6638                 while (XCheckWindowEvent(display, e->xunmap.window,
6639                     SubstructureNotifyMask, &cne))
6640                         ;
6641                 /* resend unmap because we ated it */
6642                 XUnmapWindow(display, e->xunmap.window);
6643         }
6644
6645         if (focus_mode == SWM_FOCUS_DEFAULT)
6646                 drain_enter_notify();
6647 }
6648
6649 void
6650 visibilitynotify(XEvent *e)
6651 {
6652         int                     i;
6653         struct swm_region       *r;
6654
6655         DNPRINTF(SWM_D_EVENT, "visibilitynotify: window: 0x%lx\n",
6656             e->xvisibility.window);
6657         if (e->xvisibility.state == VisibilityUnobscured)
6658                 for (i = 0; i < ScreenCount(display); i++)
6659                         TAILQ_FOREACH(r, &screens[i].rl, entry)
6660                                 if (e->xvisibility.window == r->bar_window)
6661                                         bar_update();
6662 }
6663
6664 void
6665 clientmessage(XEvent *e)
6666 {
6667         XClientMessageEvent *ev;
6668         struct ws_win *win;
6669
6670         ev = &e->xclient;
6671
6672         win = find_window(ev->window);
6673         if (win == NULL)
6674                 return;
6675
6676         DNPRINTF(SWM_D_EVENT, "clientmessage: window: 0x%lx, type: %ld\n",
6677             ev->window, ev->message_type);
6678
6679         if (ev->message_type == ewmh[_NET_ACTIVE_WINDOW].atom) {
6680                 DNPRINTF(SWM_D_EVENT, "clientmessage: _NET_ACTIVE_WINDOW\n");
6681                 focus_win(win);
6682         }
6683         if (ev->message_type == ewmh[_NET_CLOSE_WINDOW].atom) {
6684                 DNPRINTF(SWM_D_EVENT, "clientmessage: _NET_CLOSE_WINDOW\n");
6685                 if (win->can_delete)
6686                         client_msg(win, adelete);
6687                 else
6688                         XKillClient(display, win->id);
6689         }
6690         if (ev->message_type == ewmh[_NET_MOVERESIZE_WINDOW].atom) {
6691                 DNPRINTF(SWM_D_EVENT,
6692                     "clientmessage: _NET_MOVERESIZE_WINDOW\n");
6693                 if (win->floating) {
6694                         if (ev->data.l[0] & (1<<8)) /* x */
6695                                 X(win) = ev->data.l[1];
6696                         if (ev->data.l[0] & (1<<9)) /* y */
6697                                 Y(win) = ev->data.l[2];
6698                         if (ev->data.l[0] & (1<<10)) /* width */
6699                                 WIDTH(win) = ev->data.l[3];
6700                         if (ev->data.l[0] & (1<<11)) /* height */
6701                                 HEIGHT(win) = ev->data.l[4];
6702
6703                         update_window(win);
6704                 }
6705                 else {
6706                         /* TODO: Change stack sizes */
6707                         /* notify no change was made. */
6708                         config_win(win, NULL);
6709                 }
6710         }
6711         if (ev->message_type == ewmh[_NET_WM_STATE].atom) {
6712                 DNPRINTF(SWM_D_EVENT, "clientmessage: _NET_WM_STATE\n");
6713                 ewmh_update_win_state(win, ev->data.l[1], ev->data.l[0]);
6714                 if (ev->data.l[2])
6715                         ewmh_update_win_state(win, ev->data.l[2],
6716                             ev->data.l[0]);
6717
6718                 stack();
6719         }
6720 }
6721
6722 int
6723 xerror_start(Display *d, XErrorEvent *ee)
6724 {
6725         other_wm = 1;
6726         return (-1);
6727 }
6728
6729 int
6730 xerror(Display *d, XErrorEvent *ee)
6731 {
6732         /* warnx("error: %p %p", display, ee); */
6733         return (-1);
6734 }
6735
6736 int
6737 active_wm(void)
6738 {
6739         other_wm = 0;
6740         xerrorxlib = XSetErrorHandler(xerror_start);
6741
6742         /* this causes an error if some other window manager is running */
6743         XSelectInput(display, DefaultRootWindow(display),
6744             SubstructureRedirectMask);
6745         XSync(display, False);
6746         if (other_wm)
6747                 return (1);
6748
6749         XSetErrorHandler(xerror);
6750         XSync(display, False);
6751         return (0);
6752 }
6753
6754 void
6755 new_region(struct swm_screen *s, int x, int y, int w, int h)
6756 {
6757         struct swm_region       *r, *n;
6758         struct workspace        *ws = NULL;
6759         int                     i;
6760
6761         DNPRINTF(SWM_D_MISC, "new region: screen[%d]:%dx%d+%d+%d\n",
6762              s->idx, w, h, x, y);
6763
6764         /* remove any conflicting regions */
6765         n = TAILQ_FIRST(&s->rl);
6766         while (n) {
6767                 r = n;
6768                 n = TAILQ_NEXT(r, entry);
6769                 if (X(r) < (x + w) &&
6770                     (X(r) + WIDTH(r)) > x &&
6771                     Y(r) < (y + h) &&
6772                     (Y(r) + HEIGHT(r)) > y) {
6773                         if (r->ws->r != NULL)
6774                                 r->ws->old_r = r->ws->r;
6775                         r->ws->r = NULL;
6776                         XDestroyWindow(display, r->bar_window);
6777                         TAILQ_REMOVE(&s->rl, r, entry);
6778                         TAILQ_INSERT_TAIL(&s->orl, r, entry);
6779                 }
6780         }
6781
6782         /* search old regions for one to reuse */
6783
6784         /* size + location match */
6785         TAILQ_FOREACH(r, &s->orl, entry)
6786                 if (X(r) == x && Y(r) == y &&
6787                     HEIGHT(r) == h && WIDTH(r) == w)
6788                         break;
6789
6790         /* size match */
6791         TAILQ_FOREACH(r, &s->orl, entry)
6792                 if (HEIGHT(r) == h && WIDTH(r) == w)
6793                         break;
6794
6795         if (r != NULL) {
6796                 TAILQ_REMOVE(&s->orl, r, entry);
6797                 /* try to use old region's workspace */
6798                 if (r->ws->r == NULL)
6799                         ws = r->ws;
6800         } else
6801                 if ((r = calloc(1, sizeof(struct swm_region))) == NULL)
6802                         err(1, "new_region: calloc: failed to allocate memory "
6803                             "for screen");
6804
6805         /* if we don't have a workspace already, find one */
6806         if (ws == NULL) {
6807                 for (i = 0; i < workspace_limit; i++)
6808                         if (s->ws[i].r == NULL) {
6809                                 ws = &s->ws[i];
6810                                 break;
6811                         }
6812         }
6813
6814         if (ws == NULL)
6815                 errx(1, "new_region: no free workspaces");
6816
6817         X(r) = x;
6818         Y(r) = y;
6819         WIDTH(r) = w;
6820         HEIGHT(r) = h;
6821         r->s = s;
6822         r->ws = ws;
6823         r->ws_prior = NULL;
6824         ws->r = r;
6825         outputs++;
6826         TAILQ_INSERT_TAIL(&s->rl, r, entry);
6827 }
6828
6829 void
6830 scan_xrandr(int i)
6831 {
6832 #ifdef SWM_XRR_HAS_CRTC
6833         XRRCrtcInfo             *ci;
6834         XRRScreenResources      *sr;
6835         int                     c;
6836         int                     ncrtc = 0;
6837 #endif /* SWM_XRR_HAS_CRTC */
6838         struct swm_region       *r;
6839
6840
6841         if (i >= ScreenCount(display))
6842                 errx(1, "scan_xrandr: invalid screen");
6843
6844         /* remove any old regions */
6845         while ((r = TAILQ_FIRST(&screens[i].rl)) != NULL) {
6846                 r->ws->old_r = r->ws->r = NULL;
6847                 XDestroyWindow(display, r->bar_window);
6848                 TAILQ_REMOVE(&screens[i].rl, r, entry);
6849                 TAILQ_INSERT_TAIL(&screens[i].orl, r, entry);
6850         }
6851         outputs = 0;
6852
6853         /* map virtual screens onto physical screens */
6854 #ifdef SWM_XRR_HAS_CRTC
6855         if (xrandr_support) {
6856                 sr = XRRGetScreenResources(display, screens[i].root);
6857                 if (sr == NULL)
6858                         new_region(&screens[i], 0, 0,
6859                             DisplayWidth(display, i),
6860                             DisplayHeight(display, i));
6861                 else
6862                         ncrtc = sr->ncrtc;
6863
6864                 for (c = 0, ci = NULL; c < ncrtc; c++) {
6865                         ci = XRRGetCrtcInfo(display, sr, sr->crtcs[c]);
6866                         if (ci->noutput == 0)
6867                                 continue;
6868
6869                         if (ci != NULL && ci->mode == None)
6870                                 new_region(&screens[i], 0, 0,
6871                                     DisplayWidth(display, i),
6872                                     DisplayHeight(display, i));
6873                         else
6874                                 new_region(&screens[i],
6875                                     ci->x, ci->y, ci->width, ci->height);
6876                 }
6877                 if (ci)
6878                         XRRFreeCrtcInfo(ci);
6879                 XRRFreeScreenResources(sr);
6880         } else
6881 #endif /* SWM_XRR_HAS_CRTC */
6882         {
6883                 new_region(&screens[i], 0, 0, DisplayWidth(display, i),
6884                     DisplayHeight(display, i));
6885         }
6886 }
6887
6888 void
6889 screenchange(XEvent *e) {
6890         XRRScreenChangeNotifyEvent      *xe = (XRRScreenChangeNotifyEvent *)e;
6891         struct swm_region               *r;
6892         int                             i;
6893
6894         DNPRINTF(SWM_D_EVENT, "screenchange: root: 0x%lx\n", xe->root);
6895
6896         if (!XRRUpdateConfiguration(e))
6897                 return;
6898
6899         /* silly event doesn't include the screen index */
6900         for (i = 0; i < ScreenCount(display); i++)
6901                 if (screens[i].root == xe->root)
6902                         break;
6903         if (i >= ScreenCount(display))
6904                 errx(1, "screenchange: screen not found");
6905
6906         /* brute force for now, just re-enumerate the regions */
6907         scan_xrandr(i);
6908
6909         /* add bars to all regions */
6910         for (i = 0; i < ScreenCount(display); i++)
6911                 TAILQ_FOREACH(r, &screens[i].rl, entry)
6912                         bar_setup(r);
6913         stack();
6914         if (focus_mode == SWM_FOCUS_DEFAULT)
6915                 drain_enter_notify();
6916 }
6917
6918 void
6919 grab_windows(void)
6920 {
6921         Window                  d1, d2, *wins = NULL;
6922         XWindowAttributes       wa;
6923         unsigned int            no;
6924         int                     i, j;
6925         long                    state, manage;
6926
6927         for (i = 0; i < ScreenCount(display); i++) {
6928                 if (!XQueryTree(display, screens[i].root, &d1, &d2, &wins, &no))
6929                         continue;
6930
6931                 /* attach windows to a region */
6932                 /* normal windows */
6933                 for (j = 0; j < no; j++) {
6934                         if (!XGetWindowAttributes(display, wins[j], &wa) ||
6935                             wa.override_redirect ||
6936                             XGetTransientForHint(display, wins[j], &d1))
6937                                 continue;
6938
6939                         state = getstate(wins[j]);
6940                         manage = state == IconicState;
6941                         if (wa.map_state == IsViewable || manage)
6942                                 manage_window(wins[j]);
6943                 }
6944                 /* transient windows */
6945                 for (j = 0; j < no; j++) {
6946                         if (!XGetWindowAttributes(display, wins[j], &wa) ||
6947                             wa.override_redirect)
6948                                 continue;
6949
6950                         state = getstate(wins[j]);
6951                         manage = state == IconicState;
6952                         if (XGetTransientForHint(display, wins[j], &d1) &&
6953                             manage)
6954                                 manage_window(wins[j]);
6955                 }
6956                 if (wins) {
6957                         XFree(wins);
6958                         wins = NULL;
6959                 }
6960         }
6961 }
6962
6963 void
6964 setup_screens(void)
6965 {
6966         int                     i, j, k;
6967         int                     errorbase, major, minor;
6968         struct workspace        *ws;
6969         XGCValues               gcv;
6970
6971         if ((screens = calloc(ScreenCount(display),
6972              sizeof(struct swm_screen))) == NULL)
6973                 err(1, "setup_screens: calloc: failed to allocate memory for "
6974                     "screens");
6975
6976         /* initial Xrandr setup */
6977         xrandr_support = XRRQueryExtension(display,
6978             &xrandr_eventbase, &errorbase);
6979         if (xrandr_support)
6980                 if (XRRQueryVersion(display, &major, &minor) && major < 1)
6981                         xrandr_support = 0;
6982
6983         /* map physical screens */
6984         for (i = 0; i < ScreenCount(display); i++) {
6985                 DNPRINTF(SWM_D_WS, "setup_screens: init screen: %d\n", i);
6986                 screens[i].idx = i;
6987                 TAILQ_INIT(&screens[i].rl);
6988                 TAILQ_INIT(&screens[i].orl);
6989                 screens[i].root = RootWindow(display, i);
6990
6991                 /* set default colors */
6992                 setscreencolor("red", i + 1, SWM_S_COLOR_FOCUS);
6993                 setscreencolor("rgb:88/88/88", i + 1, SWM_S_COLOR_UNFOCUS);
6994                 setscreencolor("rgb:00/80/80", i + 1, SWM_S_COLOR_BAR_BORDER);
6995                 setscreencolor("black", i + 1, SWM_S_COLOR_BAR);
6996                 setscreencolor("rgb:a0/a0/a0", i + 1, SWM_S_COLOR_BAR_FONT);
6997
6998                 /* create graphics context on screen with default font color */
6999                 screens[i].bar_gc = XCreateGC(display, screens[i].root, 0,
7000                     &gcv);
7001
7002                 XSetForeground(display, screens[i].bar_gc,
7003                     screens[i].c[SWM_S_COLOR_BAR_FONT].color);
7004
7005                 /* set default cursor */
7006                 XDefineCursor(display, screens[i].root,
7007                     XCreateFontCursor(display, XC_left_ptr));
7008
7009                 /* init all workspaces */
7010                 /* XXX these should be dynamically allocated too */
7011                 for (j = 0; j < SWM_WS_MAX; j++) {
7012                         ws = &screens[i].ws[j];
7013                         ws->idx = j;
7014                         ws->name = NULL;
7015                         ws->focus = NULL;
7016                         ws->r = NULL;
7017                         ws->old_r = NULL;
7018                         TAILQ_INIT(&ws->winlist);
7019                         TAILQ_INIT(&ws->unmanagedlist);
7020
7021                         for (k = 0; layouts[k].l_stack != NULL; k++)
7022                                 if (layouts[k].l_config != NULL)
7023                                         layouts[k].l_config(ws,
7024                                             SWM_ARG_ID_STACKINIT);
7025                         ws->cur_layout = &layouts[0];
7026                         ws->cur_layout->l_string(ws);
7027                 }
7028
7029                 scan_xrandr(i);
7030
7031                 if (xrandr_support)
7032                         XRRSelectInput(display, screens[i].root,
7033                             RRScreenChangeNotifyMask);
7034         }
7035 }
7036
7037 void
7038 setup_globals(void)
7039 {
7040         if ((bar_fonts = strdup(SWM_BAR_FONTS)) == NULL)
7041                 err(1, "setup_globals: strdup: failed to allocate memory.");
7042
7043         if ((spawn_term[0] = strdup("xterm")) == NULL)
7044                 err(1, "setup_globals: strdup: failed to allocate memory.");
7045
7046         if ((clock_format = strdup("%a %b %d %R %Z %Y")) == NULL)
7047                 err(1, "setup_globals: strdup: failed to allocate memory.");
7048 }
7049
7050 void
7051 workaround(void)
7052 {
7053         int                     i;
7054         Atom                    netwmcheck, netwmname, utf8_string;
7055         Window                  root, win;
7056
7057         /* work around sun jdk bugs, code from wmname */
7058         netwmcheck = XInternAtom(display, "_NET_SUPPORTING_WM_CHECK", False);
7059         netwmname = XInternAtom(display, "_NET_WM_NAME", False);
7060         utf8_string = XInternAtom(display, "UTF8_STRING", False);
7061         for (i = 0; i < ScreenCount(display); i++) {
7062                 root = screens[i].root;
7063                 win = XCreateSimpleWindow(display,root, 0, 0, 1, 1, 0,
7064                     screens[i].c[SWM_S_COLOR_UNFOCUS].color,
7065                     screens[i].c[SWM_S_COLOR_UNFOCUS].color);
7066
7067                 XChangeProperty(display, root, netwmcheck, XA_WINDOW, 32,
7068                     PropModeReplace, (unsigned char *)&win, 1);
7069                 XChangeProperty(display, win, netwmcheck, XA_WINDOW, 32,
7070                     PropModeReplace, (unsigned char *)&win, 1);
7071                 XChangeProperty(display, win, netwmname, utf8_string, 8,
7072                     PropModeReplace, (unsigned char*)"LG3D", strlen("LG3D"));
7073         }
7074 }
7075
7076 int
7077 main(int argc, char *argv[])
7078 {
7079         struct swm_region       *r, *rr;
7080         struct ws_win           *winfocus = NULL;
7081         struct timeval          tv;
7082         union arg               a;
7083         char                    conf[PATH_MAX], *cfile = NULL;
7084         struct stat             sb;
7085         XEvent                  e;
7086         int                     xfd, i;
7087         fd_set                  rd;
7088         struct sigaction        sact;
7089
7090         start_argv = argv;
7091         warnx("Welcome to spectrwm V%s Build: %s", SPECTRWM_VERSION, buildstr);
7092         if (!setlocale(LC_CTYPE, "") || !setlocale(LC_TIME, "") ||
7093             !XSupportsLocale())
7094                 warnx("no locale support");
7095
7096         if (!X_HAVE_UTF8_STRING)
7097                 warnx("no UTF-8 support");
7098
7099         if (!(display = XOpenDisplay(0)))
7100                 errx(1, "can not open display");
7101
7102         if (active_wm())
7103                 errx(1, "other wm running");
7104
7105         /* handle some signals */
7106         bzero(&sact, sizeof(sact));
7107         sigemptyset(&sact.sa_mask);
7108         sact.sa_flags = 0;
7109         sact.sa_handler = sighdlr;
7110         sigaction(SIGINT, &sact, NULL);
7111         sigaction(SIGQUIT, &sact, NULL);
7112         sigaction(SIGTERM, &sact, NULL);
7113         sigaction(SIGHUP, &sact, NULL);
7114
7115         sact.sa_handler = sighdlr;
7116         sact.sa_flags = SA_NOCLDSTOP;
7117         sigaction(SIGCHLD, &sact, NULL);
7118
7119         astate = XInternAtom(display, "WM_STATE", False);
7120         aprot = XInternAtom(display, "WM_PROTOCOLS", False);
7121         adelete = XInternAtom(display, "WM_DELETE_WINDOW", False);
7122         takefocus = XInternAtom(display, "WM_TAKE_FOCUS", False);
7123         a_wmname = XInternAtom(display, "WM_NAME", False);
7124         a_netwmname = XInternAtom(display, "_NET_WM_NAME", False);
7125         a_utf8_string = XInternAtom(display, "UTF8_STRING", False);
7126         a_string = XInternAtom(display, "STRING", False);
7127         a_swm_iconic = XInternAtom(display, "_SWM_ICONIC", False);
7128
7129         /* look for local and global conf file */
7130         pwd = getpwuid(getuid());
7131         if (pwd == NULL)
7132                 errx(1, "invalid user: %d", getuid());
7133
7134         setup_globals();
7135         setup_screens();
7136         setup_keys();
7137         setup_quirks();
7138         setup_spawn();
7139
7140         /* load config */
7141         for (i = 0; ; i++) {
7142                 conf[0] = '\0';
7143                 switch (i) {
7144                 case 0:
7145                         /* ~ */
7146                         snprintf(conf, sizeof conf, "%s/.%s",
7147                             pwd->pw_dir, SWM_CONF_FILE);
7148                         break;
7149                 case 1:
7150                         /* global */
7151                         snprintf(conf, sizeof conf, "/etc/%s",
7152                             SWM_CONF_FILE);
7153                         break;
7154                 case 2:
7155                         /* ~ compat */
7156                         snprintf(conf, sizeof conf, "%s/.%s",
7157                             pwd->pw_dir, SWM_CONF_FILE_OLD);
7158                         break;
7159                 case 3:
7160                         /* global compat */
7161                         snprintf(conf, sizeof conf, "/etc/%s",
7162                             SWM_CONF_FILE_OLD);
7163                         break;
7164                 default:
7165                         goto noconfig;
7166                 }
7167
7168                 if (strlen(conf) && stat(conf, &sb) != -1)
7169                         if (S_ISREG(sb.st_mode)) {
7170                                 cfile = conf;
7171                                 break;
7172                         }
7173         }
7174 noconfig:
7175
7176         /* load conf (if any) and refresh font color in bar graphics contexts */
7177         if (cfile && conf_load(cfile, SWM_CONF_DEFAULT) == 0)
7178                 for (i = 0; i < ScreenCount(display); ++i)
7179                         XSetForeground(display, screens[i].bar_gc,
7180                             screens[i].c[SWM_S_COLOR_BAR_FONT].color);
7181
7182         setup_ewmh();
7183         /* set some values to work around bad programs */
7184         workaround();
7185         /* grab existing windows (before we build the bars) */
7186         grab_windows();
7187
7188         if (getenv("SWM_STARTED") == NULL)
7189                 setenv("SWM_STARTED", "YES", 1);
7190
7191         /* setup all bars */
7192         for (i = 0; i < ScreenCount(display); i++)
7193                 TAILQ_FOREACH(r, &screens[i].rl, entry) {
7194                         if (winfocus == NULL)
7195                                 winfocus = TAILQ_FIRST(&r->ws->winlist);
7196                         bar_setup(r);
7197                 }
7198
7199         unfocus_all();
7200
7201         grabkeys();
7202         stack();
7203         if (focus_mode == SWM_FOCUS_DEFAULT)
7204                 drain_enter_notify();
7205
7206         xfd = ConnectionNumber(display);
7207         while (running) {
7208                 while (XPending(display)) {
7209                         XNextEvent(display, &e);
7210                         if (running == 0)
7211                                 goto done;
7212                         if (e.type < LASTEvent) {
7213                                 DNPRINTF(SWM_D_EVENTQ ,"XEvent: handled: %s, "
7214                                     "window: 0x%lx, type: %s (%d), %d remaining"
7215                                     "\n", YESNO(handler[e.type]),
7216                                     e.xany.window, geteventname(&e),
7217                                     e.type, QLength(display));
7218
7219                                 if (handler[e.type])
7220                                         handler[e.type](&e);
7221                         } else {
7222                                 DNPRINTF(SWM_D_EVENTQ, "XRandr Event: window: "
7223                                     "0x%lx, type: %s (%d)\n", e.xany.window,
7224                                     xrandr_geteventname(&e), e.type);
7225
7226                                 switch (e.type - xrandr_eventbase) {
7227                                 case RRScreenChangeNotify:
7228                                         screenchange(&e);
7229                                         break;
7230                                 default:
7231                                         break;
7232                                 }
7233                         }
7234                 }
7235
7236                 /* if we are being restarted go focus on first window */
7237                 if (winfocus) {
7238                         rr = winfocus->ws->r;
7239                         if (rr == NULL) {
7240                                 /* not a visible window */
7241                                 winfocus = NULL;
7242                                 continue;
7243                         }
7244                         /* move pointer to first screen if multi screen */
7245                         if (ScreenCount(display) > 1 || outputs > 1)
7246                                 XWarpPointer(display, None, rr->s[0].root,
7247                                     0, 0, 0, 0, X(rr),
7248                                     Y(rr) + (bar_enabled ? bar_height : 0));
7249
7250                         a.id = SWM_ARG_ID_FOCUSCUR;
7251                         focus(rr, &a);
7252                         winfocus = NULL;
7253                         continue;
7254                 }
7255
7256                 FD_ZERO(&rd);
7257                 FD_SET(xfd, &rd);
7258                 tv.tv_sec = 1;
7259                 tv.tv_usec = 0;
7260                 if (select(xfd + 1, &rd, NULL, NULL, &tv) == -1)
7261                         if (errno != EINTR)
7262                                 DNPRINTF(SWM_D_MISC, "select failed");
7263                 if (restart_wm == 1)
7264                         restart(NULL, NULL);
7265                 if (search_resp == 1)
7266                         search_do_resp();
7267                 if (running == 0)
7268                         goto done;
7269                 if (bar_alarm) {
7270                         bar_alarm = 0;
7271                         bar_update();
7272                 }
7273         }
7274 done:
7275         teardown_ewmh();
7276         bar_extra_stop();
7277
7278         for (i = 0; i < ScreenCount(display); ++i)
7279                 if (screens[i].bar_gc != NULL)
7280                         XFreeGC(display, screens[i].bar_gc);
7281
7282         XFreeFontSet(display, bar_fs);
7283         XCloseDisplay(display);
7284
7285         return (0);
7286 }