use std::sync::Arc;
use crate::config::OxiosConfig;
pub struct BrowserApi {
#[cfg(feature = "native-browser")]
engine: tokio::sync::OnceCell<Arc<dyn oxi_sdk::BrowserEngine>>,
config: oxi_sdk::BrowseConfig,
}
impl std::fmt::Debug for BrowserApi {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("BrowserApi")
.field("config", &self.config)
.finish()
}
}
impl BrowserApi {
pub fn new(config: oxi_sdk::BrowseConfig) -> Self {
Self {
#[cfg(feature = "native-browser")]
engine: tokio::sync::OnceCell::new(),
config,
}
}
pub fn from_config(config: &OxiosConfig) -> Option<Self> {
if config.browser.enabled {
Some(Self::new(config.browser.engine.clone()))
} else {
None
}
}
#[cfg(feature = "native-browser")]
pub async fn engine(&self) -> anyhow::Result<Arc<dyn oxi_sdk::BrowserEngine>> {
self.engine
.get_or_try_init(|| async {
let backend = oxi_sdk::OxiBrowserEngine::with_config(self.config.clone())
.await
.map_err(|e| anyhow::anyhow!("browser engine init failed: {e}"))?;
Ok(Arc::new(backend) as Arc<dyn oxi_sdk::BrowserEngine>)
})
.await
.map(Arc::clone)
}
#[cfg(feature = "native-browser")]
pub fn try_engine(&self) -> Option<Arc<dyn oxi_sdk::BrowserEngine>> {
self.engine.get().cloned()
}
#[cfg(not(feature = "native-browser"))]
pub fn try_engine(&self) -> Option<Arc<dyn oxi_sdk::BrowserEngine>> {
None
}
}