//! Iframe loading: discover iframe elements, fetch their content, parse into //! nested Documents, and produce rendered surfaces for layout/rendering. use std::collections::HashMap; use we_dom::{Document, NodeData, NodeId}; use we_image::pixel::Image; use we_layout::ReplacedContent; use we_url::{Origin, Url}; use crate::browsing_context::{BrowsingContextId, BrowsingContextTree, SandboxFlags}; use crate::loader::{Resource, ResourceLoader}; /// Data about a loaded iframe for rendering. pub struct IframeData { /// The browsing context ID for this iframe. pub context_id: BrowsingContextId, /// The NodeId of the iframe element in the parent document. pub node_id: NodeId, /// Display width (from attributes or default 300). pub width: f32, /// Display height (from attributes or default 150). pub height: f32, } /// Default iframe width per HTML spec. const DEFAULT_IFRAME_WIDTH: f32 = 300.0; /// Default iframe height per HTML spec. const DEFAULT_IFRAME_HEIGHT: f32 = 150.0; /// Scan a document for iframe elements and return their dimensions for layout. /// Adds entries to the image_sizes map so layout treats iframes as replaced elements. pub fn collect_iframe_sizes(doc: &Document, image_sizes: &mut HashMap) { collect_iframe_sizes_recursive(doc, doc.root(), image_sizes); } fn collect_iframe_sizes_recursive( doc: &Document, node: NodeId, sizes: &mut HashMap, ) { if let NodeData::Element { ref tag_name, .. } = *doc.node_data(node) { if tag_name == "iframe" { let width = doc .get_attribute(node, "width") .and_then(|v| v.parse::().ok()) .unwrap_or(DEFAULT_IFRAME_WIDTH); let height = doc .get_attribute(node, "height") .and_then(|v| v.parse::().ok()) .unwrap_or(DEFAULT_IFRAME_HEIGHT); sizes.insert(node, ReplacedContent::Size(width, height)); return; // Don't recurse into iframe content. } } for child in doc.children(node) { collect_iframe_sizes_recursive(doc, child, sizes); } } /// Load all iframes found in a document. For each iframe with a `src` attribute, /// fetches the HTML, parses it, and creates a nested browsing context. /// /// Returns a list of loaded iframe data and adds rendered surfaces to the /// iframe_images map. pub fn load_iframes( doc: &Document, loader: &mut ResourceLoader, base_url: &Url, parent_origin: &Origin, parent_context_id: BrowsingContextId, context_tree: &mut BrowsingContextTree, ) -> Vec { let mut results = Vec::new(); load_iframes_recursive( doc, doc.root(), loader, base_url, parent_origin, parent_context_id, context_tree, &mut results, ); results } #[allow(clippy::too_many_arguments)] fn load_iframes_recursive( doc: &Document, node: NodeId, loader: &mut ResourceLoader, base_url: &Url, parent_origin: &Origin, parent_context_id: BrowsingContextId, context_tree: &mut BrowsingContextTree, results: &mut Vec, ) { if let NodeData::Element { ref tag_name, .. } = *doc.node_data(node) { if tag_name == "iframe" { if let Some(iframe_data) = load_single_iframe( doc, node, loader, base_url, parent_origin, parent_context_id, context_tree, ) { results.push(iframe_data); } return; // Don't recurse into iframe content. } } for child in doc.children(node) { load_iframes_recursive( doc, child, loader, base_url, parent_origin, parent_context_id, context_tree, results, ); } } /// Load a single iframe element. fn load_single_iframe( doc: &Document, node: NodeId, loader: &mut ResourceLoader, base_url: &Url, parent_origin: &Origin, parent_context_id: BrowsingContextId, context_tree: &mut BrowsingContextTree, ) -> Option { let width = doc .get_attribute(node, "width") .and_then(|v| v.parse::().ok()) .unwrap_or(DEFAULT_IFRAME_WIDTH); let height = doc .get_attribute(node, "height") .and_then(|v| v.parse::().ok()) .unwrap_or(DEFAULT_IFRAME_HEIGHT); // Parse sandbox attribute. let sandbox = if doc.get_attribute(node, "sandbox").is_some() { SandboxFlags::parse(doc.get_attribute(node, "sandbox")) } else { SandboxFlags::NONE }; let name = doc.get_attribute(node, "name").unwrap_or("").to_string(); // Check for srcdoc first, then src. let (iframe_doc, iframe_origin, iframe_url) = if let Some(srcdoc) = doc.get_attribute(node, "srcdoc") { // srcdoc: parse the attribute value as HTML. Origin is parent's origin. let parsed = we_html::parse_html(srcdoc); (parsed, parent_origin.clone(), None) } else if let Some(src) = doc.get_attribute(node, "src") { let src = src.to_string(); match load_iframe_src(&src, loader, base_url) { Some((parsed_doc, url)) => { let origin = url.origin(); (parsed_doc, origin, Some(url)) } None => { // Failed to load: create empty document. (Document::new(), Origin::Opaque, None) } } } else { // No src or srcdoc: empty iframe (about:blank). (Document::new(), parent_origin.clone(), None) }; let context_id = context_tree.create_nested( parent_context_id, node, iframe_doc, iframe_origin, iframe_url, sandbox, name, ); Some(IframeData { context_id, node_id: node, width, height, }) } /// Fetch and parse an iframe's src URL. fn load_iframe_src( src: &str, loader: &mut ResourceLoader, base_url: &Url, ) -> Option<(Document, Url)> { // about:blank is handled specially. if src == "about:blank" || src.is_empty() { return Some((Document::new(), Url::parse("about:blank").ok()?)); } // Resolve relative URL against base. let url = Url::parse_with_base(src, base_url).ok()?; // Fetch the iframe content as a navigation (always allowed cross-origin). match loader.fetch_navigation(&url) { Ok(resource) => { let html_text = match resource { Resource::Html { text, .. } => text, Resource::Other { data, .. } => { // Try to decode as text. String::from_utf8(data).unwrap_or_default() } _ => return None, }; let doc = we_html::parse_html(&html_text); Some((doc, url)) } Err(e) => { eprintln!("[we] iframe load error for {src}: {e}"); None } } } /// Render an iframe's content to a BGRA pixel buffer. /// /// Creates a mini rendering pipeline for the iframe document (resolve styles โ†’ /// layout โ†’ build display list โ†’ render) using the production Metal renderer /// offscreen. Returns a white image if styling fails or Metal is unavailable. pub fn render_iframe_to_image( doc: &Document, width: u32, height: u32, font: &we_text::font::Font, ) -> Image { use we_css::parser::Stylesheet; use we_layout::layout; use we_platform::metal::{ClearColor, Device}; use we_render::{build_display_list, GpuRenderer, RenderFonts}; let white = || Image { width, height, data: vec![255u8; (width * height * 4) as usize], }; let stylesheet = Stylesheet { rules: Vec::new() }; let image_sizes = HashMap::new(); let viewport = (width as f32, height as f32); let styled = match we_style::computed::resolve_styles( doc, std::slice::from_ref(&stylesheet), viewport, ) { Some(s) => s, None => return white(), }; let tree = layout( &styled, doc, width as f32, height as f32, font, &image_sizes, ); let display_list = build_display_list(&tree); // Clear the iframe canvas to its document's propagated background color // (CSS2 ยง14.2), matching the main-document behavior. let clear = match we_render::canvas_background_color(&tree) { Some(c) => ClearColor::new( c.r as f64 / 255.0, c.g as f64 / 255.0, c.b as f64 / 255.0, 1.0, ), None => ClearColor::new(1.0, 1.0, 1.0, 1.0), }; // Render offscreen through the production Metal pipeline. let image_refs = HashMap::new(); let rendered = Device::system_default() .and_then(GpuRenderer::new) .and_then(|mut backend| { backend.render_to_pixels( &display_list, RenderFonts::new(font, None), &image_refs, width, height, clear, ) }); match rendered { Some(data) => Image { width, height, data, }, None => white(), } } #[cfg(test)] mod tests { use super::*; #[test] fn collect_iframe_sizes_default() { let mut doc = Document::new(); let root = doc.root(); let html = doc.create_element("html"); let body = doc.create_element("body"); let iframe = doc.create_element("iframe"); doc.append_child(root, html); doc.append_child(html, body); doc.append_child(body, iframe); let mut sizes = HashMap::new(); collect_iframe_sizes(&doc, &mut sizes); assert_eq!( sizes.get(&iframe), Some(&ReplacedContent::Size(300.0, 150.0)) ); } #[test] fn collect_iframe_sizes_custom() { let mut doc = Document::new(); let root = doc.root(); let html = doc.create_element("html"); let body = doc.create_element("body"); let iframe = doc.create_element("iframe"); doc.set_attribute(iframe, "width", "500"); doc.set_attribute(iframe, "height", "400"); doc.append_child(root, html); doc.append_child(html, body); doc.append_child(body, iframe); let mut sizes = HashMap::new(); collect_iframe_sizes(&doc, &mut sizes); assert_eq!( sizes.get(&iframe), Some(&ReplacedContent::Size(500.0, 400.0)) ); } #[test] fn collect_iframe_sizes_multiple() { let mut doc = Document::new(); let root = doc.root(); let html = doc.create_element("html"); let body = doc.create_element("body"); let iframe1 = doc.create_element("iframe"); let iframe2 = doc.create_element("iframe"); doc.set_attribute(iframe2, "width", "200"); doc.append_child(root, html); doc.append_child(html, body); doc.append_child(body, iframe1); doc.append_child(body, iframe2); let mut sizes = HashMap::new(); collect_iframe_sizes(&doc, &mut sizes); assert_eq!(sizes.len(), 2); assert_eq!( sizes.get(&iframe1), Some(&ReplacedContent::Size(300.0, 150.0)) ); assert_eq!( sizes.get(&iframe2), Some(&ReplacedContent::Size(200.0, 150.0)) ); } }