1use std::ffi::OsString;
11#[cfg(unix)]
12use std::os::unix::process::CommandExt;
13use std::path::PathBuf;
14use std::process::{Child, Command as ChildCommand, Stdio};
15
16pub struct Open<Msg> {
41 program: OsString,
42 args: Vec<OsString>,
43 target: Option<OsString>,
44 dir: Option<PathBuf>,
45 env: Vec<(OsString, OsString)>,
46 on_open: Option<Box<dyn FnOnce(OpenOutcome) -> Msg + Send>>,
47}
48
49impl<Msg: Send + 'static> Open<Msg> {
50 #[must_use]
53 pub fn new(target: impl Into<OsString>) -> Self {
54 let target = target.into();
55 let (program, args) = opener(target.clone());
56 Self { program, args, target: Some(target), dir: None, env: Vec::new(), on_open: None }
57 }
58
59 #[must_use]
62 pub fn program(program: impl Into<OsString>) -> Self {
63 Self { program: program.into(), args: Vec::new(), target: None, dir: None, env: Vec::new(), on_open: None }
64 }
65
66 #[must_use]
68 pub fn arg(mut self, arg: impl Into<OsString>) -> Self {
69 self.args.push(arg.into());
70 self
71 }
72
73 #[must_use]
75 pub fn args(mut self, args: impl IntoIterator<Item = impl Into<OsString>>) -> Self {
76 self.args.extend(args.into_iter().map(Into::into));
77 self
78 }
79
80 #[must_use]
82 pub fn dir(mut self, dir: impl Into<PathBuf>) -> Self {
83 self.dir = Some(dir.into());
84 self
85 }
86
87 #[must_use]
89 pub fn env(mut self, key: impl Into<OsString>, value: impl Into<OsString>) -> Self {
90 self.env.push((key.into(), value.into()));
91 self
92 }
93
94 #[must_use]
99 pub fn answer(mut self, on_open: impl FnOnce(OpenOutcome) -> Msg + Send + 'static) -> Self {
100 self.on_open = Some(Box::new(on_open));
101 self
102 }
103
104 pub(crate) fn request(&self) -> OpenRequest {
106 OpenRequest { program: self.program.clone(), args: self.args.clone(), target: self.target.clone() }
107 }
108
109 pub(crate) fn finish(self, outcome: OpenOutcome) -> Option<Msg> {
111 self.on_open.map(|on_open| on_open(outcome))
112 }
113
114 pub(crate) fn start(self) -> (Option<Msg>, Option<Child>) {
120 let mut command = ChildCommand::new(&self.program);
121 command.args(&self.args);
122 if let Some(dir) = &self.dir {
123 command.current_dir(dir);
124 }
125 for (key, value) in &self.env {
126 command.env(key, value);
127 }
128 command.stdin(Stdio::null()).stdout(Stdio::null()).stderr(Stdio::null());
130 #[cfg(unix)]
132 command.process_group(0);
133 match command.spawn() {
134 Ok(child) => (self.finish(OpenOutcome::Opened), Some(child)),
135 Err(error) => (self.finish(OpenOutcome::Failed(error.to_string())), None),
136 }
137 }
138
139 pub(crate) fn map<B: Send + 'static>(self, map: impl FnOnce(Msg) -> B + Send + 'static) -> Open<B> {
141 let on_open = self.on_open;
142 Open {
143 program: self.program,
144 args: self.args,
145 target: self.target,
146 dir: self.dir,
147 env: self.env,
148 on_open: on_open.map(|on_open| -> Box<dyn FnOnce(OpenOutcome) -> B + Send> {
149 Box::new(move |outcome| map(on_open(outcome)))
150 }),
151 }
152 }
153}
154
155#[derive(Debug, Clone, PartialEq, Eq)]
157pub enum OpenOutcome {
158 Opened,
161 Failed(String),
164}
165
166#[derive(Debug, Clone, PartialEq, Eq)]
168pub struct OpenRequest {
169 pub program: OsString,
171 pub args: Vec<OsString>,
173 pub target: Option<OsString>,
176}
177
178#[cfg(target_os = "macos")]
180fn opener(target: OsString) -> (OsString, Vec<OsString>) {
181 (OsString::from("open"), vec![target])
182}
183
184#[cfg(all(unix, not(target_os = "macos")))]
186fn opener(target: OsString) -> (OsString, Vec<OsString>) {
187 (OsString::from("xdg-open"), vec![target])
188}
189
190#[cfg(windows)]
193fn opener(target: OsString) -> (OsString, Vec<OsString>) {
194 (OsString::from("cmd"), vec![OsString::from("/C"), OsString::from("start"), OsString::new(), target])
195}
196
197#[cfg(test)]
198mod tests {
199 use super::*;
200
201 #[test]
202 fn an_address_goes_to_the_opener_of_this_desktop_with_the_target_kept_for_the_test() {
203 let request = Open::new("https://example.com/sign-in").answer(|outcome| outcome).request();
204 assert_eq!(request.target.as_deref(), Some(std::ffi::OsStr::new("https://example.com/sign-in")));
205 assert_eq!(request.args, [OsString::from("https://example.com/sign-in")]);
206 assert!(!request.program.is_empty(), "the desktop's opener is named: {:?}", request.program);
207 }
208
209 #[test]
210 fn a_program_of_its_own_carries_its_arguments_and_no_target() {
211 let request = Open::<OpenOutcome>::program("gimp").arg("--new-instance").args(["a.png", "b.png"]).request();
212 assert_eq!(request.program, OsString::from("gimp"));
213 assert_eq!(request.args, ["--new-instance", "a.png", "b.png"].map(OsString::from));
214 assert_eq!(request.target, None, "nothing was handed to an opener");
215 }
216
217 #[test]
218 fn a_program_that_starts_answers_opened_and_leaves_a_child_to_wait_for() {
219 let (message, child) = Open::program("sh").args(["-c", "exit 0"]).answer(|outcome| outcome).start();
220 assert_eq!(message, Some(OpenOutcome::Opened));
221 let mut child = child.expect("a program that started has a child");
222 assert!(child.wait().is_ok(), "the caller is what reaps it");
223 }
224
225 #[test]
226 fn a_program_that_is_not_there_fails_with_the_reason_and_leaves_no_child() {
227 let (message, child) = Open::program("quvyta-no-such-program").answer(|outcome| outcome).start();
228 let Some(OpenOutcome::Failed(reason)) = message else {
229 panic!("a program that is not there cannot have been opened: {message:?}");
230 };
231 assert!(!reason.is_empty(), "the reason names what went wrong");
232 assert!(child.is_none(), "nothing was started");
233 }
234
235 #[test]
236 fn the_directory_and_the_environment_reach_the_program() {
237 let path = std::env::temp_dir().join(format!(
238 "quvyta-open-{}",
239 std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap_or_default().as_nanos()
240 ));
241 let (message, child) = Open::program("sh")
242 .args(["-c", r#"test "$QUVYTA_OPEN_TEST" = ok && pwd > "$0""#, &path.to_string_lossy()])
243 .dir("/")
244 .env("QUVYTA_OPEN_TEST", "ok")
245 .answer(|outcome| outcome)
246 .start();
247 assert_eq!(message, Some(OpenOutcome::Opened));
248 let status = child.expect("a child").wait().expect("it ends");
249 assert_eq!(status.code(), Some(0), "the environment reached it");
250 assert_eq!(std::fs::read_to_string(&path).unwrap_or_default().trim(), "/", "it ran in the directory");
251 let _ = std::fs::remove_file(&path);
252 }
253
254 #[test]
255 fn an_opening_without_an_answer_delivers_nothing() {
256 let (message, child) = Open::<OpenOutcome>::program("sh").args(["-c", "exit 0"]).start();
257 assert!(message.is_none(), "no message was asked for");
258 let _ = child.expect("a child").wait();
259 }
260
261 #[test]
262 fn a_mapped_opening_delivers_the_converted_message() {
263 let open = Open::new("https://example.com").answer(|outcome| outcome);
264 let mapped = open.map(|outcome| format!("{outcome:?}"));
265 assert_eq!(mapped.finish(OpenOutcome::Opened), Some("Opened".to_owned()));
266 }
267}