use native_gui_core::advanced::{EngineInfo, OperationId};
use native_gui_core::error::{GuiError, GuiResult};
use native_gui_core::events::UiEvent;
use native_gui_core::webview::{
decode_json_string, json_string, WebViewBackend, WebViewCommand, WebViewContent, WebViewError,
WebViewOptions, WebViewState,
};
use native_gui_core::widgets::WidgetKind;
use native_gui_core::WidgetId;
use super::MockBackend;
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct MockWebView {
pub options: WebViewOptions,
pub history: Vec<(String, Option<String>)>,
pub current: Option<usize>,
pub documents: Vec<Option<String>>,
pub scripts: Vec<String>,
pub posted: Vec<String>,
pub commands: Vec<WebViewCommand>,
}
impl MockWebView {
fn current_page(&self) -> Option<&(String, Option<String>)> {
self.current.and_then(|index| self.history.get(index))
}
}
fn unwrap_script(wrapped: &str) -> Option<String> {
let start = wrapped.find("(0,eval)(")? + "(0,eval)(".len();
let end = wrapped[start..].find(");var j=")? + start;
decode_json_string(&wrapped[start..end])
}
fn data_url_html(url: &str) -> Option<String> {
let encoded = url.strip_prefix("data:text/html,")?;
let bytes = encoded.as_bytes();
let mut out = Vec::with_capacity(bytes.len());
let mut index = 0;
while index < bytes.len() {
let hex = bytes
.get(index + 1..index + 3)
.and_then(|pair| std::str::from_utf8(pair).ok())
.and_then(|pair| u8::from_str_radix(pair, 16).ok());
match (bytes[index], hex) {
(b'%', Some(value)) => {
out.push(value);
index += 3;
}
(byte, _) => {
out.push(byte);
index += 1;
}
}
}
String::from_utf8(out).ok()
}
fn html_title(html: &str) -> Option<String> {
let lower = html.to_ascii_lowercase();
let start = lower.find("<title>")? + "<title>".len();
let end = lower[start..].find("</title>")? + start;
Some(html[start..end].trim().to_owned())
}
impl MockBackend {
fn mock_webview(&mut self, host: WidgetId) -> GuiResult<&mut MockWebView> {
if !self.created.contains_key(&host) {
return Err(GuiError::WidgetNotFound(host.0));
}
self.webviews
.get_mut(&host)
.ok_or_else(|| WebViewError::NotAWebView(host).into())
}
fn mock_visit(&mut self, host: WidgetId, url: String, html: Option<String>) {
let title = html.as_deref().and_then(html_title);
if let Some(view) = self.webviews.get_mut(&host) {
let keep = view.current.map_or(0, |index| index + 1);
view.history.truncate(keep);
view.documents.truncate(keep);
view.history.push((url.clone(), title.clone()));
view.documents.push(html);
view.current = Some(view.history.len() - 1);
}
self.mock_report_load(host, url, title);
}
fn mock_report_load(&mut self, host: WidgetId, url: String, title: Option<String>) {
self.events.push_back(UiEvent::WebViewLoadStarted {
widget_id: host,
url: url.clone(),
});
if let Some(title) = title {
self.events.push_back(UiEvent::WebViewTitleChanged {
widget_id: host,
title,
});
}
self.events.push_back(UiEvent::WebViewLoadFinished {
widget_id: host,
url,
});
}
pub fn webview_page_navigate(&mut self, host: WidgetId, url: &str) -> GuiResult<()> {
let allowed = self.mock_webview(host)?.options.allows(url);
if allowed {
self.mock_visit(host, url.to_owned(), None);
} else {
self.events.push_back(UiEvent::WebViewNavigationBlocked {
widget_id: host,
url: url.to_owned(),
});
}
Ok(())
}
pub fn webview_page_message(&mut self, host: WidgetId, body: &str) -> GuiResult<()> {
let source = self
.mock_webview(host)?
.current_page()
.map(|(url, _)| url.clone())
.unwrap_or_default();
self.events.push_back(UiEvent::WebViewMessage {
widget_id: host,
source,
body: body.to_owned(),
});
Ok(())
}
pub(crate) fn forget_webview(&mut self, host: WidgetId) {
self.webviews.remove(&host);
}
}
impl WebViewBackend for MockBackend {
fn webview_engine(&mut self) -> GuiResult<EngineInfo> {
if self.webview_runtime_missing {
return Err(WebViewError::RuntimeUnavailable(
"the Mock lane was told the engine is missing".into(),
)
.into());
}
Ok(EngineInfo {
name: "Mock".into(),
version: env!("CARGO_PKG_VERSION").into(),
})
}
fn create_webview(&mut self, host: WidgetId, options: &WebViewOptions) -> GuiResult<()> {
self.webview_engine()?;
match self.created.get(&host) {
None => return Err(GuiError::WidgetNotFound(host.0)),
Some(spec) if spec.kind != WidgetKind::Container => {
return Err(GuiError::UnsupportedWidget("webview host"));
}
Some(_) => {}
}
self.webviews.insert(
host,
MockWebView {
options: options.clone(),
..MockWebView::default()
},
);
Ok(())
}
fn webview_load(&mut self, host: WidgetId, content: &WebViewContent) -> GuiResult<()> {
self.mock_webview(host)?;
match content {
WebViewContent::Url(url) => {
let html = data_url_html(url);
self.mock_visit(host, url.clone(), html)
}
WebViewContent::Html { html, base_url } => self.mock_visit(
host,
base_url.clone().unwrap_or_else(|| "about:blank".into()),
Some(html.clone()),
),
}
Ok(())
}
fn webview_command(&mut self, host: WidgetId, command: WebViewCommand) -> GuiResult<()> {
let view = self.mock_webview(host)?;
view.commands.push(command);
let target = match (command, view.current) {
(WebViewCommand::GoBack, Some(index)) if index > 0 => Some(index - 1),
(WebViewCommand::GoForward, Some(index)) if index + 1 < view.history.len() => {
Some(index + 1)
}
(WebViewCommand::Reload, Some(index)) => Some(index),
_ => None,
};
if let Some(index) = target {
view.current = Some(index);
let (url, title) = view.history[index].clone();
self.mock_report_load(host, url, title);
}
Ok(())
}
fn webview_state(&self, host: WidgetId) -> GuiResult<WebViewState> {
let view = self
.webviews
.get(&host)
.ok_or(WebViewError::NotAWebView(host))?;
let page = view.current_page();
Ok(WebViewState {
url: page.map(|(url, _)| url.clone()),
title: page.and_then(|(_, title)| title.clone()),
loading: false,
can_go_back: view.current.is_some_and(|index| index > 0),
can_go_forward: view
.current
.is_some_and(|index| index + 1 < view.history.len()),
})
}
fn webview_evaluate(
&mut self,
host: WidgetId,
operation: OperationId,
script: &str,
) -> GuiResult<()> {
let script = unwrap_script(script).unwrap_or_else(|| script.to_owned());
let view = self.mock_webview(host)?;
view.scripts.push(script.clone());
let page = view.current_page().cloned();
let expression = script.trim().trim_end_matches(';').trim();
let result = if let Some(message) = expression.strip_prefix("throw ") {
Err(decode_json_string(message)
.or_else(|| decode_json_string(&message.replace('\'', "\"")))
.unwrap_or_else(|| message.to_owned()))
} else if expression == "document.title" {
Ok(page
.and_then(|(_, title)| title)
.map_or_else(|| "\"\"".to_owned(), |title| json_string(&title)))
} else if expression == "location.href" || expression == "window.location.href" {
Ok(page.map_or_else(|| "null".to_owned(), |(url, _)| json_string(&url)))
} else if let Ok(number) = expression.parse::<i64>() {
Ok(number.to_string())
} else if let Some((a, b)) = expression.split_once('+') {
match (a.trim().parse::<i64>(), b.trim().parse::<i64>()) {
(Ok(a), Ok(b)) => Ok((a + b).to_string()),
_ => Ok("null".to_owned()),
}
} else {
Ok("null".to_owned())
};
self.events.push_back(UiEvent::WebViewScriptResult {
widget_id: host,
operation,
result,
});
Ok(())
}
fn webview_post_message(&mut self, host: WidgetId, message: &str) -> GuiResult<()> {
self.mock_webview(host)?.posted.push(message.to_owned());
Ok(())
}
}
#[cfg(test)]
mod tests {
use super::*;
use native_gui_core::webview::wrap_script;
#[test]
fn wrapped_scripts_unwrap() {
let script = "document.title // \"x\"\n1";
assert_eq!(unwrap_script(&wrap_script(script)).as_deref(), Some(script));
}
#[test]
fn data_urls_carry_their_document() {
let html = data_url_html("data:text/html,%3Ctitle%3EOne%3C/title%3EOne").unwrap();
assert_eq!(html_title(&html).as_deref(), Some("One"));
assert_eq!(data_url_html("https://example.com/"), None);
}
#[test]
fn titles_are_read_from_html() {
assert_eq!(
html_title("<html><TITLE> Hi </title></html>").as_deref(),
Some("Hi")
);
assert_eq!(html_title("<p>no title</p>"), None);
}
}