use std::ffi::OsString;
#[cfg(unix)]
use std::os::unix::process::CommandExt;
use std::path::PathBuf;
use std::process::{Child, Command as ChildCommand, Stdio};
pub struct Open<Msg> {
program: OsString,
args: Vec<OsString>,
target: Option<OsString>,
dir: Option<PathBuf>,
env: Vec<(OsString, OsString)>,
on_open: Option<Box<dyn FnOnce(OpenOutcome) -> Msg + Send>>,
}
impl<Msg: Send + 'static> Open<Msg> {
#[must_use]
pub fn new(target: impl Into<OsString>) -> Self {
let target = target.into();
let (program, args) = opener(target.clone());
Self { program, args, target: Some(target), dir: None, env: Vec::new(), on_open: None }
}
#[must_use]
pub fn program(program: impl Into<OsString>) -> Self {
Self { program: program.into(), args: Vec::new(), target: None, dir: None, env: Vec::new(), on_open: None }
}
#[must_use]
pub fn arg(mut self, arg: impl Into<OsString>) -> Self {
self.args.push(arg.into());
self
}
#[must_use]
pub fn args(mut self, args: impl IntoIterator<Item = impl Into<OsString>>) -> Self {
self.args.extend(args.into_iter().map(Into::into));
self
}
#[must_use]
pub fn dir(mut self, dir: impl Into<PathBuf>) -> Self {
self.dir = Some(dir.into());
self
}
#[must_use]
pub fn env(mut self, key: impl Into<OsString>, value: impl Into<OsString>) -> Self {
self.env.push((key.into(), value.into()));
self
}
#[must_use]
pub fn answer(mut self, on_open: impl FnOnce(OpenOutcome) -> Msg + Send + 'static) -> Self {
self.on_open = Some(Box::new(on_open));
self
}
pub(crate) fn request(&self) -> OpenRequest {
OpenRequest {
program: self.program.clone(),
args: self.args.clone(),
target: self.target.clone(),
dir: self.dir.clone(),
}
}
pub(crate) fn finish(self, outcome: OpenOutcome) -> Option<Msg> {
self.on_open.map(|on_open| on_open(outcome))
}
pub(crate) fn start(self) -> (Option<Msg>, Option<Child>) {
let mut command = ChildCommand::new(&self.program);
command.args(&self.args);
if let Some(dir) = &self.dir {
command.current_dir(dir);
}
for (key, value) in &self.env {
command.env(key, value);
}
command.stdin(Stdio::null()).stdout(Stdio::null()).stderr(Stdio::null());
#[cfg(unix)]
command.process_group(0);
match command.spawn() {
Ok(child) => (self.finish(OpenOutcome::Opened), Some(child)),
Err(error) => (self.finish(OpenOutcome::Failed(error.to_string())), None),
}
}
pub(crate) fn map<B: Send + 'static>(self, map: impl FnOnce(Msg) -> B + Send + 'static) -> Open<B> {
let on_open = self.on_open;
Open {
program: self.program,
args: self.args,
target: self.target,
dir: self.dir,
env: self.env,
on_open: on_open.map(|on_open| -> Box<dyn FnOnce(OpenOutcome) -> B + Send> {
Box::new(move |outcome| map(on_open(outcome)))
}),
}
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum OpenOutcome {
Opened,
Failed(String),
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct OpenRequest {
pub program: OsString,
pub args: Vec<OsString>,
pub target: Option<OsString>,
pub dir: Option<PathBuf>,
}
#[cfg(target_os = "macos")]
fn opener(target: OsString) -> (OsString, Vec<OsString>) {
(OsString::from("open"), vec![target])
}
#[cfg(all(unix, not(target_os = "macos")))]
fn opener(target: OsString) -> (OsString, Vec<OsString>) {
(OsString::from("xdg-open"), vec![target])
}
#[cfg(windows)]
fn opener(target: OsString) -> (OsString, Vec<OsString>) {
(OsString::from("cmd"), vec![OsString::from("/C"), OsString::from("start"), OsString::new(), target])
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn an_address_goes_to_the_opener_of_this_desktop_with_the_target_kept_for_the_test() {
let request = Open::new("https://example.com/sign-in").answer(|outcome| outcome).request();
assert_eq!(request.target.as_deref(), Some(std::ffi::OsStr::new("https://example.com/sign-in")));
assert_eq!(request.args, [OsString::from("https://example.com/sign-in")]);
assert!(!request.program.is_empty(), "the desktop's opener is named: {:?}", request.program);
}
#[test]
fn a_program_of_its_own_carries_its_arguments_and_no_target() {
let request = Open::<OpenOutcome>::program("gimp").arg("--new-instance").args(["a.png", "b.png"]).request();
assert_eq!(request.program, OsString::from("gimp"));
assert_eq!(request.args, ["--new-instance", "a.png", "b.png"].map(OsString::from));
assert_eq!(request.target, None, "nothing was handed to an opener");
assert_eq!(request.dir, None, "without `dir` the program starts where the application runs");
let placed = Open::<OpenOutcome>::program("gimp").dir("/srv/pictures").request();
assert_eq!(placed.dir, Some(PathBuf::from("/srv/pictures")), "the folder is recorded");
}
#[test]
fn a_program_that_starts_answers_opened_and_leaves_a_child_to_wait_for() {
let (message, child) = Open::program("sh").args(["-c", "exit 0"]).answer(|outcome| outcome).start();
assert_eq!(message, Some(OpenOutcome::Opened));
let mut child = child.expect("a program that started has a child");
assert!(child.wait().is_ok(), "the caller is what reaps it");
}
#[test]
fn a_program_that_is_not_there_fails_with_the_reason_and_leaves_no_child() {
let (message, child) = Open::program("quvyta-no-such-program").answer(|outcome| outcome).start();
let Some(OpenOutcome::Failed(reason)) = message else {
panic!("a program that is not there cannot have been opened: {message:?}");
};
assert!(!reason.is_empty(), "the reason names what went wrong");
assert!(child.is_none(), "nothing was started");
}
#[test]
fn the_directory_and_the_environment_reach_the_program() {
let path = std::env::temp_dir().join(format!(
"quvyta-open-{}",
std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap_or_default().as_nanos()
));
let (message, child) = Open::program("sh")
.args(["-c", r#"test "$QUVYTA_OPEN_TEST" = ok && pwd > "$0""#, &path.to_string_lossy()])
.dir("/")
.env("QUVYTA_OPEN_TEST", "ok")
.answer(|outcome| outcome)
.start();
assert_eq!(message, Some(OpenOutcome::Opened));
let status = child.expect("a child").wait().expect("it ends");
assert_eq!(status.code(), Some(0), "the environment reached it");
assert_eq!(std::fs::read_to_string(&path).unwrap_or_default().trim(), "/", "it ran in the directory");
let _ = std::fs::remove_file(&path);
}
#[test]
fn an_opening_without_an_answer_delivers_nothing() {
let (message, child) = Open::<OpenOutcome>::program("sh").args(["-c", "exit 0"]).start();
assert!(message.is_none(), "no message was asked for");
let _ = child.expect("a child").wait();
}
#[test]
fn a_mapped_opening_delivers_the_converted_message() {
let open = Open::new("https://example.com").answer(|outcome| outcome);
let mapped = open.map(|outcome| format!("{outcome:?}"));
assert_eq!(mapped.finish(OpenOutcome::Opened), Some("Opened".to_owned()));
}
}