From e8f75c9aea37d49d988f209281169af1fed05d8e Mon Sep 17 00:00:00 2001 From: Martin Robinson Date: Fri, 3 Jan 2025 19:55:01 +0100 Subject: [PATCH] script: Expose node helpers as `NodeTraits` and give more descriptive names (#34832) This puts a few commonly used `Node` helpers into a trait (`NodeTraits`) and gives them more descriptive names and documentation. The renames: - `document_from_node` -> `NodeTraits::owner_document` - `window_from_node` -> `NodeTraits::owner_window` - `stylesheets_owner_from_node `NodeTraits::stylesheet_list_owner` - `containing_shadow_root` -> `NodeTraits::containing_shadow_root` Signed-off-by: Martin Robinson --- components/script/animations.rs | 4 +- components/script/canvas_state.rs | 4 +- components/script/devtools.rs | 12 +-- components/script/dom/cssstyledeclaration.rs | 16 ++-- components/script/dom/cssstylerule.rs | 4 +- components/script/dom/cssstylesheet.rs | 7 +- .../script/dom/customelementregistry.rs | 6 +- components/script/dom/document.rs | 11 ++- components/script/dom/documentfragment.rs | 4 +- components/script/dom/domstringmap.rs | 5 +- components/script/dom/domtokenlist.rs | 5 +- components/script/dom/element.rs | 73 +++++++++-------- components/script/dom/elementinternals.rs | 6 +- components/script/dom/eventtarget.rs | 4 +- components/script/dom/htmlanchorelement.rs | 4 +- components/script/dom/htmlbaseelement.rs | 10 +-- components/script/dom/htmlbodyelement.rs | 14 ++-- components/script/dom/htmlbuttonelement.rs | 4 +- components/script/dom/htmlcanvaselement.rs | 10 +-- components/script/dom/htmlcollection.rs | 5 +- components/script/dom/htmldatalistelement.rs | 4 +- components/script/dom/htmldetailselement.rs | 4 +- components/script/dom/htmldialogelement.rs | 4 +- components/script/dom/htmlelement.rs | 54 +++++++------ components/script/dom/htmlfieldsetelement.rs | 6 +- components/script/dom/htmlformelement.rs | 23 +++--- components/script/dom/htmlframesetelement.rs | 2 +- components/script/dom/htmlheadelement.rs | 6 +- components/script/dom/htmliframeelement.rs | 22 +++--- components/script/dom/htmlimageelement.rs | 43 +++++----- components/script/dom/htmlinputelement.rs | 21 +++-- components/script/dom/htmllinkelement.rs | 16 ++-- components/script/dom/htmlmediaelement.rs | 76 +++++++++--------- components/script/dom/htmlmetaelement.rs | 6 +- components/script/dom/htmlobjectelement.rs | 4 +- .../script/dom/htmloptionscollection.rs | 4 +- components/script/dom/htmloutputelement.rs | 4 +- components/script/dom/htmlscriptelement.rs | 39 +++++----- components/script/dom/htmlselectelement.rs | 6 +- components/script/dom/htmlstyleelement.rs | 18 ++--- components/script/dom/htmltableelement.rs | 21 ++--- components/script/dom/htmltablerowelement.rs | 4 +- .../script/dom/htmltablesectionelement.rs | 14 ++-- components/script/dom/htmltemplateelement.rs | 9 ++- components/script/dom/htmltextareaelement.rs | 7 +- components/script/dom/htmlvideoelement.rs | 19 ++--- components/script/dom/macros.rs | 6 +- components/script/dom/mutationrecord.rs | 20 ++--- components/script/dom/node.rs | 78 +++++++++++-------- components/script/dom/resizeobserver.rs | 4 +- components/script/dom/selection.rs | 4 +- components/script/dom/shadowroot.rs | 6 +- components/script/dom/svgelement.rs | 4 +- components/script/dom/textcontrol.rs | 4 +- components/script/dom/uievent.rs | 4 +- components/script/dom/userscripts.rs | 4 +- .../script/dom/webglrenderingcontext.rs | 9 +-- .../script/dom/webgpu/gpucanvascontext.rs | 4 +- components/script/dom/window.rs | 4 +- components/script/image_listener.rs | 4 +- components/script/layout_image.rs | 4 +- components/script/links.rs | 6 +- components/script/script_module.rs | 7 +- components/script/script_thread.rs | 4 +- components/script/stylesheet_loader.rs | 13 ++-- components/script/webdriver_handlers.rs | 8 +- 66 files changed, 415 insertions(+), 426 deletions(-) diff --git a/components/script/animations.rs b/components/script/animations.rs index 0c9366dbcf3..380333bf251 100644 --- a/components/script/animations.rs +++ b/components/script/animations.rs @@ -30,7 +30,7 @@ use crate::dom::bindings::root::{Dom, DomRoot}; use crate::dom::bindings::str::DOMString; use crate::dom::bindings::trace::NoTrace; use crate::dom::event::Event; -use crate::dom::node::{from_untrusted_node_address, window_from_node, Node, NodeDamage}; +use crate::dom::node::{from_untrusted_node_address, Node, NodeDamage, NodeTraits}; use crate::dom::transitionevent::TransitionEvent; use crate::dom::window::Window; use crate::script_runtime::CanGc; @@ -516,7 +516,7 @@ impl Animations { DOMString::from(pseudo_element.to_css_string()) }); let elapsed_time = Finite::new(event.elapsed_time as f32).unwrap(); - let window = window_from_node(&*node); + let window = node.owner_window(); if event.event_type.is_transition_event() { let event_init = TransitionEventInit { diff --git a/components/script/canvas_state.rs b/components/script/canvas_state.rs index 0d5e934a5e4..0641a108244 100644 --- a/components/script/canvas_state.rs +++ b/components/script/canvas_state.rs @@ -53,7 +53,7 @@ use crate::dom::element::{cors_setting_for_element, Element}; use crate::dom::globalscope::GlobalScope; use crate::dom::htmlcanvaselement::{CanvasContext, HTMLCanvasElement}; use crate::dom::imagedata::ImageData; -use crate::dom::node::{window_from_node, Node, NodeDamage}; +use crate::dom::node::{Node, NodeDamage, NodeTraits}; use crate::dom::offscreencanvas::{OffscreenCanvas, OffscreenCanvasContext}; use crate::dom::paintworkletglobalscope::PaintWorkletGlobalScope; use crate::dom::textmetrics::TextMetrics; @@ -1086,7 +1086,7 @@ impl CanvasState { None => return, // offscreen canvas doesn't have a placeholder canvas }; let node = canvas.upcast::(); - let window = window_from_node(canvas); + let window = canvas.owner_window(); let resolved_font_style = match window.resolved_font_style_query(node, value.to_string(), can_gc) { Some(value) => value, diff --git a/components/script/devtools.rs b/components/script/devtools.rs index 7610c2c14f3..00b6f767a24 100644 --- a/components/script/devtools.rs +++ b/components/script/devtools.rs @@ -37,7 +37,7 @@ use crate::dom::document::AnimationFrameCallback; use crate::dom::element::Element; use crate::dom::globalscope::GlobalScope; use crate::dom::htmlscriptelement::SourceCode; -use crate::dom::node::{stylesheets_owner_from_node, window_from_node, Node, ShadowIncluding}; +use crate::dom::node::{Node, NodeTraits, ShadowIncluding}; use crate::dom::types::HTMLElement; use crate::realms::enter_realm; use crate::script_module::ScriptFetchOptions; @@ -152,7 +152,7 @@ pub fn handle_get_children( let inline: Vec<_> = parent .children() .map(|child| { - let window = window_from_node(&*child); + let window = child.owner_window(); let Some(elem) = child.downcast::() else { return false; }; @@ -231,7 +231,7 @@ pub fn handle_get_stylesheet_style( let document = documents.find_document(pipeline)?; let _realm = enter_realm(document.window()); - let owner = stylesheets_owner_from_node(&*node); + let owner = node.stylesheet_list_owner(); let stylesheet = owner.stylesheet_at(stylesheet)?; let list = stylesheet.GetCssRules().ok()?; @@ -275,7 +275,7 @@ pub fn handle_get_selectors( let document = documents.find_document(pipeline)?; let _realm = enter_realm(document.window()); - let owner = stylesheets_owner_from_node(&*node); + let owner = node.stylesheet_list_owner(); let rules = (0..owner.stylesheet_count()) .filter_map(|i| { @@ -312,7 +312,7 @@ pub fn handle_get_computed_style( Some(found_node) => found_node, }; - let window = window_from_node(&*node); + let window = node.owner_window(); let elem = node .downcast::() .expect("This should be an element"); @@ -353,7 +353,7 @@ pub fn handle_get_layout( let width = rect.Width() as f32; let height = rect.Height() as f32; - let window = window_from_node(&*node); + let window = node.owner_window(); let elem = node .downcast::() .expect("should be getting layout of element"); diff --git a/components/script/dom/cssstyledeclaration.rs b/components/script/dom/cssstyledeclaration.rs index 732077ca6a1..464938aa9da 100644 --- a/components/script/dom/cssstyledeclaration.rs +++ b/components/script/dom/cssstyledeclaration.rs @@ -28,7 +28,7 @@ use crate::dom::bindings::root::{Dom, DomRoot}; use crate::dom::bindings::str::DOMString; use crate::dom::cssrule::CSSRule; use crate::dom::element::Element; -use crate::dom::node::{document_from_node, stylesheets_owner_from_node, window_from_node, Node}; +use crate::dom::node::{Node, NodeTraits}; use crate::dom::window::Window; use crate::script_runtime::CanGc; @@ -67,7 +67,7 @@ impl CSSStyleOwner { let mut changed = true; match *self { CSSStyleOwner::Element(ref el) => { - let document = document_from_node(&**el); + let document = el.owner_document(); let shared_lock = document.style_shared_lock(); let mut attr = el.style_attribute().borrow_mut().take(); let result = if attr.is_some() { @@ -122,8 +122,7 @@ impl CSSStyleOwner { // If this is changed, see also // CSSStyleRule::SetSelectorText, which does the same thing. if let Some(owner) = rule.parent_stylesheet().get_owner() { - stylesheets_owner_from_node(owner.upcast::()) - .invalidate_stylesheets(); + owner.stylesheet_list_owner().invalidate_stylesheets(); } } result @@ -138,7 +137,7 @@ impl CSSStyleOwner { match *self { CSSStyleOwner::Element(ref el) => match *el.style_attribute().borrow() { Some(ref pdb) => { - let document = document_from_node(&**el); + let document = el.owner_document(); let guard = document.style_shared_lock().read(); f(pdb.read_with(&guard)) }, @@ -156,14 +155,14 @@ impl CSSStyleOwner { fn window(&self) -> DomRoot { match *self { - CSSStyleOwner::Element(ref el) => window_from_node(&**el), + CSSStyleOwner::Element(ref el) => el.owner_window(), CSSStyleOwner::CSSRule(ref rule, _) => DomRoot::from_ref(rule.global().as_window()), } } fn base_url(&self) -> ServoUrl { match *self { - CSSStyleOwner::Element(ref el) => window_from_node(&**el).Document().base_url(), + CSSStyleOwner::Element(ref el) => el.owner_document().base_url(), CSSStyleOwner::CSSRule(ref rule, _) => ServoUrl::from( rule.parent_stylesheet() .style_stylesheet() @@ -259,7 +258,8 @@ impl CSSStyleDeclaration { return DOMString::new(); } let addr = node.to_trusted_node_address(); - window_from_node(node).resolved_style_query(addr, self.pseudo, property, can_gc) + node.owner_window() + .resolved_style_query(addr, self.pseudo, property, can_gc) }, } } diff --git a/components/script/dom/cssstylerule.rs b/components/script/dom/cssstylerule.rs index dc0414881f2..669c1c6779e 100644 --- a/components/script/dom/cssstylerule.rs +++ b/components/script/dom/cssstylerule.rs @@ -20,7 +20,7 @@ use crate::dom::bindings::str::DOMString; use crate::dom::cssrule::{CSSRule, SpecificCSSRule}; use crate::dom::cssstyledeclaration::{CSSModificationAccess, CSSStyleDeclaration, CSSStyleOwner}; use crate::dom::cssstylesheet::CSSStyleSheet; -use crate::dom::node::{stylesheets_owner_from_node, Node}; +use crate::dom::node::NodeTraits; use crate::dom::window::Window; use crate::script_runtime::CanGc; @@ -120,7 +120,7 @@ impl CSSStyleRuleMethods for CSSStyleRule { let stylerule = self.stylerule.write_with(&mut guard); mem::swap(&mut stylerule.selectors, &mut s); if let Some(owner) = self.cssrule.parent_stylesheet().get_owner() { - stylesheets_owner_from_node(owner.upcast::()).invalidate_stylesheets(); + owner.stylesheet_list_owner().invalidate_stylesheets(); } } } diff --git a/components/script/dom/cssstylesheet.rs b/components/script/dom/cssstylesheet.rs index 4b1a7e1e63a..4b32453f73b 100644 --- a/components/script/dom/cssstylesheet.rs +++ b/components/script/dom/cssstylesheet.rs @@ -11,14 +11,13 @@ use style::stylesheets::{CssRuleTypes, Stylesheet as StyleStyleSheet}; use crate::dom::bindings::codegen::Bindings::CSSStyleSheetBinding::CSSStyleSheetMethods; use crate::dom::bindings::error::{Error, ErrorResult, Fallible}; -use crate::dom::bindings::inheritance::Castable; use crate::dom::bindings::reflector::{reflect_dom_object, DomObject}; use crate::dom::bindings::root::{DomRoot, MutNullableDom}; use crate::dom::bindings::str::DOMString; use crate::dom::cssrulelist::{CSSRuleList, RulesSource}; use crate::dom::element::Element; use crate::dom::medialist::MediaList; -use crate::dom::node::{stylesheets_owner_from_node, Node}; +use crate::dom::node::NodeTraits; use crate::dom::stylesheet::StyleSheet; use crate::dom::window::Window; use crate::script_runtime::CanGc; @@ -86,7 +85,9 @@ impl CSSStyleSheet { pub fn set_disabled(&self, disabled: bool) { if self.style_stylesheet.set_disabled(disabled) && self.get_owner().is_some() { - stylesheets_owner_from_node(self.get_owner().unwrap().upcast::()) + self.get_owner() + .unwrap() + .stylesheet_list_owner() .invalidate_stylesheets(); } } diff --git a/components/script/dom/customelementregistry.rs b/components/script/dom/customelementregistry.rs index 5e71738fb7d..bf31cecaea9 100644 --- a/components/script/dom/customelementregistry.rs +++ b/components/script/dom/customelementregistry.rs @@ -43,7 +43,7 @@ use crate::dom::element::Element; use crate::dom::globalscope::GlobalScope; use crate::dom::htmlelement::HTMLElement; use crate::dom::htmlformelement::{FormControl, HTMLFormElement}; -use crate::dom::node::{document_from_node, window_from_node, Node, ShadowIncluding}; +use crate::dom::node::{Node, NodeTraits, ShadowIncluding}; use crate::dom::promise::Promise; use crate::dom::window::Window; use crate::microtask::Microtask; @@ -895,7 +895,7 @@ fn run_upgrade_constructor( element: &Element, can_gc: CanGc, ) -> ErrorResult { - let window = window_from_node(element); + let window = element.owner_window(); let cx = GlobalScope::get_cx(); rooted!(in(*cx) let constructor_val = ObjectValue(constructor.callback())); rooted!(in(*cx) let mut element_val = UndefinedValue()); @@ -954,7 +954,7 @@ fn run_upgrade_constructor( /// pub fn try_upgrade_element(element: &Element) { // Step 1 - let document = document_from_node(element); + let document = element.owner_document(); let namespace = element.namespace(); let local_name = element.local_name(); let is = element.get_is(); diff --git a/components/script/dom/document.rs b/components/script/dom/document.rs index 229d0b11e3f..c4614c00a53 100644 --- a/components/script/dom/document.rs +++ b/components/script/dom/document.rs @@ -152,8 +152,7 @@ use crate::dom::location::Location; use crate::dom::messageevent::MessageEvent; use crate::dom::mouseevent::MouseEvent; use crate::dom::node::{ - self, document_from_node, window_from_node, CloneChildrenFlag, Node, NodeDamage, NodeFlags, - ShadowIncluding, + self, CloneChildrenFlag, Node, NodeDamage, NodeFlags, NodeTraits, ShadowIncluding, }; use crate::dom::nodeiterator::NodeIterator; use crate::dom::nodelist::NodeList; @@ -2261,7 +2260,7 @@ impl Document { let iframes: Vec<_> = self.iframes().iter().collect(); for iframe in &iframes { // TODO: handle the case of cross origin iframes. - let document = document_from_node(&**iframe); + let document = iframe.owner_document(); can_unload = document.prompt_to_unload(true, can_gc); if !document.salvageable() { self.salvageable.set(false); @@ -2333,7 +2332,7 @@ impl Document { let iframes: Vec<_> = self.iframes().iter().collect(); for iframe in &iframes { // TODO: handle the case of cross origin iframes. - let document = document_from_node(&**iframe); + let document = iframe.owner_document(); document.unload(true, can_gc); if !document.salvageable() { self.salvageable.set(false); @@ -2501,7 +2500,7 @@ impl Document { // https://html.spec.whatwg.org/multipage/#shared-declarative-refresh-steps document.window.upcast::().schedule_callback( OneshotTimerCallback::RefreshRedirectDue(RefreshRedirectDue { - window: window_from_node(&*document), + window: DomRoot::from_ref(document.window()), url: url.clone(), }), Duration::from_secs(*time), @@ -5314,7 +5313,7 @@ impl DocumentMethods for Document { // TODO: prompt to unload. // TODO: set unload_event_start and unload_event_end - window_from_node(self).set_navigation_start(); + self.window().set_navigation_start(); // Step 8 // TODO: https://github.com/servo/servo/issues/21937 diff --git a/components/script/dom/documentfragment.rs b/components/script/dom/documentfragment.rs index 2f57692e1fb..0dc7eb53227 100644 --- a/components/script/dom/documentfragment.rs +++ b/components/script/dom/documentfragment.rs @@ -18,7 +18,7 @@ use crate::dom::bindings::str::DOMString; use crate::dom::document::Document; use crate::dom::element::Element; use crate::dom::htmlcollection::HTMLCollection; -use crate::dom::node::{window_from_node, Node}; +use crate::dom::node::{Node, NodeTraits}; use crate::dom::nodelist::NodeList; use crate::dom::virtualmethods::VirtualMethods; use crate::dom::window::Window; @@ -77,7 +77,7 @@ impl DocumentFragmentMethods for DocumentFragment { // https://dom.spec.whatwg.org/#dom-parentnode-children fn Children(&self) -> DomRoot { - let window = window_from_node(self); + let window = self.owner_window(); HTMLCollection::children(&window, self.upcast()) } diff --git a/components/script/dom/domstringmap.rs b/components/script/dom/domstringmap.rs index 952e5491abb..2d72a9d4597 100644 --- a/components/script/dom/domstringmap.rs +++ b/components/script/dom/domstringmap.rs @@ -10,7 +10,7 @@ use crate::dom::bindings::reflector::{reflect_dom_object, Reflector}; use crate::dom::bindings::root::{Dom, DomRoot}; use crate::dom::bindings::str::DOMString; use crate::dom::htmlelement::HTMLElement; -use crate::dom::node::window_from_node; +use crate::dom::node::NodeTraits; use crate::script_runtime::CanGc; #[dom_struct] @@ -28,10 +28,9 @@ impl DOMStringMap { } pub fn new(element: &HTMLElement) -> DomRoot { - let window = window_from_node(element); reflect_dom_object( Box::new(DOMStringMap::new_inherited(element)), - &*window, + &*element.owner_window(), CanGc::note(), ) } diff --git a/components/script/dom/domtokenlist.rs b/components/script/dom/domtokenlist.rs index 33620c68d21..7465649b056 100644 --- a/components/script/dom/domtokenlist.rs +++ b/components/script/dom/domtokenlist.rs @@ -14,7 +14,7 @@ use crate::dom::bindings::reflector::{reflect_dom_object, Reflector}; use crate::dom::bindings::root::{Dom, DomRoot}; use crate::dom::bindings::str::DOMString; use crate::dom::element::Element; -use crate::dom::node::window_from_node; +use crate::dom::node::NodeTraits; use crate::script_runtime::CanGc; #[dom_struct] @@ -46,14 +46,13 @@ impl DOMTokenList { local_name: &LocalName, supported_tokens: Option>, ) -> DomRoot { - let window = window_from_node(element); reflect_dom_object( Box::new(DOMTokenList::new_inherited( element, local_name.clone(), supported_tokens, )), - &*window, + &*element.owner_window(), CanGc::note(), ) } diff --git a/components/script/dom/element.rs b/components/script/dom/element.rs index b7c2949660f..006d99eb2f1 100644 --- a/components/script/dom/element.rs +++ b/components/script/dom/element.rs @@ -137,8 +137,8 @@ use crate::dom::htmlvideoelement::{HTMLVideoElement, LayoutHTMLVideoElementHelpe use crate::dom::mutationobserver::{Mutation, MutationObserver}; use crate::dom::namednodemap::NamedNodeMap; use crate::dom::node::{ - document_from_node, window_from_node, BindContext, ChildrenMutation, LayoutNodeHelpers, Node, - NodeDamage, NodeFlags, ShadowIncluding, UnbindContext, + BindContext, ChildrenMutation, LayoutNodeHelpers, Node, NodeDamage, NodeFlags, NodeTraits, + ShadowIncluding, UnbindContext, }; use crate::dom::nodelist::NodeList; use crate::dom::promise::Promise; @@ -1748,7 +1748,7 @@ impl Element { }; let value = &**attr.value(); // XXXManishearth this doesn't handle `javascript:` urls properly - document_from_node(self) + self.owner_document() .base_url() .join(value) .map(|parsed| USVString(parsed.into_string())) @@ -1972,7 +1972,7 @@ impl Element { if let Some(template) = self.downcast::() { template.Content(can_gc).upcast::().owner_doc() } else { - document_from_node(self) + self.owner_document() } }; let fragment = DocumentFragment::new(&context_document, can_gc); @@ -2011,8 +2011,7 @@ impl Element { if !self.is_connected() { return false; } - let document = document_from_node(self); - document.get_allow_fullscreen() + self.owner_document().get_allow_fullscreen() } // https://html.spec.whatwg.org/multipage/#home-subtree @@ -2088,8 +2087,7 @@ impl Element { // https://html.spec.whatwg.org/multipage/#focus-fixup-rule if !is_sequentially_focusable { - let document = document_from_node(self); - document.perform_focus_fixup_rule(self, can_gc); + self.owner_document().perform_focus_fixup_rule(self, can_gc); } } @@ -2176,7 +2174,7 @@ impl ElementMethods for Element { // https://dom.spec.whatwg.org/#dom-element-attributes fn Attributes(&self) -> DomRoot { self.attr_list - .or_init(|| NamedNodeMap::new(&window_from_node(self), self)) + .or_init(|| NamedNodeMap::new(&self.owner_window(), self)) } // https://dom.spec.whatwg.org/#dom-element-hasattributes @@ -2413,7 +2411,7 @@ impl ElementMethods for Element { // https://dom.spec.whatwg.org/#dom-element-getelementsbytagname fn GetElementsByTagName(&self, localname: DOMString) -> DomRoot { - let window = window_from_node(self); + let window = self.owner_window(); HTMLCollection::by_qualified_name(&window, self.upcast(), LocalName::from(&*localname)) } @@ -2423,19 +2421,19 @@ impl ElementMethods for Element { maybe_ns: Option, localname: DOMString, ) -> DomRoot { - let window = window_from_node(self); + let window = self.owner_window(); HTMLCollection::by_tag_name_ns(&window, self.upcast(), localname, maybe_ns) } // https://dom.spec.whatwg.org/#dom-element-getelementsbyclassname fn GetElementsByClassName(&self, classes: DOMString) -> DomRoot { - let window = window_from_node(self); + let window = self.owner_window(); HTMLCollection::by_class_name(&window, self.upcast(), classes) } // https://drafts.csswg.org/cssom-view/#dom-element-getclientrects fn GetClientRects(&self, can_gc: CanGc) -> DomRoot { - let win = window_from_node(self); + let win = self.owner_window(); let raw_rects = self.upcast::().content_boxes(can_gc); let rects: Vec> = raw_rects .iter() @@ -2455,7 +2453,7 @@ impl ElementMethods for Element { // https://drafts.csswg.org/cssom-view/#dom-element-getboundingclientrect fn GetBoundingClientRect(&self, can_gc: CanGc) -> DomRoot { - let win = window_from_node(self); + let win = self.owner_window(); let rect = self.upcast::().bounding_content_box_or_zero(can_gc); DOMRect::new( win.upcast(), @@ -2749,7 +2747,7 @@ impl ElementMethods for Element { self.local_name().clone(), ); - let result = if document_from_node(self).is_html_document() { + let result = if self.owner_document().is_html_document() { self.upcast::() .html_serialize(ChildrenOnly(Some(qname))) } else { @@ -2792,7 +2790,7 @@ impl ElementMethods for Element { /// fn GetOuterHTML(&self) -> Fallible { - let result = if document_from_node(self).is_html_document() { + let result = if self.owner_document().is_html_document() { self.upcast::().html_serialize(IncludeNode) } else { self.upcast::().xml_serialize(XmlIncludeNode) @@ -2803,7 +2801,7 @@ impl ElementMethods for Element { /// fn SetOuterHTML(&self, value: DOMString, can_gc: CanGc) -> ErrorResult { - let context_document = document_from_node(self); + let context_document = self.owner_document(); let context_node = self.upcast::(); // Step 1. let context_parent = match context_node.GetParentNode() { @@ -2859,7 +2857,7 @@ impl ElementMethods for Element { // https://dom.spec.whatwg.org/#dom-parentnode-children fn Children(&self) -> DomRoot { - let window = window_from_node(self); + let window = self.owner_window(); HTMLCollection::children(&window, self.upcast()) } @@ -2930,7 +2928,7 @@ impl ElementMethods for Element { // https://dom.spec.whatwg.org/#dom-element-matches fn Matches(&self, selectors: DOMString) -> Fallible { - let doc = document_from_node(self); + let doc = self.owner_document(); let url = doc.url(); let selectors = match SelectorParser::parse_author_origin_no_namespace( &selectors, @@ -2953,7 +2951,7 @@ impl ElementMethods for Element { // https://dom.spec.whatwg.org/#dom-element-closest fn Closest(&self, selectors: DOMString) -> Fallible>> { - let doc = document_from_node(self); + let doc = self.owner_document(); let url = doc.url(); let selectors = match SelectorParser::parse_author_origin_no_namespace( &selectors, @@ -2985,7 +2983,7 @@ impl ElementMethods for Element { // https://dom.spec.whatwg.org/#dom-element-insertadjacenttext fn InsertAdjacentText(&self, where_: DOMString, data: DOMString, can_gc: CanGc) -> ErrorResult { // Step 1. - let text = Text::new(data, &document_from_node(self), can_gc); + let text = Text::new(data, &self.owner_document(), can_gc); // Step 2. let where_ = where_.parse::()?; @@ -3055,7 +3053,7 @@ impl ElementMethods for Element { // https://fullscreen.spec.whatwg.org/#dom-element-requestfullscreen fn RequestFullscreen(&self, can_gc: CanGc) -> Rc { - let doc = document_from_node(self); + let doc = self.owner_document(); doc.enter_fullscreen(self, can_gc) } @@ -3488,7 +3486,7 @@ impl VirtualMethods for Element { attr.swap_value(&mut value); block } else { - let win = window_from_node(self); + let win = self.owner_window(); Arc::new(doc.style_shared_lock().wrap(parse_style_attribute( &attr.value(), &UrlExtraData(doc.base_url().get_arc()), @@ -3512,7 +3510,7 @@ impl VirtualMethods for Element { None } }); - let containing_shadow_root = self.upcast::().containing_shadow_root(); + let containing_shadow_root = self.containing_shadow_root(); if node.is_connected() { let value = attr.value().as_atom().clone(); match mutation { @@ -3614,7 +3612,7 @@ impl VirtualMethods for Element { f.bind_form_control_to_tree(); } - let doc = document_from_node(self); + let doc = self.owner_document(); if let Some(ref shadow_root) = self.shadow_root() { shadow_root.bind_to_tree(context); @@ -3627,14 +3625,14 @@ impl VirtualMethods for Element { self.update_sequentially_focusable_status(CanGc::note()); if let Some(ref id) = *self.id_attribute.borrow() { - if let Some(shadow_root) = self.upcast::().containing_shadow_root() { + if let Some(shadow_root) = self.containing_shadow_root() { shadow_root.register_element_id(self, id.clone()); } else { doc.register_element_id(self, id.clone()); } } if let Some(ref name) = self.name_attribute() { - if self.upcast::().containing_shadow_root().is_none() { + if self.containing_shadow_root().is_none() { doc.register_element_name(self, name.clone()); } } @@ -3659,21 +3657,21 @@ impl VirtualMethods for Element { self.update_sequentially_focusable_status(CanGc::note()); - let doc = document_from_node(self); + let doc = self.owner_document(); let fullscreen = doc.GetFullscreenElement(); if fullscreen.as_deref() == Some(self) { doc.exit_fullscreen(CanGc::note()); } if let Some(ref value) = *self.id_attribute.borrow() { - if let Some(ref shadow_root) = self.upcast::().containing_shadow_root() { + if let Some(ref shadow_root) = self.containing_shadow_root() { shadow_root.unregister_element_id(self, value.clone()); } else { doc.unregister_element_id(self, value.clone()); } } if let Some(ref value) = self.name_attribute() { - if self.upcast::().containing_shadow_root().is_none() { + if self.containing_shadow_root().is_none() { doc.unregister_element_name(self, value.clone()); } } @@ -3711,7 +3709,7 @@ impl VirtualMethods for Element { fn adopting_steps(&self, old_doc: &Document) { self.super_type().unwrap().adopting_steps(old_doc); - if document_from_node(self).is_html_document() != old_doc.is_html_document() { + if self.owner_document().is_html_document() != old_doc.is_html_document() { self.tag_name.clear(); } } @@ -3737,8 +3735,7 @@ impl SelectorsElement for DomRoot { } fn containing_shadow_host(&self) -> Option { - self.upcast::() - .containing_shadow_root() + self.containing_shadow_root() .map(|shadow_root| shadow_root.Host()) } @@ -4004,7 +4001,7 @@ impl Element { rect.size = Size2D::::new(viewport_dimensions.width, viewport_dimensions.height); } - self.ensure_rare_data().client_rect = Some(window_from_node(self).cache_layout_value(rect)); + self.ensure_rare_data().client_rect = Some(self.owner_window().cache_layout_value(rect)); rect } @@ -4282,7 +4279,7 @@ impl Element { // https://html.spec.whatwg.org/multipage/#cannot-navigate pub fn cannot_navigate(&self) -> bool { - let document = document_from_node(self); + let document = self.owner_document(); // Step 1. !document.is_fully_active() || @@ -4441,7 +4438,7 @@ impl TaskOnce for ElementPerformFullscreenEnter { fn run_once(self) { let element = self.element.root(); let promise = self.promise.root(); - let document = document_from_node(&*element); + let document = element.owner_document(); // Step 7.1 if self.error || !element.fullscreen_element_ready_check() { @@ -4485,7 +4482,7 @@ impl TaskOnce for ElementPerformFullscreenExit { #[allow(crown::unrooted_must_root)] fn run_once(self) { let element = self.element.root(); - let document = document_from_node(&*element); + let document = element.owner_document(); // TODO Step 9.1-5 // Step 9.6 element.set_fullscreen_state(false); @@ -4548,7 +4545,7 @@ pub(crate) fn referrer_policy_for_element(element: &Element) -> ReferrerPolicy { element .get_attribute_by_name(DOMString::from_string(String::from("referrerpolicy"))) .map(|attribute: DomRoot| determine_policy_for_token(&attribute.Value())) - .unwrap_or(document_from_node(element).get_referrer_policy()) + .unwrap_or(element.owner_document().get_referrer_policy()) } pub(crate) fn cors_setting_for_element(element: &Element) -> Option { diff --git a/components/script/dom/elementinternals.rs b/components/script/dom/elementinternals.rs index 1baf20caed5..bb717e9e419 100644 --- a/components/script/dom/elementinternals.rs +++ b/components/script/dom/elementinternals.rs @@ -21,7 +21,7 @@ use crate::dom::element::Element; use crate::dom::file::File; use crate::dom::htmlelement::HTMLElement; use crate::dom::htmlformelement::{FormDatum, FormDatumValue, HTMLFormElement}; -use crate::dom::node::{window_from_node, Node}; +use crate::dom::node::{Node, NodeTraits}; use crate::dom::nodelist::NodeList; use crate::dom::validation::{is_barred_by_datalist_ancestor, Validatable}; use crate::dom::validitystate::{ValidationFlags, ValidityState}; @@ -88,7 +88,7 @@ impl ElementInternals { } pub fn new(element: &HTMLElement) -> DomRoot { - let global = window_from_node(element); + let global = element.owner_window(); reflect_dom_object( Box::new(ElementInternals::new_inherited(element)), &*global, @@ -348,7 +348,7 @@ impl Validatable for ElementInternals { debug_assert!(self.is_target_form_associated()); self.validity_state.or_init(|| { ValidityState::new( - &window_from_node(self.target_element.upcast::()), + &self.target_element.owner_window(), self.target_element.upcast(), ) }) diff --git a/components/script/dom/eventtarget.rs b/components/script/dom/eventtarget.rs index 09931ec0a17..b2d2ae7ef83 100644 --- a/components/script/dom/eventtarget.rs +++ b/components/script/dom/eventtarget.rs @@ -52,7 +52,7 @@ use crate::dom::errorevent::ErrorEvent; use crate::dom::event::{Event, EventBubbles, EventCancelable, EventStatus}; use crate::dom::globalscope::GlobalScope; use crate::dom::htmlformelement::FormControlElementHelpers; -use crate::dom::node::document_from_node; +use crate::dom::node::NodeTraits; use crate::dom::virtualmethods::VirtualMethods; use crate::dom::window::Window; use crate::dom::workerglobalscope::WorkerGlobalScope; @@ -501,7 +501,7 @@ impl EventTarget { // Step 3.1 let element = self.downcast::(); let document = match element { - Some(element) => document_from_node(element), + Some(element) => element.owner_document(), None => self.downcast::().unwrap().Document(), }; diff --git a/components/script/dom/htmlanchorelement.rs b/components/script/dom/htmlanchorelement.rs index 4e6df0f5212..6c15ff4bc23 100644 --- a/components/script/dom/htmlanchorelement.rs +++ b/components/script/dom/htmlanchorelement.rs @@ -30,7 +30,7 @@ use crate::dom::eventtarget::EventTarget; use crate::dom::htmlelement::HTMLElement; use crate::dom::htmlimageelement::HTMLImageElement; use crate::dom::mouseevent::MouseEvent; -use crate::dom::node::{document_from_node, BindContext, Node}; +use crate::dom::node::{BindContext, Node, NodeTraits}; use crate::dom::urlhelper::UrlHelper; use crate::dom::virtualmethods::VirtualMethods; use crate::links::{follow_hyperlink, LinkRelations}; @@ -95,7 +95,7 @@ impl HTMLAnchorElement { // Step 3. Let url be the result of encoding-parsing a URL given this element's // href content attribute's value, relative to this element's node document. - let document = document_from_node(self); + let document = self.owner_document(); let url = document.encoding_parse_a_url(&attribute.value()); // Step 4. If url is not failure, then set this element's url to url. diff --git a/components/script/dom/htmlbaseelement.rs b/components/script/dom/htmlbaseelement.rs index 9618eebacd1..b67888e3f2e 100644 --- a/components/script/dom/htmlbaseelement.rs +++ b/components/script/dom/htmlbaseelement.rs @@ -15,7 +15,7 @@ use crate::dom::bindings::str::DOMString; use crate::dom::document::Document; use crate::dom::element::{AttributeMutation, Element}; use crate::dom::htmlelement::HTMLElement; -use crate::dom::node::{document_from_node, BindContext, Node, UnbindContext}; +use crate::dom::node::{BindContext, Node, NodeTraits, UnbindContext}; use crate::dom::virtualmethods::VirtualMethods; use crate::script_runtime::CanGc; @@ -60,7 +60,7 @@ impl HTMLBaseElement { "The frozen base url is only defined for base elements \ that have a base url.", ); - let document = document_from_node(self); + let document = self.owner_document(); let base = document.fallback_base_url(); let parsed = base.join(&href.value()); parsed.unwrap_or(base) @@ -74,7 +74,7 @@ impl HTMLBaseElement { } if self.upcast::().has_attribute(&local_name!("href")) { - let document = document_from_node(self); + let document = self.owner_document(); document.refresh_base_element(); } } @@ -84,7 +84,7 @@ impl HTMLBaseElementMethods for HTMLBaseElement { // https://html.spec.whatwg.org/multipage/#dom-base-href fn Href(&self) -> DOMString { // Step 1. - let document = document_from_node(self); + let document = self.owner_document(); // Step 2. let attr = self @@ -120,7 +120,7 @@ impl VirtualMethods for HTMLBaseElement { fn attribute_mutated(&self, attr: &Attr, mutation: AttributeMutation) { self.super_type().unwrap().attribute_mutated(attr, mutation); if *attr.local_name() == local_name!("href") { - document_from_node(self).refresh_base_element(); + self.owner_document().refresh_base_element(); } } diff --git a/components/script/dom/htmlbodyelement.rs b/components/script/dom/htmlbodyelement.rs index 0b749b779a5..01ff408ae5e 100644 --- a/components/script/dom/htmlbodyelement.rs +++ b/components/script/dom/htmlbodyelement.rs @@ -20,7 +20,7 @@ use crate::dom::document::Document; use crate::dom::element::{AttributeMutation, Element, LayoutElementHelpers}; use crate::dom::eventtarget::EventTarget; use crate::dom::htmlelement::HTMLElement; -use crate::dom::node::{document_from_node, window_from_node, BindContext, Node}; +use crate::dom::node::{BindContext, Node, NodeTraits}; use crate::dom::virtualmethods::VirtualMethods; use crate::script_runtime::CanGc; @@ -86,10 +86,8 @@ impl HTMLBodyElementMethods for HTMLBodyElement { // https://html.spec.whatwg.org/multipage/#dom-body-background fn SetBackground(&self, input: DOMString, can_gc: CanGc) { - let value = AttrValue::from_resolved_url( - &document_from_node(self).base_url().get_arc(), - input.into(), - ); + let value = + AttrValue::from_resolved_url(&self.owner_document().base_url().get_arc(), input.into()); self.upcast::() .set_attribute(&local_name!("background"), value, can_gc); } @@ -152,7 +150,7 @@ impl VirtualMethods for HTMLBodyElement { return; } - let window = window_from_node(self); + let window = self.owner_window(); window.prevent_layout_until_load_event(); if window.is_top_level() { window.send_to_embedder(EmbedderMsg::HeadParsed); @@ -165,7 +163,7 @@ impl VirtualMethods for HTMLBodyElement { AttrValue::from_legacy_color(value.into()) }, local_name!("background") => AttrValue::from_resolved_url( - &document_from_node(self).base_url().get_arc(), + &self.owner_document().base_url().get_arc(), value.into(), ), _ => self @@ -178,7 +176,7 @@ impl VirtualMethods for HTMLBodyElement { fn attribute_mutated(&self, attr: &Attr, mutation: AttributeMutation) { let do_super_mutate = match (attr.local_name(), mutation) { (name, AttributeMutation::Set(_)) if name.starts_with("on") => { - let window = window_from_node(self); + let window = self.owner_window(); // https://html.spec.whatwg.org/multipage/ // #event-handlers-on-elements,-document-objects,-and-window-objects:event-handlers-3 match name { diff --git a/components/script/dom/htmlbuttonelement.rs b/components/script/dom/htmlbuttonelement.rs index 25f90802c16..793a6a212da 100644 --- a/components/script/dom/htmlbuttonelement.rs +++ b/components/script/dom/htmlbuttonelement.rs @@ -26,7 +26,7 @@ use crate::dom::htmlformelement::{ FormControl, FormDatum, FormDatumValue, FormSubmitterElement, HTMLFormElement, ResetFrom, SubmittedFrom, }; -use crate::dom::node::{window_from_node, BindContext, Node, UnbindContext}; +use crate::dom::node::{BindContext, Node, NodeTraits, UnbindContext}; use crate::dom::nodelist::NodeList; use crate::dom::validation::{is_barred_by_datalist_ancestor, Validatable}; use crate::dom::validitystate::{ValidationFlags, ValidityState}; @@ -333,7 +333,7 @@ impl Validatable for HTMLButtonElement { fn validity_state(&self) -> DomRoot { self.validity_state - .or_init(|| ValidityState::new(&window_from_node(self), self.upcast())) + .or_init(|| ValidityState::new(&self.owner_window(), self.upcast())) } fn is_instance_validatable(&self) -> bool { diff --git a/components/script/dom/htmlcanvaselement.rs b/components/script/dom/htmlcanvaselement.rs index cbfadf251ee..93e53cb7545 100644 --- a/components/script/dom/htmlcanvaselement.rs +++ b/components/script/dom/htmlcanvaselement.rs @@ -48,7 +48,7 @@ use crate::dom::gpucanvascontext::GPUCanvasContext; use crate::dom::htmlelement::HTMLElement; use crate::dom::mediastream::MediaStream; use crate::dom::mediastreamtrack::MediaStreamTrack; -use crate::dom::node::{window_from_node, Node}; +use crate::dom::node::{Node, NodeTraits}; use crate::dom::virtualmethods::VirtualMethods; use crate::dom::webgl2renderingcontext::WebGL2RenderingContext; use crate::dom::webglrenderingcontext::WebGLRenderingContext; @@ -197,7 +197,7 @@ impl HTMLCanvasElement { _ => None, }; } - let window = window_from_node(self); + let window = self.owner_window(); let size = self.get_size(); let context = CanvasRenderingContext2D::new(window.upcast::(), self, size); *self.context.borrow_mut() = Some(CanvasContext::Context2d(Dom::from_ref(&*context))); @@ -216,7 +216,7 @@ impl HTMLCanvasElement { _ => None, }; } - let window = window_from_node(self); + let window = self.owner_window(); let size = self.get_size(); let attrs = Self::get_gl_attributes(cx, options)?; let canvas = HTMLCanvasElementOrOffscreenCanvas::HTMLCanvasElement(DomRoot::from_ref(self)); @@ -248,7 +248,7 @@ impl HTMLCanvasElement { _ => None, }; } - let window = window_from_node(self); + let window = self.owner_window(); let size = self.get_size(); let attrs = Self::get_gl_attributes(cx, options)?; let canvas = HTMLCanvasElementOrOffscreenCanvas::HTMLCanvasElement(DomRoot::from_ref(self)); @@ -279,7 +279,7 @@ impl HTMLCanvasElement { .recv() .expect("Failed to get WebGPU channel") .map(|channel| { - let window = window_from_node(self); + let window = self.owner_window(); let context = GPUCanvasContext::new(window.upcast::(), self, channel); *self.context.borrow_mut() = Some(CanvasContext::WebGPU(Dom::from_ref(&*context))); context diff --git a/components/script/dom/htmlcollection.rs b/components/script/dom/htmlcollection.rs index 5e2c1130b21..6294c9b93d9 100644 --- a/components/script/dom/htmlcollection.rs +++ b/components/script/dom/htmlcollection.rs @@ -18,7 +18,7 @@ use crate::dom::bindings::str::DOMString; use crate::dom::bindings::trace::JSTraceable; use crate::dom::bindings::xmlname::namespace_from_domstring; use crate::dom::element::Element; -use crate::dom::node::{document_from_node, Node}; +use crate::dom::node::{Node, NodeTraits}; use crate::dom::window::Window; use crate::script_runtime::CanGc; @@ -282,7 +282,8 @@ impl HTMLCollection { } impl CollectionFilter for ClassNameFilter { fn filter(&self, elem: &Element, _root: &Node) -> bool { - let case_sensitivity = document_from_node(elem) + let case_sensitivity = elem + .owner_document() .quirks_mode() .classes_and_ids_case_sensitivity(); diff --git a/components/script/dom/htmldatalistelement.rs b/components/script/dom/htmldatalistelement.rs index c54c5c41298..105f6e2225d 100644 --- a/components/script/dom/htmldatalistelement.rs +++ b/components/script/dom/htmldatalistelement.rs @@ -13,7 +13,7 @@ use crate::dom::document::Document; use crate::dom::htmlcollection::HTMLCollection; use crate::dom::htmlelement::HTMLElement; use crate::dom::htmloptionelement::HTMLOptionElement; -use crate::dom::node::{window_from_node, Node}; +use crate::dom::node::{Node, NodeTraits}; use crate::script_runtime::CanGc; #[dom_struct] @@ -54,7 +54,7 @@ impl HTMLDataListElement { impl HTMLDataListElementMethods for HTMLDataListElement { // https://html.spec.whatwg.org/multipage/#dom-datalist-options fn Options(&self) -> DomRoot { - HTMLCollection::new_with_filter_fn(&window_from_node(self), self.upcast(), |element, _| { + HTMLCollection::new_with_filter_fn(&self.owner_window(), self.upcast(), |element, _| { element.is::() }) } diff --git a/components/script/dom/htmldetailselement.rs b/components/script/dom/htmldetailselement.rs index 9d5a1030720..39baba43a5c 100644 --- a/components/script/dom/htmldetailselement.rs +++ b/components/script/dom/htmldetailselement.rs @@ -17,7 +17,7 @@ use crate::dom::document::Document; use crate::dom::element::AttributeMutation; use crate::dom::eventtarget::EventTarget; use crate::dom::htmlelement::HTMLElement; -use crate::dom::node::{window_from_node, Node, NodeDamage}; +use crate::dom::node::{Node, NodeDamage, NodeTraits}; use crate::dom::virtualmethods::VirtualMethods; use crate::script_runtime::CanGc; @@ -82,7 +82,7 @@ impl VirtualMethods for HTMLDetailsElement { let counter = self.toggle_counter.get() + 1; self.toggle_counter.set(counter); - let window = window_from_node(self); + let window = self.owner_window(); let this = Trusted::new(self); // FIXME(nox): Why are errors silenced here? let _ = window.task_manager().dom_manipulation_task_source().queue( diff --git a/components/script/dom/htmldialogelement.rs b/components/script/dom/htmldialogelement.rs index 860072566d7..e556e9ed99b 100644 --- a/components/script/dom/htmldialogelement.rs +++ b/components/script/dom/htmldialogelement.rs @@ -15,7 +15,7 @@ use crate::dom::document::Document; use crate::dom::element::Element; use crate::dom::eventtarget::EventTarget; use crate::dom::htmlelement::HTMLElement; -use crate::dom::node::{window_from_node, Node}; +use crate::dom::node::{Node, NodeTraits}; use crate::script_runtime::CanGc; #[dom_struct] @@ -102,7 +102,7 @@ impl HTMLDialogElementMethods for HTMLDialogElement { fn Close(&self, return_value: Option) { let element = self.upcast::(); let target = self.upcast::(); - let win = window_from_node(self); + let win = self.owner_window(); // Step 1 & 2 if element diff --git a/components/script/dom/htmlelement.rs b/components/script/dom/htmlelement.rs index 4917024fa2c..1c69482c0e4 100644 --- a/components/script/dom/htmlelement.rs +++ b/components/script/dom/htmlelement.rs @@ -46,9 +46,7 @@ use crate::dom::htmlhtmlelement::HTMLHtmlElement; use crate::dom::htmlinputelement::{HTMLInputElement, InputType}; use crate::dom::htmllabelelement::HTMLLabelElement; use crate::dom::htmltextareaelement::HTMLTextAreaElement; -use crate::dom::node::{ - document_from_node, window_from_node, BindContext, Node, ShadowIncluding, UnbindContext, -}; +use crate::dom::node::{BindContext, Node, NodeTraits, ShadowIncluding, UnbindContext}; use crate::dom::text::Text; use crate::dom::virtualmethods::VirtualMethods; use crate::script_runtime::CanGc; @@ -117,7 +115,7 @@ impl HTMLElement { /// fn get_inner_outer_text(&self, can_gc: CanGc) -> DOMString { let node = self.upcast::(); - let window = window_from_node(node); + let window = node.owner_window(); let element = self.as_element(); // Step 1. @@ -139,7 +137,7 @@ impl HTMLElementMethods for HTMLElement { // https://html.spec.whatwg.org/multipage/#the-style-attribute fn Style(&self) -> DomRoot { self.style_decl.or_init(|| { - let global = window_from_node(self); + let global = self.owner_window(); CSSStyleDeclaration::new( &global, CSSStyleOwner::Element(Dom::from_ref(self.upcast())), @@ -190,7 +188,7 @@ impl HTMLElementMethods for HTMLElement { // https://html.spec.whatwg.org/multipage/#handler-onerror fn GetOnerror(&self, can_gc: CanGc) -> Option> { if self.is_body_or_frameset() { - let document = document_from_node(self); + let document = self.owner_document(); if document.has_browsing_context() { document.window().GetOnerror() } else { @@ -205,7 +203,7 @@ impl HTMLElementMethods for HTMLElement { // https://html.spec.whatwg.org/multipage/#handler-onerror fn SetOnerror(&self, listener: Option>) { if self.is_body_or_frameset() { - let document = document_from_node(self); + let document = self.owner_document(); if document.has_browsing_context() { document.window().SetOnerror(listener) } @@ -219,7 +217,7 @@ impl HTMLElementMethods for HTMLElement { // https://html.spec.whatwg.org/multipage/#handler-onload fn GetOnload(&self, can_gc: CanGc) -> Option> { if self.is_body_or_frameset() { - let document = document_from_node(self); + let document = self.owner_document(); if document.has_browsing_context() { document.window().GetOnload() } else { @@ -234,7 +232,7 @@ impl HTMLElementMethods for HTMLElement { // https://html.spec.whatwg.org/multipage/#handler-onload fn SetOnload(&self, listener: Option>) { if self.is_body_or_frameset() { - let document = document_from_node(self); + let document = self.owner_document(); if document.has_browsing_context() { document.window().SetOnload(listener) } @@ -247,7 +245,7 @@ impl HTMLElementMethods for HTMLElement { // https://html.spec.whatwg.org/multipage/#handler-onblur fn GetOnblur(&self, can_gc: CanGc) -> Option> { if self.is_body_or_frameset() { - let document = document_from_node(self); + let document = self.owner_document(); if document.has_browsing_context() { document.window().GetOnblur() } else { @@ -262,7 +260,7 @@ impl HTMLElementMethods for HTMLElement { // https://html.spec.whatwg.org/multipage/#handler-onblur fn SetOnblur(&self, listener: Option>) { if self.is_body_or_frameset() { - let document = document_from_node(self); + let document = self.owner_document(); if document.has_browsing_context() { document.window().SetOnblur(listener) } @@ -275,7 +273,7 @@ impl HTMLElementMethods for HTMLElement { // https://html.spec.whatwg.org/multipage/#handler-onfocus fn GetOnfocus(&self, can_gc: CanGc) -> Option> { if self.is_body_or_frameset() { - let document = document_from_node(self); + let document = self.owner_document(); if document.has_browsing_context() { document.window().GetOnfocus() } else { @@ -290,7 +288,7 @@ impl HTMLElementMethods for HTMLElement { // https://html.spec.whatwg.org/multipage/#handler-onfocus fn SetOnfocus(&self, listener: Option>) { if self.is_body_or_frameset() { - let document = document_from_node(self); + let document = self.owner_document(); if document.has_browsing_context() { document.window().SetOnfocus(listener) } @@ -303,7 +301,7 @@ impl HTMLElementMethods for HTMLElement { // https://html.spec.whatwg.org/multipage/#handler-onresize fn GetOnresize(&self, can_gc: CanGc) -> Option> { if self.is_body_or_frameset() { - let document = document_from_node(self); + let document = self.owner_document(); if document.has_browsing_context() { document.window().GetOnresize() } else { @@ -318,7 +316,7 @@ impl HTMLElementMethods for HTMLElement { // https://html.spec.whatwg.org/multipage/#handler-onresize fn SetOnresize(&self, listener: Option>) { if self.is_body_or_frameset() { - let document = document_from_node(self); + let document = self.owner_document(); if document.has_browsing_context() { document.window().SetOnresize(listener) } @@ -331,7 +329,7 @@ impl HTMLElementMethods for HTMLElement { // https://html.spec.whatwg.org/multipage/#handler-onscroll fn GetOnscroll(&self, can_gc: CanGc) -> Option> { if self.is_body_or_frameset() { - let document = document_from_node(self); + let document = self.owner_document(); if document.has_browsing_context() { document.window().GetOnscroll() } else { @@ -346,7 +344,7 @@ impl HTMLElementMethods for HTMLElement { // https://html.spec.whatwg.org/multipage/#handler-onscroll fn SetOnscroll(&self, listener: Option>) { if self.is_body_or_frameset() { - let document = document_from_node(self); + let document = self.owner_document(); if document.has_browsing_context() { document.window().SetOnscroll(listener) } @@ -412,7 +410,7 @@ impl HTMLElementMethods for HTMLElement { fn Focus(&self, can_gc: CanGc) { // TODO: Mark the element as locked for focus and run the focusing steps. // https://html.spec.whatwg.org/multipage/#focusing-steps - let document = document_from_node(self); + let document = self.owner_document(); document.request_focus(Some(self.upcast()), FocusType::Element, can_gc); } @@ -423,7 +421,7 @@ impl HTMLElementMethods for HTMLElement { return; } // https://html.spec.whatwg.org/multipage/#unfocusing-steps - let document = document_from_node(self); + let document = self.owner_document(); document.request_focus(None, FocusType::Element, can_gc); } @@ -434,7 +432,7 @@ impl HTMLElementMethods for HTMLElement { } let node = self.upcast::(); - let window = window_from_node(self); + let window = self.owner_window(); let (element, _) = window.offset_parent_query(node, can_gc); element @@ -447,7 +445,7 @@ impl HTMLElementMethods for HTMLElement { } let node = self.upcast::(); - let window = window_from_node(self); + let window = self.owner_window(); let (_, rect) = window.offset_parent_query(node, can_gc); rect.origin.y.to_nearest_px() @@ -460,7 +458,7 @@ impl HTMLElementMethods for HTMLElement { } let node = self.upcast::(); - let window = window_from_node(self); + let window = self.owner_window(); let (_, rect) = window.offset_parent_query(node, can_gc); rect.origin.x.to_nearest_px() @@ -469,7 +467,7 @@ impl HTMLElementMethods for HTMLElement { // https://drafts.csswg.org/cssom-view/#dom-htmlelement-offsetwidth fn OffsetWidth(&self, can_gc: CanGc) -> i32 { let node = self.upcast::(); - let window = window_from_node(self); + let window = self.owner_window(); let (_, rect) = window.offset_parent_query(node, can_gc); rect.size.width.to_nearest_px() @@ -478,7 +476,7 @@ impl HTMLElementMethods for HTMLElement { // https://drafts.csswg.org/cssom-view/#dom-htmlelement-offsetheight fn OffsetHeight(&self, can_gc: CanGc) -> i32 { let node = self.upcast::(); - let window = window_from_node(self); + let window = self.owner_window(); let (_, rect) = window.offset_parent_query(node, can_gc); rect.size.height.to_nearest_px() @@ -512,7 +510,7 @@ impl HTMLElementMethods for HTMLElement { }; let node = self.upcast::(); - let document = document_from_node(self); + let document = self.owner_document(); // Step 2: Let next be this's next sibling. let next = node.GetNextSibling(); @@ -600,7 +598,7 @@ impl HTMLElementMethods for HTMLElement { // Note: the element can pass this check without yet being a custom // element, as long as there is a registered definition // that could upgrade it to one later. - let registry = document_from_node(self).window().CustomElements(); + let registry = self.owner_document().window().CustomElements(); let definition = registry.lookup_definition(self.as_element().local_name(), None); // Step 3: If definition is null, then throw an "NotSupportedError" DOMException @@ -943,7 +941,7 @@ impl HTMLElement { /// fn rendered_text_fragment(&self, input: DOMString, can_gc: CanGc) -> DomRoot { // Step 1: Let fragment be a new DocumentFragment whose node document is document. - let document = document_from_node(self); + let document = self.owner_document(); let fragment = DocumentFragment::new(&document, can_gc); // Step 2: Let position be a position variable for input, initially pointing at the start @@ -1036,7 +1034,7 @@ impl VirtualMethods for HTMLElement { let evtarget = self.upcast::(); let source_line = 1; //TODO(#9604) get current JS execution line evtarget.set_event_handler_uncompiled( - window_from_node(self).get_url(), + self.owner_window().get_url(), source_line, &name[2..], // FIXME(ajeffrey): Convert directly from AttrValue to DOMString diff --git a/components/script/dom/htmlfieldsetelement.rs b/components/script/dom/htmlfieldsetelement.rs index ee91fa4c6ba..fe5df5b3cdd 100644 --- a/components/script/dom/htmlfieldsetelement.rs +++ b/components/script/dom/htmlfieldsetelement.rs @@ -21,7 +21,7 @@ use crate::dom::htmlcollection::HTMLCollection; use crate::dom::htmlelement::HTMLElement; use crate::dom::htmlformelement::{FormControl, HTMLFormElement}; use crate::dom::htmllegendelement::HTMLLegendElement; -use crate::dom::node::{window_from_node, Node, ShadowIncluding}; +use crate::dom::node::{Node, NodeTraits, ShadowIncluding}; use crate::dom::validation::Validatable; use crate::dom::validitystate::ValidityState; use crate::dom::virtualmethods::VirtualMethods; @@ -88,7 +88,7 @@ impl HTMLFieldSetElement { impl HTMLFieldSetElementMethods for HTMLFieldSetElement { // https://html.spec.whatwg.org/multipage/#dom-fieldset-elements fn Elements(&self) -> DomRoot { - HTMLCollection::new_with_filter_fn(&window_from_node(self), self.upcast(), |element, _| { + HTMLCollection::new_with_filter_fn(&self.owner_window(), self.upcast(), |element, _| { element .downcast::() .is_some_and(HTMLElement::is_listed_element) @@ -271,7 +271,7 @@ impl Validatable for HTMLFieldSetElement { fn validity_state(&self) -> DomRoot { self.validity_state - .or_init(|| ValidityState::new(&window_from_node(self), self.upcast())) + .or_init(|| ValidityState::new(&self.owner_window(), self.upcast())) } fn is_instance_validatable(&self) -> bool { diff --git a/components/script/dom/htmlformelement.rs b/components/script/dom/htmlformelement.rs index e3271211190..70e578dace9 100644 --- a/components/script/dom/htmlformelement.rs +++ b/components/script/dom/htmlformelement.rs @@ -73,8 +73,7 @@ use crate::dom::htmloutputelement::HTMLOutputElement; use crate::dom::htmlselectelement::HTMLSelectElement; use crate::dom::htmltextareaelement::HTMLTextAreaElement; use crate::dom::node::{ - document_from_node, window_from_node, BindContext, Node, NodeFlags, UnbindContext, - VecPreOrderInsertionHelper, + BindContext, Node, NodeFlags, NodeTraits, UnbindContext, VecPreOrderInsertionHelper, }; use crate::dom::nodelist::{NodeList, RadioListMode}; use crate::dom::radionodelist::RadioNodeList; @@ -421,7 +420,7 @@ impl HTMLFormElementMethods for HTMLFormElement { let filter = Box::new(ElementsFilter { form: DomRoot::from_ref(self), }); - let window = window_from_node(self); + let window = self.owner_window(); HTMLFormControlsCollection::new(&window, self, filter) })) } @@ -439,7 +438,7 @@ impl HTMLFormElementMethods for HTMLFormElement { // https://html.spec.whatwg.org/multipage/#the-form-element%3Adetermine-the-value-of-a-named-property fn NamedGetter(&self, name: DOMString) -> Option { - let window = window_from_node(self); + let window = self.owner_window(); let name = Atom::from(name); @@ -687,7 +686,7 @@ impl HTMLFormElement { } // Step 1, 3 - document_from_node(self).encoding() + self.owner_document().encoding() } // https://html.spec.whatwg.org/multipage/#text/plain-encoding-algorithm @@ -735,7 +734,7 @@ impl HTMLFormElement { return; } // Step 3 - let doc = document_from_node(self); + let doc = self.owner_document(); let base = doc.base_url(); // TODO: Handle browsing contexts (Step 4, 5) // Step 6 @@ -1220,7 +1219,7 @@ impl HTMLFormElement { // Step 3-6 let ret = self.get_unclean_dataset(submitter, encoding); - let window = window_from_node(self); + let window = self.owner_window(); // Step 6 let form_data = FormData::new(Some(ret), &window.global(), can_gc); @@ -1543,7 +1542,7 @@ pub trait FormControl: DomObject { let new_owner = if self.is_listed() && has_form_id && elem.is_connected() { // Step 3 - let doc = document_from_node(node); + let doc = node.owner_document(); let form_id = elem.get_string_attribute(&local_name!("form")); doc.GetElementById(form_id) .and_then(DomRoot::downcast::) @@ -1596,8 +1595,8 @@ pub trait FormControl: DomObject { let node = elem.upcast::(); if self.is_listed() && !form_id.is_empty() && node.is_connected() { - let doc = document_from_node(node); - doc.register_form_id_listener(form_id, self); + node.owner_document() + .register_form_id_listener(form_id, self); } } @@ -1606,8 +1605,8 @@ pub trait FormControl: DomObject { let form_id = elem.get_string_attribute(&local_name!("form")); if self.is_listed() && !form_id.is_empty() { - let doc = document_from_node(elem.upcast::()); - doc.unregister_form_id_listener(form_id, self); + elem.owner_document() + .unregister_form_id_listener(form_id, self); } } diff --git a/components/script/dom/htmlframesetelement.rs b/components/script/dom/htmlframesetelement.rs index c7d401411f7..eeefee178d3 100644 --- a/components/script/dom/htmlframesetelement.rs +++ b/components/script/dom/htmlframesetelement.rs @@ -12,7 +12,7 @@ use crate::dom::bindings::inheritance::Castable; use crate::dom::bindings::root::DomRoot; use crate::dom::document::Document; use crate::dom::htmlelement::HTMLElement; -use crate::dom::node::{document_from_node, Node}; +use crate::dom::node::{Node, NodeTraits}; use crate::script_runtime::CanGc; #[dom_struct] diff --git a/components/script/dom/htmlheadelement.rs b/components/script/dom/htmlheadelement.rs index 3b0f40d2f22..54a2b49b59b 100644 --- a/components/script/dom/htmlheadelement.rs +++ b/components/script/dom/htmlheadelement.rs @@ -14,7 +14,7 @@ use crate::dom::document::{determine_policy_for_token, Document}; use crate::dom::element::Element; use crate::dom::htmlelement::HTMLElement; use crate::dom::htmlmetaelement::HTMLMetaElement; -use crate::dom::node::{document_from_node, BindContext, Node, ShadowIncluding}; +use crate::dom::node::{BindContext, Node, NodeTraits, ShadowIncluding}; use crate::dom::userscripts::load_script; use crate::dom::virtualmethods::VirtualMethods; use crate::script_runtime::CanGc; @@ -56,7 +56,7 @@ impl HTMLHeadElement { /// pub fn set_document_referrer(&self) { - let doc = document_from_node(self); + let doc = self.owner_document(); if doc.GetHead().as_deref() != Some(self) { return; @@ -87,7 +87,7 @@ impl HTMLHeadElement { /// pub fn set_content_security_policy(&self) { - let doc = document_from_node(self); + let doc = self.owner_document(); if doc.GetHead().as_deref() != Some(self) { return; diff --git a/components/script/dom/htmliframeelement.rs b/components/script/dom/htmliframeelement.rs index c0b43296f22..5de8470b568 100644 --- a/components/script/dom/htmliframeelement.rs +++ b/components/script/dom/htmliframeelement.rs @@ -37,7 +37,7 @@ use crate::dom::element::{ use crate::dom::eventtarget::EventTarget; use crate::dom::globalscope::GlobalScope; use crate::dom::htmlelement::HTMLElement; -use crate::dom::node::{document_from_node, window_from_node, Node, NodeDamage, UnbindContext}; +use crate::dom::node::{Node, NodeDamage, NodeTraits, UnbindContext}; use crate::dom::virtualmethods::VirtualMethods; use crate::dom::windowproxy::WindowProxy; use crate::script_runtime::CanGc; @@ -105,7 +105,7 @@ impl HTMLIFrameElement { if url.is_empty() { None } else { - document_from_node(self).base_url().join(&url).ok() + self.owner_document().base_url().join(&url).ok() } }) .unwrap_or_else(|| ServoUrl::parse("about:blank").unwrap()) @@ -148,7 +148,7 @@ impl HTMLIFrameElement { Some(id) => id, }; - let document = document_from_node(self); + let document = self.owner_document(); { let load_blocker = &self.load_blocker; @@ -180,7 +180,7 @@ impl HTMLIFrameElement { }, }; - let window = window_from_node(self); + let window = self.owner_window(); let old_pipeline_id = self.pipeline_id(); let new_pipeline_id = PipelineId::new(); self.pending_pipeline_id.set(Some(new_pipeline_id)); @@ -256,8 +256,8 @@ impl HTMLIFrameElement { .has_attribute(&local_name!("srcdoc")) { let url = ServoUrl::parse("about:srcdoc").unwrap(); - let document = document_from_node(self); - let window = window_from_node(self); + let document = self.owner_document(); + let window = self.owner_window(); let pipeline_id = Some(window.upcast::().pipeline_id()); let mut load_data = LoadData::new( LoadOrigin::Script(document.origin().immutable().clone()), @@ -277,7 +277,7 @@ impl HTMLIFrameElement { return; } - let window = window_from_node(self); + let window = self.owner_window(); // https://html.spec.whatwg.org/multipage/#attr-iframe-name // Note: the spec says to set the name 'when the nested browsing context is created'. @@ -307,7 +307,7 @@ impl HTMLIFrameElement { // Step 2.4: Let referrerPolicy be the current state of element's referrerpolicy content // attribute. - let document = document_from_node(self); + let document = self.owner_document(); let referrer_policy_token = self.ReferrerPolicy(); // Note: despite not being explicitly stated in the spec steps, this falls back to @@ -390,8 +390,8 @@ impl HTMLIFrameElement { // compatible #4965](https://github.com/whatwg/html/issues/4965) // let url = ServoUrl::parse("about:blank").unwrap(); - let document = document_from_node(self); - let window = window_from_node(self); + let document = self.owner_document(); + let window = self.owner_window(); let pipeline_id = Some(window.upcast::().pipeline_id()); let load_data = LoadData::new( LoadOrigin::Script(document.origin().immutable().clone()), @@ -763,7 +763,7 @@ impl VirtualMethods for HTMLIFrameElement { LoadBlocker::terminate(blocker, CanGc::note()); // https://html.spec.whatwg.org/multipage/#a-browsing-context-is-discarded - let window = window_from_node(self); + let window = self.owner_window(); let (sender, receiver) = ProfiledIpc::channel(self.global().time_profiler_chan().clone()).unwrap(); diff --git a/components/script/dom/htmlimageelement.rs b/components/script/dom/htmlimageelement.rs index a95f49ef2ef..5cd9797a28e 100644 --- a/components/script/dom/htmlimageelement.rs +++ b/components/script/dom/htmlimageelement.rs @@ -82,10 +82,7 @@ use crate::dom::htmlmapelement::HTMLMapElement; use crate::dom::htmlpictureelement::HTMLPictureElement; use crate::dom::htmlsourceelement::HTMLSourceElement; use crate::dom::mouseevent::MouseEvent; -use crate::dom::node::{ - document_from_node, window_from_node, BindContext, Node, NodeDamage, ShadowIncluding, - UnbindContext, -}; +use crate::dom::node::{BindContext, Node, NodeDamage, NodeTraits, ShadowIncluding, UnbindContext}; use crate::dom::performanceresourcetiming::InitiatorType; use crate::dom::promise::Promise; use crate::dom::values::UNSIGNED_LONG_MAX; @@ -357,7 +354,7 @@ pub(crate) fn image_fetch_request( impl HTMLImageElement { /// Update the current image with a valid URL. fn fetch_image(&self, img_url: &ServoUrl, can_gc: CanGc) { - let window = window_from_node(self); + let window = self.owner_window(); let image_cache = window.image_cache(); let sender = generate_cache_listener_for_element(self); let cache_result = image_cache.track_image( @@ -393,8 +390,8 @@ impl HTMLImageElement { } fn fetch_request(&self, img_url: &ServoUrl, id: PendingImageId) { - let document = document_from_node(self); - let window = window_from_node(self); + let document = self.owner_document(); + let window = self.owner_window(); let context = ImageContext { image_cache: window.image_cache(), @@ -691,7 +688,7 @@ impl HTMLImageElement { source_size_list: &mut SourceSizeList, _width: Option, ) -> Au { - let document = document_from_node(self); + let document = self.owner_document(); let quirks_mode = document.quirks_mode(); let result = source_size_list.evaluate(document.window().layout().device(), quirks_mode); result @@ -699,7 +696,7 @@ impl HTMLImageElement { /// fn matches_environment(&self, media_query: String) -> bool { - let document = document_from_node(self); + let document = self.owner_document(); let quirks_mode = document.quirks_mode(); let document_url_data = UrlExtraData(document.url().get_arc()); // FIXME(emilio): This should do the same that we do for other media @@ -792,7 +789,8 @@ impl HTMLImageElement { // Step 5 let mut best_candidate = max; - let device_pixel_ratio = document_from_node(self) + let device_pixel_ratio = self + .owner_document() .window() .window_size() .device_pixel_ratio @@ -821,7 +819,7 @@ impl HTMLImageElement { request.source_url = Some(src.clone()); request.image = None; request.metadata = None; - let document = document_from_node(self); + let document = self.owner_document(); LoadBlocker::terminate(&request.blocker, can_gc); *request.blocker.borrow_mut() = Some(LoadBlocker::new(&document, LoadType::Image(url.clone()))); @@ -882,7 +880,7 @@ impl HTMLImageElement { /// Step 8-12 of html.spec.whatwg.org/multipage/#update-the-image-data fn update_the_image_data_sync_steps(&self, can_gc: CanGc) { - let document = document_from_node(self); + let document = self.owner_document(); let window = document.window(); let task_source = window.task_manager().dom_manipulation_task_source(); let this = Trusted::new(self); @@ -949,7 +947,7 @@ impl HTMLImageElement { /// pub fn update_the_image_data(&self, can_gc: CanGc) { - let document = document_from_node(self); + let document = self.owner_document(); let window = document.window(); let elem = self.upcast::(); let src = elem.get_url_attribute(&local_name!("src")); @@ -1072,7 +1070,7 @@ impl HTMLImageElement { let trusted_node = Trusted::new(elem); let (responder_sender, responder_receiver) = ipc::channel().unwrap(); - let window = window_from_node(elem); + let window = elem.owner_window(); let (task_source, canceller) = window .task_manager() .networking_task_source_with_canceller(); @@ -1106,7 +1104,7 @@ impl HTMLImageElement { } let elem = self.upcast::(); - let document = document_from_node(elem); + let document = elem.owner_document(); let has_pending_request = matches!(self.image_request.get(), ImageRequestPhase::Pending); // Step 2 @@ -1152,7 +1150,7 @@ impl HTMLImageElement { can_gc, ); - let window = window_from_node(self); + let window = self.owner_window(); let image_cache = window.image_cache(); // Step 14 @@ -1203,7 +1201,7 @@ impl HTMLImageElement { // Step 2 for fn react_to_decode_image_sync_steps(&self, promise: Rc) { - let document = document_from_node(self); + let document = self.owner_document(); // Step 2.1 of if !document.is_fully_active() || matches!(self.current_request.borrow().state, State::Broken) @@ -1233,7 +1231,7 @@ impl HTMLImageElement { } fn reject_image_decode_promises(&self) { - let document = document_from_node(self); + let document = self.owner_document(); for promise in self.image_decode_promises.borrow().iter() { promise.reject_native(&DOMException::new( &document.global(), @@ -1251,7 +1249,7 @@ impl HTMLImageElement { selected_pixel_density: f64, ) { let this = Trusted::new(self); - let window = window_from_node(self); + let window = self.owner_window(); let src = src.0; let _ = window.task_manager().dom_manipulation_task_source().queue( task!(image_load_event: move || { @@ -1369,7 +1367,8 @@ impl HTMLImageElement { return None; } - let useMapElements = document_from_node(self) + let useMapElements = self + .owner_document() .upcast::() .traverse_preorder(ShadowIncluding::No) .filter_map(DomRoot::downcast::) @@ -1847,7 +1846,7 @@ impl VirtualMethods for HTMLImageElement { if let Some(s) = self.super_type() { s.bind_to_tree(context); } - let document = document_from_node(self); + let document = self.owner_document(); if context.tree_connected { document.register_responsive_image(self); } @@ -1863,7 +1862,7 @@ impl VirtualMethods for HTMLImageElement { fn unbind_from_tree(&self, context: &UnbindContext) { self.super_type().unwrap().unbind_from_tree(context); - let document = document_from_node(self); + let document = self.owner_document(); document.unregister_responsive_image(self); // The element is removed from a picture parent element diff --git a/components/script/dom/htmlinputelement.rs b/components/script/dom/htmlinputelement.rs index 1a8eb3c6c06..21898720d75 100644 --- a/components/script/dom/htmlinputelement.rs +++ b/components/script/dom/htmlinputelement.rs @@ -66,8 +66,7 @@ use crate::dom::htmlformelement::{ use crate::dom::keyboardevent::KeyboardEvent; use crate::dom::mouseevent::MouseEvent; use crate::dom::node::{ - document_from_node, window_from_node, BindContext, CloneChildrenFlag, Node, NodeDamage, - ShadowIncluding, UnbindContext, + BindContext, CloneChildrenFlag, Node, NodeDamage, NodeTraits, ShadowIncluding, UnbindContext, }; use crate::dom::nodelist::NodeList; use crate::dom::textcontrol::{TextControlElement, TextControlSelection}; @@ -1271,7 +1270,7 @@ impl HTMLInputElementMethods for HTMLInputElement { }, ValueMode::Filename => { if value.is_empty() { - let window = window_from_node(self); + let window = self.owner_window(); let fl = FileList::new(&window, vec![]); self.filelist.set(Some(&fl)); } else { @@ -1842,7 +1841,7 @@ impl HTMLInputElement { // https://html.spec.whatwg.org/multipage/#file-upload-state-(type=file) // Select files by invoking UI or by passed in argument fn select_files(&self, opt_test_paths: Option>, can_gc: CanGc) { - let window = window_from_node(self); + let window = self.owner_window(); let origin = get_blob_origin(&window.get_url()); let resource_threads = window.upcast::().resource_threads(); @@ -2064,7 +2063,7 @@ impl HTMLInputElement { // https://html.spec.whatwg.org/multipage/#implicit-submission #[allow(unsafe_code)] fn implicit_submission(&self, can_gc: CanGc) { - let doc = document_from_node(self); + let doc = self.owner_document(); let node = doc.upcast::(); let owner = self.form_owner(); let form = match owner { @@ -2319,7 +2318,7 @@ impl VirtualMethods for HTMLInputElement { } if new_type == InputType::File { - let window = window_from_node(self); + let window = self.owner_window(); let filelist = FileList::new(&window, vec![]); self.filelist.set(Some(&filelist)); } @@ -2532,7 +2531,7 @@ impl VirtualMethods for HTMLInputElement { // the space key. There's no nice way to catch this so let's use this for // now. if let Some(point_in_target) = mouse_event.point_in_target() { - let window = window_from_node(self); + let window = self.owner_window(); let index = window.text_index_query( self.upcast::(), point_in_target, @@ -2577,7 +2576,7 @@ impl VirtualMethods for HTMLInputElement { self.input_type().is_textual_or_password() { if event.IsTrusted() { - let window = window_from_node(self); + let window = self.owner_window(); window .task_manager() .user_interaction_task_source() @@ -2656,7 +2655,7 @@ impl Validatable for HTMLInputElement { fn validity_state(&self) -> DomRoot { self.validity_state - .or_init(|| ValidityState::new(&window_from_node(self), self.upcast())) + .or_init(|| ValidityState::new(&self.owner_window(), self.upcast())) } fn is_instance_validatable(&self) -> bool { @@ -2833,7 +2832,7 @@ impl Activatable for HTMLInputElement { // Step 1: If the element does not have a form owner, then return. if let Some(form_owner) = self.form_owner() { // Step 2: If the element's node document is not fully active, then return. - let document = document_from_node(self); + let document = self.owner_document(); if !document.is_fully_active() { return; @@ -2852,7 +2851,7 @@ impl Activatable for HTMLInputElement { // https://html.spec.whatwg.org/multipage/#reset-button-state-(type=reset):activation-behavior // Step 1: If the element does not have a form owner, then return. if let Some(form_owner) = self.form_owner() { - let document = document_from_node(self); + let document = self.owner_document(); // Step 2: If the element's node document is not fully active, then return. if !document.is_fully_active() { diff --git a/components/script/dom/htmllinkelement.rs b/components/script/dom/htmllinkelement.rs index f34f508c71c..9f6e34dccfc 100644 --- a/components/script/dom/htmllinkelement.rs +++ b/components/script/dom/htmllinkelement.rs @@ -47,10 +47,7 @@ use crate::dom::element::{ ElementCreator, }; use crate::dom::htmlelement::HTMLElement; -use crate::dom::node::{ - document_from_node, stylesheets_owner_from_node, window_from_node, BindContext, Node, - UnbindContext, -}; +use crate::dom::node::{BindContext, Node, NodeTraits, UnbindContext}; use crate::dom::performanceresourcetiming::InitiatorType; use crate::dom::stylesheet::StyleSheet as DOMStyleSheet; use crate::dom::virtualmethods::VirtualMethods; @@ -160,7 +157,7 @@ impl HTMLLinkElement { // HTMLStyleElement::set_stylesheet. #[allow(crown::unrooted_must_root)] pub fn set_stylesheet(&self, s: Arc) { - let stylesheets_owner = stylesheets_owner_from_node(self); + let stylesheets_owner = self.stylesheet_list_owner(); if let Some(ref s) = *self.stylesheet.borrow() { stylesheets_owner.remove_stylesheet(self.upcast(), s) } @@ -177,7 +174,7 @@ impl HTMLLinkElement { self.get_stylesheet().map(|sheet| { self.cssom_stylesheet.or_init(|| { CSSStyleSheet::new( - &window_from_node(self), + &self.owner_window(), self.upcast::(), "text/css".into(), None, // todo handle location @@ -298,7 +295,8 @@ impl VirtualMethods for HTMLLinkElement { if let Some(s) = self.stylesheet.borrow_mut().take() { self.clean_stylesheet_ownership(); - stylesheets_owner_from_node(self).remove_stylesheet(self.upcast(), &s); + self.stylesheet_list_owner() + .remove_stylesheet(self.upcast(), &s); } } } @@ -391,7 +389,7 @@ impl HTMLLinkElement { /// fn handle_stylesheet_url(&self, href: &str) { - let document = document_from_node(self); + let document = self.owner_document(); if document.browsing_context().is_none() { return; } @@ -463,7 +461,7 @@ impl HTMLLinkElement { } fn handle_favicon_url(&self, href: &str, _sizes: &Option) { - let document = document_from_node(self); + let document = self.owner_document(); match document.base_url().join(href) { Ok(url) => { let window = document.window(); diff --git a/components/script/dom/htmlmediaelement.rs b/components/script/dom/htmlmediaelement.rs index a93d645ee08..d5e8ab5d1fd 100644 --- a/components/script/dom/htmlmediaelement.rs +++ b/components/script/dom/htmlmediaelement.rs @@ -88,7 +88,7 @@ use crate::dom::htmlvideoelement::HTMLVideoElement; use crate::dom::mediaerror::MediaError; use crate::dom::mediafragmentparser::MediaFragmentParser; use crate::dom::mediastream::MediaStream; -use crate::dom::node::{document_from_node, window_from_node, Node, NodeDamage, UnbindContext}; +use crate::dom::node::{Node, NodeDamage, NodeTraits, UnbindContext}; use crate::dom::performanceresourcetiming::InitiatorType; use crate::dom::promise::Promise; use crate::dom::shadowroot::IsUserAgentWidget; @@ -513,8 +513,7 @@ impl HTMLMediaElement { pub fn delay_load_event(&self, delay: bool, can_gc: CanGc) { let blocker = &self.delaying_the_load_event_flag; if delay && blocker.borrow().is_none() { - *blocker.borrow_mut() = - Some(LoadBlocker::new(&document_from_node(self), LoadType::Media)); + *blocker.borrow_mut() = Some(LoadBlocker::new(&self.owner_document(), LoadType::Media)); } else if !delay && blocker.borrow().is_some() { LoadBlocker::terminate(blocker, can_gc); } @@ -524,7 +523,7 @@ impl HTMLMediaElement { fn time_marches_on(&self) { // Step 6. if Instant::now() > self.next_timeupdate_event.get() { - let window = window_from_node(self); + let window = self.owner_window(); window .task_manager() .media_element_task_source() @@ -548,7 +547,7 @@ impl HTMLMediaElement { self.take_pending_play_promises(Err(Error::Abort)); // Step 2.3. - let window = window_from_node(self); + let window = self.owner_window(); let this = Trusted::new(self); let generation_id = self.generation_id.get(); let _ = window.task_manager().media_element_task_source().queue( @@ -595,7 +594,7 @@ impl HTMLMediaElement { self.take_pending_play_promises(Ok(())); // Step 2. - let window = window_from_node(self); + let window = self.owner_window(); let this = Trusted::new(self); let generation_id = self.generation_id.get(); // FIXME(nox): Why are errors silenced here? @@ -634,7 +633,7 @@ impl HTMLMediaElement { return; } - let window = window_from_node(self); + let window = self.owner_window(); let task_source = window.task_manager().media_element_task_source(); // Step 1. @@ -728,7 +727,7 @@ impl HTMLMediaElement { // media element's node document when the src attribute was last // changed, which is why we need to pass the base URL in the task // right here. - let doc = document_from_node(self); + let doc = self.owner_document(); let task = MediaElementMicrotask::ResourceSelection { elem: DomRoot::from_ref(self), generation_id: self.generation_id.get(), @@ -788,7 +787,7 @@ impl HTMLMediaElement { self.network_state.set(NetworkState::Loading); // Step 8. - let window = window_from_node(self); + let window = self.owner_window(); window .task_manager() .media_element_task_source() @@ -870,7 +869,7 @@ impl HTMLMediaElement { return; } - let document = document_from_node(self); + let document = self.owner_document(); let destination = match self.media_type_id() { HTMLMediaElementTypeId::HTMLAudioElement => Destination::Audio, HTMLMediaElementTypeId::HTMLVideoElement => Destination::Video, @@ -910,7 +909,8 @@ impl HTMLMediaElement { // TODO: If this is supposed to to be a "fetch" as defined in the specification // this should probably be integrated into the Document's list of cancellable fetches. - document_from_node(self).fetch_background(request, listener, Some(cancel_receiver)); + self.owner_document() + .fetch_background(request, listener, Some(cancel_receiver)); } // https://html.spec.whatwg.org/multipage/#concept-media-load-resource @@ -937,7 +937,7 @@ impl HTMLMediaElement { self.network_state.set(NetworkState::Idle); // Step 4.remote.1.2. - let window = window_from_node(self); + let window = self.owner_window(); window .task_manager() .media_element_task_source() @@ -1007,7 +1007,7 @@ impl HTMLMediaElement { /// /// [steps]: https://html.spec.whatwg.org/multipage/#dedicated-media-source-failure-steps fn queue_dedicated_media_source_failure_steps(&self) { - let window = window_from_node(self); + let window = self.owner_window(); let this = Trusted::new(self); let generation_id = self.generation_id.get(); self.take_pending_play_promises(Err(Error::NotSupported)); @@ -1022,7 +1022,7 @@ impl HTMLMediaElement { this.fulfill_in_flight_play_promises(|| { // Step 1. this.error.set(Some(&*MediaError::new( - &window_from_node(&*this), + &this.owner_window(), MEDIA_ERR_SRC_NOT_SUPPORTED, ))); @@ -1058,7 +1058,7 @@ impl HTMLMediaElement { } fn queue_ratechange_event(&self) { - let window = window_from_node(self); + let window = self.owner_window(); let task_source = window.task_manager().media_element_task_source(); task_source.queue_simple_event(self.upcast(), atom!("ratechange"), &window); } @@ -1110,7 +1110,7 @@ impl HTMLMediaElement { self.fulfill_in_flight_play_promises(|| ()); } - let window = window_from_node(self); + let window = self.owner_window(); let task_source = window.task_manager().media_element_task_source(); // Step 5. @@ -1291,7 +1291,7 @@ impl HTMLMediaElement { // servo-media with gstreamer does not support inaccurate seeking for now. // Step 10. - let window = window_from_node(self); + let window = self.owner_window(); let task_source = window.task_manager().media_element_task_source(); task_source.queue_simple_event(self.upcast(), atom!("seeking"), &window); @@ -1316,7 +1316,7 @@ impl HTMLMediaElement { self.time_marches_on(); // Step 16. - let window = window_from_node(self); + let window = self.owner_window(); let task_source = window.task_manager().media_element_task_source(); task_source.queue_simple_event(self.upcast(), atom!("timeupdate"), &window); @@ -1339,7 +1339,7 @@ impl HTMLMediaElement { self.upcast::().dirty(NodeDamage::OtherNodeDamage); if pref!(media.testing.enabled) { - let window = window_from_node(self); + let window = self.owner_window(); let task_source = window.task_manager().media_element_task_source(); task_source.queue_simple_event(self.upcast(), atom!("postershown"), &window); } @@ -1360,7 +1360,7 @@ impl HTMLMediaElement { _ => StreamType::Seekable, }; - let window = window_from_node(self); + let window = self.owner_window(); let (action_sender, action_receiver) = ipc::channel::().unwrap(); let video_renderer: Option>> = match self.media_type_id() { @@ -1513,7 +1513,7 @@ impl HTMLMediaElement { // the HTMLMediaElementMethods::Ended method // Step 3. - let window = window_from_node(self); + let window = self.owner_window(); let this = Trusted::new(self); let _ = window.task_manager().media_element_task_source().queue( @@ -1548,7 +1548,7 @@ impl HTMLMediaElement { PlaybackDirection::Backwards => { if self.playback_position.get() <= self.earliest_possible_position() { - let window = window_from_node(self); + let window = self.owner_window(); window .task_manager() @@ -1578,7 +1578,7 @@ impl HTMLMediaElement { } // 2. Set the error attribute to the result of creating a MediaError with MEDIA_ERR_DECODE. self.error.set(Some(&*MediaError::new( - &window_from_node(self), + &self.owner_window(), MEDIA_ERR_DECODE, ))); @@ -1611,7 +1611,7 @@ impl HTMLMediaElement { 0 => DOMString::from("main"), _ => DOMString::new(), }; - let window = window_from_node(self); + let window = self.owner_window(); let audio_track = AudioTrack::new( &window, DOMString::new(), @@ -1670,7 +1670,7 @@ impl HTMLMediaElement { 0 => DOMString::from("main"), _ => DOMString::new(), }; - let window = window_from_node(self); + let window = self.owner_window(); let video_track = VideoTrack::new( &window, DOMString::new(), @@ -1737,7 +1737,7 @@ impl HTMLMediaElement { self.duration.set(f64::INFINITY); } if previous_duration != self.duration.get() { - let window = window_from_node(self); + let window = self.owner_window(); let task_source = window.task_manager().media_element_task_source(); task_source.queue_simple_event(self.upcast(), atom!("durationchange"), &window); } @@ -1911,7 +1911,7 @@ impl HTMLMediaElement { let shadow_root = element .attach_shadow(IsUserAgentWidget::Yes, ShadowRootMode::Closed, false) .unwrap(); - let document = document_from_node(self); + let document = self.owner_document(); let script = HTMLScriptElement::new( local_name!("script"), None, @@ -1965,7 +1965,7 @@ impl HTMLMediaElement { fn remove_controls(&self) { if let Some(id) = self.media_controls_id.borrow_mut().take() { - document_from_node(self).unregister_media_controls(&id); + self.owner_document().unregister_media_controls(&id); } } @@ -2130,7 +2130,7 @@ impl HTMLMediaElementMethods for HTMLMediaElement { } self.muted.set(value); - let window = window_from_node(self); + let window = self.owner_window(); window .task_manager() .media_element_task_source() @@ -2229,7 +2229,7 @@ impl HTMLMediaElementMethods for HTMLMediaElement { let state = self.ready_state.get(); - let window = window_from_node(self); + let window = self.owner_window(); // FIXME(nox): Why are errors silenced here? let task_source = window.task_manager().media_element_task_source(); if self.Paused() { @@ -2418,21 +2418,21 @@ impl HTMLMediaElementMethods for HTMLMediaElement { // https://html.spec.whatwg.org/multipage/#dom-media-audiotracks fn AudioTracks(&self) -> DomRoot { - let window = window_from_node(self); + let window = self.owner_window(); self.audio_tracks_list .or_init(|| AudioTrackList::new(&window, &[], Some(self))) } // https://html.spec.whatwg.org/multipage/#dom-media-videotracks fn VideoTracks(&self) -> DomRoot { - let window = window_from_node(self); + let window = self.owner_window(); self.video_tracks_list .or_init(|| VideoTrackList::new(&window, &[], Some(self))) } // https://html.spec.whatwg.org/multipage/#dom-media-texttracks fn TextTracks(&self) -> DomRoot { - let window = window_from_node(self); + let window = self.owner_window(); self.text_tracks_list .or_init(|| TextTrackList::new(&window, &[])) } @@ -2444,7 +2444,7 @@ impl HTMLMediaElementMethods for HTMLMediaElement { label: DOMString, language: DOMString, ) -> DomRoot { - let window = window_from_node(self); + let window = self.owner_window(); // Step 1 & 2 // FIXME(#22314, dlrobertson) set the ready state to Loaded let track = TextTrack::new( @@ -2478,7 +2478,7 @@ impl HTMLMediaElementMethods for HTMLMediaElement { if *value != self.volume.get() { self.volume.set(*value); - let window = window_from_node(self); + let window = self.owner_window(); window .task_manager() .media_element_task_source() @@ -2809,7 +2809,7 @@ impl FetchResponseListener for HTMLMediaElementFetchListener { // https://html.spec.whatwg.org/multipage/#concept-media-load-resource step 4, // => "If mode is remote" step 2 if Instant::now() > self.next_progress_event { - let window = window_from_node(&*elem); + let window = elem.owner_window(); window .task_manager() .media_element_task_source() @@ -2880,7 +2880,7 @@ impl FetchResponseListener for HTMLMediaElementFetchListener { // Step 2 elem.error.set(Some(&*MediaError::new( - &window_from_node(&*elem), + &elem.owner_window(), MEDIA_ERR_NETWORK, ))); @@ -2925,7 +2925,7 @@ impl ResourceTimingListener for HTMLMediaElementFetchListener { } fn resource_timing_global(&self) -> DomRoot { - document_from_node(&*self.elem.root()).global() + self.elem.root().owner_document().global() } } diff --git a/components/script/dom/htmlmetaelement.rs b/components/script/dom/htmlmetaelement.rs index 6a8863cbf84..fa298907430 100644 --- a/components/script/dom/htmlmetaelement.rs +++ b/components/script/dom/htmlmetaelement.rs @@ -27,7 +27,7 @@ use crate::dom::globalscope::GlobalScope; use crate::dom::htmlelement::HTMLElement; use crate::dom::htmlheadelement::HTMLHeadElement; use crate::dom::location::NavigationType; -use crate::dom::node::{document_from_node, window_from_node, BindContext, Node, UnbindContext}; +use crate::dom::node::{BindContext, Node, NodeTraits, UnbindContext}; use crate::dom::virtualmethods::VirtualMethods; use crate::dom::window::Window; use crate::script_runtime::CanGc; @@ -146,7 +146,7 @@ impl HTMLMetaElement { /// fn shared_declarative_refresh_steps(&self, content: DOMString) { // 1 - let document = document_from_node(self); + let document = self.owner_document(); if document.will_declaratively_refresh() { return; } @@ -206,7 +206,7 @@ impl HTMLMetaElement { // 12-13 if document.completely_loaded() { // TODO: handle active sandboxing flag - let window = window_from_node(self); + let window = self.owner_window(); window.upcast::().schedule_callback( OneshotTimerCallback::RefreshRedirectDue(RefreshRedirectDue { window: window.clone(), diff --git a/components/script/dom/htmlobjectelement.rs b/components/script/dom/htmlobjectelement.rs index 32bf6aae815..49fbaaec053 100644 --- a/components/script/dom/htmlobjectelement.rs +++ b/components/script/dom/htmlobjectelement.rs @@ -20,7 +20,7 @@ use crate::dom::document::Document; use crate::dom::element::{AttributeMutation, Element}; use crate::dom::htmlelement::HTMLElement; use crate::dom::htmlformelement::{FormControl, HTMLFormElement}; -use crate::dom::node::{window_from_node, Node}; +use crate::dom::node::{Node, NodeTraits}; use crate::dom::validation::Validatable; use crate::dom::validitystate::ValidityState; use crate::dom::virtualmethods::VirtualMethods; @@ -139,7 +139,7 @@ impl Validatable for HTMLObjectElement { fn validity_state(&self) -> DomRoot { self.validity_state - .or_init(|| ValidityState::new(&window_from_node(self), self.upcast())) + .or_init(|| ValidityState::new(&self.owner_window(), self.upcast())) } fn is_instance_validatable(&self) -> bool { diff --git a/components/script/dom/htmloptionscollection.rs b/components/script/dom/htmloptionscollection.rs index d025f827e70..0820b2999b0 100644 --- a/components/script/dom/htmloptionscollection.rs +++ b/components/script/dom/htmloptionscollection.rs @@ -24,7 +24,7 @@ use crate::dom::element::Element; use crate::dom::htmlcollection::{CollectionFilter, HTMLCollection}; use crate::dom::htmloptionelement::HTMLOptionElement; use crate::dom::htmlselectelement::HTMLSelectElement; -use crate::dom::node::{document_from_node, Node}; +use crate::dom::node::{Node, NodeTraits}; use crate::dom::window::Window; use crate::script_runtime::CanGc; @@ -57,7 +57,7 @@ impl HTMLOptionsCollection { fn add_new_elements(&self, count: u32, can_gc: CanGc) -> ErrorResult { let root = self.upcast().root_node(); - let document = document_from_node(&*root); + let document = root.owner_document(); for _ in 0..count { let element = diff --git a/components/script/dom/htmloutputelement.rs b/components/script/dom/htmloutputelement.rs index a3e4def8cc9..b2415260b62 100644 --- a/components/script/dom/htmloutputelement.rs +++ b/components/script/dom/htmloutputelement.rs @@ -16,7 +16,7 @@ use crate::dom::document::Document; use crate::dom::element::{AttributeMutation, Element}; use crate::dom::htmlelement::HTMLElement; use crate::dom::htmlformelement::{FormControl, HTMLFormElement}; -use crate::dom::node::{window_from_node, Node}; +use crate::dom::node::{Node, NodeTraits}; use crate::dom::nodelist::NodeList; use crate::dom::validation::Validatable; use crate::dom::validitystate::ValidityState; @@ -188,7 +188,7 @@ impl Validatable for HTMLOutputElement { fn validity_state(&self) -> DomRoot { self.validity_state - .or_init(|| ValidityState::new(&window_from_node(self), self.upcast())) + .or_init(|| ValidityState::new(&self.owner_window(), self.upcast())) } fn is_instance_validatable(&self) -> bool { diff --git a/components/script/dom/htmlscriptelement.rs b/components/script/dom/htmlscriptelement.rs index 3c34ff70d0d..1095d847354 100644 --- a/components/script/dom/htmlscriptelement.rs +++ b/components/script/dom/htmlscriptelement.rs @@ -54,9 +54,7 @@ use crate::dom::element::{ use crate::dom::event::{Event, EventBubbles, EventCancelable, EventStatus}; use crate::dom::globalscope::GlobalScope; use crate::dom::htmlelement::HTMLElement; -use crate::dom::node::{ - document_from_node, window_from_node, ChildrenMutation, CloneChildrenFlag, Node, -}; +use crate::dom::node::{ChildrenMutation, CloneChildrenFlag, Node, NodeTraits}; use crate::dom::performanceresourcetiming::InitiatorType; use crate::dom::virtualmethods::VirtualMethods; use crate::fetch::create_a_potential_cors_request; @@ -343,7 +341,7 @@ fn finish_fetching_a_classic_script( // Step 11, Asynchronously complete this algorithm with script, // which refers to step 26.6 "When the chosen algorithm asynchronously completes", // of https://html.spec.whatwg.org/multipage/#prepare-a-script - let document = document_from_node(elem); + let document = elem.owner_document(); match script_kind { ExternalScriptKind::Asap => document.asap_script_loaded(elem, load), @@ -537,7 +535,7 @@ impl ResourceTimingListener for ClassicContext { } fn resource_timing_global(&self) -> DomRoot { - document_from_node(&*self.elem.root()).global() + self.elem.root().owner_document().global() } } @@ -578,7 +576,7 @@ fn fetch_a_classic_script( character_encoding: &'static Encoding, ) { // Step 1, 2. - let doc = document_from_node(script); + let doc = script.owner_document(); let request = script_fetch_request( url.clone(), cors_setting, @@ -652,7 +650,7 @@ impl HTMLScriptElement { self.already_started.set(true); // Step 12. - let doc = document_from_node(self); + let doc = self.owner_document(); if self.parser_inserted.get() && *self.parser_document != *doc { return; } @@ -916,7 +914,7 @@ impl HTMLScriptElement { /// pub fn execute(&self, result: ScriptResult) { // Step 1. - let doc = document_from_node(self); + let doc = self.owner_document(); if self.parser_inserted.get() && *doc != *self.parser_document { return; } @@ -940,7 +938,7 @@ impl HTMLScriptElement { // Step 3. let neutralized_doc = if script.external || script.type_ == ScriptType::Module { debug!("loading external script, url = {}", script.url); - let doc = document_from_node(self); + let doc = self.owner_document(); doc.incr_ignore_destructive_writes_counter(); Some(doc) } else { @@ -948,7 +946,7 @@ impl HTMLScriptElement { }; // Step 4. - let document = document_from_node(self); + let document = self.owner_document(); let old_script = document.GetCurrentScript(); match script.type_ { @@ -982,13 +980,13 @@ impl HTMLScriptElement { pub fn run_a_classic_script(&self, script: &ScriptOrigin, can_gc: CanGc) { // TODO use a settings object rather than this element's document/window // Step 2 - let document = document_from_node(self); + let document = self.owner_document(); if !document.is_fully_active() || !document.is_scripting_enabled() { return; } // Steps 4-10 - let window = window_from_node(self); + let window = self.owner_window(); let line_number = if script.external { 1 } else { @@ -1012,13 +1010,13 @@ impl HTMLScriptElement { pub fn run_a_module_script(&self, script: &ScriptOrigin, _rethrow_errors: bool, can_gc: CanGc) { // TODO use a settings object rather than this element's document/window // Step 2 - let document = document_from_node(self); + let document = self.owner_document(); if !document.is_fully_active() || !document.is_scripting_enabled() { return; } // Step 4 - let window = window_from_node(self); + let window = self.owner_window(); let global = window.upcast::(); let _aes = AutoEntryScript::new(global); @@ -1063,7 +1061,7 @@ impl HTMLScriptElement { } pub fn queue_error_event(&self) { - let window = window_from_node(self); + let window = self.owner_window(); window .task_manager() .dom_manipulation_task_source() @@ -1165,7 +1163,7 @@ impl HTMLScriptElement { cancelable: EventCancelable, can_gc: CanGc, ) -> EventStatus { - let window = window_from_node(self); + let window = self.owner_window(); let event = Event::new(window.upcast(), type_, bubbles, cancelable, can_gc); event.fire(self.upcast(), can_gc) } @@ -1198,10 +1196,11 @@ impl VirtualMethods for HTMLScriptElement { // This method can be invoked while there are script/layout blockers present // as DOM mutations have not yet settled. We use a delayed task to avoid // running any scripts until the DOM tree is safe for interactions. - document_from_node(self).add_delayed_task(task!(ScriptPrepare: move || { - let this = script.root(); - this.prepare(CanGc::note()); - })); + self.owner_document() + .add_delayed_task(task!(ScriptPrepare: move || { + let this = script.root(); + this.prepare(CanGc::note()); + })); } } diff --git a/components/script/dom/htmlselectelement.rs b/components/script/dom/htmlselectelement.rs index ad0784b7b45..d21e84c2087 100644 --- a/components/script/dom/htmlselectelement.rs +++ b/components/script/dom/htmlselectelement.rs @@ -34,7 +34,7 @@ use crate::dom::htmlformelement::{FormControl, FormDatum, FormDatumValue, HTMLFo use crate::dom::htmloptgroupelement::HTMLOptGroupElement; use crate::dom::htmloptionelement::HTMLOptionElement; use crate::dom::htmloptionscollection::HTMLOptionsCollection; -use crate::dom::node::{window_from_node, BindContext, Node, UnbindContext}; +use crate::dom::node::{BindContext, Node, NodeTraits, UnbindContext}; use crate::dom::nodelist::NodeList; use crate::dom::validation::{is_barred_by_datalist_ancestor, Validatable}; use crate::dom::validitystate::{ValidationFlags, ValidityState}; @@ -279,7 +279,7 @@ impl HTMLSelectElementMethods for HTMLSelectElement { // https://html.spec.whatwg.org/multipage/#dom-select-options fn Options(&self) -> DomRoot { self.options.or_init(|| { - let window = window_from_node(self); + let window = self.owner_window(); HTMLOptionsCollection::new(&window, self, Box::new(OptionsFilter)) }) } @@ -510,7 +510,7 @@ impl Validatable for HTMLSelectElement { fn validity_state(&self) -> DomRoot { self.validity_state - .or_init(|| ValidityState::new(&window_from_node(self), self.upcast())) + .or_init(|| ValidityState::new(&self.owner_window(), self.upcast())) } fn is_instance_validatable(&self) -> bool { diff --git a/components/script/dom/htmlstyleelement.rs b/components/script/dom/htmlstyleelement.rs index 3c228f45586..1d3111e38ec 100644 --- a/components/script/dom/htmlstyleelement.rs +++ b/components/script/dom/htmlstyleelement.rs @@ -24,10 +24,7 @@ use crate::dom::cssstylesheet::CSSStyleSheet; use crate::dom::document::Document; use crate::dom::element::{Element, ElementCreator}; use crate::dom::htmlelement::HTMLElement; -use crate::dom::node::{ - document_from_node, stylesheets_owner_from_node, window_from_node, BindContext, - ChildrenMutation, Node, UnbindContext, -}; +use crate::dom::node::{BindContext, ChildrenMutation, Node, NodeTraits, UnbindContext}; use crate::dom::stylesheet::StyleSheet as DOMStyleSheet; use crate::dom::virtualmethods::VirtualMethods; use crate::script_runtime::CanGc; @@ -91,8 +88,8 @@ impl HTMLStyleElement { let element = self.upcast::(); assert!(node.is_connected()); - let window = window_from_node(node); - let doc = document_from_node(self); + let window = node.owner_window(); + let doc = self.owner_document(); let mq_attribute = element.get_attribute(&ns!(), &local_name!("media")); let mq_str = match mq_attribute { @@ -136,7 +133,7 @@ impl HTMLStyleElement { // No subresource loads were triggered, queue load event if self.pending_loads.get() == 0 { - let window = window_from_node(self); + let window = self.owner_window(); window .task_manager() .dom_manipulation_task_source() @@ -149,7 +146,7 @@ impl HTMLStyleElement { // FIXME(emilio): This is duplicated with HTMLLinkElement::set_stylesheet. #[allow(crown::unrooted_must_root)] pub fn set_stylesheet(&self, s: Arc) { - let stylesheets_owner = stylesheets_owner_from_node(self); + let stylesheets_owner = self.stylesheet_list_owner(); if let Some(ref s) = *self.stylesheet.borrow() { stylesheets_owner.remove_stylesheet(self.upcast(), s) } @@ -166,7 +163,7 @@ impl HTMLStyleElement { self.get_stylesheet().map(|sheet| { self.cssom_stylesheet.or_init(|| { CSSStyleSheet::new( - &window_from_node(self), + &self.owner_window(), self.upcast::(), "text/css".into(), None, // todo handle location @@ -235,7 +232,8 @@ impl VirtualMethods for HTMLStyleElement { if context.tree_connected { if let Some(s) = self.stylesheet.borrow_mut().take() { self.clean_stylesheet_ownership(); - stylesheets_owner_from_node(self).remove_stylesheet(self.upcast(), &s) + self.stylesheet_list_owner() + .remove_stylesheet(self.upcast(), &s) } } } diff --git a/components/script/dom/htmltableelement.rs b/components/script/dom/htmltableelement.rs index 6699bc5975a..ca97199908a 100644 --- a/components/script/dom/htmltableelement.rs +++ b/components/script/dom/htmltableelement.rs @@ -26,7 +26,7 @@ use crate::dom::htmltablecaptionelement::HTMLTableCaptionElement; use crate::dom::htmltablecolelement::HTMLTableColElement; use crate::dom::htmltablerowelement::HTMLTableRowElement; use crate::dom::htmltablesectionelement::HTMLTableSectionElement; -use crate::dom::node::{document_from_node, window_from_node, Node}; +use crate::dom::node::{Node, NodeTraits}; use crate::dom::virtualmethods::VirtualMethods; use crate::script_runtime::CanGc; @@ -149,13 +149,8 @@ impl HTMLTableElement { return section; } - let section = HTMLTableSectionElement::new( - atom.clone(), - None, - &document_from_node(self), - None, - can_gc, - ); + let section = + HTMLTableSectionElement::new(atom.clone(), None, &self.owner_document(), None, can_gc); match *atom { local_name!("thead") => self.SetTHead(Some(§ion)), local_name!("tfoot") => self.SetTFoot(Some(§ion)), @@ -192,7 +187,7 @@ impl HTMLTableElementMethods for HTMLTableElement { // https://html.spec.whatwg.org/multipage/#dom-table-rows fn Rows(&self) -> DomRoot { let filter = self.get_rows(); - HTMLCollection::new(&window_from_node(self), self.upcast(), Box::new(filter)) + HTMLCollection::new(&self.owner_window(), self.upcast(), Box::new(filter)) } // https://html.spec.whatwg.org/multipage/#dom-table-caption @@ -225,7 +220,7 @@ impl HTMLTableElementMethods for HTMLTableElement { let caption = HTMLTableCaptionElement::new( local_name!("caption"), None, - &document_from_node(self), + &self.owner_document(), None, can_gc, ); @@ -302,7 +297,7 @@ impl HTMLTableElementMethods for HTMLTableElement { fn TBodies(&self) -> DomRoot { self.tbodies.or_init(|| { HTMLCollection::new_with_filter_fn( - &window_from_node(self), + &self.owner_window(), self.upcast(), |element, root| { element.is::() && @@ -318,7 +313,7 @@ impl HTMLTableElementMethods for HTMLTableElement { let tbody = HTMLTableSectionElement::new( local_name!("tbody"), None, - &document_from_node(self), + &self.owner_document(), None, can_gc, ); @@ -346,7 +341,7 @@ impl HTMLTableElementMethods for HTMLTableElement { let new_row = HTMLTableRowElement::new( local_name!("tr"), None, - &document_from_node(self), + &self.owner_document(), None, can_gc, ); diff --git a/components/script/dom/htmltablerowelement.rs b/components/script/dom/htmltablerowelement.rs index 00627511502..ae0d8082db3 100644 --- a/components/script/dom/htmltablerowelement.rs +++ b/components/script/dom/htmltablerowelement.rs @@ -23,7 +23,7 @@ use crate::dom::htmlelement::HTMLElement; use crate::dom::htmltablecellelement::HTMLTableCellElement; use crate::dom::htmltableelement::HTMLTableElement; use crate::dom::htmltablesectionelement::HTMLTableSectionElement; -use crate::dom::node::{window_from_node, Node}; +use crate::dom::node::{Node, NodeTraits}; use crate::dom::virtualmethods::VirtualMethods; use crate::script_runtime::CanGc; @@ -87,7 +87,7 @@ impl HTMLTableRowElementMethods for HTMLTableRowElement { fn Cells(&self) -> DomRoot { self.cells.or_init(|| { HTMLCollection::new_with_filter_fn( - &window_from_node(self), + &self.owner_window(), self.upcast(), |element, root| { (element.is::()) && diff --git a/components/script/dom/htmltablesectionelement.rs b/components/script/dom/htmltablesectionelement.rs index 55cfca59675..9123e1c20ea 100644 --- a/components/script/dom/htmltablesectionelement.rs +++ b/components/script/dom/htmltablesectionelement.rs @@ -19,7 +19,7 @@ use crate::dom::element::{Element, LayoutElementHelpers}; use crate::dom::htmlcollection::HTMLCollection; use crate::dom::htmlelement::HTMLElement; use crate::dom::htmltablerowelement::HTMLTableRowElement; -use crate::dom::node::{window_from_node, Node}; +use crate::dom::node::{Node, NodeTraits}; use crate::dom::virtualmethods::VirtualMethods; use crate::script_runtime::CanGc; @@ -64,14 +64,10 @@ impl HTMLTableSectionElement { impl HTMLTableSectionElementMethods for HTMLTableSectionElement { // https://html.spec.whatwg.org/multipage/#dom-tbody-rows fn Rows(&self) -> DomRoot { - HTMLCollection::new_with_filter_fn( - &window_from_node(self), - self.upcast(), - |element, root| { - element.is::() && - element.upcast::().GetParentNode().as_deref() == Some(root) - }, - ) + HTMLCollection::new_with_filter_fn(&self.owner_window(), self.upcast(), |element, root| { + element.is::() && + element.upcast::().GetParentNode().as_deref() == Some(root) + }) } // https://html.spec.whatwg.org/multipage/#dom-tbody-insertrow diff --git a/components/script/dom/htmltemplateelement.rs b/components/script/dom/htmltemplateelement.rs index ce83c8b2efe..19e46879b83 100644 --- a/components/script/dom/htmltemplateelement.rs +++ b/components/script/dom/htmltemplateelement.rs @@ -14,7 +14,7 @@ use crate::dom::bindings::root::{DomRoot, MutNullableDom}; use crate::dom::document::Document; use crate::dom::documentfragment::DocumentFragment; use crate::dom::htmlelement::HTMLElement; -use crate::dom::node::{document_from_node, CloneChildrenFlag, Node}; +use crate::dom::node::{CloneChildrenFlag, Node, NodeTraits}; use crate::dom::virtualmethods::VirtualMethods; use crate::script_runtime::CanGc; @@ -64,7 +64,7 @@ impl HTMLTemplateElementMethods for HTMLTemplateElement { /// fn Content(&self, can_gc: CanGc) -> DomRoot { self.contents.or_init(|| { - let doc = document_from_node(self); + let doc = self.owner_document(); doc.appropriate_template_contents_owner_document(can_gc) .CreateDocumentFragment(can_gc) }) @@ -80,8 +80,9 @@ impl VirtualMethods for HTMLTemplateElement { fn adopting_steps(&self, old_doc: &Document) { self.super_type().unwrap().adopting_steps(old_doc); // Step 1. - let doc = - document_from_node(self).appropriate_template_contents_owner_document(CanGc::note()); + let doc = self + .owner_document() + .appropriate_template_contents_owner_document(CanGc::note()); // Step 2. Node::adopt(self.Content(CanGc::note()).upcast(), &doc); } diff --git a/components/script/dom/htmltextareaelement.rs b/components/script/dom/htmltextareaelement.rs index cfdca55e527..8d3aa032924 100644 --- a/components/script/dom/htmltextareaelement.rs +++ b/components/script/dom/htmltextareaelement.rs @@ -34,8 +34,7 @@ use crate::dom::htmlformelement::{FormControl, HTMLFormElement}; use crate::dom::htmlinputelement::HTMLInputElement; use crate::dom::keyboardevent::KeyboardEvent; use crate::dom::node::{ - window_from_node, BindContext, ChildrenMutation, CloneChildrenFlag, Node, NodeDamage, - UnbindContext, + BindContext, ChildrenMutation, CloneChildrenFlag, Node, NodeDamage, NodeTraits, UnbindContext, }; use crate::dom::nodelist::NodeList; use crate::dom::textcontrol::{TextControlElement, TextControlSelection}; @@ -651,7 +650,7 @@ impl VirtualMethods for HTMLTextAreaElement { } } else if event.type_() == atom!("keypress") && !event.DefaultPrevented() { if event.IsTrusted() { - let window = window_from_node(self); + let window = self.owner_window(); window .task_manager() .user_interaction_task_source() @@ -714,7 +713,7 @@ impl Validatable for HTMLTextAreaElement { fn validity_state(&self) -> DomRoot { self.validity_state - .or_init(|| ValidityState::new(&window_from_node(self), self.upcast())) + .or_init(|| ValidityState::new(&self.owner_window(), self.upcast())) } fn is_instance_validatable(&self) -> bool { diff --git a/components/script/dom/htmlvideoelement.rs b/components/script/dom/htmlvideoelement.rs index 77a00c1d481..0b10bafb16a 100644 --- a/components/script/dom/htmlvideoelement.rs +++ b/components/script/dom/htmlvideoelement.rs @@ -37,7 +37,7 @@ use crate::dom::document::Document; use crate::dom::element::{AttributeMutation, Element, LayoutElementHelpers}; use crate::dom::globalscope::GlobalScope; use crate::dom::htmlmediaelement::{HTMLMediaElement, ReadyState}; -use crate::dom::node::{document_from_node, window_from_node, Node}; +use crate::dom::node::{Node, NodeTraits}; use crate::dom::performanceresourcetiming::InitiatorType; use crate::dom::virtualmethods::VirtualMethods; use crate::fetch::FetchCanceller; @@ -125,7 +125,7 @@ impl HTMLVideoElement { let sent_resize = if self.htmlmediaelement.get_ready_state() == ReadyState::HaveNothing { None } else { - let window = window_from_node(self); + let window = self.owner_window(); let task_source = window.task_manager().media_element_task_source(); task_source.queue_simple_event(self.upcast(), atom!("resize"), &window); Some((width, height)) @@ -168,7 +168,7 @@ impl HTMLVideoElement { } // Step 3. - let poster_url = match document_from_node(self).url().join(poster_url) { + let poster_url = match self.owner_document().url().join(poster_url) { Ok(url) => url, Err(_) => return, }; @@ -176,7 +176,7 @@ impl HTMLVideoElement { // Step 4. // We use the image cache for poster frames so we save as much // network activity as possible. - let window = window_from_node(self); + let window = self.owner_window(); let image_cache = window.image_cache(); let sender = generate_cache_listener_for_element(self); let cache_result = image_cache.track_image( @@ -211,7 +211,7 @@ impl HTMLVideoElement { can_gc: CanGc, ) { // Continuation of step 4. - let document = document_from_node(self); + let document = self.owner_document(); let request = RequestBuilder::new(poster_url.clone(), document.global().get_referrer()) .destination(Destination::Image) .credentials_mode(CredentialsMode::Include) @@ -228,7 +228,7 @@ impl HTMLVideoElement { let blocker = &self.load_blocker; LoadBlocker::terminate(blocker, can_gc); *blocker.borrow_mut() = Some(LoadBlocker::new( - &document_from_node(self), + &self.owner_document(), LoadType::Image(poster_url.clone()), )); @@ -236,7 +236,8 @@ impl HTMLVideoElement { // TODO: If this is supposed to to be a "fetch" as defined in the specification // this should probably be integrated into the Document's list of cancellable fetches. - document_from_node(self).fetch_background(request, context, Some(cancel_receiver)); + self.owner_document() + .fetch_background(request, context, Some(cancel_receiver)); } } @@ -418,7 +419,7 @@ impl ResourceTimingListener for PosterFrameFetchContext { } fn resource_timing_global(&self) -> DomRoot { - document_from_node(&*self.elem.root()).global() + self.elem.root().owner_document().global() } } @@ -430,7 +431,7 @@ impl PreInvoke for PosterFrameFetchContext { impl PosterFrameFetchContext { fn new(elem: &HTMLVideoElement, url: ServoUrl, id: PendingImageId) -> PosterFrameFetchContext { - let window = window_from_node(elem); + let window = elem.owner_window(); PosterFrameFetchContext { image_cache: window.image_cache(), elem: Trusted::new(elem), diff --git a/components/script/dom/macros.rs b/components/script/dom/macros.rs index 32c76d2f24e..24589db02fb 100644 --- a/components/script/dom/macros.rs +++ b/components/script/dom/macros.rs @@ -128,7 +128,7 @@ macro_rules! make_form_action_getter( use $crate::dom::bindings::inheritance::Castable; use $crate::dom::element::Element; let element = self.upcast::(); - let doc = $crate::dom::node::document_from_node(self); + let doc = $crate::dom::node::NodeTraits::owner_document(self); let attr = element.get_attribute(&html5ever::ns!(), &html5ever::local_name!($htmlname)); let value = attr.as_ref().map(|attr| attr.value()); let value = match value { @@ -410,7 +410,7 @@ macro_rules! define_event_handler( macro_rules! define_window_owned_event_handler( ($handler: ty, $event_type: ident, $getter: ident, $setter: ident) => ( fn $getter(&self) -> Option<::std::rc::Rc<$handler>> { - let document = document_from_node(self); + let document = self.owner_document(); if document.has_browsing_context() { document.window().$getter() } else { @@ -419,7 +419,7 @@ macro_rules! define_window_owned_event_handler( } fn $setter(&self, listener: Option<::std::rc::Rc<$handler>>) { - let document = document_from_node(self); + let document = self.owner_document(); if document.has_browsing_context() { document.window().$setter(listener) } diff --git a/components/script/dom/mutationrecord.rs b/components/script/dom/mutationrecord.rs index 5e438a61fd4..5280b5a7113 100644 --- a/components/script/dom/mutationrecord.rs +++ b/components/script/dom/mutationrecord.rs @@ -9,7 +9,7 @@ use crate::dom::bindings::codegen::Bindings::MutationRecordBinding::MutationReco use crate::dom::bindings::reflector::{reflect_dom_object, Reflector}; use crate::dom::bindings::root::{Dom, DomRoot, MutNullableDom}; use crate::dom::bindings::str::DOMString; -use crate::dom::node::{window_from_node, Node}; +use crate::dom::node::{Node, NodeTraits}; use crate::dom::nodelist::NodeList; use crate::script_runtime::CanGc; @@ -46,7 +46,7 @@ impl MutationRecord { None, None, )); - reflect_dom_object(record, &*window_from_node(target), CanGc::note()) + reflect_dom_object(record, &*target.owner_window(), CanGc::note()) } pub fn character_data_mutated( @@ -65,7 +65,7 @@ impl MutationRecord { None, None, )), - &*window_from_node(target), + &*target.owner_window(), CanGc::note(), ) } @@ -77,7 +77,7 @@ impl MutationRecord { next_sibling: Option<&Node>, prev_sibling: Option<&Node>, ) -> DomRoot { - let window = window_from_node(target); + let window = target.owner_window(); let added_nodes = added_nodes.map(|list| NodeList::new_simple_list_slice(&window, list)); let removed_nodes = removed_nodes.map(|list| NodeList::new_simple_list_slice(&window, list)); @@ -154,18 +154,14 @@ impl MutationRecordMethods for MutationRecord { // https://dom.spec.whatwg.org/#dom-mutationrecord-addednodes fn AddedNodes(&self) -> DomRoot { - self.added_nodes.or_init(|| { - let window = window_from_node(&*self.target); - NodeList::empty(&window) - }) + self.added_nodes + .or_init(|| NodeList::empty(&self.target.owner_window())) } // https://dom.spec.whatwg.org/#dom-mutationrecord-removednodes fn RemovedNodes(&self) -> DomRoot { - self.removed_nodes.or_init(|| { - let window = window_from_node(&*self.target); - NodeList::empty(&window) - }) + self.removed_nodes + .or_init(|| NodeList::empty(&self.target.owner_window())) } // https://dom.spec.whatwg.org/#dom-mutationrecord-previoussibling diff --git a/components/script/dom/node.rs b/components/script/dom/node.rs index 93064696ea6..09684c5d9e9 100644 --- a/components/script/dom/node.rs +++ b/components/script/dom/node.rs @@ -413,7 +413,7 @@ impl Node { // Spec says the choice of which global to create // the mouse event on is not well-defined, // and refers to heycam/webidl#135 - let win = window_from_node(self); + let win = self.owner_window(); let mouse_event = MouseEvent::new( &win, // ambiguous in spec @@ -813,7 +813,7 @@ impl Node { /// Returns the rendered bounding content box if the element is rendered, /// and none otherwise. pub fn bounding_content_box(&self, can_gc: CanGc) -> Option> { - window_from_node(self).content_box_query(self, can_gc) + self.owner_window().content_box_query(self, can_gc) } pub fn bounding_content_box_or_zero(&self, can_gc: CanGc) -> Rect { @@ -821,11 +821,11 @@ impl Node { } pub fn content_boxes(&self, can_gc: CanGc) -> Vec> { - window_from_node(self).content_boxes_query(self, can_gc) + self.owner_window().content_boxes_query(self, can_gc) } pub fn client_rect(&self, can_gc: CanGc) -> Rect { - window_from_node(self).client_rect_query(self, can_gc) + self.owner_window().client_rect_query(self, can_gc) } /// @@ -1044,7 +1044,7 @@ impl Node { /// #[allow(unsafe_code)] pub fn query_selector_all(&self, selectors: DOMString) -> Fallible> { - let window = window_from_node(self); + let window = self.owner_window(); let iter = self.query_selector_iter(selectors)?; Ok(NodeList::new_simple_list(&window, iter)) } @@ -1296,7 +1296,10 @@ impl Node { } pub fn style(&self, can_gc: CanGc) -> Option> { - if !window_from_node(self).layout_reflow(QueryMsg::StyleQuery, can_gc) { + if !self + .owner_window() + .layout_reflow(QueryMsg::StyleQuery, can_gc) + { return None; } self.style_data @@ -2018,8 +2021,7 @@ impl Node { }; // Step 4. - let document = document_from_node(parent); - Node::adopt(node, &document); + Node::adopt(node, &parent.owner_document()); // Step 5. Node::insert( @@ -2216,7 +2218,7 @@ impl Node { if string.len() == 0 { Node::replace_all(None, parent); } else { - let text = Text::new(string, &document_from_node(parent), can_gc); + let text = Text::new(string, &parent.owner_document(), can_gc); Node::replace_all(Some(text.upcast::()), parent); }; } @@ -2574,7 +2576,7 @@ impl Node { /// pub fn fragment_serialization_algorithm(&self, require_well_formed: bool) -> DOMString { // Step 1. Let context document be node's node document. - let context_document = document_from_node(self); + let context_document = self.owner_document(); // Step 2. If context document is an HTML document, return the result of HTML fragment serialization algorithm // with node, false, and « ». @@ -2894,7 +2896,7 @@ impl NodeMethods for Node { let previous_sibling = child.GetPreviousSibling(); // Step 10. - let document = document_from_node(self); + let document = self.owner_document(); Node::adopt(node, &document); let removed_child = if node != child { @@ -3310,30 +3312,44 @@ impl NodeMethods for Node { } } -pub fn document_from_node + DomObject>(derived: &T) -> DomRoot { - derived.upcast().owner_doc() +pub(crate) trait NodeTraits { + /// Get the [`Document`] that owns this node. Note that this may differ from the + /// [`Document`] that the node was created in if it was adopted by a different + /// [`Document`] (the owner). + fn owner_document(&self) -> DomRoot; + /// Get the [`Window`] of the [`Document`] that owns this node. Note that this may + /// differ from the [`Document`] that the node was created in if it was adopted by a + /// different [`Document`] (the owner). + fn owner_window(&self) -> DomRoot; + /// If this [`Node`] is contained in a [`ShadowRoot`] return it, otherwise `None`. + fn containing_shadow_root(&self) -> Option>; + /// Get the stylesheet owner for this node: either the [`Document`] or the [`ShadowRoot`] + /// of the node. + #[allow(crown::unrooted_must_root)] + fn stylesheet_list_owner(&self) -> StyleSheetListOwner; } -pub fn containing_shadow_root + DomObject>( - derived: &T, -) -> Option> { - derived.upcast().containing_shadow_root() -} - -#[allow(crown::unrooted_must_root)] -pub fn stylesheets_owner_from_node + DomObject>( - derived: &T, -) -> StyleSheetListOwner { - if let Some(shadow_root) = containing_shadow_root(derived) { - StyleSheetListOwner::ShadowRoot(Dom::from_ref(&*shadow_root)) - } else { - StyleSheetListOwner::Document(Dom::from_ref(&*document_from_node(derived))) +impl + DomObject> NodeTraits for T { + fn owner_document(&self) -> DomRoot { + self.upcast().owner_doc() } -} -pub fn window_from_node + DomObject>(derived: &T) -> DomRoot { - let document = document_from_node(derived); - DomRoot::from_ref(document.window()) + fn owner_window(&self) -> DomRoot { + DomRoot::from_ref(self.owner_document().window()) + } + + fn containing_shadow_root(&self) -> Option> { + Node::containing_shadow_root(self.upcast()) + } + + #[allow(crown::unrooted_must_root)] + fn stylesheet_list_owner(&self) -> StyleSheetListOwner { + self.containing_shadow_root() + .map(|shadow_root| StyleSheetListOwner::ShadowRoot(Dom::from_ref(&*shadow_root))) + .unwrap_or_else(|| { + StyleSheetListOwner::Document(Dom::from_ref(&*self.owner_document())) + }) + } } impl VirtualMethods for Node { diff --git a/components/script/dom/resizeobserver.rs b/components/script/dom/resizeobserver.rs index b3e7f680725..c7bc2f9f7a7 100644 --- a/components/script/dom/resizeobserver.rs +++ b/components/script/dom/resizeobserver.rs @@ -21,7 +21,7 @@ use crate::dom::bindings::reflector::{reflect_dom_object_with_proto, Reflector}; use crate::dom::bindings::root::{Dom, DomRoot}; use crate::dom::domrectreadonly::DOMRectReadOnly; use crate::dom::element::Element; -use crate::dom::node::{window_from_node, Node}; +use crate::dom::node::{Node, NodeTraits}; use crate::dom::resizeobserverentry::ResizeObserverEntry; use crate::dom::resizeobserversize::{ResizeObserverSize, ResizeObserverSizeImpl}; use crate::dom::window::Window; @@ -111,7 +111,7 @@ impl ResizeObserver { let width = box_size.width().to_f64_px(); let height = box_size.height().to_f64_px(); let size_impl = ResizeObserverSizeImpl::new(width, height); - let window = window_from_node(&**target); + let window = target.owner_window(); let observer_size = ResizeObserverSize::new(&window, size_impl, can_gc); // Note: content rect is built from content box size. diff --git a/components/script/dom/selection.rs b/components/script/dom/selection.rs index 7347a6464ec..ae2beee74d5 100644 --- a/components/script/dom/selection.rs +++ b/components/script/dom/selection.rs @@ -17,7 +17,7 @@ use crate::dom::bindings::root::{Dom, DomRoot, MutNullableDom}; use crate::dom::bindings::str::DOMString; use crate::dom::document::Document; use crate::dom::eventtarget::EventTarget; -use crate::dom::node::{window_from_node, Node}; +use crate::dom::node::Node; use crate::dom::range::Range; use crate::script_runtime::CanGc; @@ -88,7 +88,7 @@ impl Selection { return; } let this = Trusted::new(self); - let window = window_from_node(&*self.document); + let window = self.document.window(); window .task_manager() .user_interaction_task_source() // w3c/selection-api#117 diff --git a/components/script/dom/shadowroot.rs b/components/script/dom/shadowroot.rs index ea7b778f1ff..49005e49da8 100644 --- a/components/script/dom/shadowroot.rs +++ b/components/script/dom/shadowroot.rs @@ -25,7 +25,7 @@ use crate::dom::documentfragment::DocumentFragment; use crate::dom::documentorshadowroot::{DocumentOrShadowRoot, StyleSheetInDocument}; use crate::dom::element::Element; use crate::dom::node::{ - document_from_node, BindContext, Node, NodeDamage, NodeFlags, ShadowIncluding, UnbindContext, + BindContext, Node, NodeDamage, NodeFlags, NodeTraits, ShadowIncluding, UnbindContext, }; use crate::dom::stylesheetlist::{StyleSheetList, StyleSheetListOwner}; use crate::dom::virtualmethods::VirtualMethods; @@ -314,7 +314,7 @@ impl VirtualMethods for ShadowRoot { } if context.tree_connected { - let document = document_from_node(self); + let document = self.owner_document(); document.register_shadow_root(self); } @@ -332,7 +332,7 @@ impl VirtualMethods for ShadowRoot { } if context.tree_connected { - let document = document_from_node(self); + let document = self.owner_document(); document.unregister_shadow_root(self); } } diff --git a/components/script/dom/svgelement.rs b/components/script/dom/svgelement.rs index 3c738b1f54e..d96f0ff3e50 100644 --- a/components/script/dom/svgelement.rs +++ b/components/script/dom/svgelement.rs @@ -13,7 +13,7 @@ use crate::dom::bindings::root::{Dom, DomRoot, MutNullableDom}; use crate::dom::cssstyledeclaration::{CSSModificationAccess, CSSStyleDeclaration, CSSStyleOwner}; use crate::dom::document::Document; use crate::dom::element::Element; -use crate::dom::node::{window_from_node, Node}; +use crate::dom::node::{Node, NodeTraits}; use crate::dom::virtualmethods::VirtualMethods; use crate::script_runtime::CanGc; @@ -70,7 +70,7 @@ impl SVGElementMethods for SVGElement { // https://html.spec.whatwg.org/multipage/#the-style-attribute fn Style(&self) -> DomRoot { self.style_decl.or_init(|| { - let global = window_from_node(self); + let global = self.owner_window(); CSSStyleDeclaration::new( &global, CSSStyleOwner::Element(Dom::from_ref(self.upcast())), diff --git a/components/script/dom/textcontrol.rs b/components/script/dom/textcontrol.rs index 73a23f59dc8..7e94e404d40 100644 --- a/components/script/dom/textcontrol.rs +++ b/components/script/dom/textcontrol.rs @@ -16,7 +16,7 @@ use crate::dom::bindings::error::{Error, ErrorResult}; use crate::dom::bindings::str::DOMString; use crate::dom::event::{EventBubbles, EventCancelable}; use crate::dom::eventtarget::EventTarget; -use crate::dom::node::{window_from_node, Node, NodeDamage}; +use crate::dom::node::{Node, NodeDamage, NodeTraits}; use crate::textinput::{SelectionDirection, SelectionState, TextInput, UTF8Bytes}; pub trait TextControlElement: DerivedFrom + DerivedFrom { @@ -300,7 +300,7 @@ impl<'a, E: TextControlElement> TextControlSelection<'a, E> { // Step 6 if textinput.selection_state() != original_selection_state { - let window = window_from_node(self.element); + let window = self.element.owner_window(); window .task_manager() .user_interaction_task_source() diff --git a/components/script/dom/uievent.rs b/components/script/dom/uievent.rs index 025e4637ea3..650160e5efb 100644 --- a/components/script/dom/uievent.rs +++ b/components/script/dom/uievent.rs @@ -9,7 +9,7 @@ use dom_struct::dom_struct; use js::rust::HandleObject; use servo_atoms::Atom; -use super::node::document_from_node; +use super::node::NodeTraits; use crate::dom::bindings::codegen::Bindings::EventBinding::EventMethods; use crate::dom::bindings::codegen::Bindings::UIEventBinding; use crate::dom::bindings::codegen::Bindings::UIEventBinding::UIEventMethods; @@ -106,7 +106,7 @@ impl UIEvent { if let Some(target_) = target_ { let element = target_.downcast::(); let document = match element { - Some(element) => document_from_node(element), + Some(element) => element.owner_document(), None => target_.downcast::().unwrap().Document(), }; self.view.set(Some(document.window())); diff --git a/components/script/dom/userscripts.rs b/components/script/dom/userscripts.rs index 5ac6e5042e7..781616a669c 100644 --- a/components/script/dom/userscripts.rs +++ b/components/script/dom/userscripts.rs @@ -15,12 +15,12 @@ use crate::dom::bindings::str::DOMString; use crate::dom::globalscope::GlobalScope; use crate::dom::htmlheadelement::HTMLHeadElement; use crate::dom::htmlscriptelement::SourceCode; -use crate::dom::node::document_from_node; +use crate::dom::node::NodeTraits; use crate::script_module::ScriptFetchOptions; use crate::script_runtime::CanGc; pub fn load_script(head: &HTMLHeadElement) { - let doc = document_from_node(head); + let doc = head.owner_document(); let path_str = match doc.window().get_userscripts_path() { Some(p) => p, None => return, diff --git a/components/script/dom/webglrenderingcontext.rs b/components/script/dom/webglrenderingcontext.rs index 0ee426c619c..0d0c03a61a8 100644 --- a/components/script/dom/webglrenderingcontext.rs +++ b/components/script/dom/webglrenderingcontext.rs @@ -57,7 +57,7 @@ use crate::dom::bindings::str::DOMString; use crate::dom::element::cors_setting_for_element; use crate::dom::event::{Event, EventBubbles, EventCancelable}; use crate::dom::htmlcanvaselement::{utils as canvas_utils, LayoutCanvasRenderingContextHelpers}; -use crate::dom::node::{document_from_node, window_from_node, Node, NodeDamage}; +use crate::dom::node::{Node, NodeDamage, NodeTraits}; use crate::dom::promise::Promise; use crate::dom::vertexarrayobject::VertexAttribData; use crate::dom::webgl_extensions::WebGLExtensions; @@ -551,8 +551,7 @@ impl WebGLRenderingContext { match self.canvas { HTMLCanvasElementOrOffscreenCanvas::HTMLCanvasElement(ref canvas) => { canvas.upcast::().dirty(NodeDamage::OtherNodeDamage); - let document = document_from_node(&**canvas); - document.add_dirty_webgl_canvas(self); + canvas.owner_document().add_dirty_webgl_canvas(self); }, HTMLCanvasElementOrOffscreenCanvas::OffscreenCanvas(_) => {}, } @@ -665,7 +664,7 @@ impl WebGLRenderingContext { TexImageSource::HTMLImageElement(image) => { let document = match self.canvas { HTMLCanvasElementOrOffscreenCanvas::HTMLCanvasElement(ref canvas) => { - document_from_node(&**canvas) + canvas.owner_document() }, HTMLCanvasElementOrOffscreenCanvas::OffscreenCanvas(ref _canvas) => { // TODO: Support retrieving image pixels here for OffscreenCanvas @@ -683,7 +682,7 @@ impl WebGLRenderingContext { let window = match self.canvas { HTMLCanvasElementOrOffscreenCanvas::HTMLCanvasElement(ref canvas) => { - window_from_node(&**canvas) + canvas.owner_window() }, // This is marked as unreachable as we should have returned already HTMLCanvasElementOrOffscreenCanvas::OffscreenCanvas(_) => unreachable!(), diff --git a/components/script/dom/webgpu/gpucanvascontext.rs b/components/script/dom/webgpu/gpucanvascontext.rs index af01c0e8af8..cb6d7a2182a 100644 --- a/components/script/dom/webgpu/gpucanvascontext.rs +++ b/components/script/dom/webgpu/gpucanvascontext.rs @@ -38,7 +38,7 @@ use crate::dom::bindings::weakref::WeakRef; use crate::dom::document::WebGPUContextsMap; use crate::dom::globalscope::GlobalScope; use crate::dom::htmlcanvaselement::{HTMLCanvasElement, LayoutCanvasRenderingContextHelpers}; -use crate::dom::node::{document_from_node, Node, NodeDamage}; +use crate::dom::node::{Node, NodeDamage, NodeTraits}; use crate::script_runtime::CanGc; impl HTMLCanvasElementOrOffscreenCanvas { @@ -141,7 +141,7 @@ impl GPUCanvasContext { } pub fn new(global: &GlobalScope, canvas: &HTMLCanvasElement, channel: WebGPU) -> DomRoot { - let document = document_from_node(canvas); + let document = canvas.owner_document(); let this = reflect_dom_object( Box::new(GPUCanvasContext::new_inherited( global, diff --git a/components/script/dom/window.rs b/components/script/dom/window.rs index fc3d13e60eb..2e2645b72ea 100644 --- a/components/script/dom/window.rs +++ b/components/script/dom/window.rs @@ -133,7 +133,7 @@ use crate::dom::mediaquerylist::{MediaQueryList, MediaQueryListMatchState}; use crate::dom::mediaquerylistevent::MediaQueryListEvent; use crate::dom::messageevent::MessageEvent; use crate::dom::navigator::Navigator; -use crate::dom::node::{document_from_node, from_untrusted_node_address, Node, NodeDamage}; +use crate::dom::node::{from_untrusted_node_address, Node, NodeDamage, NodeTraits}; use crate::dom::performance::Performance; use crate::dom::promise::Promise; use crate::dom::screen::Screen; @@ -882,7 +882,7 @@ impl WindowMethods for Window { let container = window_proxy.frame_element()?; // Step 6. - let container_doc = document_from_node(container); + let container_doc = container.owner_document(); let current_doc = GlobalScope::current() .expect("No current global object") .as_window() diff --git a/components/script/image_listener.rs b/components/script/image_listener.rs index c07ccd4b231..b2e5c9e8b80 100644 --- a/components/script/image_listener.rs +++ b/components/script/image_listener.rs @@ -10,7 +10,7 @@ use net_traits::image_cache::{ImageResponse, PendingImageResponse}; use crate::dom::bindings::conversions::DerivedFrom; use crate::dom::bindings::refcounted::Trusted; use crate::dom::bindings::reflector::DomObject; -use crate::dom::node::{window_from_node, Node}; +use crate::dom::node::{Node, NodeTraits}; use crate::script_runtime::CanGc; pub trait ImageCacheListener { @@ -26,7 +26,7 @@ pub fn generate_cache_listener_for_element< let trusted_node = Trusted::new(elem); let (responder_sender, responder_receiver) = ipc::channel().unwrap(); - let window = window_from_node(elem); + let window = elem.owner_window(); let (task_source, canceller) = window .task_manager() .networking_task_source_with_canceller(); diff --git a/components/script/layout_image.rs b/components/script/layout_image.rs index 5c6b3b7fb84..e3fac59b72d 100644 --- a/components/script/layout_image.rs +++ b/components/script/layout_image.rs @@ -21,7 +21,7 @@ use crate::dom::bindings::reflector::DomObject; use crate::dom::bindings::root::DomRoot; use crate::dom::document::Document; use crate::dom::globalscope::GlobalScope; -use crate::dom::node::{document_from_node, Node}; +use crate::dom::node::{Node, NodeTraits}; use crate::dom::performanceresourcetiming::InitiatorType; use crate::network_listener::{self, PreInvoke, ResourceTimingListener}; use crate::script_runtime::CanGc; @@ -97,7 +97,7 @@ pub fn fetch_image_for_layout( id: PendingImageId, cache: Arc, ) { - let document = document_from_node(node); + let document = node.owner_document(); let context = LayoutImageContext { id, cache, diff --git a/components/script/links.rs b/components/script/links.rs index d4d318c180e..3dec6c639f9 100644 --- a/components/script/links.rs +++ b/components/script/links.rs @@ -19,7 +19,7 @@ use crate::dom::htmlanchorelement::HTMLAnchorElement; use crate::dom::htmlareaelement::HTMLAreaElement; use crate::dom::htmlformelement::HTMLFormElement; use crate::dom::htmllinkelement::HTMLLinkElement; -use crate::dom::node::document_from_node; +use crate::dom::node::NodeTraits; use crate::dom::types::{Element, GlobalScope}; use crate::script_runtime::CanGc; @@ -322,7 +322,7 @@ pub fn get_element_target(subject: &Element) -> Option { return Some(subject.get_string_attribute(&local_name!("target"))); } - let doc = document_from_node(subject).base_element(); + let doc = subject.owner_document().base_element(); match doc { Some(doc) => { let element = doc.upcast::(); @@ -348,7 +348,7 @@ pub fn follow_hyperlink( } // Step 2, done in Step 7. - let document = document_from_node(subject); + let document = subject.owner_document(); let window = document.window(); // Step 3: source browsing context. diff --git a/components/script/script_module.rs b/components/script/script_module.rs index cb199ad27d1..63b9527c4e4 100644 --- a/components/script/script_module.rs +++ b/components/script/script_module.rs @@ -65,7 +65,7 @@ use crate::dom::globalscope::GlobalScope; use crate::dom::htmlscriptelement::{ HTMLScriptElement, ScriptId, ScriptOrigin, ScriptType, SCRIPT_JS_MIMES, }; -use crate::dom::node::document_from_node; +use crate::dom::node::NodeTraits; use crate::dom::performanceresourcetiming::InitiatorType; use crate::dom::promise::Promise; use crate::dom::promisenativehandler::{Callback, PromiseNativeHandler}; @@ -962,8 +962,7 @@ impl ModuleOwner { ModuleOwner::Window(script) => { let global = self.global(); - let document = document_from_node(&*script.root()); - + let document = script.root().owner_document(); let load = { let module_tree = module_identity.get_module_tree(&global); @@ -1745,7 +1744,7 @@ fn fetch_single_module_script( let document: Option> = match &owner { ModuleOwner::Worker(_) | ModuleOwner::DynamicModule(_) => None, - ModuleOwner::Window(script) => Some(document_from_node(&*script.root())), + ModuleOwner::Window(script) => Some(script.root().owner_document()), }; // Step 7-8. diff --git a/components/script/script_thread.rs b/components/script/script_thread.rs index 8a820a7b6bd..f970d351d35 100644 --- a/components/script/script_thread.rs +++ b/components/script/script_thread.rs @@ -130,7 +130,7 @@ use crate::dom::globalscope::GlobalScope; use crate::dom::htmlanchorelement::HTMLAnchorElement; use crate::dom::htmliframeelement::HTMLIFrameElement; use crate::dom::mutationobserver::MutationObserver; -use crate::dom::node::{window_from_node, Node, ShadowIncluding}; +use crate::dom::node::{Node, NodeTraits, ShadowIncluding}; use crate::dom::performanceentry::PerformanceEntry; use crate::dom::performancepainttiming::PerformancePaintTiming; use crate::dom::servoparser::{ParserContext, ServoParser}; @@ -3062,7 +3062,7 @@ impl ScriptThread { .find_iframe(parent_id, browsing_context_id) }); let parent_browsing_context = match (parent_info, iframe.as_ref()) { - (_, Some(iframe)) => Some(window_from_node(&**iframe).window_proxy()), + (_, Some(iframe)) => Some(iframe.owner_window().window_proxy()), (Some(parent_id), _) => self.remote_window_proxy( window.upcast(), top_level_browsing_context_id, diff --git a/components/script/stylesheet_loader.rs b/components/script/stylesheet_loader.rs index f31201bb4fc..4266d50ce34 100644 --- a/components/script/stylesheet_loader.rs +++ b/components/script/stylesheet_loader.rs @@ -37,7 +37,7 @@ use crate::dom::eventtarget::EventTarget; use crate::dom::globalscope::GlobalScope; use crate::dom::htmlelement::HTMLElement; use crate::dom::htmllinkelement::{HTMLLinkElement, RequestGenerationId}; -use crate::dom::node::{containing_shadow_root, document_from_node, window_from_node}; +use crate::dom::node::NodeTraits; use crate::dom::performanceresourcetiming::InitiatorType; use crate::dom::shadowroot::ShadowRoot; use crate::fetch::create_a_potential_cors_request; @@ -179,7 +179,7 @@ impl FetchResponseListener for StylesheetContext { let protocol_encoding_label = metadata.charset.as_deref(); let final_url = metadata.final_url; - let win = window_from_node(&*elem); + let win = elem.owner_window(); let loader = StylesheetLoader::for_element(&elem); match self.source { @@ -288,7 +288,7 @@ impl ResourceTimingListener for StylesheetContext { } fn resource_timing_global(&self) -> DomRoot { - document_from_node(&*self.elem.root()).global() + self.elem.root().owner_document().global() } } @@ -310,8 +310,11 @@ impl StylesheetLoader<'_> { cors_setting: Option, integrity_metadata: String, ) { - let document = document_from_node(self.elem); - let shadow_root = containing_shadow_root(self.elem).map(|sr| Trusted::new(&*sr)); + let document = self.elem.owner_document(); + let shadow_root = self + .elem + .containing_shadow_root() + .map(|sr| Trusted::new(&*sr)); let gen = self .elem .downcast::() diff --git a/components/script/webdriver_handlers.rs b/components/script/webdriver_handlers.rs index 2cd65a354b7..c1795a51f74 100644 --- a/components/script/webdriver_handlers.rs +++ b/components/script/webdriver_handlers.rs @@ -58,7 +58,7 @@ use crate::dom::htmliframeelement::HTMLIFrameElement; use crate::dom::htmlinputelement::{HTMLInputElement, InputType}; use crate::dom::htmloptionelement::HTMLOptionElement; use crate::dom::htmlselectelement::HTMLSelectElement; -use crate::dom::node::{window_from_node, Node, ShadowIncluding}; +use crate::dom::node::{Node, NodeTraits, ShadowIncluding}; use crate::dom::nodelist::NodeList; use crate::dom::window::Window; use crate::dom::xmlserializer::XMLSerializer; @@ -414,8 +414,8 @@ pub fn handle_get_browsing_context_id( // https://w3c.github.io/webdriver/#dfn-center-point fn get_element_in_view_center_point(element: &Element, can_gc: CanGc) -> Option> { - window_from_node(element.upcast::()) - .Document() + element + .owner_document() .GetBody() .map(DomRoot::upcast::) .and_then(|body| { @@ -1088,7 +1088,7 @@ pub fn handle_get_css( reply .send( find_node_by_unique_id(documents, pipeline, node_id).map(|node| { - let window = window_from_node(&*node); + let window = node.owner_window(); let element = node.downcast::().unwrap(); String::from( window