use std::time::Duration;
use isothrum_runner::{ErrorCode, ProcessSpec, ProviderNeed};
use crate::context::Context;
use crate::exec;
use crate::host::{Arch, HostOs, qemu_system};
pub const UTM_WAIT: Duration = Duration::from_secs(60);
const UTM_ASK: Duration = Duration::from_secs(15);
const UTM_RETRY: Duration = Duration::from_secs(1);
const UTM_PROBE: &str = "tell application \"UTM\" to get id of every virtual machine";
const NOT_AUTHORIZED: i32 = -1743;
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub enum NotReady {
Needs(ProviderNeed),
NotOpened {
said: String,
},
NoAnswer {
waited: Duration,
said: String,
},
Emulator {
arch: Arch,
program: &'static str,
},
}
impl NotReady {
#[must_use]
pub fn code(&self) -> ErrorCode {
match self {
NotReady::Needs(_) => ErrorCode::ProviderRefused,
NotReady::NotOpened { .. } | NotReady::Emulator { .. } => ErrorCode::ToolMissing,
NotReady::NoAnswer { .. } => ErrorCode::Timeout,
}
}
}
impl std::fmt::Display for NotReady {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
NotReady::Needs(ProviderNeed::Automation) => f.write_str("macOS doesn't allow this app to control UTM (Automation permission)"),
NotReady::Needs(need) => write!(f, "the system refuses what the hypervisor needs ({need:?})"),
NotReady::NotOpened { said } => write!(f, "UTM couldn't be opened: {said}"),
NotReady::NoAnswer { waited, said } => write!(f, "UTM didn't answer within {} s: {said}", waited.as_secs()),
NotReady::Emulator { program, .. } => write!(f, "QEMU's emulator {program} isn't installed"),
}
}
}
impl std::error::Error for NotReady {}
pub async fn utm(cx: &Context, wait: Duration, waiting: &mut (dyn FnMut() + Send)) -> Result<(), NotReady> {
if cx.host.os != HostOs::Macos {
return Ok(());
}
let app = cx.host.devices.utm_app.to_string_lossy().into_owned();
let open = ProcessSpec::new("open", ["-g", "-j", "-a", app.as_str()]);
match cx.probe_within(cx.probe_timeout, &open).await {
Ok(opened) if opened.success() => {}
Ok(failed) => return Err(NotReady::NotOpened { said: failed.reason() }),
Err(e) => return Err(NotReady::NotOpened { said: e.to_string() }),
}
let ask = ProcessSpec::new("osascript", ["-e", UTM_PROBE]);
let started = tokio::time::Instant::now();
let mut said_waiting = false;
loop {
let said = match cx.probe_within(UTM_ASK, &ask).await {
Ok(answer) if answer.success() => return Ok(()),
Ok(refused) if apple_event(&exec::all_lines(&refused)) == Some(NOT_AUTHORIZED) => {
return Err(NotReady::Needs(ProviderNeed::Automation));
}
Ok(refused) => refused.reason(),
Err(e) => e.to_string(),
};
if started.elapsed() >= wait {
return Err(NotReady::NoAnswer { waited: wait, said });
}
if !said_waiting {
waiting();
said_waiting = true;
}
tokio::time::sleep(UTM_RETRY).await;
}
}
pub async fn emulators(cx: &Context, machines: impl IntoIterator<Item = Arch>) -> Result<Vec<Arch>, NotReady> {
let mut emulated = Vec::new();
for arch in machines {
if arch == cx.host.arch || emulated.contains(&arch) {
continue;
}
let program = qemu_system(arch);
if cx.read_ok(program, &["--version"]).await.is_err() {
return Err(NotReady::Emulator { arch, program });
}
emulated.push(arch);
}
Ok(emulated)
}
fn apple_event(said: &str) -> Option<i32> {
said.match_indices("(-")
.filter_map(|(at, _)| {
let rest = said.get(at + 1..)?;
rest.get(..rest.find(')')?)?.parse::<i32>().ok()
})
.last()
}
#[cfg(test)]
mod tests;