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