yazi_core/tab/commands/
shell.rs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
use std::{borrow::Cow, fmt::Display};

use anyhow::bail;
use yazi_config::{open::Opener, popup::InputCfg};
use yazi_proxy::{AppProxy, InputProxy, TasksProxy};
use yazi_shared::{event::{CmdCow, Data}, url::Url};

use crate::tab::Tab;

pub struct Opt {
	run: Cow<'static, str>,
	cwd: Option<Url>,

	block:       bool,
	orphan:      bool,
	interactive: bool,

	cursor: Option<usize>,
}

impl TryFrom<CmdCow> for Opt {
	type Error = anyhow::Error;

	fn try_from(mut c: CmdCow) -> Result<Self, Self::Error> {
		let me = Self {
			run: c.take_first_str().unwrap_or_default(),
			cwd: c.take_url("cwd"),

			block:       c.bool("block"),
			orphan:      c.bool("orphan"),
			interactive: c.bool("interactive"),

			cursor: c.get("cursor").and_then(Data::as_usize),
		};

		if me.cursor.is_some_and(|c| c > me.run.chars().count()) {
			bail!("The cursor position is out of bounds.");
		}

		Ok(me)
	}
}

impl Tab {
	pub fn shell(&mut self, opt: impl TryInto<Opt, Error = impl Display>) {
		if !self.try_escape_visual() {
			return;
		}

		let mut opt = match opt.try_into() {
			Ok(o) => o as Opt,
			Err(e) => return AppProxy::notify_warn("`shell` command", e),
		};

		let cwd = opt.cwd.take().unwrap_or_else(|| self.cwd().clone());
		let selected = self.hovered_and_selected().cloned().collect();
		tokio::spawn(async move {
			if opt.interactive {
				let mut result =
					InputProxy::show(InputCfg::shell(opt.block).with_value(opt.run).with_cursor(opt.cursor));
				match result.recv().await {
					Some(Ok(e)) => opt.run = Cow::Owned(e),
					_ => return,
				}
			}
			if opt.run.is_empty() {
				return;
			}

			TasksProxy::open_with(
				Cow::Owned(Opener {
					run:    opt.run.into_owned(),
					block:  opt.block,
					orphan: opt.orphan,
					desc:   Default::default(),
					for_:   None,
					spread: true,
				}),
				cwd,
				selected,
			);
		});
	}
}