xref: /netbsd-src/external/bsd/tmux/dist/window.c (revision 946379e7b37692fc43f68eb0d1c10daa0a7f3b6c)
1 /* $OpenBSD$ */
2 
3 /*
4  * Copyright (c) 2007 Nicholas Marriott <nicm@users.sourceforge.net>
5  *
6  * Permission to use, copy, modify, and distribute this software for any
7  * purpose with or without fee is hereby granted, provided that the above
8  * copyright notice and this permission notice appear in all copies.
9  *
10  * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
11  * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
12  * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
13  * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
14  * WHATSOEVER RESULTING FROM LOSS OF MIND, USE, DATA OR PROFITS, WHETHER
15  * IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING
16  * OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
17  */
18 
19 #include <sys/types.h>
20 
21 #include <errno.h>
22 #include <fcntl.h>
23 #include <fnmatch.h>
24 #include <stdint.h>
25 #include <stdlib.h>
26 #include <string.h>
27 #include <termios.h>
28 #include <unistd.h>
29 
30 #include "tmux.h"
31 
32 /*
33  * Each window is attached to a number of panes, each of which is a pty. This
34  * file contains code to handle them.
35  *
36  * A pane has two buffers attached, these are filled and emptied by the main
37  * server poll loop. Output data is received from pty's in screen format,
38  * translated and returned as a series of escape sequences and strings via
39  * input_parse (in input.c). Input data is received as key codes and written
40  * directly via input_key.
41  *
42  * Each pane also has a "virtual" screen (screen.c) which contains the current
43  * state and is redisplayed when the window is reattached to a client.
44  *
45  * Windows are stored directly on a global array and wrapped in any number of
46  * winlink structs to be linked onto local session RB trees. A reference count
47  * is maintained and a window removed from the global list and destroyed when
48  * it reaches zero.
49  */
50 
51 /* Global window list. */
52 struct windows windows;
53 
54 /* Global panes tree. */
55 struct window_pane_tree all_window_panes;
56 u_int	next_window_pane_id;
57 u_int	next_window_id;
58 u_int	next_active_point;
59 
60 void	window_pane_timer_callback(int, short, void *);
61 void	window_pane_read_callback(struct bufferevent *, void *);
62 void	window_pane_error_callback(struct bufferevent *, short, void *);
63 
64 struct window_pane *window_pane_choose_best(struct window_pane **, u_int);
65 
66 RB_GENERATE(windows, window, entry, window_cmp);
67 
68 int
69 window_cmp(struct window *w1, struct window *w2)
70 {
71 	return (w1->id - w2->id);
72 }
73 
74 RB_GENERATE(winlinks, winlink, entry, winlink_cmp);
75 
76 int
77 winlink_cmp(struct winlink *wl1, struct winlink *wl2)
78 {
79 	return (wl1->idx - wl2->idx);
80 }
81 
82 RB_GENERATE(window_pane_tree, window_pane, tree_entry, window_pane_cmp);
83 
84 int
85 window_pane_cmp(struct window_pane *wp1, struct window_pane *wp2)
86 {
87 	return (wp1->id - wp2->id);
88 }
89 
90 struct winlink *
91 winlink_find_by_window(struct winlinks *wwl, struct window *w)
92 {
93 	struct winlink	*wl;
94 
95 	RB_FOREACH(wl, winlinks, wwl) {
96 		if (wl->window == w)
97 			return (wl);
98 	}
99 
100 	return (NULL);
101 }
102 
103 struct winlink *
104 winlink_find_by_index(struct winlinks *wwl, int idx)
105 {
106 	struct winlink	wl;
107 
108 	if (idx < 0)
109 		fatalx("bad index");
110 
111 	wl.idx = idx;
112 	return (RB_FIND(winlinks, wwl, &wl));
113 }
114 
115 struct winlink *
116 winlink_find_by_window_id(struct winlinks *wwl, u_int id)
117 {
118 	struct winlink *wl;
119 
120 	RB_FOREACH(wl, winlinks, wwl) {
121 		if (wl->window->id == id)
122 			return (wl);
123 	}
124 	return (NULL);
125 }
126 
127 int
128 winlink_next_index(struct winlinks *wwl, int idx)
129 {
130 	int	i;
131 
132 	i = idx;
133 	do {
134 		if (winlink_find_by_index(wwl, i) == NULL)
135 			return (i);
136 		if (i == INT_MAX)
137 			i = 0;
138 		else
139 			i++;
140 	} while (i != idx);
141 	return (-1);
142 }
143 
144 u_int
145 winlink_count(struct winlinks *wwl)
146 {
147 	struct winlink	*wl;
148 	u_int		 n;
149 
150 	n = 0;
151 	RB_FOREACH(wl, winlinks, wwl)
152 		n++;
153 
154 	return (n);
155 }
156 
157 struct winlink *
158 winlink_add(struct winlinks *wwl, int idx)
159 {
160 	struct winlink	*wl;
161 
162 	if (idx < 0) {
163 		if ((idx = winlink_next_index(wwl, -idx - 1)) == -1)
164 			return (NULL);
165 	} else if (winlink_find_by_index(wwl, idx) != NULL)
166 		return (NULL);
167 
168 	wl = xcalloc(1, sizeof *wl);
169 	wl->idx = idx;
170 	RB_INSERT(winlinks, wwl, wl);
171 
172 	return (wl);
173 }
174 
175 void
176 winlink_set_window(struct winlink *wl, struct window *w)
177 {
178 	wl->window = w;
179 	w->references++;
180 }
181 
182 void
183 winlink_remove(struct winlinks *wwl, struct winlink *wl)
184 {
185 	struct window	*w = wl->window;
186 
187 	RB_REMOVE(winlinks, wwl, wl);
188 	free(wl->status_text);
189 	free(wl);
190 
191 	if (w != NULL)
192 		window_remove_ref(w);
193 }
194 
195 struct winlink *
196 winlink_next(struct winlink *wl)
197 {
198 	return (RB_NEXT(winlinks, wwl, wl));
199 }
200 
201 struct winlink *
202 winlink_previous(struct winlink *wl)
203 {
204 	return (RB_PREV(winlinks, wwl, wl));
205 }
206 
207 struct winlink *
208 winlink_next_by_number(struct winlink *wl, struct session *s, int n)
209 {
210 	for (; n > 0; n--) {
211 		if ((wl = RB_NEXT(winlinks, wwl, wl)) == NULL)
212 			wl = RB_MIN(winlinks, &s->windows);
213 	}
214 
215 	return (wl);
216 }
217 
218 struct winlink *
219 winlink_previous_by_number(struct winlink *wl, struct session *s, int n)
220 {
221 	for (; n > 0; n--) {
222 		if ((wl = RB_PREV(winlinks, wwl, wl)) == NULL)
223 			wl = RB_MAX(winlinks, &s->windows);
224 	}
225 
226 	return (wl);
227 }
228 
229 void
230 winlink_stack_push(struct winlink_stack *stack, struct winlink *wl)
231 {
232 	if (wl == NULL)
233 		return;
234 
235 	winlink_stack_remove(stack, wl);
236 	TAILQ_INSERT_HEAD(stack, wl, sentry);
237 }
238 
239 void
240 winlink_stack_remove(struct winlink_stack *stack, struct winlink *wl)
241 {
242 	struct winlink	*wl2;
243 
244 	if (wl == NULL)
245 		return;
246 
247 	TAILQ_FOREACH(wl2, stack, sentry) {
248 		if (wl2 == wl) {
249 			TAILQ_REMOVE(stack, wl, sentry);
250 			return;
251 		}
252 	}
253 }
254 
255 struct window *
256 window_find_by_id_str(const char *s)
257 {
258 	const char	*errstr;
259 	u_int		 id;
260 
261 	if (*s != '@')
262 		return (NULL);
263 
264 	id = strtonum(s + 1, 0, UINT_MAX, &errstr);
265 	if (errstr != NULL)
266 		return (NULL);
267 	return (window_find_by_id(id));
268 }
269 
270 struct window *
271 window_find_by_id(u_int id)
272 {
273 	struct window	w;
274 
275 	w.id = id;
276 	return (RB_FIND(windows, &windows, &w));
277 }
278 
279 void
280 window_update_activity(struct window *w)
281 {
282 	gettimeofday(&w->activity_time, NULL);
283 	alerts_queue(w, WINDOW_ACTIVITY);
284 }
285 
286 struct window *
287 window_create1(u_int sx, u_int sy)
288 {
289 	struct window	*w;
290 
291 	w = xcalloc(1, sizeof *w);
292 	w->name = NULL;
293 	w->flags = 0;
294 
295 	TAILQ_INIT(&w->panes);
296 	w->active = NULL;
297 
298 	w->lastlayout = -1;
299 	w->layout_root = NULL;
300 
301 	w->sx = sx;
302 	w->sy = sy;
303 
304 	options_init(&w->options, &global_w_options);
305 
306 	w->references = 0;
307 
308 	w->id = next_window_id++;
309 	RB_INSERT(windows, &windows, w);
310 
311 	window_update_activity(w);
312 
313 	return (w);
314 }
315 
316 struct window *
317 window_create(const char *name, int argc, char **argv, const char *path,
318     const char *shell, int cwd, struct environ *env, struct termios *tio,
319     u_int sx, u_int sy, u_int hlimit, char **cause)
320 {
321 	struct window		*w;
322 	struct window_pane	*wp;
323 
324 	w = window_create1(sx, sy);
325 	wp = window_add_pane(w, hlimit);
326 	layout_init(w, wp);
327 
328 	if (window_pane_spawn(wp, argc, argv, path, shell, cwd, env, tio,
329 	    cause) != 0) {
330 		window_destroy(w);
331 		return (NULL);
332 	}
333 
334 	w->active = TAILQ_FIRST(&w->panes);
335 	if (name != NULL) {
336 		w->name = xstrdup(name);
337 		options_set_number(&w->options, "automatic-rename", 0);
338 	} else
339 		w->name = default_window_name(w);
340 
341 	return (w);
342 }
343 
344 void
345 window_destroy(struct window *w)
346 {
347 	RB_REMOVE(windows, &windows, w);
348 
349 	if (w->layout_root != NULL)
350 		layout_free_cell(w->layout_root);
351 	if (w->saved_layout_root != NULL)
352 		layout_free_cell(w->saved_layout_root);
353 	free(w->old_layout);
354 
355 	if (event_initialized(&w->name_event))
356 		evtimer_del(&w->name_event);
357 
358 	if (event_initialized(&w->alerts_timer))
359 		evtimer_del(&w->alerts_timer);
360 
361 	options_free(&w->options);
362 
363 	window_destroy_panes(w);
364 
365 	free(w->name);
366 	free(w);
367 }
368 
369 void
370 window_remove_ref(struct window *w)
371 {
372 	if (w->references == 0)
373 		fatal("bad reference count");
374 	w->references--;
375 	if (w->references == 0)
376 		window_destroy(w);
377 }
378 
379 void
380 window_set_name(struct window *w, const char *new_name)
381 {
382 	free(w->name);
383 	w->name = xstrdup(new_name);
384 	notify_window_renamed(w);
385 }
386 
387 void
388 window_resize(struct window *w, u_int sx, u_int sy)
389 {
390 	w->sx = sx;
391 	w->sy = sy;
392 }
393 
394 int
395 window_has_pane(struct window *w, struct window_pane *wp)
396 {
397 	struct window_pane	*wp1;
398 
399 	TAILQ_FOREACH(wp1, &w->panes, entry) {
400 		if (wp1 == wp)
401 			return (1);
402 	}
403 	return (0);
404 }
405 
406 int
407 window_set_active_pane(struct window *w, struct window_pane *wp)
408 {
409 	if (wp == w->active)
410 		return (0);
411 	w->last = w->active;
412 	w->active = wp;
413 	while (!window_pane_visible(w->active)) {
414 		w->active = TAILQ_PREV(w->active, window_panes, entry);
415 		if (w->active == NULL)
416 			w->active = TAILQ_LAST(&w->panes, window_panes);
417 		if (w->active == wp)
418 			return (1);
419 	}
420 	w->active->active_point = next_active_point++;
421 	w->active->flags |= PANE_CHANGED;
422 	return (1);
423 }
424 
425 void
426 window_redraw_active_switch(struct window *w, struct window_pane *wp)
427 {
428 	const struct grid_cell	*agc, *wgc;
429 
430 	if (wp == w->active)
431 		return;
432 
433 	/*
434 	 * If window-style and window-active-style are the same, we don't need
435 	 * to redraw panes when switching active panes. Otherwise, if the
436 	 * active or inactive pane do not have a custom style, they will need
437 	 * to be redrawn.
438 	 */
439 	agc = options_get_style(&w->options, "window-active-style");
440 	wgc = options_get_style(&w->options, "window-style");
441 	if (style_equal(agc, wgc))
442 		return;
443 	if (style_equal(&grid_default_cell, &w->active->colgc))
444 		w->active->flags |= PANE_REDRAW;
445 	if (style_equal(&grid_default_cell, &wp->colgc))
446 		wp->flags |= PANE_REDRAW;
447 }
448 
449 struct window_pane *
450 window_get_active_at(struct window *w, u_int x, u_int y)
451 {
452 	struct window_pane	*wp;
453 
454 	TAILQ_FOREACH(wp, &w->panes, entry) {
455 		if (!window_pane_visible(wp))
456 			continue;
457 		if (x < wp->xoff || x > wp->xoff + wp->sx)
458 			continue;
459 		if (y < wp->yoff || y > wp->yoff + wp->sy)
460 			continue;
461 		return (wp);
462 	}
463 	return (NULL);
464 }
465 
466 struct window_pane *
467 window_find_string(struct window *w, const char *s)
468 {
469 	u_int	x, y;
470 
471 	x = w->sx / 2;
472 	y = w->sy / 2;
473 
474 	if (strcasecmp(s, "top") == 0)
475 		y = 0;
476 	else if (strcasecmp(s, "bottom") == 0)
477 		y = w->sy - 1;
478 	else if (strcasecmp(s, "left") == 0)
479 		x = 0;
480 	else if (strcasecmp(s, "right") == 0)
481 		x = w->sx - 1;
482 	else if (strcasecmp(s, "top-left") == 0) {
483 		x = 0;
484 		y = 0;
485 	} else if (strcasecmp(s, "top-right") == 0) {
486 		x = w->sx - 1;
487 		y = 0;
488 	} else if (strcasecmp(s, "bottom-left") == 0) {
489 		x = 0;
490 		y = w->sy - 1;
491 	} else if (strcasecmp(s, "bottom-right") == 0) {
492 		x = w->sx - 1;
493 		y = w->sy - 1;
494 	} else
495 		return (NULL);
496 
497 	return (window_get_active_at(w, x, y));
498 }
499 
500 int
501 window_zoom(struct window_pane *wp)
502 {
503 	struct window		*w = wp->window;
504 	struct window_pane	*wp1;
505 
506 	if (w->flags & WINDOW_ZOOMED)
507 		return (-1);
508 
509 	if (!window_pane_visible(wp))
510 		return (-1);
511 
512 	if (window_count_panes(w) == 1)
513 		return (-1);
514 
515 	if (w->active != wp)
516 		window_set_active_pane(w, wp);
517 
518 	TAILQ_FOREACH(wp1, &w->panes, entry) {
519 		wp1->saved_layout_cell = wp1->layout_cell;
520 		wp1->layout_cell = NULL;
521 	}
522 
523 	w->saved_layout_root = w->layout_root;
524 	layout_init(w, wp);
525 	w->flags |= WINDOW_ZOOMED;
526 	notify_window_layout_changed(w);
527 
528 	return (0);
529 }
530 
531 int
532 window_unzoom(struct window *w)
533 {
534 	struct window_pane	*wp;
535 
536 	if (!(w->flags & WINDOW_ZOOMED))
537 		return (-1);
538 
539 	w->flags &= ~WINDOW_ZOOMED;
540 	layout_free(w);
541 	w->layout_root = w->saved_layout_root;
542 	w->saved_layout_root = NULL;
543 
544 	TAILQ_FOREACH(wp, &w->panes, entry) {
545 		wp->layout_cell = wp->saved_layout_cell;
546 		wp->saved_layout_cell = NULL;
547 	}
548 	layout_fix_panes(w, w->sx, w->sy);
549 	notify_window_layout_changed(w);
550 
551 	return (0);
552 }
553 
554 struct window_pane *
555 window_add_pane(struct window *w, u_int hlimit)
556 {
557 	struct window_pane	*wp;
558 
559 	wp = window_pane_create(w, w->sx, w->sy, hlimit);
560 	if (TAILQ_EMPTY(&w->panes))
561 		TAILQ_INSERT_HEAD(&w->panes, wp, entry);
562 	else
563 		TAILQ_INSERT_AFTER(&w->panes, w->active, wp, entry);
564 	return (wp);
565 }
566 
567 void
568 window_lost_pane(struct window *w, struct window_pane *wp)
569 {
570 	if (wp == marked_window_pane)
571 		server_clear_marked();
572 
573 	if (wp == w->active) {
574 		w->active = w->last;
575 		w->last = NULL;
576 		if (w->active == NULL) {
577 			w->active = TAILQ_PREV(wp, window_panes, entry);
578 			if (w->active == NULL)
579 				w->active = TAILQ_NEXT(wp, entry);
580 		}
581 	} else if (wp == w->last)
582 		w->last = NULL;
583 }
584 
585 void
586 window_remove_pane(struct window *w, struct window_pane *wp)
587 {
588 	window_lost_pane(w, wp);
589 
590 	TAILQ_REMOVE(&w->panes, wp, entry);
591 	window_pane_destroy(wp);
592 }
593 
594 struct window_pane *
595 window_pane_at_index(struct window *w, u_int idx)
596 {
597 	struct window_pane	*wp;
598 	u_int			 n;
599 
600 	n = options_get_number(&w->options, "pane-base-index");
601 	TAILQ_FOREACH(wp, &w->panes, entry) {
602 		if (n == idx)
603 			return (wp);
604 		n++;
605 	}
606 	return (NULL);
607 }
608 
609 struct window_pane *
610 window_pane_next_by_number(struct window *w, struct window_pane *wp, u_int n)
611 {
612 	for (; n > 0; n--) {
613 		if ((wp = TAILQ_NEXT(wp, entry)) == NULL)
614 			wp = TAILQ_FIRST(&w->panes);
615 	}
616 
617 	return (wp);
618 }
619 
620 struct window_pane *
621 window_pane_previous_by_number(struct window *w, struct window_pane *wp,
622     u_int n)
623 {
624 	for (; n > 0; n--) {
625 		if ((wp = TAILQ_PREV(wp, window_panes, entry)) == NULL)
626 			wp = TAILQ_LAST(&w->panes, window_panes);
627 	}
628 
629 	return (wp);
630 }
631 
632 int
633 window_pane_index(struct window_pane *wp, u_int *i)
634 {
635 	struct window_pane	*wq;
636 	struct window		*w = wp->window;
637 
638 	*i = options_get_number(&w->options, "pane-base-index");
639 	TAILQ_FOREACH(wq, &w->panes, entry) {
640 		if (wp == wq) {
641 			return (0);
642 		}
643 		(*i)++;
644 	}
645 
646 	return (-1);
647 }
648 
649 u_int
650 window_count_panes(struct window *w)
651 {
652 	struct window_pane	*wp;
653 	u_int			 n;
654 
655 	n = 0;
656 	TAILQ_FOREACH(wp, &w->panes, entry)
657 		n++;
658 	return (n);
659 }
660 
661 void
662 window_destroy_panes(struct window *w)
663 {
664 	struct window_pane	*wp;
665 
666 	while (!TAILQ_EMPTY(&w->panes)) {
667 		wp = TAILQ_FIRST(&w->panes);
668 		TAILQ_REMOVE(&w->panes, wp, entry);
669 		window_pane_destroy(wp);
670 	}
671 }
672 
673 /* Retuns the printable flags on a window, empty string if no flags set. */
674 char *
675 window_printable_flags(struct session *s, struct winlink *wl)
676 {
677 	char	flags[32];
678 	int	pos;
679 
680 	pos = 0;
681 	if (wl->flags & WINLINK_ACTIVITY)
682 		flags[pos++] = '#';
683 	if (wl->flags & WINLINK_BELL)
684 		flags[pos++] = '!';
685 	if (wl->flags & WINLINK_SILENCE)
686 		flags[pos++] = '~';
687 	if (wl == s->curw)
688 		flags[pos++] = '*';
689 	if (wl == TAILQ_FIRST(&s->lastw))
690 		flags[pos++] = '-';
691 	if (server_check_marked() && wl == marked_winlink)
692 		flags[pos++] = 'M';
693 	if (wl->window->flags & WINDOW_ZOOMED)
694 		flags[pos++] = 'Z';
695 	flags[pos] = '\0';
696 	return (xstrdup(flags));
697 }
698 
699 struct window_pane *
700 window_pane_find_by_id_str(const char *s)
701 {
702 	const char	*errstr;
703 	u_int		 id;
704 
705 	if (*s != '%')
706 		return (NULL);
707 
708 	id = strtonum(s + 1, 0, UINT_MAX, &errstr);
709 	if (errstr != NULL)
710 		return (NULL);
711 	return (window_pane_find_by_id(id));
712 }
713 
714 struct window_pane *
715 window_pane_find_by_id(u_int id)
716 {
717 	struct window_pane	wp;
718 
719 	wp.id = id;
720 	return (RB_FIND(window_pane_tree, &all_window_panes, &wp));
721 }
722 
723 struct window_pane *
724 window_pane_create(struct window *w, u_int sx, u_int sy, u_int hlimit)
725 {
726 	struct window_pane	*wp;
727 	char			 host[HOST_NAME_MAX + 1];
728 
729 	wp = xcalloc(1, sizeof *wp);
730 	wp->window = w;
731 
732 	wp->id = next_window_pane_id++;
733 	RB_INSERT(window_pane_tree, &all_window_panes, wp);
734 
735 	wp->argc = 0;
736 	wp->argv = NULL;
737 	wp->shell = NULL;
738 	wp->cwd = -1;
739 
740 	wp->fd = -1;
741 	wp->event = NULL;
742 
743 	wp->mode = NULL;
744 
745 	wp->layout_cell = NULL;
746 
747 	wp->xoff = 0;
748 	wp->yoff = 0;
749 
750 	wp->sx = sx;
751 	wp->sy = sy;
752 
753 	wp->pipe_fd = -1;
754 	wp->pipe_off = 0;
755 	wp->pipe_event = NULL;
756 
757 	wp->saved_grid = NULL;
758 
759 	memcpy(&wp->colgc, &grid_default_cell, sizeof wp->colgc);
760 
761 	screen_init(&wp->base, sx, sy, hlimit);
762 	wp->screen = &wp->base;
763 
764 	if (gethostname(host, sizeof host) == 0)
765 		screen_set_title(&wp->base, host);
766 
767 	input_init(wp);
768 
769 	return (wp);
770 }
771 
772 void
773 window_pane_destroy(struct window_pane *wp)
774 {
775 	window_pane_reset_mode(wp);
776 
777 	if (event_initialized(&wp->timer))
778 		evtimer_del(&wp->timer);
779 
780 	if (wp->fd != -1) {
781 #ifdef HAVE_UTEMPTER
782 		utempter_remove_record(wp->fd);
783 #endif
784 		bufferevent_free(wp->event);
785 		close(wp->fd);
786 	}
787 
788 	input_free(wp);
789 
790 	screen_free(&wp->base);
791 	if (wp->saved_grid != NULL)
792 		grid_destroy(wp->saved_grid);
793 
794 	if (wp->pipe_fd != -1) {
795 		bufferevent_free(wp->pipe_event);
796 		close(wp->pipe_fd);
797 	}
798 
799 	RB_REMOVE(window_pane_tree, &all_window_panes, wp);
800 
801 	utmp_destroy(wp->utmp);
802 	close(wp->cwd);
803 	free(wp->shell);
804 	cmd_free_argv(wp->argc, wp->argv);
805 	free(wp);
806 }
807 
808 int
809 window_pane_spawn(struct window_pane *wp, int argc, char **argv,
810     const char *path, const char *shell, int cwd, struct environ *env,
811     struct termios *tio, char **cause)
812 {
813 	struct winsize	 ws;
814 	char		*argv0, *cmd, **argvp, paneid[16];
815 	const char	*ptr, *first;
816 	struct termios	 tio2;
817 #ifdef HAVE_UTEMPTER
818 	char		 s[32];
819 #endif
820 	int		 i;
821 
822 	if (wp->fd != -1) {
823 		bufferevent_free(wp->event);
824 		close(wp->fd);
825 	}
826 	if (argc > 0) {
827 		cmd_free_argv(wp->argc, wp->argv);
828 		wp->argc = argc;
829 		wp->argv = cmd_copy_argv(argc, argv);
830 	}
831 	if (shell != NULL) {
832 		free(wp->shell);
833 		wp->shell = xstrdup(shell);
834 	}
835 	if (cwd != -1) {
836 		close(wp->cwd);
837 		wp->cwd = dup(cwd);
838 	}
839 
840 	cmd = cmd_stringify_argv(wp->argc, wp->argv);
841 	log_debug("spawn: %s -- %s", wp->shell, cmd);
842 	for (i = 0; i < wp->argc; i++)
843 		log_debug("spawn: argv[%d] = %s", i, wp->argv[i]);
844 
845 	memset(&ws, 0, sizeof ws);
846 	ws.ws_col = screen_size_x(&wp->base);
847 	ws.ws_row = screen_size_y(&wp->base);
848 
849 	switch (wp->pid = forkpty(&wp->fd, wp->tty, NULL, &ws)) {
850 	case -1:
851 		wp->fd = -1;
852 		xasprintf(cause, "%s: %s", cmd, strerror(errno));
853 		free(cmd);
854 		return (-1);
855 	case 0:
856 		if (fchdir(wp->cwd) != 0)
857 			chdir("/");
858 
859 		if (tcgetattr(STDIN_FILENO, &tio2) != 0)
860 			fatal("tcgetattr failed");
861 		if (tio != NULL)
862 			memcpy(tio2.c_cc, tio->c_cc, sizeof tio2.c_cc);
863 		tio2.c_cc[VERASE] = '\177';
864 #ifdef IUTF8
865 		if (options_get_number(&wp->window->options, "utf8"))
866 			tio2.c_iflag |= IUTF8;
867 #endif
868 		if (tcsetattr(STDIN_FILENO, TCSANOW, &tio2) != 0)
869 			fatal("tcgetattr failed");
870 
871 		closefrom(STDERR_FILENO + 1);
872 
873 		if (path != NULL)
874 			environ_set(env, "PATH", path);
875 		xsnprintf(paneid, sizeof paneid, "%%%u", wp->id);
876 		environ_set(env, "TMUX_PANE", paneid);
877 		environ_push(env);
878 
879 		clear_signals(1);
880 		log_close();
881 
882 		setenv("SHELL", wp->shell, 1);
883 		ptr = strrchr(wp->shell, '/');
884 
885 		/*
886 		 * If given one argument, assume it should be passed to sh -c;
887 		 * with more than one argument, use execvp(). If there is no
888 		 * arguments, create a login shell.
889 		 */
890 		if (wp->argc > 0) {
891 			if (wp->argc != 1) {
892 				/* Copy to ensure argv ends in NULL. */
893 				argvp = cmd_copy_argv(wp->argc, wp->argv);
894 				execvp(argvp[0], argvp);
895 				fatal("execvp failed");
896 			}
897 			first = wp->argv[0];
898 
899 			if (ptr != NULL && *(ptr + 1) != '\0')
900 				xasprintf(&argv0, "%s", ptr + 1);
901 			else
902 				xasprintf(&argv0, "%s", wp->shell);
903 			execl(wp->shell, argv0, "-c", first, (char *)NULL);
904 			fatal("execl failed");
905 		}
906 		if (ptr != NULL && *(ptr + 1) != '\0')
907 			xasprintf(&argv0, "-%s", ptr + 1);
908 		else
909 			xasprintf(&argv0, "-%s", wp->shell);
910 		execl(wp->shell, argv0, (char *)NULL);
911 		fatal("execl failed");
912 	}
913 
914 #ifdef HAVE_UTEMPTER
915 	xsnprintf(s, sizeof s, "tmux(%lu).%%%u", (long) getpid(), wp->id);
916 	utempter_add_record(wp->fd, s);
917 #endif
918 
919 	setblocking(wp->fd, 0);
920 
921 	wp->event = bufferevent_new(wp->fd, window_pane_read_callback, NULL,
922 	    window_pane_error_callback, wp);
923 
924 	bufferevent_setwatermark(wp->event, EV_READ, 0, READ_SIZE);
925 	bufferevent_enable(wp->event, EV_READ|EV_WRITE);
926 
927 	wp->utmp = utmp_create(wp->tty);
928 
929 	free(cmd);
930 	return (0);
931 }
932 
933 void
934 window_pane_timer_callback(unused int fd, unused short events, void *data)
935 {
936 	window_pane_read_callback(NULL, data);
937 }
938 
939 void
940 window_pane_read_callback(unused struct bufferevent *bufev, void *data)
941 {
942 	struct window_pane	*wp = data;
943 	struct evbuffer		*evb = wp->event->input;
944 	char			*new_data;
945 	size_t			 new_size, available;
946 	struct client		*c;
947 	struct timeval		 tv;
948 
949 	if (event_initialized(&wp->timer))
950 		evtimer_del(&wp->timer);
951 
952 	log_debug("%%%u has %zu bytes", wp->id, EVBUFFER_LENGTH(evb));
953 
954 	TAILQ_FOREACH(c, &clients, entry) {
955 		if (!tty_client_ready(c, wp))
956 			continue;
957 
958 		available = EVBUFFER_LENGTH(c->tty.event->output);
959 		if (available > READ_BACKOFF)
960 			goto start_timer;
961 	}
962 
963 	new_size = EVBUFFER_LENGTH(evb) - wp->pipe_off;
964 	if (wp->pipe_fd != -1 && new_size > 0) {
965 		new_data = (char *)EVBUFFER_DATA(evb);
966 		bufferevent_write(wp->pipe_event, new_data, new_size);
967 	}
968 
969 	input_parse(wp);
970 
971 	wp->pipe_off = EVBUFFER_LENGTH(evb);
972 	return;
973 
974 start_timer:
975 	log_debug("%%%u backing off (%s %zu > %d)", wp->id, c->ttyname,
976 	    available, READ_BACKOFF);
977 
978 	tv.tv_sec = 0;
979 	tv.tv_usec = READ_TIME;
980 
981 	evtimer_set(&wp->timer, window_pane_timer_callback, wp);
982 	evtimer_add(&wp->timer, &tv);
983 }
984 
985 void
986 window_pane_error_callback(unused struct bufferevent *bufev, unused short what,
987     void *data)
988 {
989 	struct window_pane *wp = data;
990 
991 	server_destroy_pane(wp);
992 }
993 
994 void
995 window_pane_resize(struct window_pane *wp, u_int sx, u_int sy)
996 {
997 	if (sx == wp->sx && sy == wp->sy)
998 		return;
999 	wp->sx = sx;
1000 	wp->sy = sy;
1001 
1002 	screen_resize(&wp->base, sx, sy, wp->saved_grid == NULL);
1003 	if (wp->mode != NULL)
1004 		wp->mode->resize(wp, sx, sy);
1005 
1006 	wp->flags |= PANE_RESIZE;
1007 }
1008 
1009 /*
1010  * Enter alternative screen mode. A copy of the visible screen is saved and the
1011  * history is not updated
1012  */
1013 void
1014 window_pane_alternate_on(struct window_pane *wp, struct grid_cell *gc,
1015     int cursor)
1016 {
1017 	struct screen	*s = &wp->base;
1018 	u_int		 sx, sy;
1019 
1020 	if (wp->saved_grid != NULL)
1021 		return;
1022 	if (!options_get_number(&wp->window->options, "alternate-screen"))
1023 		return;
1024 	sx = screen_size_x(s);
1025 	sy = screen_size_y(s);
1026 
1027 	wp->saved_grid = grid_create(sx, sy, 0);
1028 	grid_duplicate_lines(wp->saved_grid, 0, s->grid, screen_hsize(s), sy);
1029 	if (cursor) {
1030 		wp->saved_cx = s->cx;
1031 		wp->saved_cy = s->cy;
1032 	}
1033 	memcpy(&wp->saved_cell, gc, sizeof wp->saved_cell);
1034 
1035 	grid_view_clear(s->grid, 0, 0, sx, sy);
1036 
1037 	wp->base.grid->flags &= ~GRID_HISTORY;
1038 
1039 	wp->flags |= PANE_REDRAW;
1040 }
1041 
1042 /* Exit alternate screen mode and restore the copied grid. */
1043 void
1044 window_pane_alternate_off(struct window_pane *wp, struct grid_cell *gc,
1045     int cursor)
1046 {
1047 	struct screen	*s = &wp->base;
1048 	u_int		 sx, sy;
1049 
1050 	if (wp->saved_grid == NULL)
1051 		return;
1052 	if (!options_get_number(&wp->window->options, "alternate-screen"))
1053 		return;
1054 	sx = screen_size_x(s);
1055 	sy = screen_size_y(s);
1056 
1057 	/*
1058 	 * If the current size is bigger, temporarily resize to the old size
1059 	 * before copying back.
1060 	 */
1061 	if (sy > wp->saved_grid->sy)
1062 		screen_resize(s, sx, wp->saved_grid->sy, 1);
1063 
1064 	/* Restore the grid, cursor position and cell. */
1065 	grid_duplicate_lines(s->grid, screen_hsize(s), wp->saved_grid, 0, sy);
1066 	if (cursor)
1067 		s->cx = wp->saved_cx;
1068 	if (s->cx > screen_size_x(s) - 1)
1069 		s->cx = screen_size_x(s) - 1;
1070 	if (cursor)
1071 		s->cy = wp->saved_cy;
1072 	if (s->cy > screen_size_y(s) - 1)
1073 		s->cy = screen_size_y(s) - 1;
1074 	memcpy(gc, &wp->saved_cell, sizeof *gc);
1075 
1076 	/*
1077 	 * Turn history back on (so resize can use it) and then resize back to
1078 	 * the current size.
1079 	 */
1080 	wp->base.grid->flags |= GRID_HISTORY;
1081 	if (sy > wp->saved_grid->sy || sx != wp->saved_grid->sx)
1082 		screen_resize(s, sx, sy, 1);
1083 
1084 	grid_destroy(wp->saved_grid);
1085 	wp->saved_grid = NULL;
1086 
1087 	wp->flags |= PANE_REDRAW;
1088 }
1089 
1090 int
1091 window_pane_set_mode(struct window_pane *wp, const struct window_mode *mode)
1092 {
1093 	struct screen	*s;
1094 
1095 	if (wp->mode != NULL)
1096 		return (1);
1097 	wp->mode = mode;
1098 
1099 	if ((s = wp->mode->init(wp)) != NULL)
1100 		wp->screen = s;
1101 	wp->flags |= (PANE_REDRAW|PANE_CHANGED);
1102 	return (0);
1103 }
1104 
1105 void
1106 window_pane_reset_mode(struct window_pane *wp)
1107 {
1108 	if (wp->mode == NULL)
1109 		return;
1110 
1111 	wp->mode->free(wp);
1112 	wp->mode = NULL;
1113 
1114 	wp->screen = &wp->base;
1115 	wp->flags |= (PANE_REDRAW|PANE_CHANGED);
1116 }
1117 
1118 void
1119 window_pane_key(struct window_pane *wp, struct client *c, struct session *s,
1120     int key, struct mouse_event *m)
1121 {
1122 	struct window_pane	*wp2;
1123 
1124 	if (KEYC_IS_MOUSE(key) && m == NULL)
1125 		return;
1126 
1127 	if (wp->mode != NULL) {
1128 		if (wp->mode->key != NULL)
1129 			wp->mode->key(wp, c, s, key, m);
1130 		return;
1131 	}
1132 
1133 	if (wp->fd == -1 || wp->flags & PANE_INPUTOFF)
1134 		return;
1135 
1136 	input_key(wp, key, m);
1137 
1138 	if (KEYC_IS_MOUSE(key))
1139 		return;
1140 	if (options_get_number(&wp->window->options, "synchronize-panes")) {
1141 		TAILQ_FOREACH(wp2, &wp->window->panes, entry) {
1142 			if (wp2 == wp || wp2->mode != NULL)
1143 				continue;
1144 			if (wp2->fd != -1 && window_pane_visible(wp2))
1145 				input_key(wp2, key, NULL);
1146 		}
1147 	}
1148 }
1149 
1150 int
1151 window_pane_visible(struct window_pane *wp)
1152 {
1153 	struct window	*w = wp->window;
1154 
1155 	if (wp->layout_cell == NULL)
1156 		return (0);
1157 	if (wp->xoff >= w->sx || wp->yoff >= w->sy)
1158 		return (0);
1159 	if (wp->xoff + wp->sx > w->sx || wp->yoff + wp->sy > w->sy)
1160 		return (0);
1161 	return (1);
1162 }
1163 
1164 char *
1165 window_pane_search(struct window_pane *wp, const char *searchstr,
1166     u_int *lineno)
1167 {
1168 	struct screen	*s = &wp->base;
1169 	char		*newsearchstr, *line, *msg;
1170 	u_int	 	 i;
1171 
1172 	msg = NULL;
1173 	xasprintf(&newsearchstr, "*%s*", searchstr);
1174 
1175 	for (i = 0; i < screen_size_y(s); i++) {
1176 		line = grid_view_string_cells(s->grid, 0, i, screen_size_x(s));
1177 		if (fnmatch(newsearchstr, line, 0) == 0) {
1178 			msg = line;
1179 			if (lineno != NULL)
1180 				*lineno = i;
1181 			break;
1182 		}
1183 		free(line);
1184 	}
1185 
1186 	free(newsearchstr);
1187 	return (msg);
1188 }
1189 
1190 /* Get MRU pane from a list. */
1191 struct window_pane *
1192 window_pane_choose_best(struct window_pane **list, u_int size)
1193 {
1194 	struct window_pane	*next, *best;
1195 	u_int			 i;
1196 
1197 	if (size == 0)
1198 		return (NULL);
1199 
1200 	best = list[0];
1201 	for (i = 1; i < size; i++) {
1202 		next = list[i];
1203 		if (next->active_point > best->active_point)
1204 			best = next;
1205 	}
1206 	return (best);
1207 }
1208 
1209 /*
1210  * Find the pane directly above another. We build a list of those adjacent to
1211  * top edge and then choose the best.
1212  */
1213 struct window_pane *
1214 window_pane_find_up(struct window_pane *wp)
1215 {
1216 	struct window_pane	*next, *best, **list;
1217 	u_int			 edge, left, right, end, size;
1218 	int			 found;
1219 
1220 	if (wp == NULL || !window_pane_visible(wp))
1221 		return (NULL);
1222 
1223 	list = NULL;
1224 	size = 0;
1225 
1226 	edge = wp->yoff;
1227 	if (edge == 0)
1228 		edge = wp->window->sy + 1;
1229 
1230 	left = wp->xoff;
1231 	right = wp->xoff + wp->sx;
1232 
1233 	TAILQ_FOREACH(next, &wp->window->panes, entry) {
1234 		if (next == wp || !window_pane_visible(next))
1235 			continue;
1236 		if (next->yoff + next->sy + 1 != edge)
1237 			continue;
1238 		end = next->xoff + next->sx - 1;
1239 
1240 		found = 0;
1241 		if (next->xoff < left && end > right)
1242 			found = 1;
1243 		else if (next->xoff >= left && next->xoff <= right)
1244 			found = 1;
1245 		else if (end >= left && end <= right)
1246 			found = 1;
1247 		if (!found)
1248 			continue;
1249 		list = xreallocarray(list, size + 1, sizeof *list);
1250 		list[size++] = next;
1251 	}
1252 
1253 	best = window_pane_choose_best(list, size);
1254 	free(list);
1255 	return (best);
1256 }
1257 
1258 /* Find the pane directly below another. */
1259 struct window_pane *
1260 window_pane_find_down(struct window_pane *wp)
1261 {
1262 	struct window_pane	*next, *best, **list;
1263 	u_int			 edge, left, right, end, size;
1264 	int			 found;
1265 
1266 	if (wp == NULL || !window_pane_visible(wp))
1267 		return (NULL);
1268 
1269 	list = NULL;
1270 	size = 0;
1271 
1272 	edge = wp->yoff + wp->sy + 1;
1273 	if (edge >= wp->window->sy)
1274 		edge = 0;
1275 
1276 	left = wp->xoff;
1277 	right = wp->xoff + wp->sx;
1278 
1279 	TAILQ_FOREACH(next, &wp->window->panes, entry) {
1280 		if (next == wp || !window_pane_visible(next))
1281 			continue;
1282 		if (next->yoff != edge)
1283 			continue;
1284 		end = next->xoff + next->sx - 1;
1285 
1286 		found = 0;
1287 		if (next->xoff < left && end > right)
1288 			found = 1;
1289 		else if (next->xoff >= left && next->xoff <= right)
1290 			found = 1;
1291 		else if (end >= left && end <= right)
1292 			found = 1;
1293 		if (!found)
1294 			continue;
1295 		list = xreallocarray(list, size + 1, sizeof *list);
1296 		list[size++] = next;
1297 	}
1298 
1299 	best = window_pane_choose_best(list, size);
1300 	free(list);
1301 	return (best);
1302 }
1303 
1304 /* Find the pane directly to the left of another. */
1305 struct window_pane *
1306 window_pane_find_left(struct window_pane *wp)
1307 {
1308 	struct window_pane	*next, *best, **list;
1309 	u_int			 edge, top, bottom, end, size;
1310 	int			 found;
1311 
1312 	if (wp == NULL || !window_pane_visible(wp))
1313 		return (NULL);
1314 
1315 	list = NULL;
1316 	size = 0;
1317 
1318 	edge = wp->xoff;
1319 	if (edge == 0)
1320 		edge = wp->window->sx + 1;
1321 
1322 	top = wp->yoff;
1323 	bottom = wp->yoff + wp->sy;
1324 
1325 	TAILQ_FOREACH(next, &wp->window->panes, entry) {
1326 		if (next == wp || !window_pane_visible(next))
1327 			continue;
1328 		if (next->xoff + next->sx + 1 != edge)
1329 			continue;
1330 		end = next->yoff + next->sy - 1;
1331 
1332 		found = 0;
1333 		if (next->yoff < top && end > bottom)
1334 			found = 1;
1335 		else if (next->yoff >= top && next->yoff <= bottom)
1336 			found = 1;
1337 		else if (end >= top && end <= bottom)
1338 			found = 1;
1339 		if (!found)
1340 			continue;
1341 		list = xreallocarray(list, size + 1, sizeof *list);
1342 		list[size++] = next;
1343 	}
1344 
1345 	best = window_pane_choose_best(list, size);
1346 	free(list);
1347 	return (best);
1348 }
1349 
1350 /* Find the pane directly to the right of another. */
1351 struct window_pane *
1352 window_pane_find_right(struct window_pane *wp)
1353 {
1354 	struct window_pane	*next, *best, **list;
1355 	u_int			 edge, top, bottom, end, size;
1356 	int			 found;
1357 
1358 	if (wp == NULL || !window_pane_visible(wp))
1359 		return (NULL);
1360 
1361 	list = NULL;
1362 	size = 0;
1363 
1364 	edge = wp->xoff + wp->sx + 1;
1365 	if (edge >= wp->window->sx)
1366 		edge = 0;
1367 
1368 	top = wp->yoff;
1369 	bottom = wp->yoff + wp->sy;
1370 
1371 	TAILQ_FOREACH(next, &wp->window->panes, entry) {
1372 		if (next == wp || !window_pane_visible(next))
1373 			continue;
1374 		if (next->xoff != edge)
1375 			continue;
1376 		end = next->yoff + next->sy - 1;
1377 
1378 		found = 0;
1379 		if (next->yoff < top && end > bottom)
1380 			found = 1;
1381 		else if (next->yoff >= top && next->yoff <= bottom)
1382 			found = 1;
1383 		else if (end >= top && end <= bottom)
1384 			found = 1;
1385 		if (!found)
1386 			continue;
1387 		list = xreallocarray(list, size + 1, sizeof *list);
1388 		list[size++] = next;
1389 	}
1390 
1391 	best = window_pane_choose_best(list, size);
1392 	free(list);
1393 	return (best);
1394 }
1395 
1396 /* Clear alert flags for a winlink */
1397 void
1398 winlink_clear_flags(struct winlink *wl)
1399 {
1400 	struct session	*s;
1401 	struct winlink	*wl_loop;
1402 
1403 	RB_FOREACH(s, sessions, &sessions) {
1404 		RB_FOREACH(wl_loop, winlinks, &s->windows) {
1405 			if (wl_loop->window != wl->window)
1406 				continue;
1407 			if ((wl_loop->flags & WINLINK_ALERTFLAGS) == 0)
1408 				continue;
1409 
1410 			wl_loop->flags &= ~WINLINK_ALERTFLAGS;
1411 			wl_loop->window->flags &= ~WINDOW_ALERTFLAGS;
1412 			server_status_session(s);
1413 		}
1414 	}
1415 }
1416 
1417 int
1418 winlink_shuffle_up(struct session *s, struct winlink *wl)
1419 {
1420 	int	 idx, last;
1421 
1422 	idx = wl->idx + 1;
1423 
1424 	/* Find the next free index. */
1425 	for (last = idx; last < INT_MAX; last++) {
1426 		if (winlink_find_by_index(&s->windows, last) == NULL)
1427 			break;
1428 	}
1429 	if (last == INT_MAX)
1430 		return (-1);
1431 
1432 	/* Move everything from last - 1 to idx up a bit. */
1433 	for (; last > idx; last--) {
1434 		wl = winlink_find_by_index(&s->windows, last - 1);
1435 		server_link_window(s, wl, s, last, 0, 0, NULL);
1436 		server_unlink_window(s, wl);
1437 	}
1438 
1439 	return (idx);
1440 }
1441