xref: /netbsd-src/external/bsd/tmux/dist/cmd-find.c (revision bdc22b2e01993381dcefeff2bc9b56ca75a4235c)
1 /* $OpenBSD$ */
2 
3 /*
4  * Copyright (c) 2015 Nicholas Marriott <nicholas.marriott@gmail.com>
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 <fnmatch.h>
22 #include <limits.h>
23 #include <stdlib.h>
24 #include <string.h>
25 #include <unistd.h>
26 
27 #include "tmux.h"
28 
29 static int	cmd_find_session_better(struct session *, struct session *,
30 		    int);
31 static struct session *cmd_find_best_session(struct session **, u_int, int);
32 static int	cmd_find_best_session_with_window(struct cmd_find_state *);
33 static int	cmd_find_best_winlink_with_window(struct cmd_find_state *);
34 
35 static const char *cmd_find_map_table(const char *[][2], const char *);
36 
37 static int	cmd_find_get_session(struct cmd_find_state *, const char *);
38 static int	cmd_find_get_window(struct cmd_find_state *, const char *, int);
39 static int	cmd_find_get_window_with_session(struct cmd_find_state *,
40 		    const char *);
41 static int	cmd_find_get_pane(struct cmd_find_state *, const char *, int);
42 static int	cmd_find_get_pane_with_session(struct cmd_find_state *,
43 		    const char *);
44 static int	cmd_find_get_pane_with_window(struct cmd_find_state *,
45 		    const char *);
46 
47 static const char *cmd_find_session_table[][2] = {
48 	{ NULL, NULL }
49 };
50 static const char *cmd_find_window_table[][2] = {
51 	{ "{start}", "^" },
52 	{ "{last}", "!" },
53 	{ "{end}", "$" },
54 	{ "{next}", "+" },
55 	{ "{previous}", "-" },
56 	{ NULL, NULL }
57 };
58 static const char *cmd_find_pane_table[][2] = {
59 	{ "{last}", "!" },
60 	{ "{next}", "+" },
61 	{ "{previous}", "-" },
62 	{ "{top}", "top" },
63 	{ "{bottom}", "bottom" },
64 	{ "{left}", "left" },
65 	{ "{right}", "right" },
66 	{ "{top-left}", "top-left" },
67 	{ "{top-right}", "top-right" },
68 	{ "{bottom-left}", "bottom-left" },
69 	{ "{bottom-right}", "bottom-right" },
70 	{ "{up-of}", "{up-of}" },
71 	{ "{down-of}", "{down-of}" },
72 	{ "{left-of}", "{left-of}" },
73 	{ "{right-of}", "{right-of}" },
74 	{ NULL, NULL }
75 };
76 
77 /* Get session from TMUX if present. */
78 static struct session *
79 cmd_find_try_TMUX(struct client *c)
80 {
81 	struct environ_entry	*envent;
82 	char			 tmp[256];
83 	long long		 pid;
84 	u_int			 session;
85 
86 	envent = environ_find(c->environ, "TMUX");
87 	if (envent == NULL)
88 		return (NULL);
89 
90 	if (sscanf(envent->value, "%255[^,],%lld,%d", tmp, &pid, &session) != 3)
91 		return (NULL);
92 	if (pid != getpid())
93 		return (NULL);
94 	log_debug("client %p TMUX %s (session @%u)", c, envent->value, session);
95 	return (session_find_by_id(session));
96 }
97 
98 /* Find pane containing client if any. */
99 static struct window_pane *
100 cmd_find_inside_pane(struct client *c)
101 {
102 	struct window_pane	*wp;
103 
104 	if (c == NULL)
105 		return (NULL);
106 
107 	RB_FOREACH(wp, window_pane_tree, &all_window_panes) {
108 		if (strcmp(wp->tty, c->ttyname) == 0)
109 			break;
110 	}
111 	return (wp);
112 }
113 
114 /* Is this client better? */
115 static int
116 cmd_find_client_better(struct client *c, struct client *than)
117 {
118 	if (than == NULL)
119 		return (1);
120 	return (timercmp(&c->activity_time, &than->activity_time, >));
121 }
122 
123 /* Find best client for session. */
124 static struct client *
125 cmd_find_best_client(struct session *s)
126 {
127 	struct client	*c_loop, *c;
128 
129 	if (s->flags & SESSION_UNATTACHED)
130 		s = NULL;
131 
132 	c = NULL;
133 	TAILQ_FOREACH(c_loop, &clients, entry) {
134 		if (c_loop->session == NULL)
135 			continue;
136 		if (s != NULL && c_loop->session != s)
137 			continue;
138 		if (cmd_find_client_better(c_loop, c))
139 			c = c_loop;
140 	}
141 	return (c);
142 }
143 
144 /* Is this session better? */
145 static int
146 cmd_find_session_better(struct session *s, struct session *than, int flags)
147 {
148 	int	attached;
149 
150 	if (than == NULL)
151 		return (1);
152 	if (flags & CMD_FIND_PREFER_UNATTACHED) {
153 		attached = (~than->flags & SESSION_UNATTACHED);
154 		if (attached && (s->flags & SESSION_UNATTACHED))
155 			return (1);
156 		else if (!attached && (~s->flags & SESSION_UNATTACHED))
157 			return (0);
158 	}
159 	return (timercmp(&s->activity_time, &than->activity_time, >));
160 }
161 
162 /* Find best session from a list, or all if list is NULL. */
163 static struct session *
164 cmd_find_best_session(struct session **slist, u_int ssize, int flags)
165 {
166 	struct session	 *s_loop, *s;
167 	u_int		  i;
168 
169 	s = NULL;
170 	if (slist != NULL) {
171 		for (i = 0; i < ssize; i++) {
172 			if (cmd_find_session_better(slist[i], s, flags))
173 				s = slist[i];
174 		}
175 	} else {
176 		RB_FOREACH(s_loop, sessions, &sessions) {
177 			if (cmd_find_session_better(s_loop, s, flags))
178 				s = s_loop;
179 		}
180 	}
181 	return (s);
182 }
183 
184 /* Find best session and winlink for window. */
185 static int
186 cmd_find_best_session_with_window(struct cmd_find_state *fs)
187 {
188 	struct session	**slist = NULL;
189 	u_int		  ssize;
190 	struct session	 *s;
191 
192 	ssize = 0;
193 	RB_FOREACH(s, sessions, &sessions) {
194 		if (!session_has(s, fs->w))
195 			continue;
196 		slist = xreallocarray(slist, ssize + 1, sizeof *slist);
197 		slist[ssize++] = s;
198 	}
199 	if (ssize == 0)
200 		goto fail;
201 	fs->s = cmd_find_best_session(slist, ssize, fs->flags);
202 	if (fs->s == NULL)
203 		goto fail;
204 	free(slist);
205 	return (cmd_find_best_winlink_with_window(fs));
206 
207 fail:
208 	free(slist);
209 	return (-1);
210 }
211 
212 /*
213  * Find the best winlink for a window (the current if it contains the pane,
214  * otherwise the first).
215  */
216 static int
217 cmd_find_best_winlink_with_window(struct cmd_find_state *fs)
218 {
219 	struct winlink	 *wl, *wl_loop;
220 
221 	wl = NULL;
222 	if (fs->s->curw != NULL && fs->s->curw->window == fs->w)
223 		wl = fs->s->curw;
224 	else {
225 		RB_FOREACH(wl_loop, winlinks, &fs->s->windows) {
226 			if (wl_loop->window == fs->w) {
227 				wl = wl_loop;
228 				break;
229 			}
230 		}
231 	}
232 	if (wl == NULL)
233 		return (-1);
234 	fs->wl = wl;
235 	fs->idx = fs->wl->idx;
236 	return (0);
237 }
238 
239 /* Maps string in table. */
240 static const char *
241 cmd_find_map_table(const char *table[][2], const char *s)
242 {
243 	u_int	i;
244 
245 	for (i = 0; table[i][0] != NULL; i++) {
246 		if (strcmp(s, table[i][0]) == 0)
247 			return (table[i][1]);
248 	}
249 	return (s);
250 }
251 
252 /* Find session from string. Fills in s. */
253 static int
254 cmd_find_get_session(struct cmd_find_state *fs, const char *session)
255 {
256 	struct session	*s, *s_loop;
257 	struct client	*c;
258 
259 	log_debug("%s: %s", __func__, session);
260 
261 	/* Check for session ids starting with $. */
262 	if (*session == '$') {
263 		fs->s = session_find_by_id_str(session);
264 		if (fs->s == NULL)
265 			return (-1);
266 		return (0);
267 	}
268 
269 	/* Look for exactly this session. */
270 	fs->s = session_find(session);
271 	if (fs->s != NULL)
272 		return (0);
273 
274 	/* Look for as a client. */
275 	c = cmd_find_client(NULL, session, 1);
276 	if (c != NULL && c->session != NULL) {
277 		fs->s = c->session;
278 		return (0);
279 	}
280 
281 	/* Stop now if exact only. */
282 	if (fs->flags & CMD_FIND_EXACT_SESSION)
283 		return (-1);
284 
285 	/* Otherwise look for prefix. */
286 	s = NULL;
287 	RB_FOREACH(s_loop, sessions, &sessions) {
288 		if (strncmp(session, s_loop->name, strlen(session)) == 0) {
289 			if (s != NULL)
290 				return (-1);
291 			s = s_loop;
292 		}
293 	}
294 	if (s != NULL) {
295 		fs->s = s;
296 		return (0);
297 	}
298 
299 	/* Then as a pattern. */
300 	s = NULL;
301 	RB_FOREACH(s_loop, sessions, &sessions) {
302 		if (fnmatch(session, s_loop->name, 0) == 0) {
303 			if (s != NULL)
304 				return (-1);
305 			s = s_loop;
306 		}
307 	}
308 	if (s != NULL) {
309 		fs->s = s;
310 		return (0);
311 	}
312 
313 	return (-1);
314 }
315 
316 /* Find window from string. Fills in s, wl, w. */
317 static int
318 cmd_find_get_window(struct cmd_find_state *fs, const char *window, int only)
319 {
320 	log_debug("%s: %s", __func__, window);
321 
322 	/* Check for window ids starting with @. */
323 	if (*window == '@') {
324 		fs->w = window_find_by_id_str(window);
325 		if (fs->w == NULL)
326 			return (-1);
327 		return (cmd_find_best_session_with_window(fs));
328 	}
329 
330 	/* Not a window id, so use the current session. */
331 	fs->s = fs->current->s;
332 
333 	/* We now only need to find the winlink in this session. */
334 	if (cmd_find_get_window_with_session(fs, window) == 0)
335 		return (0);
336 
337 	/* Otherwise try as a session itself. */
338 	if (!only && cmd_find_get_session(fs, window) == 0) {
339 		fs->wl = fs->s->curw;
340 		fs->w = fs->wl->window;
341 		if (~fs->flags & CMD_FIND_WINDOW_INDEX)
342 			fs->idx = fs->wl->idx;
343 		return (0);
344 	}
345 
346 	return (-1);
347 }
348 
349 /*
350  * Find window from string, assuming it is in given session. Needs s, fills in
351  * wl and w.
352  */
353 static int
354 cmd_find_get_window_with_session(struct cmd_find_state *fs, const char *window)
355 {
356 	struct winlink	*wl;
357 	const char	*errstr;
358 	int		 idx, n, exact;
359 	struct session	*s;
360 
361 	log_debug("%s: %s", __func__, window);
362 	exact = (fs->flags & CMD_FIND_EXACT_WINDOW);
363 
364 	/*
365 	 * Start with the current window as the default. So if only an index is
366 	 * found, the window will be the current.
367 	 */
368 	fs->wl = fs->s->curw;
369 	fs->w = fs->wl->window;
370 
371 	/* Check for window ids starting with @. */
372 	if (*window == '@') {
373 		fs->w = window_find_by_id_str(window);
374 		if (fs->w == NULL || !session_has(fs->s, fs->w))
375 			return (-1);
376 		return (cmd_find_best_winlink_with_window(fs));
377 	}
378 
379 	/* Try as an offset. */
380 	if (!exact && (window[0] == '+' || window[0] == '-')) {
381 		if (window[1] != '\0')
382 			n = strtonum(window + 1, 1, INT_MAX, NULL);
383 		else
384 			n = 1;
385 		s = fs->s;
386 		if (fs->flags & CMD_FIND_WINDOW_INDEX) {
387 			if (window[0] == '+') {
388 				if (INT_MAX - s->curw->idx < n)
389 					return (-1);
390 				fs->idx = s->curw->idx + n;
391 			} else {
392 				if (n < s->curw->idx)
393 					return (-1);
394 				fs->idx = s->curw->idx - n;
395 			}
396 			return (0);
397 		}
398 		if (window[0] == '+')
399 			fs->wl = winlink_next_by_number(s->curw, s, n);
400 		else
401 			fs->wl = winlink_previous_by_number(s->curw, s, n);
402 		if (fs->wl != NULL) {
403 			fs->idx = fs->wl->idx;
404 			fs->w = fs->wl->window;
405 			return (0);
406 		}
407 	}
408 
409 	/* Try special characters. */
410 	if (!exact) {
411 		if (strcmp(window, "!") == 0) {
412 			fs->wl = TAILQ_FIRST(&fs->s->lastw);
413 			if (fs->wl == NULL)
414 				return (-1);
415 			fs->idx = fs->wl->idx;
416 			fs->w = fs->wl->window;
417 			return (0);
418 		} else if (strcmp(window, "^") == 0) {
419 			fs->wl = RB_MIN(winlinks, &fs->s->windows);
420 			if (fs->wl == NULL)
421 				return (-1);
422 			fs->idx = fs->wl->idx;
423 			fs->w = fs->wl->window;
424 			return (0);
425 		} else if (strcmp(window, "$") == 0) {
426 			fs->wl = RB_MAX(winlinks, &fs->s->windows);
427 			if (fs->wl == NULL)
428 				return (-1);
429 			fs->idx = fs->wl->idx;
430 			fs->w = fs->wl->window;
431 			return (0);
432 		}
433 	}
434 
435 	/* First see if this is a valid window index in this session. */
436 	if (window[0] != '+' && window[0] != '-') {
437 		idx = strtonum(window, 0, INT_MAX, &errstr);
438 		if (errstr == NULL) {
439 			if (fs->flags & CMD_FIND_WINDOW_INDEX) {
440 				fs->idx = idx;
441 				return (0);
442 			}
443 			fs->wl = winlink_find_by_index(&fs->s->windows, idx);
444 			if (fs->wl != NULL) {
445 				fs->w = fs->wl->window;
446 				return (0);
447 			}
448 		}
449 	}
450 
451 	/* Look for exact matches, error if more than one. */
452 	fs->wl = NULL;
453 	RB_FOREACH(wl, winlinks, &fs->s->windows) {
454 		if (strcmp(window, wl->window->name) == 0) {
455 			if (fs->wl != NULL)
456 				return (-1);
457 			fs->wl = wl;
458 		}
459 	}
460 	if (fs->wl != NULL) {
461 		fs->idx = fs->wl->idx;
462 		fs->w = fs->wl->window;
463 		return (0);
464 	}
465 
466 	/* Stop now if exact only. */
467 	if (exact)
468 		return (-1);
469 
470 	/* Try as the start of a window name, error if multiple. */
471 	fs->wl = NULL;
472 	RB_FOREACH(wl, winlinks, &fs->s->windows) {
473 		if (strncmp(window, wl->window->name, strlen(window)) == 0) {
474 			if (fs->wl != NULL)
475 				return (-1);
476 			fs->wl = wl;
477 		}
478 	}
479 	if (fs->wl != NULL) {
480 		fs->idx = fs->wl->idx;
481 		fs->w = fs->wl->window;
482 		return (0);
483 	}
484 
485 	/* Now look for pattern matches, again error if multiple. */
486 	fs->wl = NULL;
487 	RB_FOREACH(wl, winlinks, &fs->s->windows) {
488 		if (fnmatch(window, wl->window->name, 0) == 0) {
489 			if (fs->wl != NULL)
490 				return (-1);
491 			fs->wl = wl;
492 		}
493 	}
494 	if (fs->wl != NULL) {
495 		fs->idx = fs->wl->idx;
496 		fs->w = fs->wl->window;
497 		return (0);
498 	}
499 
500 	return (-1);
501 }
502 
503 /* Find pane from string. Fills in s, wl, w, wp. */
504 static int
505 cmd_find_get_pane(struct cmd_find_state *fs, const char *pane, int only)
506 {
507 	log_debug("%s: %s", __func__, pane);
508 
509 	/* Check for pane ids starting with %. */
510 	if (*pane == '%') {
511 		fs->wp = window_pane_find_by_id_str(pane);
512 		if (fs->wp == NULL)
513 			return (-1);
514 		fs->w = fs->wp->window;
515 		return (cmd_find_best_session_with_window(fs));
516 	}
517 
518 	/* Not a pane id, so try the current session and window. */
519 	fs->s = fs->current->s;
520 	fs->wl = fs->current->wl;
521 	fs->idx = fs->current->idx;
522 	fs->w = fs->current->w;
523 
524 	/* We now only need to find the pane in this window. */
525 	if (cmd_find_get_pane_with_window(fs, pane) == 0)
526 		return (0);
527 
528 	/* Otherwise try as a window itself (this will also try as session). */
529 	if (!only && cmd_find_get_window(fs, pane, 0) == 0) {
530 		fs->wp = fs->w->active;
531 		return (0);
532 	}
533 
534 	return (-1);
535 }
536 
537 /*
538  * Find pane from string, assuming it is in given session. Needs s, fills in wl
539  * and w and wp.
540  */
541 static int
542 cmd_find_get_pane_with_session(struct cmd_find_state *fs, const char *pane)
543 {
544 	log_debug("%s: %s", __func__, pane);
545 
546 	/* Check for pane ids starting with %. */
547 	if (*pane == '%') {
548 		fs->wp = window_pane_find_by_id_str(pane);
549 		if (fs->wp == NULL)
550 			return (-1);
551 		fs->w = fs->wp->window;
552 		return (cmd_find_best_winlink_with_window(fs));
553 	}
554 
555 	/* Otherwise use the current window. */
556 	fs->wl = fs->s->curw;
557 	fs->idx = fs->wl->idx;
558 	fs->w = fs->wl->window;
559 
560 	/* Now we just need to look up the pane. */
561 	return (cmd_find_get_pane_with_window(fs, pane));
562 }
563 
564 /*
565  * Find pane from string, assuming it is in the given window. Needs w, fills in
566  * wp.
567  */
568 static int
569 cmd_find_get_pane_with_window(struct cmd_find_state *fs, const char *pane)
570 {
571 	const char		*errstr;
572 	int			 idx;
573 	struct window_pane	*wp;
574 	u_int			 n;
575 
576 	log_debug("%s: %s", __func__, pane);
577 
578 	/* Check for pane ids starting with %. */
579 	if (*pane == '%') {
580 		fs->wp = window_pane_find_by_id_str(pane);
581 		if (fs->wp == NULL)
582 			return (-1);
583 		if (fs->wp->window != fs->w)
584 			return (-1);
585 		return (0);
586 	}
587 
588 	/* Try special characters. */
589 	if (strcmp(pane, "!") == 0) {
590 		if (fs->w->last == NULL)
591 			return (-1);
592 		fs->wp = fs->w->last;
593 		if (fs->wp == NULL)
594 			return (-1);
595 		return (0);
596 	} else if (strcmp(pane, "{up-of}") == 0) {
597 		fs->wp = window_pane_find_up(fs->w->active);
598 		if (fs->wp == NULL)
599 			return (-1);
600 		return (0);
601 	} else if (strcmp(pane, "{down-of}") == 0) {
602 		fs->wp = window_pane_find_down(fs->w->active);
603 		if (fs->wp == NULL)
604 			return (-1);
605 		return (0);
606 	} else if (strcmp(pane, "{left-of}") == 0) {
607 		fs->wp = window_pane_find_left(fs->w->active);
608 		if (fs->wp == NULL)
609 			return (-1);
610 		return (0);
611 	} else if (strcmp(pane, "{right-of}") == 0) {
612 		fs->wp = window_pane_find_right(fs->w->active);
613 		if (fs->wp == NULL)
614 			return (-1);
615 		return (0);
616 	}
617 
618 	/* Try as an offset. */
619 	if (pane[0] == '+' || pane[0] == '-') {
620 		if (pane[1] != '\0')
621 			n = strtonum(pane + 1, 1, INT_MAX, NULL);
622 		else
623 			n = 1;
624 		wp = fs->w->active;
625 		if (pane[0] == '+')
626 			fs->wp = window_pane_next_by_number(fs->w, wp, n);
627 		else
628 			fs->wp = window_pane_previous_by_number(fs->w, wp, n);
629 		if (fs->wp != NULL)
630 			return (0);
631 	}
632 
633 	/* Get pane by index. */
634 	idx = strtonum(pane, 0, INT_MAX, &errstr);
635 	if (errstr == NULL) {
636 		fs->wp = window_pane_at_index(fs->w, idx);
637 		if (fs->wp != NULL)
638 			return (0);
639 	}
640 
641 	/* Try as a description. */
642 	fs->wp = window_find_string(fs->w, pane);
643 	if (fs->wp != NULL)
644 		return (0);
645 
646 	return (-1);
647 }
648 
649 /* Clear state. */
650 void
651 cmd_find_clear_state(struct cmd_find_state *fs, int flags)
652 {
653 	memset(fs, 0, sizeof *fs);
654 
655 	fs->flags = flags;
656 
657 	fs->idx = -1;
658 }
659 
660 /* Check if state is empty. */
661 int
662 cmd_find_empty_state(struct cmd_find_state *fs)
663 {
664 	if (fs->s == NULL && fs->wl == NULL && fs->w == NULL && fs->wp == NULL)
665 		return (1);
666 	return (0);
667 }
668 
669 /* Check if a state if valid. */
670 int
671 cmd_find_valid_state(struct cmd_find_state *fs)
672 {
673 	struct winlink	*wl;
674 
675 	if (fs->s == NULL || fs->wl == NULL || fs->w == NULL || fs->wp == NULL)
676 		return (0);
677 
678 	if (!session_alive(fs->s))
679 		return (0);
680 
681 	RB_FOREACH(wl, winlinks, &fs->s->windows) {
682 		if (wl->window == fs->w && wl == fs->wl)
683 			break;
684 	}
685 	if (wl == NULL)
686 		return (0);
687 
688 	if (fs->w != fs->wl->window)
689 		return (0);
690 
691 	return (window_has_pane(fs->w, fs->wp));
692 }
693 
694 /* Copy a state. */
695 void
696 cmd_find_copy_state(struct cmd_find_state *dst, struct cmd_find_state *src)
697 {
698 	dst->s = src->s;
699 	dst->wl = src->wl;
700 	dst->idx = src->idx;
701 	dst->w = src->w;
702 	dst->wp = src->wp;
703 }
704 
705 /* Log the result. */
706 void
707 cmd_find_log_state(const char *prefix, struct cmd_find_state *fs)
708 {
709 	if (fs->s != NULL)
710 		log_debug("%s: s=$%u", prefix, fs->s->id);
711 	else
712 		log_debug("%s: s=none", prefix);
713 	if (fs->wl != NULL) {
714 		log_debug("%s: wl=%u %d w=@%u %s", prefix, fs->wl->idx,
715 		    fs->wl->window == fs->w, fs->w->id, fs->w->name);
716 	} else
717 		log_debug("%s: wl=none", prefix);
718 	if (fs->wp != NULL)
719 		log_debug("%s: wp=%%%u", prefix, fs->wp->id);
720 	else
721 		log_debug("%s: wp=none", prefix);
722 	if (fs->idx != -1)
723 		log_debug("%s: idx=%d", prefix, fs->idx);
724 	else
725 		log_debug("%s: idx=none", prefix);
726 }
727 
728 /* Find state from a session. */
729 void
730 cmd_find_from_session(struct cmd_find_state *fs, struct session *s, int flags)
731 {
732 	cmd_find_clear_state(fs, flags);
733 
734 	fs->s = s;
735 	fs->wl = fs->s->curw;
736 	fs->w = fs->wl->window;
737 	fs->wp = fs->w->active;
738 
739 	cmd_find_log_state(__func__, fs);
740 }
741 
742 /* Find state from a winlink. */
743 void
744 cmd_find_from_winlink(struct cmd_find_state *fs, struct winlink *wl, int flags)
745 {
746 	cmd_find_clear_state(fs, flags);
747 
748 	fs->s = wl->session;
749 	fs->wl = wl;
750 	fs->w = wl->window;
751 	fs->wp = wl->window->active;
752 
753 	cmd_find_log_state(__func__, fs);
754 }
755 
756 /* Find state from a session and window. */
757 int
758 cmd_find_from_session_window(struct cmd_find_state *fs, struct session *s,
759     struct window *w, int flags)
760 {
761 	cmd_find_clear_state(fs, flags);
762 
763 	fs->s = s;
764 	fs->w = w;
765 	if (cmd_find_best_winlink_with_window(fs) != 0) {
766 		cmd_find_clear_state(fs, flags);
767 		return (-1);
768 	}
769 	fs->wp = fs->w->active;
770 
771 	cmd_find_log_state(__func__, fs);
772 	return (0);
773 }
774 
775 /* Find state from a window. */
776 int
777 cmd_find_from_window(struct cmd_find_state *fs, struct window *w, int flags)
778 {
779 	cmd_find_clear_state(fs, flags);
780 
781 	fs->w = w;
782 	if (cmd_find_best_session_with_window(fs) != 0) {
783 		cmd_find_clear_state(fs, flags);
784 		return (-1);
785 	}
786 	if (cmd_find_best_winlink_with_window(fs) != 0) {
787 		cmd_find_clear_state(fs, flags);
788 		return (-1);
789 	}
790 	fs->wp = fs->w->active;
791 
792 	cmd_find_log_state(__func__, fs);
793 	return (0);
794 }
795 
796 /* Find state from a winlink and pane. */
797 void
798 cmd_find_from_winlink_pane(struct cmd_find_state *fs, struct winlink *wl,
799     struct window_pane *wp, int flags)
800 {
801 	cmd_find_clear_state(fs, flags);
802 
803 	fs->s = wl->session;
804 	fs->wl = wl;
805 	fs->idx = fs->wl->idx;
806 	fs->w = fs->wl->window;
807 	fs->wp = wp;
808 
809 	cmd_find_log_state(__func__, fs);
810 }
811 
812 /* Find state from a pane. */
813 int
814 cmd_find_from_pane(struct cmd_find_state *fs, struct window_pane *wp, int flags)
815 {
816 	if (cmd_find_from_window(fs, wp->window, flags) != 0)
817 		return (-1);
818 	fs->wp = wp;
819 
820 	cmd_find_log_state(__func__, fs);
821 	return (0);
822 }
823 
824 /* Find state from nothing. */
825 int
826 cmd_find_from_nothing(struct cmd_find_state *fs, int flags)
827 {
828 	cmd_find_clear_state(fs, flags);
829 
830 	fs->s = cmd_find_best_session(NULL, 0, flags);
831 	if (fs->s == NULL) {
832 		cmd_find_clear_state(fs, flags);
833 		return (-1);
834 	}
835 	fs->wl = fs->s->curw;
836 	fs->idx = fs->wl->idx;
837 	fs->w = fs->wl->window;
838 	fs->wp = fs->w->active;
839 
840 	cmd_find_log_state(__func__, fs);
841 	return (0);
842 }
843 
844 /* Find state from mouse. */
845 int
846 cmd_find_from_mouse(struct cmd_find_state *fs, struct mouse_event *m, int flags)
847 {
848 	cmd_find_clear_state(fs, flags);
849 
850 	if (!m->valid)
851 		return (-1);
852 
853 	fs->wp = cmd_mouse_pane(m, &fs->s, &fs->wl);
854 	if (fs->wp == NULL) {
855 		cmd_find_clear_state(fs, flags);
856 		return (-1);
857 	}
858 	fs->w = fs->wl->window;
859 
860 	cmd_find_log_state(__func__, fs);
861 	return (0);
862 }
863 
864 /* Find state from client. */
865 int
866 cmd_find_from_client(struct cmd_find_state *fs, struct client *c, int flags)
867 {
868 	struct session		*s;
869 	struct winlink		*wl;
870 	struct window_pane	*wp;
871 
872 	/* If no client, treat as from nothing. */
873 	if (c == NULL)
874 		return (cmd_find_from_nothing(fs, flags));
875 
876 	/* If this is an attached client, all done. */
877 	if (c->session != NULL) {
878 		cmd_find_from_session(fs, c->session, flags);
879 		return (0);
880 	}
881 	cmd_find_clear_state(fs, flags);
882 
883 	/*
884 	 * If this is an unattached client running in a pane, we can use that
885 	 * to limit the list of sessions to those containing that pane.
886 	 */
887 	wp = cmd_find_inside_pane(c);
888 	if (wp == NULL)
889 		goto unknown_pane;
890 
891 	/* If we have a session in TMUX, see if it has this pane. */
892 	s = cmd_find_try_TMUX(c);
893 	if (s != NULL) {
894 		RB_FOREACH(wl, winlinks, &s->windows) {
895 			if (window_has_pane(wl->window, wp))
896 				break;
897 		}
898 		if (wl != NULL) {
899 			fs->s = s;
900 			fs->wl = s->curw; /* use current session */
901 			fs->w = fs->wl->window;
902 			fs->wp = fs->w->active; /* use active pane */
903 
904 			cmd_find_log_state(__func__, fs);
905 			return (0);
906 		}
907 	}
908 
909 	/*
910 	 * Don't have a session, or it doesn't have this pane. Try all
911 	 * sessions.
912 	 */
913 	fs->w = wp->window;
914 	if (cmd_find_best_session_with_window(fs) != 0) {
915 		if (wp != NULL) {
916 			/*
917 			 * The window may have been destroyed but the pane
918 			 * still on all_window_panes due to something else
919 			 * holding a reference.
920 			 */
921 			goto unknown_pane;
922 		}
923 		cmd_find_clear_state(fs, 0);
924 		return (-1);
925 	}
926 	fs->wl = fs->s->curw;
927 	fs->w = fs->wl->window;
928 	fs->wp = fs->w->active; /* use active pane */
929 
930 	cmd_find_log_state(__func__, fs);
931 	return (0);
932 
933 unknown_pane:
934 	/*
935 	 * We're not running in a known pane, but maybe this client has TMUX
936 	 * in the environment. That'd give us a session.
937 	 */
938 	s = cmd_find_try_TMUX(c);
939 	if (s != NULL) {
940 		cmd_find_from_session(fs, s, flags);
941 		return (0);
942 	}
943 
944 	/* Otherwise we need to guess. */
945 	return (cmd_find_from_nothing(fs, flags));
946 }
947 
948 /*
949  * Split target into pieces and resolve for the given type. Fills in the given
950  * state. Returns 0 on success or -1 on error.
951  */
952 int
953 cmd_find_target(struct cmd_find_state *fs, struct cmdq_item *item,
954     const char *target, enum cmd_find_type type, int flags)
955 {
956 	struct mouse_event	*m;
957 	struct cmd_find_state	 current;
958 	char			*colon, *period, *copy = NULL;
959 	const char		*session, *window, *pane, *s;
960 	int			 window_only = 0, pane_only = 0;
961 
962 	/* Can fail flag implies quiet. */
963 	if (flags & CMD_FIND_CANFAIL)
964 		flags |= CMD_FIND_QUIET;
965 
966 	/* Log the arguments. */
967 	if (type == CMD_FIND_PANE)
968 		s = "pane";
969 	else if (type == CMD_FIND_WINDOW)
970 		s = "window";
971 	else if (type == CMD_FIND_SESSION)
972 		s = "session";
973 	else
974 		s = "unknown";
975 	if (target == NULL)
976 		log_debug("%s: target none, type %s", __func__, s);
977 	else
978 		log_debug("%s: target %s, type %s", __func__, target, s);
979 	log_debug("%s: item %p, flags %#x", __func__, item, flags);
980 
981 	/* Clear new state. */
982 	cmd_find_clear_state(fs, flags);
983 
984 	/* Find current state. */
985 	if (server_check_marked() && (flags & CMD_FIND_DEFAULT_MARKED)) {
986 		fs->current = &marked_pane;
987 		log_debug("%s: current is marked pane", __func__);
988 	} else if (cmd_find_valid_state(&item->shared->current)) {
989 		fs->current = &item->shared->current;
990 		log_debug("%s: current is from queue", __func__);
991 	} else if (cmd_find_from_client(&current, item->client, flags) == 0) {
992 		fs->current = &current;
993 		log_debug("%s: current is from client", __func__);
994 	} else {
995 		if (~flags & CMD_FIND_QUIET)
996 			cmdq_error(item, "no current target");
997 		goto error;
998 	}
999 	if (!cmd_find_valid_state(fs->current))
1000 		fatalx("invalid current find state");
1001 
1002 	/* An empty or NULL target is the current. */
1003 	if (target == NULL || *target == '\0')
1004 		goto current;
1005 
1006 	/* Mouse target is a plain = or {mouse}. */
1007 	if (strcmp(target, "=") == 0 || strcmp(target, "{mouse}") == 0) {
1008 		m = &item->shared->mouse;
1009 		switch (type) {
1010 		case CMD_FIND_PANE:
1011 			fs->wp = cmd_mouse_pane(m, &fs->s, &fs->wl);
1012 			if (fs->wp != NULL)
1013 				fs->w = fs->wl->window;
1014 			break;
1015 		case CMD_FIND_WINDOW:
1016 		case CMD_FIND_SESSION:
1017 			fs->wl = cmd_mouse_window(m, &fs->s);
1018 			if (fs->wl != NULL) {
1019 				fs->w = fs->wl->window;
1020 				fs->wp = fs->w->active;
1021 			}
1022 			break;
1023 		}
1024 		if (fs->wp == NULL) {
1025 			if (~flags & CMD_FIND_QUIET)
1026 				cmdq_error(item, "no mouse target");
1027 			goto error;
1028 		}
1029 		goto found;
1030 	}
1031 
1032 	/* Marked target is a plain ~ or {marked}. */
1033 	if (strcmp(target, "~") == 0 || strcmp(target, "{marked}") == 0) {
1034 		if (!server_check_marked()) {
1035 			if (~flags & CMD_FIND_QUIET)
1036 				cmdq_error(item, "no marked target");
1037 			goto error;
1038 		}
1039 		cmd_find_copy_state(fs, &marked_pane);
1040 		goto found;
1041 	}
1042 
1043 	/* Find separators if they exist. */
1044 	copy = xstrdup(target);
1045 	colon = strchr(copy, ':');
1046 	if (colon != NULL)
1047 		*colon++ = '\0';
1048 	if (colon == NULL)
1049 		period = strchr(copy, '.');
1050 	else
1051 		period = strchr(colon, '.');
1052 	if (period != NULL)
1053 		*period++ = '\0';
1054 
1055 	/* Set session, window and pane parts. */
1056 	session = window = pane = NULL;
1057 	if (colon != NULL && period != NULL) {
1058 		session = copy;
1059 		window = colon;
1060 		window_only = 1;
1061 		pane = period;
1062 		pane_only = 1;
1063 	} else if (colon != NULL && period == NULL) {
1064 		session = copy;
1065 		window = colon;
1066 		window_only = 1;
1067 	} else if (colon == NULL && period != NULL) {
1068 		window = copy;
1069 		pane = period;
1070 		pane_only = 1;
1071 	} else {
1072 		if (*copy == '$')
1073 			session = copy;
1074 		else if (*copy == '@')
1075 			window = copy;
1076 		else if (*copy == '%')
1077 			pane = copy;
1078 		else {
1079 			switch (type) {
1080 			case CMD_FIND_SESSION:
1081 				session = copy;
1082 				break;
1083 			case CMD_FIND_WINDOW:
1084 				window = copy;
1085 				break;
1086 			case CMD_FIND_PANE:
1087 				pane = copy;
1088 				break;
1089 			}
1090 		}
1091 	}
1092 
1093 	/* Set exact match flags. */
1094 	if (session != NULL && *session == '=') {
1095 		session++;
1096 		fs->flags |= CMD_FIND_EXACT_SESSION;
1097 	}
1098 	if (window != NULL && *window == '=') {
1099 		window++;
1100 		fs->flags |= CMD_FIND_EXACT_WINDOW;
1101 	}
1102 
1103 	/* Empty is the same as NULL. */
1104 	if (session != NULL && *session == '\0')
1105 		session = NULL;
1106 	if (window != NULL && *window == '\0')
1107 		window = NULL;
1108 	if (pane != NULL && *pane == '\0')
1109 		pane = NULL;
1110 
1111 	/* Map though conversion table. */
1112 	if (session != NULL)
1113 		session = cmd_find_map_table(cmd_find_session_table, session);
1114 	if (window != NULL)
1115 		window = cmd_find_map_table(cmd_find_window_table, window);
1116 	if (pane != NULL)
1117 		pane = cmd_find_map_table(cmd_find_pane_table, pane);
1118 
1119 	log_debug("%s: target %s (flags %#x): session=%s, window=%s, pane=%s",
1120 	    __func__, target, flags, session == NULL ? "none" : session,
1121 	    window == NULL ? "none" : window, pane == NULL ? "none" : pane);
1122 
1123 	/* No pane is allowed if want an index. */
1124 	if (pane != NULL && (flags & CMD_FIND_WINDOW_INDEX)) {
1125 		if (~flags & CMD_FIND_QUIET)
1126 			cmdq_error(item, "can't specify pane here");
1127 		goto error;
1128 	}
1129 
1130 	/* If the session isn't NULL, look it up. */
1131 	if (session != NULL) {
1132 		/* This will fill in session. */
1133 		if (cmd_find_get_session(fs, session) != 0)
1134 			goto no_session;
1135 
1136 		/* If window and pane are NULL, use that session's current. */
1137 		if (window == NULL && pane == NULL) {
1138 			fs->wl = fs->s->curw;
1139 			fs->idx = -1;
1140 			fs->w = fs->wl->window;
1141 			fs->wp = fs->w->active;
1142 			goto found;
1143 		}
1144 
1145 		/* If window is present but pane not, find window in session. */
1146 		if (window != NULL && pane == NULL) {
1147 			/* This will fill in winlink and window. */
1148 			if (cmd_find_get_window_with_session(fs, window) != 0)
1149 				goto no_window;
1150 			fs->wp = fs->wl->window->active;
1151 			goto found;
1152 		}
1153 
1154 		/* If pane is present but window not, find pane. */
1155 		if (window == NULL && pane != NULL) {
1156 			/* This will fill in winlink and window and pane. */
1157 			if (cmd_find_get_pane_with_session(fs, pane) != 0)
1158 				goto no_pane;
1159 			goto found;
1160 		}
1161 
1162 		/*
1163 		 * If window and pane are present, find both in session. This
1164 		 * will fill in winlink and window.
1165 		 */
1166 		if (cmd_find_get_window_with_session(fs, window) != 0)
1167 			goto no_window;
1168 		/* This will fill in pane. */
1169 		if (cmd_find_get_pane_with_window(fs, pane) != 0)
1170 			goto no_pane;
1171 		goto found;
1172 	}
1173 
1174 	/* No session. If window and pane, try them. */
1175 	if (window != NULL && pane != NULL) {
1176 		/* This will fill in session, winlink and window. */
1177 		if (cmd_find_get_window(fs, window, window_only) != 0)
1178 			goto no_window;
1179 		/* This will fill in pane. */
1180 		if (cmd_find_get_pane_with_window(fs, pane) != 0)
1181 			goto no_pane;
1182 		goto found;
1183 	}
1184 
1185 	/* If just window is present, try it. */
1186 	if (window != NULL && pane == NULL) {
1187 		/* This will fill in session, winlink and window. */
1188 		if (cmd_find_get_window(fs, window, window_only) != 0)
1189 			goto no_window;
1190 		fs->wp = fs->wl->window->active;
1191 		goto found;
1192 	}
1193 
1194 	/* If just pane is present, try it. */
1195 	if (window == NULL && pane != NULL) {
1196 		/* This will fill in session, winlink, window and pane. */
1197 		if (cmd_find_get_pane(fs, pane, pane_only) != 0)
1198 			goto no_pane;
1199 		goto found;
1200 	}
1201 
1202 current:
1203 	/* Use the current session. */
1204 	cmd_find_copy_state(fs, fs->current);
1205 	if (flags & CMD_FIND_WINDOW_INDEX)
1206 		fs->idx = -1;
1207 	goto found;
1208 
1209 error:
1210 	fs->current = NULL;
1211 	log_debug("%s: error", __func__);
1212 
1213 	free(copy);
1214 	if (flags & CMD_FIND_CANFAIL)
1215 		return (0);
1216 	return (-1);
1217 
1218 found:
1219 	fs->current = NULL;
1220 	cmd_find_log_state(__func__, fs);
1221 
1222 	free(copy);
1223 	return (0);
1224 
1225 no_session:
1226 	if (~flags & CMD_FIND_QUIET)
1227 		cmdq_error(item, "can't find session %s", session);
1228 	goto error;
1229 
1230 no_window:
1231 	if (~flags & CMD_FIND_QUIET)
1232 		cmdq_error(item, "can't find window %s", window);
1233 	goto error;
1234 
1235 no_pane:
1236 	if (~flags & CMD_FIND_QUIET)
1237 		cmdq_error(item, "can't find pane %s", pane);
1238 	goto error;
1239 }
1240 
1241 /* Find the current client. */
1242 static struct client *
1243 cmd_find_current_client(struct cmdq_item *item, int quiet)
1244 {
1245 	struct client		*c;
1246 	struct session		*s;
1247 	struct window_pane	*wp;
1248 	struct cmd_find_state	 fs;
1249 
1250 	if (item->client != NULL && item->client->session != NULL)
1251 		return (item->client);
1252 
1253 	c = NULL;
1254 	if ((wp = cmd_find_inside_pane(item->client)) != NULL) {
1255 		cmd_find_clear_state(&fs, CMD_FIND_QUIET);
1256 		fs.w = wp->window;
1257 		if (cmd_find_best_session_with_window(&fs) == 0)
1258 			c = cmd_find_best_client(fs.s);
1259 	} else {
1260 		s = cmd_find_best_session(NULL, 0, CMD_FIND_QUIET);
1261 		if (s != NULL)
1262 			c = cmd_find_best_client(s);
1263 	}
1264 	if (c == NULL && !quiet)
1265 		cmdq_error(item, "no current client");
1266 	log_debug("%s: no target, return %p", __func__, c);
1267 	return (c);
1268 }
1269 
1270 /* Find the target client or report an error and return NULL. */
1271 struct client *
1272 cmd_find_client(struct cmdq_item *item, const char *target, int quiet)
1273 {
1274 	struct client	*c;
1275 	char		*copy;
1276 	size_t		 size;
1277 
1278 	/* A NULL argument means the current client. */
1279 	if (target == NULL)
1280 		return (cmd_find_current_client(item, quiet));
1281 	copy = xstrdup(target);
1282 
1283 	/* Trim a single trailing colon if any. */
1284 	size = strlen(copy);
1285 	if (size != 0 && copy[size - 1] == ':')
1286 		copy[size - 1] = '\0';
1287 
1288 	/* Check name and path of each client. */
1289 	TAILQ_FOREACH(c, &clients, entry) {
1290 		if (c->session == NULL)
1291 			continue;
1292 		if (strcmp(copy, c->name) == 0)
1293 			break;
1294 
1295 		if (*c->ttyname == '\0')
1296 			continue;
1297 		if (strcmp(copy, c->ttyname) == 0)
1298 			break;
1299 		if (strncmp(c->ttyname, _PATH_DEV, (sizeof _PATH_DEV) - 1) != 0)
1300 			continue;
1301 		if (strcmp(copy, c->ttyname + (sizeof _PATH_DEV) - 1) == 0)
1302 			break;
1303 	}
1304 
1305 	/* If no client found, report an error. */
1306 	if (c == NULL && !quiet)
1307 		cmdq_error(item, "can't find client %s", copy);
1308 
1309 	free(copy);
1310 	log_debug("%s: target %s, return %p", __func__, target, c);
1311 	return (c);
1312 }
1313