use std::collections::HashSet;
use std::fmt;
use crate::advanced::{EngineInfo, OperationId};
use crate::error::{GuiError, GuiResult};
use crate::events::UiEvent;
use crate::ui::{Backend, Ui};
use crate::widgets::WidgetKind;
use crate::WidgetId;
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum WebViewError {
RuntimeUnavailable(String),
InvalidUrl(String),
NotAWebView(WidgetId),
Engine(String),
}
impl fmt::Display for WebViewError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
WebViewError::RuntimeUnavailable(detail) => {
write!(f, "web engine unavailable: {detail}")
}
WebViewError::InvalidUrl(url) => write!(f, "invalid URL: {url:?}"),
WebViewError::NotAWebView(widget) => write!(f, "widget {} is not a WebView", widget.0),
WebViewError::Engine(detail) => write!(f, "web engine error: {detail}"),
}
}
}
impl std::error::Error for WebViewError {}
impl From<WebViewError> for GuiError {
fn from(error: WebViewError) -> Self {
GuiError::WebView(error)
}
}
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub struct WebViewOptions {
pub devtools: bool,
pub allowed_navigation: Vec<String>,
pub user_agent: Option<String>,
}
impl WebViewOptions {
pub fn new() -> Self {
Self::default()
}
pub fn devtools(mut self, enabled: bool) -> Self {
self.devtools = enabled;
self
}
pub fn allow_navigation(mut self, prefix: impl Into<String>) -> Self {
self.allowed_navigation.push(prefix.into());
self
}
pub fn user_agent(mut self, user_agent: impl Into<String>) -> Self {
self.user_agent = Some(user_agent.into());
self
}
pub fn allows(&self, url: &str) -> bool {
self.allowed_navigation.is_empty()
|| self
.allowed_navigation
.iter()
.any(|prefix| url.starts_with(prefix.as_str()))
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum WebViewContent {
Url(String),
Html {
html: String,
base_url: Option<String>,
},
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum WebViewCommand {
Reload,
Stop,
GoBack,
GoForward,
}
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub struct WebViewState {
pub url: Option<String>,
pub title: Option<String>,
pub loading: bool,
pub can_go_back: bool,
pub can_go_forward: bool,
}
pub trait WebViewBackend: Backend {
fn webview_engine(&mut self) -> GuiResult<EngineInfo>;
fn create_webview(&mut self, host: WidgetId, options: &WebViewOptions) -> GuiResult<()>;
fn webview_load(&mut self, host: WidgetId, content: &WebViewContent) -> GuiResult<()>;
fn webview_command(&mut self, host: WidgetId, command: WebViewCommand) -> GuiResult<()>;
fn webview_state(&self, host: WidgetId) -> GuiResult<WebViewState>;
fn webview_evaluate(
&mut self,
host: WidgetId,
operation: OperationId,
script: &str,
) -> GuiResult<()>;
fn webview_post_message(&mut self, host: WidgetId, message: &str) -> GuiResult<()>;
}
pub fn json_string(text: &str) -> String {
let mut out = String::with_capacity(text.len() + 2);
out.push('"');
for ch in text.chars() {
match ch {
'"' => out.push_str("\\\""),
'\\' => out.push_str("\\\\"),
'\n' => out.push_str("\\n"),
'\r' => out.push_str("\\r"),
'\t' => out.push_str("\\t"),
'\u{2028}' => out.push_str("\\u2028"),
'\u{2029}' => out.push_str("\\u2029"),
ch if (ch as u32) < 0x20 => out.push_str(&format!("\\u{:04x}", ch as u32)),
ch => out.push(ch),
}
}
out.push('"');
out
}
pub fn decode_json_string(literal: &str) -> Option<String> {
let body = literal.trim().strip_prefix('"')?.strip_suffix('"')?;
let mut out = String::with_capacity(body.len());
let mut chars = body.chars();
while let Some(ch) = chars.next() {
match ch {
'"' => return None,
'\\' => match chars.next()? {
'"' => out.push('"'),
'\\' => out.push('\\'),
'/' => out.push('/'),
'b' => out.push('\u{8}'),
'f' => out.push('\u{c}'),
'n' => out.push('\n'),
'r' => out.push('\r'),
't' => out.push('\t'),
'u' => {
let unit = read_hex4(&mut chars)?;
if (0xD800..0xDC00).contains(&unit) {
if chars.next()? != '\\' || chars.next()? != 'u' {
return None;
}
let low = read_hex4(&mut chars)?;
if !(0xDC00..0xE000).contains(&low) {
return None;
}
let code = 0x10000 + ((unit - 0xD800) << 10) + (low - 0xDC00);
out.push(char::from_u32(code)?);
} else {
out.push(char::from_u32(unit)?);
}
}
_ => return None,
},
ch => out.push(ch),
}
}
Some(out)
}
fn read_hex4(chars: &mut std::str::Chars<'_>) -> Option<u32> {
let mut value = 0;
for _ in 0..4 {
value = value * 16 + chars.next()?.to_digit(16)?;
}
Some(value)
}
pub fn wrap_script(script: &str) -> String {
format!(
"(function(){{try{{var v=(0,eval)({});var j=JSON.stringify(v);\
return 'o'+(j===undefined?'null':j);}}catch(e){{\
return 'e'+String(e&&e.message!==undefined?e.message:e);}}}})()",
json_string(script)
)
}
pub fn decode_script_result(raw: &str) -> Result<String, String> {
if let Some(json) = raw.strip_prefix('o') {
Ok(json.to_owned())
} else if let Some(message) = raw.strip_prefix('e') {
Err(message.to_owned())
} else {
Err(format!("unexpected script result: {raw}"))
}
}
pub fn bridge_script(native_post: &str, native_subscribe: &str) -> String {
format!(
"(function(){{if(window.nativeGui){{return;}}var post={native_post};var listeners=[];\
function report(e){{setTimeout(function(){{throw e;}});}}\
var bridge={{postMessage:function(m){{post(String(m));}},\
addEventListener:function(t,l){{if(t==='message'&&typeof l==='function'){{listeners.push(l);}}}},\
removeEventListener:function(t,l){{var i=listeners.indexOf(l);if(i>=0){{listeners.splice(i,1);}}}},\
onmessage:null}};\
function deliver(data){{var ev={{data:String(data)}};\
if(typeof bridge.onmessage==='function'){{try{{bridge.onmessage(ev);}}catch(e){{report(e);}}}}\
listeners.slice().forEach(function(l){{try{{l(ev);}}catch(e){{report(e);}}}});}}\
Object.defineProperty(bridge,'__deliver',{{value:deliver}});\
Object.defineProperty(window,'nativeGui',{{value:bridge}});{native_subscribe}}})();"
)
}
pub fn deliver_script(message: &str) -> String {
format!(
"window.nativeGui&&window.nativeGui.__deliver({});",
json_string(message)
)
}
pub fn matches_app_target(target: &str, url: &str) -> bool {
target.trim_end_matches('/') == url.trim_end_matches('/')
}
pub fn validate_url(url: &str) -> Result<(), WebViewError> {
let scheme_ok = url
.split_once(':')
.map(|(scheme, _)| {
!scheme.is_empty()
&& scheme
.chars()
.next()
.is_some_and(|c| c.is_ascii_alphabetic())
&& scheme
.chars()
.all(|c| c.is_ascii_alphanumeric() || matches!(c, '+' | '-' | '.'))
})
.unwrap_or(false);
if !scheme_ok || url.chars().any(|c| c.is_whitespace() || c == '\0') {
return Err(WebViewError::InvalidUrl(url.to_owned()));
}
Ok(())
}
#[derive(Debug, Default)]
pub(crate) struct WebViewRegistry {
views: HashSet<WidgetId>,
}
impl WebViewRegistry {
pub(crate) fn forget(&mut self, widget: WidgetId) {
self.views.remove(&widget);
}
}
impl<B: Backend> Ui<B> {
pub fn is_webview(&self, widget: WidgetId) -> bool {
self.webviews.views.contains(&widget)
}
fn require_webview(&self, widget: WidgetId) -> GuiResult<()> {
if self.widget(widget).is_none() {
return Err(GuiError::WidgetNotFound(widget.0));
}
if !self.webviews.views.contains(&widget) {
return Err(WebViewError::NotAWebView(widget).into());
}
Ok(())
}
pub(crate) fn observe_webview_event(&mut self, event: &UiEvent) {
if let UiEvent::WebViewScriptResult { operation, .. } = event {
self.complete_operation(*operation);
}
}
}
impl<B: Backend + WebViewBackend> Ui<B> {
pub fn webview_engine(&mut self) -> GuiResult<EngineInfo> {
self.backend_mut().webview_engine()
}
pub fn create_webview(&mut self, options: WebViewOptions) -> GuiResult<WidgetId> {
if let Some(agent) = &options.user_agent {
if agent.contains('\0') {
return Err(WebViewError::Engine("user agent contains NUL".into()).into());
}
}
let host = self.create(WidgetKind::Container, None)?;
if let Err(error) = self.backend_mut().create_webview(host, &options) {
let _ = self.remove(host);
return Err(error);
}
self.webviews.views.insert(host);
Ok(host)
}
pub fn webview_load_url(&mut self, widget: WidgetId, url: &str) -> GuiResult<()> {
self.require_webview(widget)?;
validate_url(url)?;
self.backend_mut()
.webview_load(widget, &WebViewContent::Url(url.to_owned()))
}
pub fn webview_load_html(
&mut self,
widget: WidgetId,
html: &str,
base_url: Option<&str>,
) -> GuiResult<()> {
self.require_webview(widget)?;
if let Some(base) = base_url {
validate_url(base)?;
}
self.backend_mut().webview_load(
widget,
&WebViewContent::Html {
html: html.to_owned(),
base_url: base_url.map(str::to_owned),
},
)
}
pub fn webview_reload(&mut self, widget: WidgetId) -> GuiResult<()> {
self.webview_command(widget, WebViewCommand::Reload)
}
pub fn webview_stop(&mut self, widget: WidgetId) -> GuiResult<()> {
self.webview_command(widget, WebViewCommand::Stop)
}
pub fn webview_go_back(&mut self, widget: WidgetId) -> GuiResult<()> {
self.webview_command(widget, WebViewCommand::GoBack)
}
pub fn webview_go_forward(&mut self, widget: WidgetId) -> GuiResult<()> {
self.webview_command(widget, WebViewCommand::GoForward)
}
fn webview_command(&mut self, widget: WidgetId, command: WebViewCommand) -> GuiResult<()> {
self.require_webview(widget)?;
self.backend_mut().webview_command(widget, command)
}
pub fn webview_state(&self, widget: WidgetId) -> GuiResult<WebViewState> {
self.require_webview(widget)?;
self.backend().webview_state(widget)
}
pub fn webview_evaluate_script(
&mut self,
widget: WidgetId,
script: &str,
) -> GuiResult<OperationId> {
self.require_webview(widget)?;
let operation = self.allocate_operation_id();
let wrapped = wrap_script(script);
if let Err(error) = self
.backend_mut()
.webview_evaluate(widget, operation, &wrapped)
{
self.complete_operation(operation);
return Err(error);
}
Ok(operation)
}
pub fn webview_post_message(&mut self, widget: WidgetId, message: &str) -> GuiResult<()> {
self.require_webview(widget)?;
self.backend_mut().webview_post_message(widget, message)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn app_target_ignores_trailing_slash() {
assert!(matches_app_target(
"https://a.example",
"https://a.example/"
));
assert!(!matches_app_target(
"https://a.example/",
"https://b.example/"
));
}
#[test]
fn json_string_round_trips() {
for text in [
"",
"plain",
"quote \" and backslash \\",
"lines\nand\ttabs\r",
"\u{1}\u{1f}",
"separators \u{2028}\u{2029}",
"emoji 🙂 and ünïcode",
] {
let literal = json_string(text);
assert!(!literal.contains('\n'));
assert!(!literal.contains('\u{2028}'));
assert_eq!(
decode_json_string(&literal).as_deref(),
Some(text),
"{text:?}"
);
}
}
#[test]
fn decode_json_string_reads_surrogate_pairs_and_rejects_junk() {
assert_eq!(
decode_json_string(r#""\ud83d\ude42 \u00e9""#).as_deref(),
Some("🙂 é")
);
assert_eq!(decode_json_string(" \"x\" ").as_deref(), Some("x"));
assert_eq!(decode_json_string("x"), None);
assert_eq!(decode_json_string("\"a\"b\""), None);
assert_eq!(decode_json_string(r#""\q""#), None);
assert_eq!(decode_json_string(r#""\ud83d""#), None);
}
#[test]
fn script_results_decode() {
assert_eq!(decode_script_result("o3"), Ok("3".to_owned()));
assert_eq!(decode_script_result("o\"hi\""), Ok("\"hi\"".to_owned()));
assert_eq!(decode_script_result("eboom"), Err("boom".to_owned()));
assert!(decode_script_result("").is_err());
let wrapped = wrap_script("document.title\n// \"quoted\"");
assert!(wrapped.starts_with("(function(){"));
assert!(wrapped.contains(r#"(0,eval)("document.title\n// \"quoted\"")"#));
}
#[test]
fn bridge_and_delivery_scripts_embed_their_parts() {
let bridge = bridge_script("function(m){native(m);}", "subscribe(deliver);");
assert!(bridge.contains("var post=function(m){native(m);};"));
assert!(bridge.ends_with("subscribe(deliver);})();"));
assert!(bridge.contains("Object.defineProperty(window,'nativeGui'"));
assert_eq!(
deliver_script("a\"b"),
"window.nativeGui&&window.nativeGui.__deliver(\"a\\\"b\");"
);
}
#[test]
fn urls_are_checked() {
for good in [
"https://example.com/",
"about:blank",
"data:text/html,hi",
"file:///tmp/a.html",
"app+local://x",
] {
assert_eq!(validate_url(good), Ok(()), "{good}");
}
for bad in [
"",
"example.com",
"://x",
"1http://x",
"https://a b",
"https://a\0",
] {
assert!(validate_url(bad).is_err(), "{bad:?}");
}
}
#[test]
fn navigation_prefixes() {
let open = WebViewOptions::new();
assert!(open.allows("https://anything.example/"));
let limited = WebViewOptions::new()
.allow_navigation("https://app.example/")
.allow_navigation("about:");
assert!(limited.allows("https://app.example/page"));
assert!(limited.allows("about:blank"));
assert!(!limited.allows("https://other.example/"));
assert!(!limited.allows("https://app.example.evil/"));
}
#[test]
fn errors_display() {
let error: GuiError = WebViewError::RuntimeUnavailable("install it".into()).into();
assert_eq!(
error.to_string(),
"WebView error: web engine unavailable: install it"
);
assert_eq!(
WebViewError::NotAWebView(WidgetId(4)).to_string(),
"widget 4 is not a WebView"
);
}
}