Skip to main content

script/dom/document/
document.rs

1/* This Source Code Form is subject to the terms of the Mozilla Public
2 * License, v. 2.0. If a copy of the MPL was not distributed with this
3 * file, You can obtain one at https://mozilla.org/MPL/2.0/. */
4
5#![cfg_attr(crown, allow(crown::jscontext_first_arg))]
6
7use std::cell::{Cell, OnceCell, RefCell};
8use std::cmp::Ordering;
9use std::collections::hash_map::Entry::{Occupied, Vacant};
10use std::collections::{HashMap, HashSet, VecDeque};
11use std::default::Default;
12use std::ops::Deref;
13use std::rc::Rc;
14use std::str::FromStr;
15use std::sync::{Arc as StdArc, LazyLock};
16use std::time::Duration;
17
18use atomic_refcell::{AtomicRef, AtomicRefCell};
19use bitflags::bitflags;
20use chrono::Local;
21use content_security_policy::sandboxing_directive::SandboxingFlagSet;
22use content_security_policy::{CspList, Policy as CspPolicy, PolicyDisposition};
23use cookie::Cookie;
24use data_url::mime::Mime;
25#[cfg(feature = "devtools")]
26use devtools_traits::ScriptToDevtoolsControlMsg;
27use dom_struct::dom_struct;
28use embedder_traits::{
29    AllowOrDeny, AnimationState, CustomHandlersAutomationMode, EmbedderMsg, Image, LoadStatus,
30    Theme,
31};
32use encoding_rs::{Encoding, UTF_8};
33use html5ever::{LocalName, QualName, local_name, ns};
34use hyper_serde::Serde;
35use indexmap::IndexSet;
36use js::context::{JSContext, NoGC};
37use js::jsapi::JSObject;
38use js::realm::CurrentRealm;
39use js::rust::{HandleObject, HandleValue};
40use layout_api::{
41    ContainerTimingRecord, LCPCandidate, PendingRestyle, ReflowGoal, ReflowPhasesRun,
42    ReflowStatistics, RestyleReason, ScrollContainerQueryFlags, TrustedNodeAddress,
43};
44use malloc_size_of::MallocSizeOfOps;
45use metrics::{InteractiveFlag, InteractiveWindow, ProgressiveWebMetrics};
46use net_traits::CookieSource::NonHTTP;
47use net_traits::CoreResourceMsg::{GetCookieStringForUrl, SetCookiesForUrl};
48use net_traits::image_cache::ImageCache;
49use net_traits::policy_container::PolicyContainer;
50use net_traits::pub_domains::{Site, is_pub_domain};
51use net_traits::request::{
52    InsecureRequestsPolicy, PreloadId, PreloadKey, PreloadedResources, RequestBuilder,
53    UpgradeInsecureNavigations,
54};
55use net_traits::{ReferrerPolicy, ResourceFetchTiming};
56use paint_api::display_list::PaintTimingInfo;
57use percent_encoding::percent_decode;
58use profile_traits::mem::{Report, ReportKind};
59use profile_traits::time::TimerMetadataFrameType;
60use profile_traits::{generic_channel as profile_generic_channel, path};
61use regex::bytes::Regex;
62use rustc_hash::{FxBuildHasher, FxHashMap, FxHashSet};
63use script_bindings::callback::{RootedCallback, ThisReflector};
64use script_bindings::cell::{DomRefCell, Ref, RefMut};
65use script_bindings::domstring::TracedDOMString;
66use script_bindings::interfaces::DocumentHelpers;
67use script_bindings::reflector::reflect_dom_object_with_proto;
68use script_bindings::tasks::NonSendTaskBox;
69use script_bindings::trace::CustomTraceable;
70use script_traits::{DocumentActivity, ProgressiveWebMetricType};
71use servo_arc::Arc;
72use servo_base::cross_process_instant::CrossProcessInstant;
73use servo_base::generic_channel::GenericSend;
74use servo_base::id::{ContainerTimingID, LCPCandidateID, PipelineId, WebViewId};
75use servo_base::{Epoch, generic_channel};
76use servo_config::pref;
77use servo_constellation_traits::{
78    NavigationHistoryBehavior, PaintMetricEvent, ScriptToConstellationMessage,
79};
80use servo_media::{ClientContextId, ServoMedia};
81use servo_url::{ImmutableOrigin, MutableOrigin, ServoUrl};
82use style::attr::AttrValue;
83use style::context::QuirksMode;
84use style::dom::OpaqueNode;
85use style::invalidation::element::restyle_hints::RestyleHint;
86use style::selector_parser::Snapshot;
87use style::shared_lock::{SharedRwLock, SharedRwLockReadGuard};
88use style::str::{split_html_space_chars, str_join};
89use style::stylesheet_set::DocumentStylesheetSet;
90use style::stylesheets::{Origin, OriginSet, Stylesheet};
91use style::stylist::Stylist;
92use stylo_atoms::Atom;
93use time::Duration as TimeDuration;
94use url::{Host, Position};
95
96use crate::css::stylesheet_loader::StylesheetContextId;
97use crate::css::stylesheet_set::StylesheetSetRef;
98use crate::dom::animationtimeline::AnimationTimeline;
99use crate::dom::attr::Attr;
100use crate::dom::beforeunloadevent::BeforeUnloadEvent;
101use crate::dom::bindings::callback::{ExceptionHandling, TracedCallback};
102use crate::dom::bindings::codegen::Bindings::AnimationFrameProviderBinding::FrameRequestCallback;
103use crate::dom::bindings::codegen::Bindings::BeforeUnloadEventBinding::BeforeUnloadEvent_Binding::BeforeUnloadEventMethods;
104use crate::dom::bindings::codegen::Bindings::DocumentBinding::{
105    DocumentMethods, DocumentReadyState, DocumentVisibilityState, ElementCreationOptions,
106    NamedPropertyValue,
107};
108use crate::dom::bindings::codegen::Bindings::ElementBinding::ScrollLogicalPosition;
109use crate::dom::bindings::codegen::Bindings::EventBinding::Event_Binding::EventMethods;
110use crate::dom::bindings::codegen::Bindings::HTMLElementBinding::HTMLElementMethods;
111use crate::dom::bindings::codegen::Bindings::HTMLIFrameElementBinding::HTMLIFrameElement_Binding::HTMLIFrameElementMethods;
112use crate::dom::bindings::codegen::Bindings::IntersectionObserverBinding::IntersectionObserverMethods;
113#[cfg(any(feature = "webxr", feature = "gamepad"))]
114use crate::dom::bindings::codegen::Bindings::NavigatorBinding::Navigator_Binding::NavigatorMethods;
115use crate::dom::bindings::codegen::Bindings::NodeBinding::NodeMethods;
116use crate::dom::bindings::codegen::Bindings::NodeFilterBinding::NodeFilter;
117use crate::dom::bindings::codegen::Bindings::PerformanceBinding::PerformanceMethods;
118use crate::dom::bindings::codegen::Bindings::PermissionStatusBinding::PermissionName;
119use crate::dom::bindings::codegen::Bindings::SanitizerBinding::{
120    SetHTMLOptions, SetHTMLUnsafeOptions,
121};
122use crate::dom::bindings::codegen::Bindings::WindowBinding::{ScrollBehavior, WindowMethods};
123use crate::dom::bindings::codegen::Bindings::XPathEvaluatorBinding::XPathEvaluatorMethods;
124use crate::dom::bindings::codegen::Bindings::XPathNSResolverBinding::XPathNSResolver;
125use crate::dom::bindings::codegen::UnionTypes::{
126    BooleanOrImportNodeOptions, NodeOrString, StringOrElementCreationOptions, TrustedHTMLOrString,
127};
128use crate::dom::bindings::domname::{
129    self, is_valid_attribute_local_name, is_valid_element_local_name, namespace_from_domstring,
130};
131use crate::dom::bindings::error::{Error, ErrorInfo, ErrorResult, Fallible};
132use crate::dom::bindings::inheritance::{Castable, ElementTypeId, HTMLElementTypeId, NodeTypeId};
133use crate::dom::bindings::num::Finite;
134use crate::dom::bindings::refcounted::Trusted;
135use crate::dom::bindings::reflector::DomGlobal;
136use crate::dom::bindings::root::{
137    Dom, DomRoot, LayoutDom, MutNullableDom, ToLayout, ToLayoutOptional, UnrootedDom,
138};
139use crate::dom::bindings::str::{DOMString, USVString};
140use crate::dom::bindings::trace::{HashMapTracedValues, NoTrace};
141use crate::dom::bindings::weakref::DOMTracker;
142use crate::dom::bindings::xmlname::matches_name_production;
143use crate::dom::cdatasection::CDATASection;
144use crate::dom::comment::Comment;
145use crate::dom::compositionevent::CompositionEvent;
146use crate::dom::css::cssstylesheet::CSSStyleSheet;
147use crate::dom::css::fontfaceset::FontFaceSet;
148use crate::dom::css::stylesheetlist::{StyleSheetList, StyleSheetListOwner};
149use crate::dom::customelementregistry::{CustomElementReactionStack, CustomElementRegistry};
150use crate::dom::customevent::CustomEvent;
151use crate::dom::document::accessibility_data::AccessibilityData;
152use crate::dom::document::animation_manager::AnimationManager;
153use crate::dom::document::focus::{DocumentFocusHandler, FocusableArea};
154use crate::dom::document::iframe_collection::IFrameCollection;
155use crate::dom::document::tree_ordered_index_map::TreeOrderedIndexMap;
156use crate::dom::document::websocket::WebSocket;
157use crate::dom::document_embedder_controls::DocumentEmbedderControls;
158use crate::dom::document_event_handler::DocumentEventHandler;
159use crate::dom::document_overlay_handler::DocumentOverlayHandler;
160use crate::dom::documentfragment::DocumentFragment;
161use crate::dom::documentorshadowroot::{
162    DocumentOrShadowRoot, ServoStylesheetInDocument, StylesheetSource,
163};
164use crate::dom::documenttimeline::DocumentTimeline;
165use crate::dom::documenttype::DocumentType;
166use crate::dom::domimplementation::DOMImplementation;
167use crate::dom::domstringlist::DOMStringList;
168use crate::dom::element::attributes::storage::AttrRef;
169use crate::dom::element::{CustomElementCreationMode, Element, ElementCreator};
170use crate::dom::event::{Event, EventBubbles, EventCancelable};
171use crate::dom::eventtarget::EventTarget;
172use crate::dom::execcommand::basecommand::{CommandName, DefaultSingleLineContainerName};
173use crate::dom::execcommand::execcommands::DocumentExecCommandSupport;
174use crate::dom::focusevent::FocusEvent;
175use crate::dom::globalscope::GlobalScope;
176use crate::dom::hashchangeevent::HashChangeEvent;
177use crate::dom::history::History;
178use crate::dom::html::htmlanchorelement::HTMLAnchorElement;
179use crate::dom::html::htmlareaelement::HTMLAreaElement;
180use crate::dom::html::htmlbaseelement::HTMLBaseElement;
181use crate::dom::html::htmlcollection::{CollectionFilter, HTMLCollection};
182use crate::dom::html::htmlelement::HTMLElement;
183use crate::dom::html::htmlembedelement::HTMLEmbedElement;
184use crate::dom::html::htmlformelement::{FormControl, FormControlElementHelpers, HTMLFormElement};
185use crate::dom::html::htmlheadelement::HTMLHeadElement;
186use crate::dom::html::htmlhtmlelement::HTMLHtmlElement;
187use crate::dom::html::htmliframeelement::HTMLIFrameElement;
188use crate::dom::html::htmlimageelement::HTMLImageElement;
189use crate::dom::html::htmlmediaelement::HTMLMediaElement;
190use crate::dom::html::htmlscriptelement::{HTMLScriptElement, ScriptResult, TracedScriptResult};
191use crate::dom::html::htmltitleelement::HTMLTitleElement;
192use crate::dom::htmldetailselement::DetailsNameGroups;
193use crate::dom::intersectionobserver::IntersectionObserver;
194use crate::dom::iterators::ShadowIncluding;
195use crate::dom::keyboardevent::KeyboardEvent;
196use crate::dom::largestcontentfulpaint::LargestContentfulPaint;
197use crate::dom::location::Location;
198use crate::dom::messageevent::MessageEvent;
199use crate::dom::mouseevent::MouseEvent;
200use crate::dom::node::focus::FocusTrigger;
201use crate::dom::node::treewalker::TreeWalker;
202use crate::dom::node::virtualmethods::vtable_for;
203use crate::dom::node::{Node, NodeDamage, NodeFlags, NodeTraits};
204use crate::dom::nodeiterator::NodeIterator;
205use crate::dom::nodelist::NodeList;
206use crate::dom::pagetransitionevent::PageTransitionEvent;
207use crate::dom::performance::performancecontainertiming::PerformanceContainerTiming;
208use crate::dom::performance::performanceentry::PerformanceEntry;
209use crate::dom::performance::performancepainttiming::PerformancePaintTiming;
210use crate::dom::processinginstruction::ProcessingInstruction;
211use crate::dom::range::Range;
212use crate::dom::resizeobserver::{ResizeObservationDepth, ResizeObserver};
213use crate::dom::sanitizer::Sanitizer;
214use crate::dom::selection::Selection;
215use crate::dom::servoparser::ServoParser;
216use crate::dom::shadowroot::shadowroot::ShadowRoot;
217use crate::dom::storageevent::StorageEvent;
218use crate::dom::text::Text;
219use crate::dom::textevent::TextEvent;
220use crate::dom::touchevent::TouchEvent as DomTouchEvent;
221use crate::dom::touchlist::TouchList;
222use crate::dom::trustedtypes::trustedhtml::TrustedHTML;
223use crate::dom::types::{HTMLCanvasElement, VisibilityStateEntry};
224use crate::dom::uievent::UIEvent;
225use crate::dom::window::Window;
226use crate::dom::window::scrolling_box::{ScrollAxisState, ScrollingBox};
227use crate::dom::windowproxy::WindowProxy;
228use crate::dom::xpathevaluator::XPathEvaluator;
229use crate::dom::xpathexpression::XPathExpression;
230use crate::dom::{FlatTreeParent, RootedPromise, WeakRangeVec};
231use crate::event_loop::document_loader::{DocumentLoader, LoadType};
232use crate::event_loop::script_thread::{ScriptThread, SharedRwLocks};
233use crate::event_loop::timers::{OneshotTimerCallback, OneshotTimers};
234use crate::fetch::fetch::DeferredFetchRecordInvokeState;
235use crate::fetch::network_listener::FetchResponseListener;
236use crate::mime::{APPLICATION, CHARSET};
237use crate::navigation::navigate;
238use crate::runtime::script_runtime::compute_size;
239use crate::scripting::script_module::{ModuleRequest, ModuleStatus};
240use crate::tasks::task_manager::TaskManager;
241use crate::tasks::task_source::TaskSourceName;
242use crate::xpath::parse_expression;
243
244#[derive(Clone, Copy, PartialEq)]
245pub(crate) enum FireMouseEventType {
246    Move,
247    Over,
248    Out,
249    Enter,
250    Leave,
251}
252
253impl FireMouseEventType {
254    pub(crate) fn as_str(&self) -> &str {
255        match *self {
256            FireMouseEventType::Move => "mousemove",
257            FireMouseEventType::Over => "mouseover",
258            FireMouseEventType::Out => "mouseout",
259            FireMouseEventType::Enter => "mouseenter",
260            FireMouseEventType::Leave => "mouseleave",
261        }
262    }
263}
264
265#[derive(JSTraceable, MallocSizeOf)]
266pub(crate) struct RefreshRedirectDue {
267    #[no_trace]
268    pub(crate) url: ServoUrl,
269    /// Whether the refresh originated from a `<meta>` element.
270    pub(crate) from_meta_element: bool,
271}
272
273#[derive(Debug, Copy, Clone)]
274pub(crate) enum AbortReason {
275    PipelineExited,
276    DocumentOpen,
277    Destroy,
278    StopLoading,
279    Navigate,
280}
281
282#[derive(Debug)]
283pub(crate) enum SetParserReason {
284    AboutBlankComplete,
285    ParsingHtmlDocument,
286    ParsingHtmlScriptInput,
287    ParsingHtmlFragment,
288    ParsingXmlDocument,
289    #[expect(dead_code)]
290    // AbortReason is only read by the Debug impl.
291    Abort(AbortReason),
292    ParsingBytesChunk,
293    FinishingParser,
294}
295
296/// An LCP candidate paired with its resolved element.
297///
298/// <https://www.w3.org/TR/largest-contentful-paint/#largest-contentful-paint-candidate>
299#[derive(JSTraceable, MallocSizeOf)]
300#[cfg_attr(crown, crown::unrooted_must_root_lint::must_root)]
301struct LCPCandidateAndElement {
302    /// <https://www.w3.org/TR/largest-contentful-paint/#largest-contentful-paint-candidate-element>
303    element: Option<Dom<Element>>,
304    #[no_trace]
305    candidate: LCPCandidate,
306}
307
308/// A Container Timing update paired with its resolved elements, parked until paint
309/// reports the time at which the frame carrying it was composited.
310///
311/// <https://wicg.github.io/container-timing/>
312#[derive(JSTraceable, MallocSizeOf)]
313#[cfg_attr(crown, crown::unrooted_must_root_lint::must_root)]
314struct ContainerTimingRecordAndElements {
315    identifier: DOMString,
316    root_element: Dom<Element>,
317    last_painted_element: Option<Dom<Element>>,
318    #[no_trace]
319    record: ContainerTimingRecord,
320}
321
322impl RefreshRedirectDue {
323    /// Step 13 of <https://html.spec.whatwg.org/multipage/#shared-declarative-refresh-steps>
324    pub(crate) fn invoke(self, cx: &mut JSContext, global: &GlobalScope) {
325        let window = global
326            .downcast::<Window>()
327            .expect("Queued a RefreshRedirectDue on a non-Window globalscope");
328
329        // After the refresh has come due (as defined below),
330        // if the user has not canceled the redirect and, if meta is given,
331        // document's active sandboxing flag set does not have the sandboxed
332        // automatic features browsing context flag set,
333        // then navigate document's node navigable to urlRecord using document,
334        // with historyHandling set to "replace".
335        if self.from_meta_element &&
336            window.Document().has_active_sandboxing_flag(
337                SandboxingFlagSet::SANDBOXED_AUTOMATIC_FEATURES_BROWSING_CONTEXT_FLAG,
338            )
339        {
340            return;
341        }
342        let load_data = window.load_data_for_document(self.url, window.pipeline_id());
343        navigate(
344            cx,
345            window,
346            NavigationHistoryBehavior::Replace,
347            false,
348            load_data,
349        );
350    }
351}
352
353#[derive(Clone, Copy, Debug, JSTraceable, MallocSizeOf, PartialEq)]
354pub(crate) enum IsHTMLDocument {
355    HTMLDocument,
356    NonHTMLDocument,
357}
358
359#[derive(Clone, Copy, Default, MallocSizeOf, PartialEq)]
360pub(crate) enum TheEndLoadingPhase {
361    #[default]
362    Initial,
363    ProcessingDeferredScripts,
364    ProcessingAsSoonAsPossibleScripts,
365    WaitingForLoadEventBlockers,
366    Done,
367}
368
369/// Information about a declarative refresh
370#[derive(JSTraceable, MallocSizeOf)]
371pub(crate) enum DeclarativeRefresh {
372    PendingLoad {
373        #[no_trace]
374        url: ServoUrl,
375        time: u64,
376        /// Whether the refresh originated from a `<meta>` element.
377        from_meta_element: bool,
378    },
379    CreatedAfterLoad,
380}
381
382#[derive(JSTraceable, MallocSizeOf, PartialEq)]
383#[cfg_attr(crown, crown::unrooted_must_root_lint::must_root)]
384struct PendingScrollEvent {
385    /// The target of this pending scroll event.
386    target: Dom<EventTarget>,
387    /// The kind of event.
388    #[no_trace]
389    event: Atom,
390}
391
392impl PendingScrollEvent {
393    fn equivalent(&self, target: &EventTarget, event: &Atom) -> bool {
394        &*self.target == target && self.event == *event
395    }
396}
397
398/// Reasons why a [`Document`] might need a rendering update that is otherwise
399/// untracked via other [`Document`] properties.
400#[derive(Clone, Copy, Debug, Default, JSTraceable, MallocSizeOf)]
401pub(crate) struct RenderingUpdateReason(u8);
402
403bitflags! {
404    impl RenderingUpdateReason: u8 {
405        /// When a `ResizeObserver` starts observing a target, this becomes true, which in turn is a
406        /// signal to the [`ScriptThread`] that a rendering update should happen.
407        const ResizeObserverStartedObservingTarget = 1 << 0;
408        /// When an `IntersectionObserver` starts observing a target, this becomes true, which in turn is a
409        /// signal to the [`ScriptThread`] that a rendering update should happen.
410        const IntersectionObserverStartedObservingTarget = 1 << 1;
411        /// All web fonts have loaded and `fonts.ready` promise has been fulfilled. We want to trigger
412        /// one more rendering update possibility after this happens, so that any potential screenshot
413        /// reflects the up-to-date contents.
414        const FontReadyPromiseFulfilled = 1 << 2;
415    }
416}
417
418/// <https://html.spec.whatwg.org/multipage/#document-load-timing-info>
419#[derive(Clone, Debug, Default, MallocSizeOf)]
420pub(crate) struct NavigationTiming {
421    pub(crate) dom_loading: Cell<Option<CrossProcessInstant>>,
422    /// <https://html.spec.whatwg.org/multipage/#navigation-start-time>
423    pub(crate) navigation_start: Cell<Option<CrossProcessInstant>>,
424    /// <https://html.spec.whatwg.org/multipage/#unload-event-start-time>
425    pub(crate) unload_event_start: Cell<Option<CrossProcessInstant>>,
426    /// <https://html.spec.whatwg.org/multipage/#unload-event-end-time>
427    pub(crate) unload_event_end: Cell<Option<CrossProcessInstant>>,
428    /// <https://html.spec.whatwg.org/multipage/#dom-interactive-time>
429    pub(crate) dom_interactive: Cell<Option<CrossProcessInstant>>,
430    /// <https://html.spec.whatwg.org/multipage/#dom-content-loaded-event-start-time>
431    pub(crate) dom_content_loaded_event_start: Cell<Option<CrossProcessInstant>>,
432    /// <https://html.spec.whatwg.org/multipage/#dom-content-loaded-event-end-time>
433    pub(crate) dom_content_loaded_event_end: Cell<Option<CrossProcessInstant>>,
434    /// <https://html.spec.whatwg.org/multipage/#dom-complete-time>
435    pub(crate) dom_complete: Cell<Option<CrossProcessInstant>>,
436    /// <https://html.spec.whatwg.org/multipage/#load-event-start-time>
437    pub(crate) load_event_start: Cell<Option<CrossProcessInstant>>,
438    /// <https://html.spec.whatwg.org/multipage/#load-event-end-time>
439    pub(crate) load_event_end: Cell<Option<CrossProcessInstant>>,
440    /// Servo-only timing for when top-level content (not iframes) is complete
441    pub(crate) top_level_dom_complete: Cell<Option<CrossProcessInstant>>,
442}
443
444/// <https://dom.spec.whatwg.org/#document>
445#[dom_struct]
446pub(crate) struct Document {
447    node: Node,
448    document_or_shadow_root: DocumentOrShadowRoot,
449    window: Dom<Window>,
450    implementation: MutNullableDom<DOMImplementation>,
451    #[no_trace]
452    content_type: Mime,
453    last_modified: Option<String>,
454    #[no_trace]
455    encoding: Cell<&'static Encoding>,
456    has_browsing_context: bool,
457    is_html_document: bool,
458    #[no_trace]
459    activity: Cell<DocumentActivity>,
460    /// <https://html.spec.whatwg.org/multipage/#the-document%27s-address>
461    #[no_trace]
462    url: AtomicRefCell<ServoUrl>,
463    /// <https://html.spec.whatwg.org/multipage/#concept-document-about-base-url>
464    #[no_trace]
465    about_base_url: DomRefCell<Option<ServoUrl>>,
466    #[ignore_malloc_size_of = "defined in selectors"]
467    #[no_trace]
468    quirks_mode: Cell<QuirksMode>,
469    /// A helper used to process and store data related to input event handling.
470    event_handler: DocumentEventHandler,
471    /// A helper used to process and store data related to focus handling.
472    focus_handler: DocumentFocusHandler,
473    /// A helper used to process and store data related to overlays.
474    overlay_handler: OnceCell<DocumentOverlayHandler>,
475    /// A helper to handle showing and hiding user interface controls in the embedding layer.
476    embedder_controls: DocumentEmbedderControls,
477    id_map: TreeOrderedIndexMap,
478    name_map: TreeOrderedIndexMap,
479    tag_map: DomRefCell<HashMapTracedValues<LocalName, Dom<HTMLCollection>, FxBuildHasher>>,
480    tagns_map: DomRefCell<HashMapTracedValues<QualName, Dom<HTMLCollection>, FxBuildHasher>>,
481    classes_map: DomRefCell<HashMapTracedValues<Vec<Atom>, Dom<HTMLCollection>>>,
482    images: MutNullableDom<HTMLCollection>,
483    embeds: MutNullableDom<HTMLCollection>,
484    links: MutNullableDom<HTMLCollection>,
485    forms: MutNullableDom<HTMLCollection>,
486    scripts: MutNullableDom<HTMLCollection>,
487    anchors: MutNullableDom<HTMLCollection>,
488    applets: MutNullableDom<HTMLCollection>,
489    /// Information about the `<iframes>` in this [`Document`].
490    iframes: IFrameCollection,
491    /// Shared locks used for style attributes, author-origin stylesheets, and user and
492    /// user agent stylesheets in this document. Can be acquired once for accessing many
493    /// objects. This is shared with the owning [`ScriptThread`].
494    #[no_trace]
495    shared_style_locks: SharedRwLocks,
496    /// List of stylesheets associated with nodes in this document. |None| if the list needs to be refreshed.
497    #[custom_trace]
498    stylesheets: DomRefCell<DocumentStylesheetSet<ServoStylesheetInDocument>>,
499    stylesheet_list: MutNullableDom<StyleSheetList>,
500    ready_state: Cell<DocumentReadyState>,
501    /// The script element that is currently executing.
502    current_script: MutNullableDom<HTMLScriptElement>,
503    #[no_trace]
504    current_the_end_loading_phase: Cell<TheEndLoadingPhase>,
505    /// <https://html.spec.whatwg.org/multipage/#pending-parsing-blocking-script>
506    pending_parsing_blocking_script: DomRefCell<Option<PendingScript>>,
507    /// <https://html.spec.whatwg.org/multipage/#script-blocking-style-sheet-set>
508    /// > A Document has a script-blocking style sheet set, which is an ordered set, initially empty.
509    script_blocking_stylesheet_set: DomRefCell<IndexSet<StylesheetContextId>>,
510    /// Number of elements that block the rendering of the page.
511    /// <https://html.spec.whatwg.org/multipage/#implicitly-potentially-render-blocking>
512    render_blocking_element_count: Cell<u32>,
513    /// <https://html.spec.whatwg.org/multipage/#list-of-scripts-that-will-execute-when-the-document-has-finished-parsing>
514    deferred_scripts: PendingInOrderScriptVec,
515    /// <https://html.spec.whatwg.org/multipage/#list-of-scripts-that-will-execute-in-order-as-soon-as-possible>
516    asap_in_order_scripts_list: PendingInOrderScriptVec,
517    /// <https://html.spec.whatwg.org/multipage/#set-of-scripts-that-will-execute-as-soon-as-possible>
518    asap_scripts_set: DomRefCell<Vec<Dom<HTMLScriptElement>>>,
519    /// <https://html.spec.whatwg.org/multipage/#animation-frame-callback-identifier>
520    /// Current identifier of animation frame callback
521    animation_frame_ident: Cell<u32>,
522    /// <https://html.spec.whatwg.org/multipage/#list-of-animation-frame-callbacks>
523    /// List of animation frame callbacks
524    animation_frame_list: DomRefCell<VecDeque<(u32, Option<AnimationFrameCallback>)>>,
525    /// Whether we're in the process of running animation callbacks.
526    ///
527    /// Tracking this is not necessary for correctness. Instead, it is an optimization to avoid
528    /// sending needless `ChangeRunningAnimationsState` messages to `Paint`.
529    running_animation_callbacks: Cell<bool>,
530    /// Tracks all outstanding loads related to this document.
531    loader: DomRefCell<DocumentLoader>,
532    /// The current active HTML parser, to allow resuming after interruptions.
533    current_parser: MutNullableDom<ServoParser>,
534    /// The cached first `base` element with an `href` attribute.
535    base_element: MutNullableDom<HTMLBaseElement>,
536    /// The cached first `base` element, used for its target (doesn't need a href)
537    target_base_element: MutNullableDom<HTMLBaseElement>,
538    /// This field is set to the document itself for inert documents.
539    /// <https://html.spec.whatwg.org/multipage/#appropriate-template-contents-owner-document>
540    appropriate_template_contents_owner_document: MutNullableDom<Document>,
541    /// Information on elements needing restyle to ship over to layout when the
542    /// time comes.
543    pending_restyles: DomRefCell<FxHashMap<Dom<Element>, NoTrace<PendingRestyle>>>,
544    /// A collection of reasons that the [`Document`] needs to be restyled at the next
545    /// opportunity for a reflow. If this is empty, then the [`Document`] does not need to
546    /// be restyled.
547    #[no_trace]
548    needs_restyle: Cell<RestyleReason>,
549    /// The document's origin.
550    #[no_trace]
551    origin: DomRefCell<MutableOrigin>,
552    /// <https://html.spec.whatwg.org/multipage/#dom-document-referrer>
553    referrer: Option<String>,
554    /// <https://html.spec.whatwg.org/multipage/#target-element>
555    target_element: MutNullableDom<Element>,
556    /// <https://html.spec.whatwg.org/multipage/#concept-document-policy-container>
557    #[no_trace]
558    #[conditional_malloc_size_of]
559    policy_container: DomRefCell<StdArc<PolicyContainer>>,
560    /// <https://html.spec.whatwg.org/multipage/#map-of-preloaded-resources>
561    #[no_trace]
562    preloaded_resources: DomRefCell<PreloadedResources>,
563    /// <https://html.spec.whatwg.org/multipage/#ignore-destructive-writes-counter>
564    ignore_destructive_writes_counter: Cell<u32>,
565    /// <https://html.spec.whatwg.org/multipage/#ignore-opens-during-unload-counter>
566    ignore_opens_during_unload_counter: Cell<u32>,
567    /// The number of spurious `requestAnimationFrame()` requests we've received.
568    ///
569    /// A rAF request is considered spurious if nothing was actually reflowed.
570    spurious_animation_frames: Cell<u8>,
571
572    /// Map from ID to set of form control elements that have that ID as
573    /// their 'form' content attribute. Used to reset form controls
574    /// whenever any element with the same ID as the form attribute
575    /// is inserted or removed from the document.
576    /// See <https://html.spec.whatwg.org/multipage/#form-owner>
577    /// It is safe to use FxBuildHasher here as Atoms are in the string_cache
578    form_id_listener_map:
579        DomRefCell<HashMapTracedValues<Atom, HashSet<Dom<Element>>, FxBuildHasher>>,
580    #[no_trace]
581    interactive_time: DomRefCell<ProgressiveWebMetrics>,
582    #[no_trace]
583    tti_window: DomRefCell<InteractiveWindow>,
584    /// <https://html.spec.whatwg.org/multipage/#throw-on-dynamic-markup-insertion-counter>
585    throw_on_dynamic_markup_insertion_counter: Cell<u64>,
586    /// <https://html.spec.whatwg.org/multipage/#page-showing>
587    page_showing: Cell<bool>,
588    /// Whether the document is salvageable.
589    salvageable: Cell<bool>,
590    /// Whether the document was aborted with an active parser
591    active_parser_was_aborted: Cell<bool>,
592    /// Whether the unload event has already been fired.
593    fired_unload: Cell<bool>,
594    /// List of responsive images
595    responsive_images: DomRefCell<Vec<Dom<HTMLImageElement>>>,
596
597    /// [`NavigationTiming`] information for this [`Document`].
598    /// <https://html.spec.whatwg.org/multipage/#load-timing-info>
599    #[no_trace]
600    #[conditional_malloc_size_of]
601    navigation_timing: Rc<NavigationTiming>,
602
603    /// A [`ResourceFetchTiming`] that holds timing information for this [`Document`].
604    #[no_trace]
605    resource_fetch_timing: RefCell<Option<ResourceFetchTiming>>,
606
607    /// Number of outstanding requests to prevent JS or layout from running.
608    script_and_layout_blockers: Cell<u32>,
609    /// List of tasks to execute as soon as last script/layout blocker is removed.
610    #[ignore_malloc_size_of = "Measuring trait objects is hard"]
611    delayed_tasks: DomRefCell<VecDeque<Box<dyn NonSendTaskBox>>>,
612    /// <https://html.spec.whatwg.org/multipage/#completely-loaded>
613    completely_loaded: Cell<bool>,
614    /// Set of shadow roots connected to the document tree.
615    shadow_roots: DomRefCell<FxHashSet<Dom<ShadowRoot>>>,
616    /// Whether any of the shadow roots need the stylesheets flushed.
617    shadow_roots_styles_changed: Cell<bool>,
618    /// List of registered media controls.
619    /// We need to keep this list to allow the media controls to
620    /// access the "privileged" document.servoGetMediaControls(id) API,
621    /// where `id` needs to match any of the registered ShadowRoots
622    /// hosting the media controls UI.
623    media_controls: DomRefCell<HashMap<String, Dom<ShadowRoot>>>,
624    /// A set of dirty HTML canvas elements that need their WebRender images updated the
625    /// next time the rendering is updated.
626    dirty_canvases: DomRefCell<Vec<Dom<HTMLCanvasElement>>>,
627    /// Whether or not animated images need to have their contents updated.
628    has_pending_animated_image_update: Cell<bool>,
629    /// <https://w3c.github.io/slection-api/#dfn-selection>
630    selection: MutNullableDom<Selection>,
631    /// A timeline for animations which is used for synchronizing animations.
632    /// <https://drafts.csswg.org/web-animations/#timeline>
633    timeline: Dom<DocumentTimeline>,
634    /// Animations for this Document
635    animation_manager: AnimationManager,
636    /// The nearest inclusive ancestors to all the nodes that require a restyle.
637    dirty_root: MutNullableDom<Element>,
638    /// <https://html.spec.whatwg.org/multipage/#will-declaratively-refresh>
639    declarative_refresh: DomRefCell<Option<DeclarativeRefresh>>,
640    /// <https://drafts.csswg.org/resize-observer/#dom-document-resizeobservers-slot>
641    ///
642    /// Note: we are storing, but never removing, resize observers.
643    /// The lifetime of resize observers is specified at
644    /// <https://drafts.csswg.org/resize-observer/#lifetime>.
645    /// But implementing it comes with known problems:
646    /// - <https://bugzilla.mozilla.org/show_bug.cgi?id=1596992>
647    /// - <https://github.com/w3c/csswg-drafts/issues/4518>
648    resize_observers: DomRefCell<Vec<Dom<ResizeObserver>>>,
649    /// The set of all fonts loaded by this document.
650    /// <https://drafts.csswg.org/css-font-loading/#font-face-source>
651    fonts: MutNullableDom<FontFaceSet>,
652    /// <https://html.spec.whatwg.org/multipage/#visibility-state>
653    visibility_state: Cell<DocumentVisibilityState>,
654    /// <https://www.iana.org/assignments/http-status-codes/http-status-codes.xhtml>
655    status_code: Option<u16>,
656    /// <https://html.spec.whatwg.org/multipage/#is-initial-about:blank>
657    is_initial_about_blank: Cell<bool>,
658    /// <https://dom.spec.whatwg.org/#document-allow-declarative-shadow-roots>
659    allow_declarative_shadow_roots: Cell<bool>,
660    /// <https://w3c.github.io/webappsec-upgrade-insecure-requests/#insecure-requests-policy>
661    #[no_trace]
662    inherited_insecure_requests_policy: Cell<Option<InsecureRequestsPolicy>>,
663    /// <https://w3c.github.io/webappsec-mixed-content/#categorize-settings-object>
664    has_trustworthy_ancestor_origin: Cell<bool>,
665    /// <https://w3c.github.io/IntersectionObserver/#document-intersectionobservertaskqueued>
666    intersection_observer_task_queued: Cell<bool>,
667    /// Active intersection observers that should be processed by this document in
668    /// the update intersection observation steps.
669    /// <https://w3c.github.io/IntersectionObserver/#run-the-update-intersection-observations-steps>
670    /// > Let observer list be a list of all IntersectionObservers whose root is in the DOM tree of document.
671    /// > For the top-level browsing context, this includes implicit root observers.
672    ///
673    /// Details of which document that should process an observers is discussed further at
674    /// <https://github.com/w3c/IntersectionObserver/issues/525>.
675    ///
676    /// The lifetime of an intersection observer is specified at
677    /// <https://github.com/w3c/IntersectionObserver/issues/525>.
678    intersection_observers: DomRefCell<Vec<Dom<IntersectionObserver>>>,
679    /// <https://html.spec.whatwg.org/multipage/#lazy-load-intersection-observer>
680    lazy_load_intersection_observer: MutNullableDom<IntersectionObserver>,
681    /// The node that is currently highlighted by the devtools
682    highlighted_dom_node: MutNullableDom<Node>,
683    /// Resolved LCP candidate elements, keyed by their [LCPCandidateID].
684    lcp_candidates: DomRefCell<HashMapTracedValues<LCPCandidateID, LCPCandidateAndElement>>,
685    /// The [`PaintTimingInfo`] for this document with [`rendering_update_end_time`] set.
686    /// <https://www.w3.org/TR/paint-timing/#paint-timing-info>
687    #[no_trace]
688    paint_timing_info: Cell<PaintTimingInfo>,
689    /// Container Timing updates awaiting a paint time, keyed by their [ContainerTimingID].
690    container_timing_records:
691        DomRefCell<HashMapTracedValues<ContainerTimingID, ContainerTimingRecordAndElements>>,
692    /// The first time each container was painted, keyed by
693    /// [`ContainerTimingRecord::root_element`]. Layout has no notion of when compositing
694    /// happens, so this is remembered here, from the paint time of the first entry
695    /// reported for a given container.
696    /// <https://wicg.github.io/container-timing/#dom-performancecontainertiming-firstrendertime>
697    #[no_trace]
698    container_first_render_times: DomRefCell<HashMap<OpaqueNode, CrossProcessInstant>>,
699    /// The constructed stylesheet that is adopted by this [Document].
700    /// The DOM-side adopted stylesheet list for this [Document], including duplicates.
701    /// <https://drafts.csswg.org/cssom/#dom-documentorshadowroot-adoptedstylesheets>
702    adopted_stylesheets: DomRefCell<Vec<Dom<CSSStyleSheet>>>,
703    /// <https://drafts.csswg.org/cssom-view/#document-pending-scroll-events>
704    /// > Each Document has an associated list of pending scroll events, which stores
705    /// > pairs of (EventTarget, DOMString), initially empty.
706    pending_scroll_events: DomRefCell<Vec<PendingScrollEvent>>,
707    /// Other reasons that a rendering update might be required for this [`Document`].
708    rendering_update_reasons: Cell<RenderingUpdateReason>,
709    /// Whether or not this [`Document`] is waiting on canvas image updates. If it is
710    /// waiting it will not do any new layout until the canvas images are up-to-date in
711    /// the renderer.
712    waiting_on_canvas_image_updates: Cell<bool>,
713    /// Whether we have already noted that the document element was removed.
714    root_removal_noted: Cell<bool>,
715    /// The current rendering epoch, which is used to track updates in the renderer.
716    ///
717    ///   - Every display list update also advances the Epoch, so that the renderer knows
718    ///     when a particular display list is ready in order to take a screenshot.
719    ///   - Canvas image updates happen asynchronously and are tagged with this Epoch. Until
720    ///     those asynchronous updates are complete, the `Document` will not perform any
721    ///     more rendering updates.
722    #[no_trace]
723    current_rendering_epoch: Cell<Epoch>,
724    /// The global custom element reaction stack for this script thread.
725    #[conditional_malloc_size_of]
726    custom_element_reaction_stack: Rc<CustomElementReactionStack>,
727    #[no_trace]
728    /// <https://html.spec.whatwg.org/multipage/#active-sandboxing-flag-set>,
729    active_sandboxing_flag_set: Cell<SandboxingFlagSet>,
730    #[no_trace]
731    /// The [`SandboxingFlagSet`] use to create the browsing context for this [`Document`].
732    /// These are cached here as they cannot always be retrieved readily if the owner of
733    /// browsing context (either `<iframe>` or popup) might be in a different `ScriptThread`.
734    ///
735    /// See
736    /// <https://html.spec.whatwg.org/multipage/#determining-the-creation-sandboxing-flags>.
737    creation_sandboxing_flag_set: Cell<SandboxingFlagSet>,
738    /// The cached favicon for that document.
739    #[no_trace]
740    favicon: RefCell<Option<Image>>,
741    /// Whether an explicit `<link rel="icon">` was ever found in this [`Document`].
742    ever_had_favicon_link: Cell<bool>,
743
744    /// All websockets created that are associated with this document.
745    websockets: DOMTracker<WebSocket>,
746
747    /// <https://html.spec.whatwg.org/multipage/#playing-the-media-resource>
748    /// Active media elements that are kept alive while playing or eligible for autoplay.
749    active_media_elements: DomRefCell<FxHashSet<Dom<HTMLMediaElement>>>,
750
751    /// <https://html.spec.whatwg.org/multipage/#details-name-group>
752    details_name_groups: DomRefCell<Option<DetailsNameGroups>>,
753
754    /// <https://html.spec.whatwg.org/multipage/#registerprotocolhandler()-automation-mode>
755    #[no_trace]
756    protocol_handler_automation_mode: RefCell<CustomHandlersAutomationMode>,
757
758    /// Reflect the value of that preferences to prevent paying the cost of a RwLock access.
759    layout_animations_test_enabled: bool,
760
761    /// <https://w3c.github.io/editing/docs/execCommand/#state-override>
762    #[no_trace]
763    state_override: DomRefCell<FxHashMap<CommandName, bool>>,
764
765    /// <https://w3c.github.io/editing/docs/execCommand/#value-override>
766    #[no_trace]
767    value_override: DomRefCell<FxHashMap<CommandName, DOMString>>,
768
769    /// <https://w3c.github.io/editing/docs/execCommand/#default-single-line-container-name>
770    #[no_trace]
771    default_single_line_container_name: Cell<DefaultSingleLineContainerName>,
772
773    /// <https://w3c.github.io/editing/docs/execCommand/#css-styling-flag>
774    css_styling_flag: Cell<bool>,
775
776    /// Data necessary for maintaining the accessibility tree.
777    accessibility_data: DomRefCell<AccessibilityData>,
778
779    /// <https://html.spec.whatwg.org/multipage/#iframe-load-in-progress>
780    iframe_load_in_progress: Cell<bool>,
781    /// <https://html.spec.whatwg.org/multipage/#mute-iframe-load>
782    mute_iframe_load: Cell<bool>,
783
784    /// The mechanism by which time-outs and intervals are scheduled.
785    /// <https://html.spec.whatwg.org/multipage/#timers>
786    timers: OneshotTimers,
787
788    #[no_trace]
789    pipeline_id: PipelineId,
790
791    /// A [`TaskManager`] for this [`Window`].
792    #[conditional_malloc_size_of]
793    task_manager: Rc<TaskManager>,
794
795    #[ignore_malloc_size_of = "ImageCache"]
796    #[no_trace]
797    image_cache: StdArc<dyn ImageCache>,
798
799    /// <https://html.spec.whatwg.org/multipage/#doc-history>
800    history: MutNullableDom<History>,
801
802    /// Theme specific for this document, set by a meta element
803    #[no_trace]
804    theme: Cell<Option<Theme>>,
805
806    /// A theme override provided by devtools.
807    #[no_trace]
808    theme_override: Cell<Option<Theme>>,
809
810    /// Language specific for this document, set by a meta element
811    #[no_trace]
812    default_language: AtomicRefCell<Option<String>>,
813
814    /// True if this document is no longer the active document of its associated
815    /// window.
816    window_detached: Cell<bool>,
817
818    /// <https://html.spec.whatwg.org/multipage/#concept-document-ancestor-origins-list>
819    ancestor_origins_list: MutNullableDom<DOMStringList>,
820
821    /// <https://html.spec.whatwg.org/multipage/#concept-document-internal-ancestor-origin-objects-list>
822    #[no_trace]
823    internal_ancestor_origin_objects_list: RefCell<Option<Vec<ImmutableOrigin>>>,
824
825    /// A vector of weak references to Range instances that are live on
826    /// this document.
827    live_ranges: WeakRangeVec,
828
829    /// module map is used when importing JavaScript modules
830    /// <https://html.spec.whatwg.org/multipage/#concept-settings-object-module-map>
831    #[ignore_malloc_size_of = "mozjs"]
832    module_map: DomRefCell<HashMapTracedValues<ModuleRequest, ModuleStatus>>,
833}
834
835impl Document {
836    pub(crate) fn module_map(
837        &self,
838    ) -> &DomRefCell<HashMapTracedValues<ModuleRequest, ModuleStatus>> {
839        &self.module_map
840    }
841
842    pub(crate) fn history(&self, cx: &mut JSContext) -> DomRoot<History> {
843        self.history.or_init(|| History::new(cx, &self.window))
844    }
845
846    pub(crate) fn image_cache(&self) -> StdArc<dyn ImageCache> {
847        self.image_cache.clone()
848    }
849
850    pub(crate) fn task_manager(&self) -> Rc<TaskManager> {
851        self.task_manager.clone()
852    }
853
854    pub(crate) fn timers(&self) -> &OneshotTimers {
855        &self.timers
856    }
857
858    pub(crate) fn pipeline_id(&self) -> PipelineId {
859        self.pipeline_id
860    }
861
862    /// <https://html.spec.whatwg.org/multipage/#unloading-document-cleanup-steps>
863    fn unloading_cleanup_steps(&self, cx: &mut JSContext) {
864        // > https://fullscreen.spec.whatwg.org/#model
865        // > "Whenever the unloading document cleanup steps run with a document, fully exit fullscreen document."
866        self.overlay_handler().fully_exit_fullscreen(cx);
867
868        // Step 1. Let window be document's relevant global object.
869        // Step 2. For each WebSocket object webSocket whose relevant global object is window, make disappear webSocket.
870        if self.close_outstanding_websockets() {
871            // If this affected any WebSocket objects, then make document unsalvageable given document and "websocket".
872            self.salvageable.set(false);
873        }
874
875        self.clean_up_media_elements(cx.no_gc());
876
877        // Step 3. For each WebTransport object transport whose relevant global object is window, run the context cleanup steps given transport.
878        // TODO
879
880        // Step 4. If document's salvageable state is false, then:
881        if !self.salvageable.get() && !self.window_detached() {
882            let global_scope = self.window.as_global_scope();
883
884            // Step 4.1. For each EventSource object eventSource whose relevant global object is equal to window, forcibly close eventSource.
885            global_scope.close_event_sources();
886
887            // Step 4.2. Clear window's map of active timers.
888            self.timers.clear();
889
890            // Ensure the constellation discards all bfcache information for this document.
891            let msg = ScriptToConstellationMessage::DiscardDocument;
892            let _ = global_scope.script_to_constellation_chan().send(msg);
893        }
894    }
895
896    pub(crate) fn track_websocket(&self, websocket: &WebSocket) {
897        self.websockets.track(websocket);
898    }
899
900    fn close_outstanding_websockets(&self) -> bool {
901        let mut closed_any_websocket = false;
902        self.websockets.for_each(|websocket: DomRoot<WebSocket>| {
903            if websocket.make_disappear() {
904                closed_any_websocket = true;
905            }
906        });
907        closed_any_websocket
908    }
909
910    pub(crate) fn register_active_media_element(&self, element: &HTMLMediaElement) {
911        self.active_media_elements
912            .borrow_mut()
913            .insert(Dom::from_ref(element));
914    }
915
916    pub(crate) fn unregister_active_media_element(&self, element: &HTMLMediaElement) {
917        self.active_media_elements
918            .borrow_mut()
919            .remove(&Dom::from_ref(element));
920    }
921
922    fn clean_up_media_elements(&self, no_gc: &NoGC) {
923        let media_elements: Vec<DomRoot<HTMLMediaElement>> = self
924            .active_media_elements
925            .borrow()
926            .iter()
927            .map(|e| DomRoot::from_ref(&**e))
928            .collect();
929        self.active_media_elements.borrow_mut().clear();
930        for element in &media_elements {
931            element.clean_up_on_document_unload(self, no_gc);
932        }
933    }
934
935    fn document_element_changed(&self) {
936        if self.GetDocumentElement().is_some() {
937            // This ensures that if the document element is removed in the future, it
938            // will trigger a new empty display list.
939            self.root_removal_noted.set(false);
940        } else if !self.root_removal_noted.get() {
941            // If there is no document element, attempt to trigger a new root removal update,
942            // but do not do any updating of the dirty root or HAS_DIRTY_DESCENDANTS flags.
943            self.add_restyle_reason(RestyleReason::DOMChanged);
944            self.root_removal_noted.set(true);
945        }
946    }
947
948    /// This is a port of Gecko's restyle root architecture. The idea is that we track a
949    /// node which is the root of restyle damage. Below that root, certain nodes can be
950    /// marked with a HAS_DIRTY_DESCENDANTS flag which means they should be traversed
951    /// during styling and damage propagation. Above the dirty root nothing should be
952    /// marked with the HAS_DIRTY_DESCENDANTS flag.
953    ///
954    /// The overall algorithm is as follows:
955    /// * When the first dirty element is noted, we just set it as the restyle root.
956    /// * When additional dirty elements are noted, we propagate the given bit up
957    ///   the tree, until we either reach the dirty root or the document root.
958    /// * If we reach the document root, we then propagate the HAS_DIRTY_DESCENDANTS
959    ///   flags up the tree until we cross the path of the new root. Once
960    ///   we find this common ancestor, we record it as the restyle root, and then
961    ///   clear the bits between the new restyle root and the document root.
962    pub(crate) fn note_dirty_element(&self, no_gc: &NoGC, element: &Element) {
963        let node = element.upcast::<Node>();
964
965        debug_assert!(*node.owner_doc() == *self);
966        if !node.is_connected() {
967            return;
968        }
969
970        let parent_element = match node.parent_in_flat_tree(no_gc) {
971            FlatTreeParent::Parent(parent) => UnrootedDom::downcast::<Element>(parent),
972            FlatTreeParent::NotInFlatTree | FlatTreeParent::RootNode => return,
973        };
974
975        // The node may not have a parent element if it is a direct descendant of the
976        // `Document` node (i.e. it is the document element aka the `<html>` element in HTML
977        // documents).
978        if let Some(parent_element) = parent_element {
979            // If the parent isn't styled, then it either isn't part of the flat tree or will
980            // be styled later, ensuring the layout of the dirtied node as well.
981            if !parent_element.is_styled() {
982                return;
983            }
984            // If the parent has `display: none`, the change that caused the node to be dirty
985            // will not affect style or layout.
986            if parent_element.is_display_none() {
987                return;
988            }
989        }
990
991        let Some(old_dirty_root) = self.dirty_root.get() else {
992            node.set_flag(NodeFlags::HAS_DIRTY_DESCENDANTS, true);
993            self.set_dirty_root(no_gc, Some(element));
994            return;
995        };
996
997        let old_dirty_root_node = old_dirty_root.upcast::<Node>();
998        for ancestor in element
999            .upcast::<Node>()
1000            .inclusive_ancestors_in_flat_tree_unrooted(no_gc)
1001        {
1002            // Never mark the Document node as having dirty descendants. It's never the dirty root.
1003            if !ancestor.is::<Element>() {
1004                break;
1005            }
1006
1007            if ancestor.get_flag(NodeFlags::HAS_DIRTY_DESCENDANTS) {
1008                return;
1009            }
1010
1011            ancestor.set_flag(NodeFlags::HAS_DIRTY_DESCENDANTS, true);
1012
1013            // If this node is already under the existing dirty root, there is nothing else to
1014            // do apart from marking this node as having dirty descendants. We need to ensure
1015            // we mark the root as having dirty descendants now because that has become true.
1016            if old_dirty_root_node == &**ancestor {
1017                return;
1018            }
1019        }
1020
1021        let common_element_ancestor = old_dirty_root_node
1022            .inclusive_ancestors_in_flat_tree_unrooted(no_gc)
1023            .skip(1) // Skip the old root itself.
1024            .find_map(|ancestor| {
1025                // Never mark the Document node as having dirty descendants. It's never the dirty root.
1026                let element = ancestor.downcast::<Element>().map(DomRoot::from_ref)?;
1027                if ancestor.get_flag(NodeFlags::HAS_DIRTY_DESCENDANTS) {
1028                    return Some(element);
1029                }
1030                ancestor.set_flag(NodeFlags::HAS_DIRTY_DESCENDANTS, true);
1031                None
1032            });
1033
1034        // In the case that there was no common ancestor dirty root, one or both of the nodes
1035        // is not in the flat tree any longer. When this happens just move the dirty root to
1036        // the document element.
1037        let Some(new_dirty_root) = common_element_ancestor else {
1038            let new_dirty_root = self.GetDocumentElement();
1039            if let Some(new_dirty_root) = new_dirty_root.as_ref() {
1040                new_dirty_root
1041                    .upcast::<Node>()
1042                    .set_flag(NodeFlags::HAS_DIRTY_DESCENDANTS, true);
1043            }
1044            self.set_dirty_root(no_gc, new_dirty_root.as_deref());
1045            return;
1046        };
1047
1048        // Now mark all nodes *above* the new dirty root as not having dirty descendants
1049        // to ensure our invariant that nothing above the dirty root is marked with this
1050        // flag.
1051        for ancestor in new_dirty_root
1052            .upcast::<Node>()
1053            .inclusive_ancestors_in_flat_tree_unrooted(no_gc)
1054            .skip(1)
1055        {
1056            ancestor.set_flag(NodeFlags::HAS_DIRTY_DESCENDANTS, false)
1057        }
1058
1059        self.set_dirty_root(no_gc, Some(&*new_dirty_root));
1060    }
1061
1062    fn set_dirty_root(&self, no_gc: &NoGC, new_dirty_root: Option<&Element>) {
1063        // Assertion: No nodes above the dirty root should be marked with the HAS_DIRTY_DESCENDANTS flag.
1064        debug_assert!(new_dirty_root.as_ref().is_none_or(|new_dirty_root| {
1065            new_dirty_root
1066                .upcast::<Node>()
1067                .inclusive_ancestors_in_flat_tree_unrooted(no_gc)
1068                .skip(1)
1069                .all(|node| !node.get_flag(NodeFlags::HAS_DIRTY_DESCENDANTS))
1070        }));
1071        self.dirty_root.set(new_dirty_root);
1072    }
1073
1074    pub(crate) fn take_dirty_root(&self) -> Option<DomRoot<Element>> {
1075        self.dirty_root.take()
1076    }
1077
1078    #[inline]
1079    pub(crate) fn loader(&self) -> Ref<'_, DocumentLoader> {
1080        self.loader.borrow()
1081    }
1082
1083    #[inline]
1084    pub(crate) fn loader_mut(&self) -> RefMut<'_, DocumentLoader> {
1085        self.loader.borrow_mut()
1086    }
1087
1088    #[inline]
1089    pub(crate) fn has_browsing_context(&self) -> bool {
1090        self.has_browsing_context
1091    }
1092
1093    /// <https://html.spec.whatwg.org/multipage/#concept-document-bc>
1094    #[inline]
1095    pub(crate) fn browsing_context(&self) -> Option<DomRoot<WindowProxy>> {
1096        if self.has_browsing_context {
1097            self.window.undiscarded_window_proxy()
1098        } else {
1099            None
1100        }
1101    }
1102
1103    pub(crate) fn webview_id(&self) -> WebViewId {
1104        self.window.webview_id()
1105    }
1106
1107    #[inline]
1108    pub(crate) fn window(&self) -> &Window {
1109        &self.window
1110    }
1111
1112    #[inline]
1113    pub(crate) fn is_html_document(&self) -> bool {
1114        self.is_html_document
1115    }
1116
1117    pub(crate) fn is_xhtml_document(&self) -> bool {
1118        self.content_type.matches(APPLICATION, "xhtml+xml")
1119    }
1120
1121    /// <https://html.spec.whatwg.org/multipage/#fully-active>
1122    pub(crate) fn is_fully_active(&self) -> bool {
1123        // > A Document d is said to be fully active when d is the active document of a
1124        // > navigable navigable, and either navigable is a top-level traversable or
1125        // > navigable's container document is fully active.
1126        self.is_active() &&
1127            (self.window.is_top_level() || self.activity.get() == DocumentActivity::FullyActive)
1128    }
1129
1130    /// <https://html.spec.whatwg.org/multipage/#nav-document>
1131    pub(crate) fn is_active(&self) -> bool {
1132        // > A navigable's active document is its active session history entry's document.
1133        //
1134        // The first two checks stand in for when the document is not the active session history
1135        // entry's document, as when that happens they will be false. The session history entry
1136        // is not really implemented in script in the same way the specification says.
1137        self.browsing_context().is_some() &&
1138            !self.window_detached() &&
1139            self.activity.get() != DocumentActivity::Inactive
1140    }
1141
1142    #[inline]
1143    pub(crate) fn current_rendering_epoch(&self) -> Epoch {
1144        self.current_rendering_epoch.get()
1145    }
1146
1147    /// Get the [`Selection`] instance for this [`Document`] if there is one or `None`.
1148    #[inline]
1149    pub(crate) fn selection(&self) -> Option<DomRoot<Selection>> {
1150        self.selection.get()
1151    }
1152
1153    pub(crate) fn set_activity(&self, cx: &mut JSContext, activity: DocumentActivity) {
1154        // This function should only be called on documents with a browsing context
1155        assert!(self.has_browsing_context);
1156        if activity == self.activity.get() {
1157            return;
1158        }
1159
1160        // Set the document's activity level, reflow if necessary, and suspend or resume timers.
1161        self.activity.set(activity);
1162        let media = ServoMedia::get();
1163        let pipeline_id = self.window().pipeline_id();
1164        let client_context_id =
1165            ClientContextId::build(pipeline_id.namespace_id.0, pipeline_id.index.0.get());
1166
1167        if activity != DocumentActivity::FullyActive {
1168            if !self.window_detached() {
1169                self.window().suspend(cx);
1170            }
1171            media.suspend(&client_context_id);
1172            return;
1173        }
1174
1175        if self.window_detached() {
1176            return;
1177        }
1178
1179        self.title_changed();
1180        self.notify_embedder_favicon();
1181        self.dirty_all_nodes(cx.no_gc());
1182        self.window().resume(cx);
1183        media.resume(&client_context_id);
1184
1185        if self.ready_state.get() != DocumentReadyState::Complete {
1186            return;
1187        }
1188
1189        // This step used to be Step 4.6 in html.spec.whatwg.org/multipage/#history-traversal
1190        // But it's now Step 4 in https://html.spec.whatwg.org/multipage/#reactivate-a-document
1191        // TODO: See #32687 for more information.
1192        let document = Trusted::new(self);
1193        self.owner_global()
1194            .task_manager()
1195            .dom_manipulation_task_source()
1196            .queue(task!(fire_pageshow_event: move |cx| {
1197                let document = document.root();
1198                let window = document.window();
1199                // Step 4.6.1
1200                if document.page_showing.get() {
1201                    return;
1202                }
1203                // Step 4.6.2 Set document's page showing flag to true.
1204                document.page_showing.set(true);
1205                // Step 4.6.3 Update the visibility state of document to "visible".
1206                document.update_visibility_state(cx, DocumentVisibilityState::Visible);
1207                // Step 4.6.4 Fire a page transition event named pageshow at document's relevant
1208                // global object with true.
1209                let event = PageTransitionEvent::new(
1210                    cx,
1211                    window,
1212                    atom!("pageshow"),
1213                    false, // bubbles
1214                    false, // cancelable
1215                    true, // persisted
1216                );
1217                let event = event.upcast::<Event>();
1218                event.set_trusted(true);
1219                window.dispatch_event_with_target_override(cx, event);
1220            }))
1221    }
1222
1223    pub(crate) fn origin(&self) -> Ref<'_, MutableOrigin> {
1224        self.origin.borrow()
1225    }
1226
1227    /// <https://www.w3.org/TR/paint-timing/#paint-timing-eligible>
1228    pub(crate) fn paint_timing_eligible(&self) -> bool {
1229        // A browsing context ctx is paint-timing eligible when one of the
1230        // following apply:
1231        // > ctx is a top-level browsing context.
1232        if self.window().is_top_level() {
1233            return true;
1234        }
1235        // > ctx is a nested browsing context, and the user agent has
1236        // > configured ctx to report paint timing.
1237        if let Some(top_level_document) = self.window().top_level_document_if_local() {
1238            // > > a user agent may decide to disable paint-timing for
1239            // > > cross-origin iframes, as in some scenarios their
1240            // > > paint-timing might reveal information about the main frame.
1241            return self.origin().same_origin(&top_level_document.origin());
1242        };
1243        false
1244    }
1245
1246    /// Part of <https://html.spec.whatwg.org/multipage/#navigate-ua-inline>
1247    /// TODO: Remove this when we create documents after processing headers
1248    pub(crate) fn mark_as_internal(&self) {
1249        *self.origin.borrow_mut() = MutableOrigin::new(ImmutableOrigin::new_opaque());
1250        self.window().update_jsprincipals_from_document(self);
1251    }
1252
1253    pub(crate) fn set_protocol_handler_automation_mode(&self, mode: CustomHandlersAutomationMode) {
1254        *self.protocol_handler_automation_mode.borrow_mut() = mode;
1255    }
1256
1257    /// <https://dom.spec.whatwg.org/#concept-document-url>
1258    pub(crate) fn url(&self) -> ServoUrl {
1259        self.url.borrow().clone()
1260    }
1261
1262    pub(crate) fn set_url(&self, url: ServoUrl) {
1263        *self.url.borrow_mut() = url;
1264    }
1265
1266    pub(crate) fn about_base_url(&self) -> Option<ServoUrl> {
1267        self.about_base_url.borrow().clone()
1268    }
1269
1270    pub(crate) fn set_about_base_url(&self, about_base_url: Option<ServoUrl>) {
1271        *self.about_base_url.borrow_mut() = about_base_url;
1272    }
1273
1274    /// <https://html.spec.whatwg.org/multipage/#fallback-base-url>
1275    pub(crate) fn fallback_base_url(&self) -> ServoUrl {
1276        // Step 1. If document's URL matches about:blank or matches about:srcdoc,
1277        // and document's about base URL is non-null, then return document's about base URL.
1278        let document_url = self.url();
1279        if (document_url.matches_about_blank() || document_url.matches_about_srcdoc()) &&
1280            let Some(about_base_url) = self.about_base_url()
1281        {
1282            return about_base_url;
1283        }
1284
1285        // Step 2. Return document's URL.
1286        document_url
1287    }
1288
1289    /// <https://html.spec.whatwg.org/multipage/#document-base-url>
1290    pub(crate) fn base_url(&self) -> ServoUrl {
1291        match self.base_element() {
1292            // Step 1.
1293            None => self.fallback_base_url(),
1294            // Step 2.
1295            Some(base) => base.frozen_base_url(),
1296        }
1297    }
1298
1299    pub(crate) fn add_restyle_reason(&self, reason: RestyleReason) {
1300        self.needs_restyle.set(self.needs_restyle.get() | reason)
1301    }
1302
1303    pub(crate) fn clear_restyle_reasons(&self) {
1304        self.needs_restyle.set(RestyleReason::empty());
1305    }
1306
1307    pub(crate) fn stylesheets_changed_since_last_reflow(&self) -> bool {
1308        self.stylesheets.borrow().has_changed()
1309    }
1310
1311    pub(crate) fn restyle_reason(&self, no_gc: &NoGC) -> RestyleReason {
1312        let mut condition = self.needs_restyle.get();
1313        if self.stylesheets_changed_since_last_reflow() {
1314            condition.insert(RestyleReason::StylesheetsChanged);
1315        }
1316
1317        // FIXME: This should check the dirty bit on the document,
1318        // not the document element. Needs some layout changes to make
1319        // that workable.
1320        if let Some(root) = self.get_document_element_unrooted(no_gc) &&
1321            root.has_dirty_descendants()
1322        {
1323            condition.insert(RestyleReason::DOMChanged);
1324        }
1325
1326        if !self.pending_restyles.borrow().is_empty() {
1327            condition.insert(RestyleReason::PendingRestyles);
1328        }
1329
1330        condition
1331    }
1332
1333    /// Returns the first `base` element in the DOM that has an `href` attribute.
1334    pub(crate) fn base_element(&self) -> Option<DomRoot<HTMLBaseElement>> {
1335        self.base_element.get()
1336    }
1337
1338    /// Returns the first `base` element in the DOM (doesn't need to have an `href` attribute).
1339    pub(crate) fn target_base_element(&self) -> Option<DomRoot<HTMLBaseElement>> {
1340        self.target_base_element.get()
1341    }
1342
1343    /// Refresh the cached first base element in the DOM.
1344    pub(crate) fn refresh_base_element(&self, cx: &mut JSContext) {
1345        if let Some(base_element) = self.base_element.get() {
1346            base_element.clear_frozen_base_url();
1347        }
1348        let new_base_element = self
1349            .upcast::<Node>()
1350            .traverse_preorder(ShadowIncluding::No)
1351            .filter_map(DomRoot::downcast::<HTMLBaseElement>)
1352            .find(|element| {
1353                element
1354                    .upcast::<Element>()
1355                    .has_attribute(&local_name!("href"))
1356            });
1357        if let Some(ref new_base_element) = new_base_element {
1358            new_base_element.set_frozen_base_url(cx);
1359        }
1360        self.base_element.set(new_base_element.as_deref());
1361
1362        let new_target_base_element = self
1363            .upcast::<Node>()
1364            .traverse_preorder(ShadowIncluding::No)
1365            .filter_map(DomRoot::downcast::<HTMLBaseElement>)
1366            .next();
1367        self.target_base_element
1368            .set(new_target_base_element.as_deref());
1369    }
1370
1371    pub(crate) fn quirks_mode(&self) -> QuirksMode {
1372        self.quirks_mode.get()
1373    }
1374
1375    pub(crate) fn set_quirks_mode(&self, new_mode: QuirksMode) {
1376        let old_mode = self.quirks_mode.replace(new_mode);
1377
1378        if old_mode != new_mode {
1379            self.window.layout_mut().set_quirks_mode(new_mode);
1380        }
1381    }
1382
1383    pub(crate) fn encoding(&self) -> &'static Encoding {
1384        self.encoding.get()
1385    }
1386
1387    pub(crate) fn set_encoding(&self, encoding: &'static Encoding) {
1388        self.encoding.set(encoding);
1389    }
1390
1391    pub(crate) fn content_and_heritage_changed(&self, no_gc: &NoGC, node: &Node) {
1392        if node.is::<Document>() {
1393            self.document_element_changed();
1394        }
1395
1396        // TODO: A change to the children of a node only affects style when dealing with
1397        // selectors like `:has()`, so the application of this restyle should be more
1398        // targeted like in Gecko.
1399        // See https://searchfox.org/firefox-main/rev/7d438b99e58d16388e4327f2460d14ad4c8be075/layout/style/RestyleManager.cpp#245.
1400        node.dirty(no_gc, NodeDamage::ContentOrHeritage);
1401    }
1402
1403    /// Remove any existing association between the provided id and any elements in this document.
1404    pub(crate) fn unregister_element_id(&self, cx: &mut JSContext, id: &Atom) {
1405        self.id_map.remove(id);
1406        self.reset_form_owner_for_listeners(cx, id);
1407    }
1408
1409    /// Associate an element present in this document with the provided id.
1410    pub(crate) fn register_element_id(&self, cx: &mut JSContext, element: &Element, id: &Atom) {
1411        self.id_map.add(id, element);
1412        self.reset_form_owner_for_listeners(cx, id);
1413    }
1414
1415    /// Remove any existing association between the provided name and any elements in this document.
1416    pub(crate) fn unregister_element_name(&self, name: &Atom) {
1417        self.name_map.remove(name);
1418    }
1419
1420    /// Associate an element present in this document with the provided name.
1421    pub(crate) fn register_element_name(&self, element: &Element, name: &Atom) {
1422        self.name_map.add(name, element);
1423    }
1424
1425    pub(crate) fn register_form_id_listener<T: ?Sized + FormControl>(
1426        &self,
1427        id: DOMString,
1428        listener: &T,
1429    ) {
1430        let mut map = self.form_id_listener_map.borrow_mut();
1431        let listener = listener.to_element();
1432        let set = map.entry(Atom::from(id)).or_default();
1433        set.insert(Dom::from_ref(listener));
1434    }
1435
1436    pub(crate) fn unregister_form_id_listener<T: ?Sized + FormControl>(
1437        &self,
1438        id: DOMString,
1439        listener: &T,
1440    ) {
1441        let mut map = self.form_id_listener_map.borrow_mut();
1442        if let Occupied(mut entry) = map.entry(Atom::from(id)) {
1443            entry
1444                .get_mut()
1445                .remove(&Dom::from_ref(listener.to_element()));
1446            if entry.get().is_empty() {
1447                entry.remove();
1448            }
1449        }
1450    }
1451
1452    /// <https://html.spec.whatwg.org/multipage/#find-a-potential-indicated-element>
1453    fn find_a_potential_indicated_element(
1454        &self,
1455        cx: &mut JSContext,
1456        fragment: &str,
1457    ) -> Option<DomRoot<Element>> {
1458        // Step 1. If there is an element in the document tree whose root is
1459        // document and that has an ID equal to fragment, then return the first such element in tree order.
1460        // Step 3. Return null.
1461        self.get_element_by_id(cx.no_gc(), &Atom::from(fragment))
1462            // Step 2. If there is an a element in the document tree whose root is
1463            // document that has a name attribute whose value is equal to fragment,
1464            // then return the first such element in tree order.
1465            .or_else(|| self.get_anchor_by_name(cx, fragment))
1466    }
1467
1468    /// Attempt to find a named element in this page's document.
1469    /// <https://html.spec.whatwg.org/multipage/#the-indicated-part-of-the-document>
1470    fn select_indicated_part(&self, cx: &mut JSContext, fragment: &str) -> Option<DomRoot<Node>> {
1471        // Step 1. If document's URL does not equal url with exclude fragments set to true, then return null.
1472        //
1473        // Already handled by calling function
1474
1475        // Step 2. Let fragment be url's fragment.
1476        //
1477        // Already handled by calling function
1478
1479        // Step 3. If fragment is the empty string, then return the special value top of the document.
1480        if fragment.is_empty() {
1481            return Some(DomRoot::from_ref(self.upcast()));
1482        }
1483        // Step 4. Let potentialIndicatedElement be the result of finding a potential indicated element given document and fragment.
1484        if let Some(potential_indicated_element) =
1485            self.find_a_potential_indicated_element(cx, fragment)
1486        {
1487            // Step 5. If potentialIndicatedElement is not null, then return potentialIndicatedElement.
1488            return Some(DomRoot::upcast(potential_indicated_element));
1489        }
1490        // Step 6. Let fragmentBytes be the result of percent-decoding fragment.
1491        let fragment_bytes = percent_decode(fragment.as_bytes());
1492        // Step 7. Let decodedFragment be the result of running UTF-8 decode without BOM on fragmentBytes.
1493        let Ok(decoded_fragment) = fragment_bytes.decode_utf8() else {
1494            return None;
1495        };
1496        // Step 8. Set potentialIndicatedElement to the result of finding a potential indicated element given document and decodedFragment.
1497        if let Some(potential_indicated_element) =
1498            self.find_a_potential_indicated_element(cx, &decoded_fragment)
1499        {
1500            // Step 9. If potentialIndicatedElement is not null, then return potentialIndicatedElement.
1501            return Some(DomRoot::upcast(potential_indicated_element));
1502        }
1503        // Step 10. If decodedFragment is an ASCII case-insensitive match for the string top, then return the top of the document.
1504        if decoded_fragment.eq_ignore_ascii_case("top") {
1505            return Some(DomRoot::from_ref(self.upcast()));
1506        }
1507        // Step 11. Return null.
1508        None
1509    }
1510
1511    /// <https://html.spec.whatwg.org/multipage/#scroll-to-the-fragment-identifier>
1512    pub(crate) fn scroll_to_the_fragment(&self, cx: &mut JSContext, fragment: &str) {
1513        // Step 1. If document's indicated part is null, then set document's target element to null.
1514        //
1515        // > For an HTML document document, its indicated part is the result of
1516        // > selecting the indicated part given document and document's URL.
1517        let Some(indicated_part) = self.select_indicated_part(cx, fragment) else {
1518            self.set_target_element(cx.no_gc(), None);
1519            return;
1520        };
1521        // Step 2. Otherwise, if document's indicated part is top of the document, then:
1522        if *indicated_part == *self.upcast() {
1523            // Step 2.1. Set document's target element to null.
1524            self.set_target_element(cx.no_gc(), None);
1525            // Step 2.2. Scroll to the beginning of the document for document. [CSSOMVIEW]
1526            //
1527            // FIXME(stshine): this should be the origin of the stacking context space,
1528            // which may differ under the influence of writing mode.
1529            self.window.scroll(cx, 0.0, 0.0, ScrollBehavior::Instant);
1530            // Step 2.3. Return.
1531            return;
1532        }
1533        // Step 3. Otherwise:
1534        // Step 3.2. Let target be document's indicated part.
1535        let Some(target) = indicated_part.downcast::<Element>() else {
1536            // Step 3.1. Assert: document's indicated part is an element.
1537            unreachable!("Indicated part should always be an element");
1538        };
1539        // Step 3.3. Set document's target element to target.
1540        self.set_target_element(cx.no_gc(), Some(target));
1541        // Step 3.4. Run the ancestor revealing algorithm on target.
1542        // TODO
1543        // Step 3.5. Scroll target into view, with behavior set to "auto", block set to "start", and inline set to "nearest". [CSSOMVIEW]
1544        target.scroll_into_view_with_options(
1545            cx,
1546            ScrollBehavior::Auto,
1547            ScrollAxisState::new_always_scroll_position(ScrollLogicalPosition::Start),
1548            ScrollAxisState::new_always_scroll_position(ScrollLogicalPosition::Nearest),
1549            None,
1550            None,
1551        );
1552
1553        // Step 3.6. Run the focusing steps for target, with the Document's viewport as the fallback
1554        // target.
1555        indicated_part.run_the_focusing_steps(
1556            cx,
1557            Some(FocusableArea::Viewport),
1558            FocusTrigger::Script,
1559        );
1560
1561        // Step 3.7. Move the sequential focus navigation starting point to target.
1562        self.focus_handler()
1563            .set_sequential_focus_navigation_starting_point(target.upcast());
1564    }
1565
1566    fn get_anchor_by_name(&self, cx: &mut JSContext, name: &str) -> Option<DomRoot<Element>> {
1567        let document_element = self.GetDocumentElement()?;
1568        self.name_map
1569            .get_all(cx.no_gc(), document_element.upcast(), &Atom::from(name))
1570            .iter()
1571            .find(|element| element.is::<HTMLAnchorElement>())
1572            .map(|element| DomRoot::from_ref(&**element))
1573    }
1574
1575    pub(crate) fn notify_embedder_of_load_completion(&self) {
1576        if self.window().is_top_level() && !self.loader().aborted() {
1577            self.send_to_embedder(EmbedderMsg::NotifyLoadStatusChanged(
1578                self.webview_id(),
1579                LoadStatus::Complete,
1580            ));
1581            self.maybe_fetch_fallback_favicon();
1582        }
1583    }
1584
1585    /// Set the `readyState` of this [`Document`] to `loading` for the purposes of the
1586    /// "initialize a document object" part of the specification.
1587    ///
1588    /// See <https://html.spec.whatwg.org/multipage/#initialise-the-document-object>.
1589    pub(crate) fn set_document_readiness_to_loading_for_initialization(&self) {
1590        // https://html.spec.whatwg.org/multipage/#initialise-the-document-object
1591        // > such initial about:blank Document are never created by this algorithm
1592        // TODO(47417): Once "creating a new browsing context" properly exists, remove this check
1593        if self.is_initial_about_blank() {
1594            return;
1595        }
1596
1597        // From <https://w3c.github.io/navigation-timing/#dom-performancetiming-domloading>:
1598        // > This attribute must return the time immediately before the user agent sets the
1599        // > current document readiness to "loading".
1600        update_with_current_instant(&self.navigation_timing.dom_loading);
1601
1602        if self.window.is_top_level() {
1603            let webview_id = self.webview_id();
1604            self.send_to_embedder(EmbedderMsg::NotifyLoadStatusChanged(
1605                webview_id,
1606                LoadStatus::Started,
1607            ));
1608            self.send_to_embedder(EmbedderMsg::Status(webview_id, None));
1609            self.send_to_embedder(EmbedderMsg::SetFavicon(webview_id, None));
1610        }
1611
1612        self.ready_state.set(DocumentReadyState::Loading);
1613    }
1614
1615    /// <https://html.spec.whatwg.org/multipage/#update-the-current-document-readiness>
1616    pub(crate) fn update_the_current_document_readiness(
1617        &self,
1618        cx: &mut JSContext,
1619        state: DocumentReadyState,
1620    ) {
1621        // Step 1. If document's current document readiness equals readinessValue, then return.
1622        if self.ready_state.get() == state {
1623            return;
1624        }
1625
1626        // Step 2. Set document's current document readiness to readinessValue.
1627        self.ready_state.set(state);
1628
1629        // Step 3. If document is associated with an HTML parser:
1630        // Step 3.1: Let now be the current high resolution time given document's relevant
1631        // global object.
1632        // Note: Handled implicitly by update_with_current_instant.
1633        match state {
1634            DocumentReadyState::Loading => {},
1635            DocumentReadyState::Complete => {
1636                // This isn't part of the specification, but it's useful to have it here to
1637                // avoid code duplication.
1638                self.notify_embedder_of_load_completion();
1639
1640                // Step 3.2: If readinessValue is "complete", and document's load timing info's
1641                // DOM complete time is 0, then set document's load timing info's DOM complete
1642                // time to now.
1643                // Note: "check for zero" is handled by `.update_with_current_instant`.
1644                update_with_current_instant(&self.navigation_timing.dom_complete);
1645            },
1646            DocumentReadyState::Interactive => {
1647                // Step 3.3: Otherwise, if readinessValue is "interactive", and document's load timing
1648                // info's DOM interactive time is 0, then set document's load timing info's DOM
1649                // interactive time to now.
1650                // Note: "check for zero" is handled by `.update_with_current_instant`.
1651                update_with_current_instant(&self.navigation_timing.dom_interactive)
1652            },
1653        };
1654
1655        // Step 4. Fire an event named readystatechange at document.
1656        self.upcast::<EventTarget>()
1657            .fire_event(cx, atom!("readystatechange"));
1658    }
1659
1660    /// Return whether scripting is enabled or not
1661    /// <https://html.spec.whatwg.org/multipage/#concept-n-script>
1662    pub(crate) fn scripting_enabled(&self) -> bool {
1663        // Scripting is enabled for a node node if node's node document's browsing context is non-null,
1664        // and scripting is enabled for node's relevant settings object.
1665        self.has_browsing_context() &&
1666        // Either settings's global object is not a Window object,
1667        // or settings's global object's associated Document's active sandboxing flag
1668        // set does not have its sandboxed scripts browsing context flag set.
1669            !self.has_active_sandboxing_flag(
1670                SandboxingFlagSet::SANDBOXED_SCRIPTS_BROWSING_CONTEXT_FLAG,
1671            )
1672    }
1673
1674    /// Handles any updates when the document's title has changed.
1675    pub(crate) fn title_changed(&self) {
1676        if self.browsing_context().is_some() {
1677            self.send_title_to_embedder();
1678            let title = String::from(self.Title());
1679            self.window
1680                .send_to_constellation(ScriptToConstellationMessage::TitleChanged(
1681                    self.window.pipeline_id(),
1682                    title.clone(),
1683                ));
1684            #[cfg(feature = "devtools")]
1685            if let Some(chan) = self.window.as_global_scope().devtools_chan() {
1686                let _ = chan.send(ScriptToDevtoolsControlMsg::TitleChanged(
1687                    self.window.pipeline_id(),
1688                    title,
1689                ));
1690            }
1691        }
1692    }
1693
1694    /// Determine the title of the [`Document`] according to the specification at:
1695    /// <https://html.spec.whatwg.org/multipage/#document.title>. The difference
1696    /// here is that when the title isn't specified `None` is returned.
1697    fn title(&self) -> Option<DOMString> {
1698        let title = self.GetDocumentElement().and_then(|root| {
1699            if root.namespace() == &ns!(svg) && root.local_name() == &local_name!("svg") {
1700                // Step 1.
1701                root.upcast::<Node>()
1702                    .child_elements()
1703                    .find(|node| {
1704                        node.namespace() == &ns!(svg) && node.local_name() == &local_name!("title")
1705                    })
1706                    .map(DomRoot::upcast::<Node>)
1707            } else {
1708                // Step 2.
1709                root.upcast::<Node>()
1710                    .traverse_preorder(ShadowIncluding::No)
1711                    .find(|node| node.is::<HTMLTitleElement>())
1712            }
1713        });
1714
1715        title.map(|title| {
1716            // Steps 3-4.
1717            let value = title.child_text_content();
1718            DOMString::from(str_join(value.str().split_html_space_characters(), " "))
1719        })
1720    }
1721
1722    /// Sends this document's title to the constellation.
1723    pub(crate) fn send_title_to_embedder(&self) {
1724        let window = self.window();
1725        if window.is_top_level() {
1726            let title = self.title().map(String::from);
1727            self.send_to_embedder(EmbedderMsg::ChangePageTitle(self.webview_id(), title));
1728        }
1729    }
1730
1731    pub(crate) fn send_to_embedder(&self, msg: EmbedderMsg) {
1732        let window = self.window();
1733        window.send_to_embedder(msg);
1734    }
1735
1736    pub(crate) fn dirty_all_nodes(&self, no_gc: &NoGC) {
1737        let root = match self.GetDocumentElement() {
1738            Some(root) => root,
1739            None => return,
1740        };
1741        for node in root
1742            .upcast::<Node>()
1743            .traverse_preorder_unrooted(no_gc, ShadowIncluding::Yes)
1744        {
1745            node.dirty(no_gc, NodeDamage::Other)
1746        }
1747    }
1748
1749    /// <https://drafts.csswg.org/cssom-view/#document-run-the-scroll-steps>
1750    pub(crate) fn run_the_scroll_steps(&self, cx: &mut JSContext) {
1751        // Step 1: For each scrolling box `box` that was scrolled:
1752        //
1753        // Note: Since scrolling is currently synchronous (no scroll animations /
1754        // smooth scrolling), we consider any box event target that had a scroll
1755        // event to be a box that scrolled. Once scrolling is asynchronous this
1756        // should reflect scrolling targets which have finished their scroll
1757        // animation.
1758        let boxes_that_were_scrolled: Vec<_> = self
1759            .pending_scroll_events
1760            .borrow()
1761            .iter()
1762            .filter_map(|pending_event| {
1763                if &*pending_event.event == "scroll" {
1764                    Some(pending_event.target.as_rooted())
1765                } else {
1766                    None
1767                }
1768            })
1769            .collect();
1770
1771        for target in boxes_that_were_scrolled.into_iter() {
1772            // Step 1.1: If box belongs to a viewport, let doc be the viewport’s associated
1773            // Document and target be the viewport. If box belongs to a VisualViewport,
1774            // let doc be the VisualViewport’s associated document and target be the
1775            // VisualViewport. Otherwise, box belongs to an element and let doc be the
1776            // element’s node document and target be the element.
1777            let Some(element) = target.downcast::<Element>() else {
1778                continue;
1779            };
1780            let document = element.owner_document();
1781
1782            // Step 1.2: If box belongs to a snap container, snapcontainer, run the
1783            // update scrollsnapchange targets steps for snapcontainer.
1784            // TODO: Implement this.
1785
1786            // Step 1.3: If (target, "scrollend") is already in doc’s pending scroll
1787            // events, abort these steps.
1788            let mut pending_scroll_events = document.pending_scroll_events.borrow_mut();
1789            let event = "scrollend".into();
1790            if pending_scroll_events
1791                .iter()
1792                .any(|existing| existing.equivalent(&target, &event))
1793            {
1794                continue;
1795            }
1796
1797            // > Step 1.4: Append (target, "scrollend") to doc’s pending scroll events.
1798            pending_scroll_events.push(PendingScrollEvent {
1799                target: target.as_traced(),
1800                event: "scrollend".into(),
1801            });
1802        }
1803
1804        // Step 2: For each item (target, type) in doc’s pending scroll events, in
1805        // the order they were added to the list, run these substeps:
1806        rooted_vec!(let pending_scroll_events <- self.pending_scroll_events.take().into_iter());
1807        for pending_event in pending_scroll_events.iter() {
1808            // Step 2.1: If target is a Document, and type is "scroll" or "scrollend",
1809            // fire an event named type that bubbles at target.
1810            let event = pending_event.event.clone();
1811            if pending_event.target.is::<Document>() {
1812                pending_event.target.fire_bubbling_event(cx, event);
1813            }
1814            // Step 2.2: Otherwise, if type is "scrollsnapchange", then:
1815            //  ....
1816            // TODO: Implement this.
1817            // Step 2.3: Otherwise, if type is "scrollsnapchanging", then:
1818            //  ...
1819            // TODO: Implement this.
1820            //
1821            // Step 2.4: Otherwise, fire an event named type at target.
1822            else {
1823                pending_event.target.fire_event(cx, event);
1824            }
1825        }
1826
1827        // Step 3. Empty doc’s pending scroll events.
1828        // Note: This is done above.
1829    }
1830
1831    /// <https://drafts.csswg.org/cssom-view/#scrolling-events>
1832    ///
1833    /// > Whenever a viewport gets scrolled (whether in response to user interaction or
1834    /// > by an API), the user agent must run these steps:
1835    pub(crate) fn handle_viewport_scroll_event(&self) {
1836        // Step 1: Let doc be the viewport’s associated Document.
1837        //
1838        // Note: This is self.
1839
1840        // >> Step 2: If doc is a snap container, run the steps to update scrollsnapchanging targets
1841        // > for doc with doc’s eventual snap target in the block axis as newBlockTarget and
1842        // > doc’s eventual snap target in the inline axis as newInlineTarget.
1843        //
1844        // TODO(#7673): Implement scroll snapping
1845
1846        // Steps 3 and 4 are shared with other scroll targets.
1847        self.finish_handle_scroll_event(self.upcast());
1848    }
1849
1850    /// <https://drafts.csswg.org/cssom-view/#scrolling-events>
1851    ///
1852    /// These are the shared steps 3 and 4 from all scroll targets listed in the
1853    /// first section of the specification.
1854    pub(crate) fn finish_handle_scroll_event(&self, event_target: &EventTarget) {
1855        // Step 3.
1856        // > If the element is already in doc’s pending scroll event targets, abort these steps.
1857        let event = "scroll".into();
1858        if self
1859            .pending_scroll_events
1860            .borrow()
1861            .iter()
1862            .any(|existing| existing.equivalent(event_target, &event))
1863        {
1864            return;
1865        }
1866
1867        // Step 4.
1868        // > Append the element to doc’s pending scroll event targets.
1869        self.pending_scroll_events
1870            .borrow_mut()
1871            .push(PendingScrollEvent {
1872                target: Dom::from_ref(event_target),
1873                event: "scroll".into(),
1874            });
1875    }
1876
1877    /// <https://dom.spec.whatwg.org/#converting-nodes-into-a-node>
1878    pub(crate) fn node_from_nodes_and_strings(
1879        &self,
1880        cx: &mut JSContext,
1881        mut nodes: Vec<NodeOrString>,
1882    ) -> Fallible<DomRoot<Node>> {
1883        if nodes.len() == 1 {
1884            Ok(match nodes.pop().unwrap() {
1885                NodeOrString::Node(node) => node,
1886                NodeOrString::String(string) => DomRoot::upcast(self.CreateTextNode(cx, string)),
1887            })
1888        } else {
1889            let fragment = DomRoot::upcast::<Node>(self.CreateDocumentFragment(cx));
1890            for node in nodes {
1891                match node {
1892                    NodeOrString::Node(node) => {
1893                        fragment.AppendChild(cx, &node)?;
1894                    },
1895                    NodeOrString::String(string) => {
1896                        let node = DomRoot::upcast::<Node>(self.CreateTextNode(cx, string));
1897                        // No try!() here because appending a text node
1898                        // should not fail.
1899                        fragment.AppendChild(cx, &node).unwrap();
1900                    },
1901                }
1902            }
1903            Ok(fragment)
1904        }
1905    }
1906
1907    pub(crate) fn get_body_attribute(&self, local_name: &LocalName) -> DOMString {
1908        match self.GetBody() {
1909            Some(ref body) if body.is_body_element() => {
1910                body.upcast::<Element>().get_string_attribute(local_name)
1911            },
1912            _ => DOMString::new(),
1913        }
1914    }
1915
1916    pub(crate) fn set_body_attribute(
1917        &self,
1918        cx: &mut JSContext,
1919        local_name: &LocalName,
1920        value: DOMString,
1921    ) {
1922        if let Some(ref body) = self.GetBody().filter(|elem| elem.is_body_element()) {
1923            let body = body.upcast::<Element>();
1924            let value = body.parse_attribute(&ns!(), local_name, value);
1925            body.set_attribute(cx, local_name, value);
1926        }
1927    }
1928
1929    pub(crate) fn set_current_script(&self, script: Option<&HTMLScriptElement>) {
1930        self.current_script.set(script);
1931    }
1932
1933    /// <https://html.spec.whatwg.org/multipage/#has-a-style-sheet-that-is-blocking-scripts>
1934    pub(crate) fn has_a_stylesheet_that_is_blocking_scripts(&self) -> bool {
1935        !self.script_blocking_stylesheet_set.borrow().is_empty()
1936    }
1937
1938    pub(crate) fn add_script_blocking_stylesheet(&self, id: StylesheetContextId) {
1939        self.script_blocking_stylesheet_set.borrow_mut().insert(id);
1940    }
1941
1942    pub(crate) fn remove_script_blocking_stylesheet(&self, id: StylesheetContextId) {
1943        self.script_blocking_stylesheet_set
1944            .borrow_mut()
1945            .shift_remove(&id);
1946    }
1947
1948    pub(crate) fn render_blocking_element_count(&self) -> u32 {
1949        self.render_blocking_element_count.get()
1950    }
1951
1952    /// <https://html.spec.whatwg.org/multipage/#block-rendering>
1953    pub(crate) fn increment_render_blocking_element_count(&self) {
1954        // Step 1. Let document be el's node document.
1955        //
1956        // That's self
1957
1958        // Step 2. If document allows adding render-blocking elements,
1959        // then append el to document's render-blocking element set.
1960        assert!(self.allows_adding_render_blocking_elements());
1961        let count_cell = &self.render_blocking_element_count;
1962        count_cell.set(count_cell.get() + 1);
1963    }
1964
1965    /// <https://html.spec.whatwg.org/multipage/#unblock-rendering>
1966    pub(crate) fn decrement_render_blocking_element_count(&self) {
1967        // Step 1. Let document be el's node document.
1968        //
1969        // That's self
1970
1971        // Step 2. Remove el from document's render-blocking element set.
1972        let count_cell = &self.render_blocking_element_count;
1973        assert!(count_cell.get() > 0);
1974        count_cell.set(count_cell.get() - 1);
1975    }
1976
1977    /// <https://html.spec.whatwg.org/multipage/#allows-adding-render-blocking-elements>
1978    pub(crate) fn allows_adding_render_blocking_elements(&self) -> bool {
1979        // > A Document document allows adding render-blocking elements
1980        // > if document's content type is "text/html" and the body element of document is null.
1981        self.is_html_document && self.GetBody().is_none()
1982    }
1983
1984    /// <https://html.spec.whatwg.org/multipage/#render-blocked>
1985    pub(crate) fn is_render_blocked(&self) -> bool {
1986        // > A Document document is render-blocked if both of the following are true:
1987        // > document's render-blocking element set is non-empty,
1988        // > or document allows adding render-blocking elements.
1989        self.render_blocking_element_count() > 0
1990        // TODO: add `allows_adding_render_blocking_elements` which currently breaks for empty iframes
1991        // > The current high resolution time given document's relevant global object
1992        // has not exceeded an implementation-defined timeout value.
1993        // TODO
1994    }
1995
1996    pub(crate) fn invalidate_stylesheets(&self, no_gc: &NoGC) {
1997        self.stylesheets.borrow_mut().force_dirty(OriginSet::all());
1998
1999        // Mark the document element dirty so a reflow will be performed.
2000        //
2001        // FIXME(emilio): Use the DocumentStylesheetSet invalidation stuff.
2002        if let Some(element) = self.GetDocumentElement() {
2003            element.upcast::<Node>().dirty(no_gc, NodeDamage::Style);
2004        }
2005    }
2006
2007    /// Whether or not this `Document` has any active requestAnimationFrame callbacks
2008    /// registered.
2009    pub(crate) fn has_active_request_animation_frame_callbacks(&self) -> bool {
2010        !self.animation_frame_list.borrow().is_empty()
2011    }
2012
2013    /// <https://html.spec.whatwg.org/multipage/#dom-window-requestanimationframe>
2014    pub(crate) fn request_animation_frame(&self, callback: AnimationFrameCallback) -> u32 {
2015        let ident = self.animation_frame_ident.get() + 1;
2016        self.animation_frame_ident.set(ident);
2017
2018        let had_animation_frame_callbacks;
2019        {
2020            let mut animation_frame_list = self.animation_frame_list.borrow_mut();
2021            had_animation_frame_callbacks = !animation_frame_list.is_empty();
2022            animation_frame_list.push_back((ident, Some(callback)));
2023        }
2024
2025        // No need to send a `ChangeRunningAnimationsState` if we're running animation callbacks:
2026        // we're guaranteed to already be in the "animation callbacks present" state.
2027        //
2028        // This reduces CPU usage by avoiding needless thread wakeups in the common case of
2029        // repeated rAF.
2030        if !self.running_animation_callbacks.get() && !had_animation_frame_callbacks {
2031            self.window().send_to_constellation(
2032                ScriptToConstellationMessage::ChangeRunningAnimationsState(
2033                    AnimationState::AnimationCallbacksPresent,
2034                ),
2035            );
2036        }
2037
2038        ident
2039    }
2040
2041    /// <https://html.spec.whatwg.org/multipage/#dom-window-cancelanimationframe>
2042    pub(crate) fn cancel_animation_frame(&self, ident: u32) {
2043        let mut list = self.animation_frame_list.borrow_mut();
2044        if let Some(pair) = list.iter_mut().find(|pair| pair.0 == ident) {
2045            pair.1 = None;
2046        }
2047    }
2048
2049    /// <https://html.spec.whatwg.org/multipage/#run-the-animation-frame-callbacks>
2050    pub(crate) fn run_the_animation_frame_callbacks(&self, cx: &mut CurrentRealm) {
2051        self.running_animation_callbacks.set(true);
2052        let timing = self.global().performance(cx).Now();
2053
2054        let num_callbacks = self.animation_frame_list.borrow().len();
2055        for _ in 0..num_callbacks {
2056            rooted!(&in(cx) let maybe_callback = self
2057                .animation_frame_list
2058                .borrow_mut()
2059                .pop_front()
2060                .unwrap()
2061                .1);
2062            if let Some(ref callback) = *maybe_callback {
2063                callback.call(cx, self, *timing);
2064            }
2065        }
2066        self.running_animation_callbacks.set(false);
2067
2068        if self.animation_frame_list.borrow().is_empty() {
2069            self.window().send_to_constellation(
2070                ScriptToConstellationMessage::ChangeRunningAnimationsState(
2071                    AnimationState::AnimationCallbacksAbsent,
2072                ),
2073            );
2074        }
2075    }
2076
2077    pub(crate) fn policy_container(&self) -> Ref<'_, StdArc<PolicyContainer>> {
2078        self.policy_container.borrow()
2079    }
2080
2081    pub(crate) fn set_policy_container(&self, policy_container: StdArc<PolicyContainer>) {
2082        *self.policy_container.borrow_mut() = policy_container;
2083        self.update_upgrade_insecure_navigations_set();
2084    }
2085
2086    pub(crate) fn set_csp_list(&self, csp_list: Option<CspList>) {
2087        StdArc::make_mut(&mut *self.policy_container.borrow_mut()).set_csp_list(csp_list);
2088        self.update_upgrade_insecure_navigations_set();
2089    }
2090
2091    /// <https://w3c.github.io/webappsec-upgrade-insecure-requests/#delivery> Step 3-4
2092    fn update_upgrade_insecure_navigations_set(&self) {
2093        if let Some(csp_list) = self.get_csp_list().as_ref() {
2094            for policy in &csp_list.0 {
2095                if policy.contains_a_directive_whose_name_is("upgrade-insecure-requests") &&
2096                    policy.disposition == PolicyDisposition::Enforce
2097                {
2098                    if let ImmutableOrigin::Tuple(_, host, port) = self.url.borrow().origin() {
2099                        let tuple = UpgradeInsecureNavigations {
2100                            host: host.to_string(),
2101                            port,
2102                        };
2103                        let global_scope = self.window.as_global_scope();
2104
2105                        global_scope
2106                            .script_to_constellation_chan()
2107                            .send(ScriptToConstellationMessage::AddTupleToUpgradeInsecureNavigationsSet(tuple.clone()))
2108                            .unwrap();
2109                        global_scope
2110                            .upgrade_insecure_navigations_set_mut()
2111                            .insert(tuple);
2112                    }
2113                    return;
2114                }
2115            }
2116        }
2117    }
2118
2119    /// <https://www.w3.org/TR/CSP/#enforced>
2120    pub(crate) fn enforce_csp_policy(&self, policy: CspPolicy) {
2121        // > A policy is enforced or monitored for a global object by inserting it into the global object’s CSP list.
2122        let mut csp_list = self.get_csp_list().clone().unwrap_or(CspList(vec![]));
2123        csp_list.push(policy);
2124        StdArc::make_mut(&mut *self.policy_container.borrow_mut()).set_csp_list(Some(csp_list));
2125    }
2126
2127    pub(crate) fn get_csp_list(&self) -> Ref<'_, Option<CspList>> {
2128        Ref::map(self.policy_container.borrow(), |policy_container| {
2129            &policy_container.csp_list
2130        })
2131    }
2132
2133    pub(crate) fn preloaded_resources(&self) -> std::cell::Ref<'_, PreloadedResources> {
2134        self.preloaded_resources.borrow()
2135    }
2136
2137    pub(crate) fn insert_preloaded_resource(&self, key: PreloadKey, preload_id: PreloadId) {
2138        self.preloaded_resources
2139            .borrow_mut()
2140            .insert(key, preload_id);
2141    }
2142
2143    pub(crate) fn fetch_blocking<Listener: FetchResponseListener>(
2144        &self,
2145        load: LoadType,
2146        request: RequestBuilder,
2147        listener: Listener,
2148    ) {
2149        self.loader_mut().add_blocking_load(load);
2150        self.fetch_background(request, listener);
2151    }
2152
2153    pub(crate) fn fetch_background<Listener: FetchResponseListener>(
2154        &self,
2155        request_builder: RequestBuilder,
2156        listener: Listener,
2157    ) {
2158        let networking_task_source = self
2159            .owner_global()
2160            .task_manager()
2161            .networking_task_source()
2162            .to_sendable();
2163        self.window()
2164            .as_global_scope()
2165            .fetch(request_builder, listener, networking_task_source);
2166    }
2167
2168    pub(crate) fn fetch_favicon<Listener: FetchResponseListener>(
2169        &self,
2170        request_builder: RequestBuilder,
2171        listener: Listener,
2172    ) {
2173        let networking_task_source = self
2174            .owner_global()
2175            .task_manager()
2176            .networking_task_source()
2177            .to_sendable();
2178        self.window().as_global_scope().fetch_favicon(
2179            request_builder,
2180            listener,
2181            networking_task_source,
2182        );
2183    }
2184
2185    /// <https://fetch.spec.whatwg.org/#deferred-fetch-control-document>
2186    fn deferred_fetch_control_document(&self) -> DomRoot<Document> {
2187        match self.window().window_proxy().frame_element() {
2188            // Step 1. If document’ node navigable’s container document is null
2189            // or a document whose origin is not same origin with document, then return document;
2190            None => DomRoot::from_ref(self),
2191            // otherwise, return the deferred-fetch control document given document’s node navigable’s container document.
2192            Some(container) => container.owner_document().deferred_fetch_control_document(),
2193        }
2194    }
2195
2196    /// <https://fetch.spec.whatwg.org/#available-deferred-fetch-quota>
2197    pub(crate) fn available_deferred_fetch_quota(&self, origin: ImmutableOrigin) -> isize {
2198        // Step 1. Let controlDocument be document’s deferred-fetch control document.
2199        let control_document = self.deferred_fetch_control_document();
2200        // Step 2. Let navigable be controlDocument’s node navigable.
2201        let navigable = control_document.window();
2202        // Step 3. Let isTopLevel be true if controlDocument’s node navigable
2203        // is a top-level traversable; otherwise false.
2204        let is_top_level = navigable.is_top_level();
2205        // Step 4. Let deferredFetchAllowed be true if controlDocument is allowed
2206        // to use the policy-controlled feature "deferred-fetch"; otherwise false.
2207        // TODO
2208        let deferred_fetch_allowed = true;
2209        // Step 5. Let deferredFetchMinimalAllowed be true if controlDocument
2210        // is allowed to use the policy-controlled feature "deferred-fetch-minimal"; otherwise false.
2211        // TODO
2212        let deferred_fetch_minimal_allowed = true;
2213        // Step 6. Let quota be the result of the first matching statement:
2214        let mut quota = match is_top_level {
2215            // isTopLevel is true and deferredFetchAllowed is false
2216            true if !deferred_fetch_allowed => 0,
2217            // isTopLevel is true and deferredFetchMinimalAllowed is false
2218            true if !deferred_fetch_minimal_allowed => 640 * 1024,
2219            // isTopLevel is true
2220            true => 512 * 1024,
2221            // deferredFetchAllowed is true, and navigable’s navigable container’s
2222            // reserved deferred-fetch quota is normal quota
2223            // TODO
2224            _ if deferred_fetch_allowed => 0,
2225            // deferredFetchMinimalAllowed is true, and navigable’s navigable container’s
2226            // reserved deferred-fetch quota is minimal quota
2227            // TODO
2228            _ if deferred_fetch_minimal_allowed => 8 * 1024,
2229            // Otherwise
2230            _ => 0,
2231        } as isize;
2232        // Step 7. Let quotaForRequestOrigin be 64 kibibytes.
2233        let mut quota_for_request_origin = 64 * 1024_isize;
2234        // Step 8. For each navigable in controlDocument’s node navigable’s
2235        // inclusive descendant navigables whose active document’s deferred-fetch control document is controlDocument:
2236        // TODO
2237        // Step 8.1. For each container in navigable’s active document’s shadow-including inclusive descendants
2238        // which is a navigable container, decrement quota by container’s reserved deferred-fetch quota.
2239        // TODO
2240        // Step 8.2. For each deferred fetch record deferredRecord of navigable’s active document’s
2241        // relevant settings object’s fetch group’s deferred fetch records:
2242        let deferred_fetches = navigable.as_global_scope().fetch_group().deferred_fetches();
2243        for deferred_fetch in deferred_fetches {
2244            // Step 8.2.1. If deferredRecord’s invoke state is not "pending", then continue.
2245            if deferred_fetch.invoke_state.get() != DeferredFetchRecordInvokeState::Pending {
2246                continue;
2247            }
2248            // Step 8.2.2. Let requestLength be the total request length of deferredRecord’s request.
2249            let request_length = deferred_fetch.request.total_request_length();
2250            // Step 8.2.3. Decrement quota by requestLength.
2251            quota -= request_length as isize;
2252            // Step 8.2.4. If deferredRecord’s request’s URL’s origin is same origin with origin,
2253            // then decrement quotaForRequestOrigin by requestLength.
2254            if deferred_fetch.request.url().origin() == origin {
2255                quota_for_request_origin -= request_length as isize;
2256            }
2257        }
2258        // Step 9. If quota is equal or less than 0, then return 0.
2259        if quota <= 0 {
2260            return 0;
2261        }
2262        // Step 10. If quota is less than quotaForRequestOrigin, then return quota.
2263        if quota < quota_for_request_origin {
2264            return quota;
2265        }
2266        // Step 11. Return quotaForRequestOrigin.
2267        quota_for_request_origin
2268    }
2269
2270    /// <https://html.spec.whatwg.org/multipage/#update-document-for-history-step-application>
2271    pub(crate) fn update_document_for_history_step_application(
2272        &self,
2273        old_url: &ServoUrl,
2274        new_url: &ServoUrl,
2275    ) {
2276        // Step 6. If documentsEntryChanged is true, then:
2277        //
2278        // It is right now since we already have a document and a new_url
2279
2280        // Step 6.1. Let oldURL be document's latest entry's URL.
2281        // Passed in as argument
2282
2283        // Step 6.2. Set document's latest entry to entry.
2284        // TODO
2285        // Step 6.3. Restore the history object state given document and entry.
2286        // TODO
2287        // Step 6.4. If documentIsNew is false, then:
2288        // TODO
2289        // Step 6.4.1. Assert: navigationType is not null.
2290        // TODO
2291        // Step 6.4.2. Update the navigation API entries for a same-document navigation given navigation, entry, and navigationType.
2292        // TODO
2293        // Step 6.4.3. Fire an event named popstate at document's relevant global object, using PopStateEvent,
2294        // with the state attribute initialized to document's history object's state and hasUAVisualTransition
2295        // initialized to true if a visual transition, to display a cached rendered state of the latest entry, was done by the user agent.
2296        // TODO
2297        // Step 6.4.4. Restore persisted state given entry.
2298        // TODO
2299
2300        // Step 6.4.5. If oldURL's fragment is not equal to entry's URL's fragment,
2301        // then queue a global task on the DOM manipulation task source given document's relevant global object
2302        // to fire an event named hashchange at document's relevant global object, using HashChangeEvent,
2303        // with the oldURL attribute initialized to the serialization of oldURL
2304        // and the newURL attribute initialized to the serialization of entry's URL.
2305        if old_url.as_url()[Position::BeforeFragment..] !=
2306            new_url.as_url()[Position::BeforeFragment..]
2307        {
2308            let window = Trusted::new(self.owner_window().deref());
2309            let old_url = old_url.to_string();
2310            let new_url = new_url.to_string();
2311            self.owner_global()
2312                .task_manager()
2313                .dom_manipulation_task_source()
2314                .queue(task!(hashchange_event: move |cx| {
2315                        let window = window.root();
2316                        HashChangeEvent::new(
2317                            cx,
2318                            &window,
2319                            atom!("hashchange"),
2320                            false,
2321                            false,
2322                            old_url,
2323                            new_url,
2324                        )
2325                        .upcast::<Event>()
2326                        .fire(cx, window.upcast());
2327                }));
2328        }
2329    }
2330
2331    pub(crate) fn finish_load_for_dropped_blocker(&self, load: LoadType) {
2332        let this = Trusted::new(self);
2333        self.owner_global()
2334            .task_manager()
2335            .dom_manipulation_task_source()
2336            .queue(task!(check_finished_load: move |cx| {
2337                this.root().finish_load(load, cx);
2338            }));
2339    }
2340
2341    /// Step 8 of <https://html.spec.whatwg.org/multipage/#the-end>
2342    /// <https://html.spec.whatwg.org/multipage/#delay-the-load-event>
2343    pub(crate) fn finish_load(&self, load: LoadType, cx: &mut JSContext) {
2344        // This does not delay the load event anymore.
2345        debug!("Document {:?} got finish_load: {:?}", self.url(), load);
2346        self.loader.borrow_mut().finish_load(&load);
2347
2348        match load {
2349            LoadType::Stylesheet(_) => {
2350                // A stylesheet finishing to load may unblock any pending
2351                // parsing-blocking script or deferred script.
2352                self.process_pending_parsing_blocking_script(cx);
2353
2354                // Step 3.
2355                self.process_deferred_scripts(cx);
2356            },
2357            LoadType::PageSource(_) => {
2358                // We finished loading the page, so if the `Window` is still waiting for
2359                // the first layout, allow it.
2360                if self.has_browsing_context && self.is_fully_active() {
2361                    self.window().allow_layout_if_necessary(cx);
2362                }
2363
2364                // Deferred scripts have to wait for page to finish loading,
2365                // this is the first opportunity to process them.
2366
2367                // Step 3.
2368                self.process_deferred_scripts(cx);
2369            },
2370            _ => {},
2371        }
2372
2373        // Step 8. Spin the event loop until there is nothing that delays the load event in the Document.
2374        let document = Trusted::new(self);
2375        self.owner_global()
2376            .task_manager()
2377            .dom_manipulation_task_source()
2378            .queue(task!(wait_for_load_blockers: move |cx| {
2379                document.root().wait_until_load_blockers_have_resolved(cx);
2380            }));
2381    }
2382
2383    /// <https://html.spec.whatwg.org/multipage/#checking-if-unloading-is-canceled>
2384    pub(crate) fn check_if_unloading_is_cancelled(
2385        &self,
2386        cx: &mut JSContext,
2387        recursive_flag: bool,
2388    ) -> bool {
2389        // TODO: Step 1, increase the event loop's termination nesting level by 1.
2390        // Step 2
2391        self.incr_ignore_opens_during_unload_counter();
2392        // Step 3-5.
2393        let beforeunload_event = BeforeUnloadEvent::new(
2394            cx,
2395            &self.window,
2396            atom!("beforeunload"),
2397            EventBubbles::Bubbles,
2398            EventCancelable::Cancelable,
2399        );
2400        let event = beforeunload_event.upcast::<Event>();
2401        event.set_trusted(true);
2402        let event_target = self.window.upcast::<EventTarget>();
2403        let has_listeners = event_target.has_listeners_for(&atom!("beforeunload"));
2404        self.window.dispatch_event_with_target_override(cx, event);
2405        // TODO: Step 6, decrease the event loop's termination nesting level by 1.
2406        // Step 7
2407        if has_listeners {
2408            self.salvageable.set(false);
2409        }
2410        let mut can_unload = true;
2411        // TODO: Step 8, also check sandboxing modals flag.
2412        let default_prevented = event.DefaultPrevented();
2413        let return_value_not_empty = !event
2414            .downcast::<BeforeUnloadEvent>()
2415            .unwrap()
2416            .ReturnValue()
2417            .is_empty();
2418        if default_prevented || return_value_not_empty {
2419            let (chan, port) = generic_channel::channel().expect("Failed to create IPC channel!");
2420            let msg = EmbedderMsg::AllowUnload(self.webview_id(), chan);
2421            self.send_to_embedder(msg);
2422            can_unload = port.recv().unwrap() == AllowOrDeny::Allow;
2423        }
2424        // Step 9
2425        if !recursive_flag {
2426            // `check_if_unloading_is_cancelled` might cause futher modifications to the DOM so collecting here prevents
2427            // a double borrow if the `IFrameCollection` needs to be validated again.
2428            let iframes: Vec<_> = self.iframes().iter().collect();
2429            for iframe in &iframes {
2430                // TODO: handle the case of cross origin iframes.
2431                let document = iframe.owner_document();
2432                can_unload = document.check_if_unloading_is_cancelled(cx, true);
2433                if !document.salvageable() {
2434                    self.salvageable.set(false);
2435                }
2436                if !can_unload {
2437                    break;
2438                }
2439            }
2440        }
2441        // Step 10
2442        self.decr_ignore_opens_during_unload_counter();
2443        can_unload
2444    }
2445
2446    /// <https://html.spec.whatwg.org/multipage/#unload-a-document>
2447    pub(crate) fn unload(&self, cx: &mut JSContext, recursive_flag: bool) {
2448        if self.window_detached() {
2449            return;
2450        }
2451
2452        // TODO: Step 1, increase the event loop's termination nesting level by 1.
2453        // Step 2
2454        self.incr_ignore_opens_during_unload_counter();
2455        // Step 3-6 If oldDocument's page showing is true:
2456        if self.page_showing.get() {
2457            // Set oldDocument's page showing to false.
2458            self.page_showing.set(false);
2459            // Fire a page transition event named pagehide at oldDocument's relevant global object with oldDocument's
2460            // salvageable state.
2461            let event = PageTransitionEvent::new(
2462                cx,
2463                &self.window,
2464                atom!("pagehide"),
2465                false,                  // bubbles
2466                false,                  // cancelable
2467                self.salvageable.get(), // persisted
2468            );
2469            let event = event.upcast::<Event>();
2470            event.set_trusted(true);
2471            self.window.dispatch_event_with_target_override(cx, event);
2472            // Step 6 Update the visibility state of oldDocument to "hidden".
2473            self.update_visibility_state(cx, DocumentVisibilityState::Hidden);
2474        }
2475        // Step 7
2476        if !self.fired_unload.get() {
2477            let event = Event::new(
2478                cx,
2479                self.window.upcast(),
2480                atom!("unload"),
2481                EventBubbles::Bubbles,
2482                EventCancelable::Cancelable,
2483            );
2484            event.set_trusted(true);
2485            let event_target = self.window.upcast::<EventTarget>();
2486            let has_listeners = event_target.has_listeners_for(&atom!("unload"));
2487            self.window.dispatch_event_with_target_override(cx, &event);
2488            self.fired_unload.set(true);
2489            // Step 9
2490            if has_listeners {
2491                self.salvageable.set(false);
2492            }
2493        }
2494        // TODO: Step 8, decrease the event loop's termination nesting level by 1.
2495
2496        // Step 13
2497        if !recursive_flag {
2498            // `unload` might cause futher modifications to the DOM so collecting here prevents
2499            // a double borrow if the `IFrameCollection` needs to be validated again.
2500            let iframes: Vec<_> = self.iframes().iter().collect();
2501            for iframe in &iframes {
2502                // TODO: handle the case of cross origin iframes.
2503                let document = iframe.owner_document();
2504                document.unload(cx, true);
2505                if !document.salvageable() {
2506                    self.salvageable.set(false);
2507                }
2508            }
2509        }
2510
2511        // Step 18. Run any unloading document cleanup steps for oldDocument that are defined by this specification and other applicable specifications.
2512        self.unloading_cleanup_steps(cx);
2513
2514        // https://w3c.github.io/FileAPI/#lifeTime
2515        self.window.as_global_scope().clean_up_all_file_resources();
2516
2517        // Step 15, End
2518        self.decr_ignore_opens_during_unload_counter();
2519
2520        // Step 20. If oldDocument's salvageable state is false, then destroy oldDocument.
2521        // TODO
2522    }
2523
2524    /// <https://html.spec.whatwg.org/multipage/#completely-finish-loading>
2525    fn completely_finish_loading(&self) {
2526        // Step 1. Assert: document's browsing context is non-null.
2527        // TODO: Adding this assert fails a lot of tests
2528
2529        // Step 2. Set document's completely loaded time to the current time.
2530        self.completely_loaded.set(true);
2531        // Step 3. Let container be document's node navigable's container.
2532        // TODO
2533
2534        // Step 4. If container is an iframe element, then queue an element task
2535        // on the DOM manipulation task source given container to run the iframe load event steps given container.
2536        //
2537        // Note: this will also result in the "iframe-load-event-steps" being run.
2538        // https://html.spec.whatwg.org/multipage/#iframe-load-event-steps
2539        self.notify_constellation_that_load_finished(false /* aborted */);
2540
2541        // Step 5. Otherwise, if container is non-null, then queue an element task on the DOM manipulation task source
2542        // given container to fire an event named load at container.
2543        // TODO
2544
2545        // Step 13 of https://html.spec.whatwg.org/multipage/#shared-declarative-refresh-steps
2546        //
2547        // At least time seconds have elapsed since document's completely loaded time,
2548        // adjusted to take into account user or user agent preferences.
2549        if let Some(DeclarativeRefresh::PendingLoad {
2550            url,
2551            time,
2552            from_meta_element,
2553        }) = &*self.declarative_refresh.borrow()
2554        {
2555            self.window.as_global_scope().schedule_callback(
2556                OneshotTimerCallback::RefreshRedirectDue(RefreshRedirectDue {
2557                    url: url.clone(),
2558                    from_meta_element: *from_meta_element,
2559                }),
2560                Duration::from_secs(*time),
2561            );
2562        }
2563    }
2564
2565    /// Step 9 of <https://html.spec.whatwg.org/multipage/#the-end>
2566    fn queue_document_completion(&self, cx: &mut JSContext) {
2567        // The initial about:blank document passes through
2568        // https://html.spec.whatwg.org/multipage/#creating-a-new-browsing-context
2569        // instead of the steps used by other documents.
2570        assert!(!self.is_initial_about_blank());
2571
2572        self.loader.borrow_mut().inhibit_events();
2573
2574        // The rest will ever run only once per document.
2575
2576        // Step 9. Queue a global task on the DOM manipulation task source given
2577        // the Document's relevant global object to run the following steps:
2578        debug!("Document loads are complete.");
2579        let document = Trusted::new(self);
2580        self.owner_global()
2581            .task_manager()
2582            .dom_manipulation_task_source()
2583            .queue(task!(fire_load_event: move |cx| {
2584                let document = document.root();
2585                // Step 9.3. Let window be the Document's relevant global object.
2586                let window = document.window();
2587                if !window.is_alive() || document.window_detached() {
2588                    return;
2589                }
2590
2591                // Step 9.1. Update the current document readiness to "complete".
2592                // This must happen even if the load was stopped.
2593                document.update_the_current_document_readiness(cx, DocumentReadyState::Complete);
2594
2595                // The document may have been stopped after this task was queued.
2596                //
2597                // The HTML specification doesn't say which events should be fired when
2598                // aborting a Document. Blink and WebKit don't fire the load event in this
2599                // situation; see <https://github.com/whatwg/html/issues/5535>.
2600                //
2601                // This check is intentionally after step 9.1 to move readystate to "complete".
2602                if document.loader().aborted() {
2603                    return;
2604                }
2605
2606                // Step 9.2. If the Document object's browsing context is null, then abort these steps.
2607                if document.browsing_context().is_none() {
2608                    return;
2609                }
2610
2611                // Step 9.4. Set the Document's load timing info's load event start time to the current high resolution time given window.
2612                update_with_current_instant(&document.navigation_timing.load_event_start);
2613
2614                // Step 9.5. Fire an event named load at window, with legacy target override flag set.
2615                let load_event = Event::new(
2616                    cx,
2617                    window.upcast(),
2618                    atom!("load"),
2619                    EventBubbles::DoesNotBubble,
2620                    EventCancelable::NotCancelable,
2621                );
2622                load_event.set_trusted(true);
2623                debug!("About to dispatch load for {:?}", document.url());
2624                window.dispatch_event_with_target_override(cx, &load_event);
2625
2626                // Step 9.6. Invoke WebDriver BiDi load complete with the Document's browsing context,
2627                // and a new WebDriver BiDi navigation status whose id is the Document object's during-loading navigation ID
2628                // for WebDriver BiDi, status is "complete", and url is the Document object's URL.
2629                // TODO
2630
2631                // Step 9.7. Set the Document object's during-loading navigation ID for WebDriver BiDi to null.
2632                // TODO
2633
2634                // Step 9.8. Set the Document's load timing info's load event end time to the current high resolution time given window.
2635                update_with_current_instant(&document.navigation_timing.load_event_end);
2636
2637                // Step 9.9. Assert: Document's page showing is false.
2638                // TODO: Adding this assert fails a lot of tests
2639
2640                // Step 9.10. Set the Document's page showing to true.
2641                document.page_showing.set(true);
2642
2643                // Step 9.11. Fire a page transition event named pageshow at window with false.
2644                let page_show_event = PageTransitionEvent::new(
2645                    cx,
2646                    window,
2647                    atom!("pageshow"),
2648                    false, // bubbles
2649                    false, // cancelable
2650                    false, // persisted
2651                );
2652                let page_show_event = page_show_event.upcast::<Event>();
2653                page_show_event.set_trusted(true);
2654                page_show_event.fire(cx, window.upcast());
2655
2656                // Step 9.12. Completely finish loading the Document.
2657                document.completely_finish_loading();
2658
2659                // Step 9.13. Queue the navigation timing entry for the Document.
2660                // TODO
2661
2662                if let Some(fragment) = document.url().fragment() {
2663                    document.scroll_to_the_fragment(cx, fragment);
2664                }
2665            }));
2666
2667        // Step 9.
2668        // TODO: pending application cache download process tasks.
2669
2670        // Step 10.
2671        // TODO: printing steps.
2672
2673        // Step 11.
2674        // TODO: ready for post-load tasks.
2675
2676        // The dom.webxr.sessionavailable pref allows webxr
2677        // content to immediately begin a session without waiting for a user gesture.
2678        // TODO: should this only happen on the first document loaded?
2679        // https://immersive-web.github.io/webxr/#user-intention
2680        // https://github.com/immersive-web/navigation/issues/10
2681        #[cfg(feature = "webxr")]
2682        if pref!(dom_webxr_sessionavailable) && self.window.is_top_level() {
2683            self.window.Navigator(cx).Xr(cx).dispatch_sessionavailable();
2684        }
2685    }
2686
2687    pub(crate) fn completely_loaded(&self) -> bool {
2688        self.completely_loaded.get()
2689    }
2690
2691    pub(crate) fn start_the_end_loading_phase(&self) {
2692        if self.is_initial_about_blank() {
2693            // TODO(47417): Once "creating a new browsing context" properly exists, remove this check
2694            self.current_the_end_loading_phase
2695                .set(TheEndLoadingPhase::Done);
2696        } else {
2697            self.current_the_end_loading_phase
2698                .set(TheEndLoadingPhase::ProcessingDeferredScripts);
2699        }
2700    }
2701
2702    /// <https://html.spec.whatwg.org/multipage/#pending-parsing-blocking-script>
2703    pub(crate) fn set_pending_parsing_blocking_script(
2704        &self,
2705        script: &HTMLScriptElement,
2706        load: Option<ScriptResult>,
2707    ) {
2708        assert!(!self.has_pending_parsing_blocking_script());
2709        *self.pending_parsing_blocking_script.borrow_mut() =
2710            Some(PendingScript::new_with_load(script, load));
2711    }
2712
2713    /// <https://html.spec.whatwg.org/multipage/#pending-parsing-blocking-script>
2714    pub(crate) fn has_pending_parsing_blocking_script(&self) -> bool {
2715        self.pending_parsing_blocking_script.borrow().is_some()
2716    }
2717
2718    /// <https://html.spec.whatwg.org/multipage/#prepare-a-script> step 22.d.
2719    pub(crate) fn pending_parsing_blocking_script_loaded(
2720        &self,
2721        element: &HTMLScriptElement,
2722        result: ScriptResult,
2723        cx: &mut JSContext,
2724    ) {
2725        {
2726            let mut blocking_script = self.pending_parsing_blocking_script.borrow_mut();
2727            let entry = blocking_script.as_mut().unwrap();
2728            assert!(&*entry.element == element);
2729            entry.loaded(result);
2730        }
2731        self.process_pending_parsing_blocking_script(cx);
2732    }
2733
2734    fn process_pending_parsing_blocking_script(&self, cx: &mut JSContext) {
2735        if self.has_a_stylesheet_that_is_blocking_scripts() {
2736            return;
2737        }
2738        let pair = self
2739            .pending_parsing_blocking_script
2740            .borrow_mut()
2741            .as_mut()
2742            .and_then(PendingScript::take_result);
2743        if let Some((element, result)) = pair {
2744            *self.pending_parsing_blocking_script.borrow_mut() = None;
2745            self.get_current_parser()
2746                .unwrap()
2747                .resume_with_pending_parsing_blocking_script(cx, &element, result);
2748        }
2749    }
2750
2751    /// <https://html.spec.whatwg.org/multipage/#set-of-scripts-that-will-execute-as-soon-as-possible>
2752    pub(crate) fn add_asap_script(&self, script: &HTMLScriptElement) {
2753        self.asap_scripts_set
2754            .borrow_mut()
2755            .push(Dom::from_ref(script));
2756    }
2757
2758    /// <https://html.spec.whatwg.org/multipage/#the-end> step 5.
2759    /// <https://html.spec.whatwg.org/multipage/#prepare-a-script> step 22.d.
2760    pub(crate) fn asap_script_loaded(
2761        &self,
2762        cx: &mut JSContext,
2763        element: &HTMLScriptElement,
2764        result: ScriptResult,
2765    ) {
2766        {
2767            let mut scripts = self.asap_scripts_set.borrow_mut();
2768            let idx = scripts
2769                .iter()
2770                .position(|entry| &**entry == element)
2771                .unwrap();
2772            scripts.swap_remove(idx);
2773        }
2774        element.execute(cx, result);
2775        self.wait_until_asap_scripts_have_executed();
2776    }
2777
2778    /// <https://html.spec.whatwg.org/multipage/#list-of-scripts-that-will-execute-in-order-as-soon-as-possible>
2779    pub(crate) fn push_asap_in_order_script(&self, script: &HTMLScriptElement) {
2780        self.asap_in_order_scripts_list.push(script);
2781    }
2782
2783    /// <https://html.spec.whatwg.org/multipage/#the-end> step 5.
2784    /// <https://html.spec.whatwg.org/multipage/#prepare-a-script> step> 22.c.
2785    pub(crate) fn asap_in_order_script_loaded(
2786        &self,
2787        cx: &mut JSContext,
2788        element: &HTMLScriptElement,
2789        result: ScriptResult,
2790    ) {
2791        self.asap_in_order_scripts_list.loaded(element, result);
2792        while let Some((element, result)) = self
2793            .asap_in_order_scripts_list
2794            .take_next_ready_to_be_executed()
2795        {
2796            element.execute(cx, result);
2797        }
2798
2799        self.wait_until_asap_scripts_have_executed();
2800    }
2801
2802    /// <https://html.spec.whatwg.org/multipage/#list-of-scripts-that-will-execute-when-the-document-has-finished-parsing>
2803    pub(crate) fn add_deferred_script(&self, script: &HTMLScriptElement) {
2804        self.deferred_scripts.push(script);
2805    }
2806
2807    /// <https://html.spec.whatwg.org/multipage/#the-end> step 3.
2808    /// <https://html.spec.whatwg.org/multipage/#prepare-a-script> step 22.d.
2809    pub(crate) fn deferred_script_loaded(
2810        &self,
2811        cx: &mut JSContext,
2812        element: &HTMLScriptElement,
2813        result: ScriptResult,
2814    ) {
2815        self.deferred_scripts.loaded(element, result);
2816        self.process_deferred_scripts(cx);
2817    }
2818
2819    /// Step 5 of <https://html.spec.whatwg.org/multipage/#the-end>
2820    fn process_deferred_scripts(&self, cx: &mut JSContext) {
2821        if self.current_the_end_loading_phase.get() != TheEndLoadingPhase::ProcessingDeferredScripts
2822        {
2823            return;
2824        }
2825
2826        // Step 5. While the list of scripts that will execute when the document has finished
2827        // parsing is not empty:
2828        // Step 5.1. Spin the event loop until the first script in the list of scripts that will
2829        // execute when the document has finished parsing has its ready to be parser-executed set to
2830        // true and the parser's Document has no style sheet that is blocking scripts.
2831        loop {
2832            if self.deferred_scripts.is_empty() {
2833                break;
2834            }
2835            if self.has_a_stylesheet_that_is_blocking_scripts() {
2836                return;
2837            }
2838            // Step 5.3. Remove the first script element from the list of scripts that will execute
2839            // when the document has finished parsing (i.e. shift out the first entry in the list).
2840            if let Some((element, result)) = self.deferred_scripts.take_next_ready_to_be_executed()
2841            {
2842                // Step 5.2. Execute the script element given by the first script in the list of
2843                // scripts that will execute when the document has finished parsing.
2844                element.execute(cx, result);
2845            } else {
2846                break;
2847            }
2848        }
2849
2850        // If the list of scripts is empty, we can move on to the next step, otherwise we will
2851        // re-enter this method as the ScriptThread's event loop spins.
2852        if self.deferred_scripts.is_empty() {
2853            self.current_the_end_loading_phase
2854                .set(TheEndLoadingPhase::ProcessingAsSoonAsPossibleScripts);
2855            self.dispatch_dom_content_loaded();
2856        }
2857    }
2858
2859    /// Step 6 of <https://html.spec.whatwg.org/multipage/#the-end>
2860    fn dispatch_dom_content_loaded(&self) {
2861        assert_ne!(
2862            self.ReadyState(),
2863            DocumentReadyState::Complete,
2864            "Complete before DOMContentLoaded?"
2865        );
2866
2867        // Step 6. Queue a global task on the DOM manipulation task source given the Document's
2868        // relevant global object to run the following substeps:
2869        let document = Trusted::new(self);
2870        self.owner_global()
2871            .task_manager()
2872            .dom_manipulation_task_source()
2873            .queue(task!(fire_dom_content_loaded_event: move |cx| {
2874                // Step 6.1. Set the Document's load timing info's DOM content loaded event start time to
2875                // the current high resolution time given the Document's relevant global object.
2876                let document = document.root();
2877                update_with_current_instant(&document.navigation_timing.dom_content_loaded_event_start);
2878                // Step 6.2. Fire an event named DOMContentLoaded at the Document object, with its bubbles attribute initialized to true.
2879                document.upcast::<EventTarget>().fire_bubbling_event(cx, atom!("DOMContentLoaded"));
2880                // Step 6.3. Set the Document's load timing info's DOM content loaded event end time to
2881                // the current high resolution time given the Document's relevant global object.
2882                update_with_current_instant(&document.navigation_timing.dom_content_loaded_event_end);
2883                // Step 6.4. Enable the client message queue of the ServiceWorkerContainer object
2884                // whose associated service worker client is the Document object's relevant settings object.
2885                // TODO
2886
2887                // Step 6.5. Invoke WebDriver BiDi DOM content loaded with the Document's browsing context,
2888                // and a new WebDriver BiDi navigation status whose id is the Document object's during-loading
2889                // navigation ID for WebDriver BiDi, status is "pending", and url is the Document object's URL.
2890                // TODO
2891            }));
2892
2893        // html parsing has finished - set dom content loaded
2894        self.interactive_time
2895            .borrow()
2896            .maybe_set_tti(InteractiveFlag::DOMContentLoaded);
2897
2898        self.wait_until_asap_scripts_have_executed();
2899    }
2900
2901    fn has_finished_all_asap_scripts(&self) -> bool {
2902        self.asap_scripts_set.borrow().is_empty() && self.asap_in_order_scripts_list.is_empty()
2903    }
2904
2905    /// Step 7 of <https://html.spec.whatwg.org/multipage/#the-end>
2906    fn wait_until_asap_scripts_have_executed(&self) {
2907        if self.current_the_end_loading_phase.get() !=
2908            TheEndLoadingPhase::ProcessingAsSoonAsPossibleScripts
2909        {
2910            return;
2911        }
2912        // Step 7. Spin the event loop until the set of scripts that will execute as soon as possible
2913        // and the list of scripts that will execute in order as soon as possible are empty.
2914        if self.has_finished_all_asap_scripts() {
2915            let document = Trusted::new(self);
2916            self.owner_global()
2917                .task_manager()
2918                .dom_manipulation_task_source()
2919                .queue(task!(transition_away_from_asap_scripts: move |cx| {
2920                    let document = document.root();
2921                    // Ensure that if this task is fired multiple times, we only progress the
2922                    // end of loading phase once.
2923                    if document.current_the_end_loading_phase.get() !=
2924                        TheEndLoadingPhase::ProcessingAsSoonAsPossibleScripts
2925                    {
2926                        return;
2927                    }
2928                    // Check again if we still fulfil the goal
2929                    if !document.has_finished_all_asap_scripts() {
2930                        return;
2931                    }
2932                    document.current_the_end_loading_phase
2933                        .set(TheEndLoadingPhase::WaitingForLoadEventBlockers);
2934                    document.wait_until_load_blockers_have_resolved(cx);
2935                }));
2936        }
2937    }
2938
2939    /// Step 8 of <https://html.spec.whatwg.org/multipage/#the-end>
2940    pub(crate) fn wait_until_load_blockers_have_resolved(&self, cx: &mut JSContext) {
2941        if self.current_the_end_loading_phase.get() !=
2942            TheEndLoadingPhase::WaitingForLoadEventBlockers
2943        {
2944            return;
2945        }
2946        // Step 8. Spin the event loop until there is nothing that delays the load event in the Document.
2947        {
2948            let loader = self.loader.borrow();
2949
2950            // Servo measures when the top-level content (not iframes) is loaded.
2951            if self
2952                .navigation_timing
2953                .top_level_dom_complete
2954                .get()
2955                .is_none() &&
2956                loader.is_only_blocked_by_iframes()
2957            {
2958                update_with_current_instant(&self.navigation_timing.top_level_dom_complete);
2959            }
2960
2961            let not_ready_for_load = loader.is_blocked() || loader.events_inhibited();
2962            if not_ready_for_load {
2963                return;
2964            }
2965        }
2966
2967        self.current_the_end_loading_phase
2968            .set(TheEndLoadingPhase::Done);
2969        self.queue_document_completion(cx);
2970    }
2971
2972    /// <https://html.spec.whatwg.org/multipage/#destroy-a-document-and-its-descendants>
2973    pub(crate) fn destroy_document_and_its_descendants(&self, cx: &mut JSContext) {
2974        // Step 1. If document is not fully active, then:
2975        if !self.is_fully_active() {
2976            // Step 1.1. Let reason be a string from user-agent specific blocking reasons.
2977            // If none apply, then let reason be "masked".
2978            // TODO
2979            // Step 1.2. Make document unsalvageable given document and reason.
2980            self.salvageable.set(false);
2981            // Step 1.3. If document's node navigable is a top-level traversable,
2982            // build not restored reasons for a top-level traversable and its descendants given document's node navigable.
2983            // TODO
2984        }
2985        // TODO(#31973): all of the steps below are implemented synchronously at the moment.
2986        // They need to become asynchronous later, at which point the counting of
2987        // numberDestroyed becomes relevant.
2988
2989        // Step 2. Let childNavigables be document's child navigables.
2990        // Step 3. Let numberDestroyed be 0.
2991        // Step 4. For each childNavigable of childNavigables, queue a global task on
2992        // the navigation and traversal task source given childNavigable's active
2993        // window to perform the following steps:
2994        // Step 4.1. Let incrementDestroyed be an algorithm step which increments numberDestroyed.
2995        // Step 4.2. Destroy a document and its descendants given childNavigable's active document and incrementDestroyed.
2996        // Step 5. Wait until numberDestroyed equals childNavigable's size.
2997        for exited_iframe in self.iframes().iter() {
2998            debug!("Destroying nested iframe document");
2999            exited_iframe.destroy_document_and_its_descendants(cx);
3000        }
3001        // Step 6. Queue a global task on the navigation and traversal task source
3002        // given document's relevant global object to perform the following steps:
3003        // TODO
3004        // Step 6.1. Destroy document.
3005        self.destroy(cx);
3006        // Step 6.2. If afterAllDestruction was given, then run it.
3007        // TODO
3008    }
3009
3010    /// <https://html.spec.whatwg.org/multipage/#destroy-a-document>
3011    pub(crate) fn destroy(&self, cx: &mut JSContext) {
3012        let exited_window = self.window();
3013        // Step 2. Abort document.
3014        self.abort(cx, AbortReason::Destroy);
3015        // Step 3. Set document's salvageable state to false.
3016        self.salvageable.set(false);
3017        // Step 4. Let ports be the list of MessagePorts whose relevant
3018        // global object's associated Document is document.
3019        // TODO
3020
3021        // Step 5. For each port in ports, disentangle port.
3022        // TODO
3023
3024        // Step 6. Run any unloading document cleanup steps for document that
3025        // are defined by this specification and other applicable specifications.
3026        self.unloading_cleanup_steps(cx);
3027
3028        // Step 7. Remove any tasks whose document is document from any task queue
3029        // (without running those tasks).
3030        exited_window
3031            .as_global_scope()
3032            .task_manager()
3033            .cancel_all_tasks_and_ignore_future_tasks();
3034
3035        // Step 8. Set document's browsing context to null.
3036        exited_window.discard_browsing_context();
3037
3038        // Step 9. Set document's node navigable's active session history entry's
3039        // document state's document to null.
3040        // TODO
3041
3042        // Step 10. Remove document from the owner set of each WorkerGlobalScope
3043        // object whose set contains document.
3044        exited_window
3045            .as_global_scope()
3046            .disable_owned_worker_animation_frame_providers();
3047
3048        // Step 11. For each workletGlobalScope in document's worklet global scopes,
3049        // terminate workletGlobalScope.
3050        // TODO
3051
3052        // This is not a specification step but needs to be done in order to ensure proper
3053        // garbage collection of this global scope.
3054        exited_window.as_global_scope().tear_down();
3055    }
3056
3057    /// <https://html.spec.whatwg.org/multipage/#active-parser>
3058    fn active_parser(&self) -> Option<DomRoot<ServoParser>> {
3059        // > A Document is said to have an active parser if it is associated with
3060        // > an HTML parser or an XML parser that has not yet been stopped or aborted.
3061        self.get_current_parser()
3062            .filter(|parser| !(parser.has_stopped() || parser.has_aborted()))
3063    }
3064
3065    /// <https://html.spec.whatwg.org/multipage/#abort-a-document>
3066    pub(crate) fn abort(&self, cx: &mut JSContext, reason: AbortReason) {
3067        // We need to inhibit the loader before anything else and prevent any further movement
3068        // through "the-end" loading phases.
3069        self.loader.borrow_mut().abort();
3070        self.current_the_end_loading_phase
3071            .set(TheEndLoadingPhase::Done);
3072
3073        // Step 1. Assert: this is running as part of a task queued on document's relevant agent's event loop.
3074        // TODO
3075
3076        // Step 2. Cancel any instances of the fetch algorithm in the context of document,
3077        // discarding any tasks queued for them, and discarding any further data received
3078        // from the network for them. If this resulted in any instances of the fetch algorithm
3079        // being canceled or any queued tasks or any network data getting discarded,
3080        // then make document unsalvageable given document and "fetch".
3081        self.script_blocking_stylesheet_set.borrow_mut().clear();
3082        *self.pending_parsing_blocking_script.borrow_mut() = None;
3083        *self.asap_scripts_set.borrow_mut() = vec![];
3084        self.asap_in_order_scripts_list.clear();
3085        self.deferred_scripts.clear();
3086
3087        let global = self.window.as_global_scope();
3088        let loads_cancelled = global.fetch_group_mut().terminate(global);
3089        let event_sources_canceled = global.close_event_sources();
3090
3091        if loads_cancelled || event_sources_canceled {
3092            // If any loads were canceled.
3093            self.salvageable.set(false);
3094        };
3095
3096        // Also Step 2.
3097        // Note: the spec says to discard any tasks queued for fetch.
3098        // This cancels all tasks on the networking task source, which might be too broad.
3099        // See https://github.com/whatwg/html/issues/3837
3100        self.owner_global()
3101            .task_manager()
3102            .cancel_pending_tasks_for_source(TaskSourceName::Networking);
3103
3104        // Step 3. If document's during-loading navigation ID for WebDriver BiDi is non-null, then:
3105        // TODO
3106
3107        // Step 4. If document has an active parser, then:
3108        if let Some(parser) = self.active_parser() {
3109            // Step 4.1. Set document's active parser was aborted to true.
3110            self.active_parser_was_aborted.set(true);
3111            // Step 4.2. Abort that parser.
3112            parser.abort(cx, reason);
3113            // Step 4.3. Make document unsalvageable given document and "parser-aborted".
3114            self.salvageable.set(false);
3115        } else if self.ready_state.get() != DocumentReadyState::Complete {
3116            // See <https://github.com/whatwg/html/issues/5535>.
3117            // All browsers set the document readiness to "complete" when aborting, even though
3118            // it isn't specified. In addition, WPT tests depend on this happening.
3119            let document = Trusted::new(self);
3120            self.owner_global()
3121                .task_manager()
3122                .dom_manipulation_task_source()
3123                .queue(task!(fire_complete: move |cx| {
3124                    let document = document.root();
3125                    if document.is_fully_active() {
3126                        document.update_the_current_document_readiness(cx, DocumentReadyState::Complete)
3127                    }
3128                }));
3129        }
3130
3131        self.window().allow_layout_if_necessary(cx);
3132    }
3133
3134    /// <https://html.spec.whatwg.org/multipage/#abort-a-document-and-its-descendants>
3135    pub(crate) fn abort_a_document_and_its_descendants(
3136        &self,
3137        cx: &mut JSContext,
3138        reason: AbortReason,
3139    ) {
3140        // Step 1. Assert: this is running as part of a task queued on document's relevant agent's event loop.
3141        // TODO
3142
3143        // Step 2. Let descendantNavigables be document's descendant navigables.
3144        // Step 3. For each descendantNavigable of descendantNavigables,
3145        // queue a global task on the navigation and traversal task source given
3146        // descendantNavigable's active window to perform the following steps:
3147        for iframe in self.iframes().iter() {
3148            if let Some(descendant_document) = iframe.GetContentDocument() {
3149                let trusted_descendant_document = Trusted::new(&*descendant_document);
3150                let document = Trusted::new(self);
3151                descendant_document
3152                    .owner_global()
3153                    .task_manager()
3154                    .navigation_and_traversal_task_source()
3155                    .queue(task!(abort_iframe_document: move |cx| {
3156                        let descendant_document = trusted_descendant_document.root();
3157                        // Step 3.1. Abort descendantNavigable's active document.
3158                        descendant_document.abort(cx, reason);
3159                        // Step 3.2. If descendantNavigable's active document's salvageable is false, then set document's salvageable to false.
3160                        if !descendant_document.salvageable.get() {
3161                            document.root().salvageable.set(false);
3162                        }
3163                    }));
3164            }
3165        }
3166
3167        // Step 4. Abort document.
3168        self.abort(cx, reason);
3169    }
3170
3171    pub(crate) fn notify_constellation_that_load_finished(&self, aborted: bool) {
3172        self.window()
3173            .send_to_constellation(ScriptToConstellationMessage::LoadFinished { aborted });
3174    }
3175
3176    pub(crate) fn set_current_parser(&self, script: Option<&ServoParser>, reason: SetParserReason) {
3177        trace!(
3178            "{} parser for {:?} due to {:?}",
3179            if script.is_some() {
3180                "setting"
3181            } else {
3182                "clearing"
3183            },
3184            self.url(),
3185            reason
3186        );
3187        self.current_parser.set(script);
3188    }
3189
3190    pub(crate) fn get_current_parser(&self) -> Option<DomRoot<ServoParser>> {
3191        self.current_parser.get()
3192    }
3193
3194    pub(crate) fn get_current_parser_line(&self) -> u32 {
3195        self.get_current_parser()
3196            .map(|parser| parser.get_current_line())
3197            .unwrap_or(0)
3198    }
3199
3200    /// <https://html.spec.whatwg.org/multipage/#concept-document-ancestor-origins-list>
3201    pub(crate) fn set_ancestor_origins_list(&self, ancestor_origins_list: &DOMStringList) {
3202        self.ancestor_origins_list.set(Some(ancestor_origins_list));
3203    }
3204
3205    /// <https://html.spec.whatwg.org/multipage/#concept-document-ancestor-origins-list>
3206    pub(crate) fn ancestor_origins_list(&self) -> Option<DomRoot<DOMStringList>> {
3207        self.ancestor_origins_list.get()
3208    }
3209
3210    /// <https://html.spec.whatwg.org/multipage/#concept-document-internal-ancestor-origin-objects-list>
3211    pub(crate) fn set_internal_ancestor_origin_objects_list(
3212        &self,
3213        internal_ancestor_origin_objects_list: Vec<ImmutableOrigin>,
3214    ) {
3215        *self.internal_ancestor_origin_objects_list.borrow_mut() =
3216            Some(internal_ancestor_origin_objects_list);
3217    }
3218
3219    /// <https://html.spec.whatwg.org/multipage/#concept-document-internal-ancestor-origin-objects-list>
3220    pub(crate) fn internal_ancestor_origin_objects_list(
3221        &self,
3222    ) -> Ref<'_, Option<Vec<ImmutableOrigin>>> {
3223        self.internal_ancestor_origin_objects_list.borrow()
3224    }
3225
3226    /// A reference to the [`IFrameCollection`] of this [`Document`], holding information about
3227    /// `<iframe>`s found within it.
3228    pub(crate) fn iframes(&self) -> &IFrameCollection {
3229        &self.iframes
3230    }
3231
3232    pub(crate) fn set_navigation_start(&self, navigation_start: CrossProcessInstant) {
3233        self.interactive_time
3234            .borrow_mut()
3235            .set_navigation_start(navigation_start);
3236    }
3237
3238    pub(crate) fn get_interactive_metrics(&self) -> Ref<'_, ProgressiveWebMetrics> {
3239        self.interactive_time.borrow()
3240    }
3241
3242    pub(crate) fn has_recorded_tti_metric(&self) -> bool {
3243        self.get_interactive_metrics().get_tti().is_some()
3244    }
3245
3246    pub(crate) fn start_tti(&self) {
3247        if self.get_interactive_metrics().needs_tti() {
3248            self.tti_window.borrow_mut().start_window();
3249        }
3250    }
3251
3252    /// check tti for this document
3253    /// if it's been 10s since this doc encountered a task over 50ms, then we consider the
3254    /// main thread available and try to set tti
3255    pub(crate) fn record_tti_if_necessary(&self) {
3256        if self.has_recorded_tti_metric() {
3257            return;
3258        }
3259        if self.tti_window.borrow().needs_check() {
3260            self.get_interactive_metrics()
3261                .maybe_set_tti(InteractiveFlag::TimeToInteractive(
3262                    self.tti_window.borrow().get_start(),
3263                ));
3264        }
3265    }
3266
3267    /// <https://html.spec.whatwg.org/multipage/#cookie-averse-document-object>
3268    pub(crate) fn is_cookie_averse(&self) -> bool {
3269        !self.has_browsing_context || !url_has_network_scheme(&self.url())
3270    }
3271
3272    pub(crate) fn custom_element_registry(&self) -> Option<DomRoot<CustomElementRegistry>> {
3273        self.document_or_shadow_root.custom_element_registry()
3274    }
3275
3276    pub(crate) fn set_custom_element_registry(&self, registry: &CustomElementRegistry) {
3277        self.document_or_shadow_root
3278            .set_custom_element_registry(Some(registry));
3279    }
3280
3281    /// <https://dom.spec.whatwg.org/#effective-global-custom-element-registry>
3282    pub(crate) fn effective_global_custom_element_registry(
3283        &self,
3284    ) -> Option<DomRoot<CustomElementRegistry>> {
3285        // Step 1. If document's custom element registry is a global custom element
3286        // registry, then return document's custom element registry..
3287        let document_custom_element_registry = self.custom_element_registry();
3288        if CustomElementRegistry::is_a_global_element_registry(
3289            document_custom_element_registry.as_deref(),
3290        ) {
3291            return document_custom_element_registry;
3292        }
3293        // Step 2. Return null.
3294        None
3295    }
3296
3297    /// Cleans up any active promises
3298    /// <https://github.com/servo/servo/issues/15318>
3299    pub(crate) fn teardown_custom_element_registry(&self) {
3300        if let Some(custom_elements) = self.custom_element_registry() {
3301            custom_elements.teardown();
3302        }
3303    }
3304
3305    pub(crate) fn increment_throw_on_dynamic_markup_insertion_counter(&self) {
3306        let counter = self.throw_on_dynamic_markup_insertion_counter.get();
3307        self.throw_on_dynamic_markup_insertion_counter
3308            .set(counter + 1);
3309    }
3310
3311    pub(crate) fn decrement_throw_on_dynamic_markup_insertion_counter(&self) {
3312        let counter = self.throw_on_dynamic_markup_insertion_counter.get();
3313        self.throw_on_dynamic_markup_insertion_counter
3314            .set(counter - 1);
3315    }
3316
3317    pub(crate) fn react_to_environment_changes(&self, cx: &JSContext) {
3318        for image in self.responsive_images.borrow().iter() {
3319            image.react_to_environment_changes(cx);
3320        }
3321    }
3322
3323    pub(crate) fn register_responsive_image(&self, img: &HTMLImageElement) {
3324        self.responsive_images.borrow_mut().push(Dom::from_ref(img));
3325    }
3326
3327    pub(crate) fn unregister_responsive_image(&self, img: &HTMLImageElement) {
3328        let index = self
3329            .responsive_images
3330            .borrow()
3331            .iter()
3332            .position(|x| **x == *img);
3333        if let Some(i) = index {
3334            self.responsive_images.borrow_mut().remove(i);
3335        }
3336    }
3337
3338    pub(crate) fn register_media_controls(&self, id: &str, controls: &ShadowRoot) {
3339        let did_have_these_media_controls = self
3340            .media_controls
3341            .borrow_mut()
3342            .insert(id.to_string(), Dom::from_ref(controls))
3343            .is_some();
3344        debug_assert!(
3345            !did_have_these_media_controls,
3346            "Trying to register known media controls"
3347        );
3348    }
3349
3350    pub(crate) fn unregister_media_controls(&self, id: &str) {
3351        let did_have_these_media_controls = self.media_controls.borrow_mut().remove(id).is_some();
3352        debug_assert!(
3353            did_have_these_media_controls,
3354            "Trying to unregister unknown media controls"
3355        );
3356    }
3357
3358    pub(crate) fn mark_canvas_as_dirty(&self, canvas: &Dom<HTMLCanvasElement>) {
3359        let mut dirty_canvases = self.dirty_canvases.borrow_mut();
3360        if dirty_canvases
3361            .iter()
3362            .any(|dirty_canvas| dirty_canvas == canvas)
3363        {
3364            return;
3365        }
3366        dirty_canvases.push(canvas.clone());
3367    }
3368
3369    /// Whether or not this [`Document`] needs a rendering update, due to changed
3370    /// contents or pending events. This is used to decide whether or not to schedule
3371    /// a call to the "update the rendering" algorithm.
3372    pub(crate) fn needs_rendering_update(&self, no_gc: &NoGC) -> bool {
3373        if !self.is_fully_active() {
3374            return false;
3375        }
3376        if !self.window().layout_blocked() &&
3377            (!self.restyle_reason(no_gc).is_empty() ||
3378                self.window().layout().needs_new_display_list() ||
3379                self.window().layout().needs_accessibility_update())
3380        {
3381            return true;
3382        }
3383        if !self.rendering_update_reasons.get().is_empty() {
3384            return true;
3385        }
3386        if self.event_handler.has_pending_input_events() {
3387            return true;
3388        }
3389        if self.has_pending_scroll_events() {
3390            return true;
3391        }
3392        if self.window().has_unhandled_resize_event() {
3393            return true;
3394        }
3395        if self.has_pending_animated_image_update.get() || !self.dirty_canvases.borrow().is_empty()
3396        {
3397            return true;
3398        }
3399        if self.window().has_pending_media_query_evaluation() {
3400            return true;
3401        }
3402        if self
3403            .selection()
3404            .is_some_and(|selection| selection.visible_selection_dirty())
3405        {
3406            return true;
3407        }
3408
3409        false
3410    }
3411
3412    /// <https://www.w3.org/TR/paint-timing/#mark-paint-timing>
3413    pub(crate) fn mark_paint_timing(&self) {
3414        // Step 2. Let paintTimingInfo be a new paint timing info, whose
3415        // rendering update end time is the current high resolution time given
3416        // document's relevant global object.
3417        self.paint_timing_info.set(PaintTimingInfo::now());
3418    }
3419
3420    /// <https://www.w3.org/TR/paint-timing/#paint-timing-info>
3421    pub(crate) fn paint_timing_info(&self) -> PaintTimingInfo {
3422        self.paint_timing_info.get()
3423    }
3424
3425    /// An implementation of step 21, 22 from
3426    /// <https://html.spec.whatwg.org/multipage/#update-the-rendering>:
3427    ///
3428    /// Returns the set of reflow phases run as a [`ReflowPhasesRun`].
3429    pub(crate) fn update_the_rendering(
3430        &self,
3431        cx: &mut JSContext,
3432    ) -> (ReflowPhasesRun, ReflowStatistics) {
3433        assert!(!self.is_render_blocked());
3434        // Step 21. For each doc of docs, mark paint timing for doc.
3435        self.mark_paint_timing();
3436
3437        // Step 22: For each doc of docs, update the rendering or user interface of
3438        // doc and its node navigable to reflect the current state.
3439        let mut phases = ReflowPhasesRun::empty();
3440        if self.has_pending_animated_image_update.get() {
3441            self.animation_manager.update_active_image_animation_frames(
3442                &self.window,
3443                self.current_animation_timeline_value(),
3444            );
3445            self.has_pending_animated_image_update.set(false);
3446            phases.insert(ReflowPhasesRun::UpdatedImageData);
3447        }
3448
3449        self.current_rendering_epoch
3450            .set(self.current_rendering_epoch.get().next());
3451        let current_rendering_epoch = self.current_rendering_epoch.get();
3452
3453        // All dirty canvases are flushed before updating the rendering.
3454        let image_keys: Vec<_> = self
3455            .dirty_canvases
3456            .borrow_mut()
3457            .drain(..)
3458            .filter_map(|canvas| canvas.update_rendering(current_rendering_epoch))
3459            .collect();
3460
3461        // The renderer should wait to display the frame until all canvas images are
3462        // uploaded. This allows canvas image uploading to happen asynchronously.
3463        let pipeline_id = self.window().pipeline_id();
3464        if !image_keys.is_empty() {
3465            phases.insert(ReflowPhasesRun::UpdatedImageData);
3466            self.waiting_on_canvas_image_updates.set(true);
3467            self.window().paint_api().delay_new_frame_for_canvas(
3468                self.webview_id(),
3469                self.window().pipeline_id(),
3470                current_rendering_epoch,
3471                image_keys,
3472            );
3473        }
3474
3475        let (reflow_phases, statistics) = self.window().reflow(cx, ReflowGoal::UpdateTheRendering);
3476        let phases = phases.union(reflow_phases);
3477
3478        self.window().paint_api().update_epoch(
3479            self.webview_id(),
3480            pipeline_id,
3481            current_rendering_epoch,
3482        );
3483
3484        (phases, statistics)
3485    }
3486
3487    pub(crate) fn handle_no_longer_waiting_on_asynchronous_image_updates(&self) {
3488        self.waiting_on_canvas_image_updates.set(false);
3489    }
3490
3491    pub(crate) fn waiting_on_canvas_image_updates(&self) -> bool {
3492        self.waiting_on_canvas_image_updates.get()
3493    }
3494
3495    /// From <https://drafts.csswg.org/css-font-loading/#fontfaceset-pending-on-the-environment>:
3496    ///
3497    /// > A FontFaceSet is pending on the environment if any of the following are true:
3498    /// >  - the document is still loading
3499    /// >  - the document has pending stylesheet requests
3500    /// >  - the document has pending layout operations which might cause the user agent to request
3501    /// >    a font, or which depend on recently-loaded fonts
3502    ///
3503    /// Returns true if the promise was fulfilled.
3504    pub(crate) fn maybe_fulfill_font_ready_promise(&self, cx: &mut JSContext) -> bool {
3505        if !self.is_fully_active() {
3506            return false;
3507        }
3508
3509        let fonts = self.Fonts(cx);
3510        if !fonts.waiting_to_fullfill_promise() {
3511            return false;
3512        }
3513        if self.window().font_context().web_fonts_still_loading() != 0 {
3514            return false;
3515        }
3516        if self.ReadyState() != DocumentReadyState::Complete {
3517            return false;
3518        }
3519        if !self.restyle_reason(cx.no_gc()).is_empty() {
3520            return false;
3521        }
3522        if !self.rendering_update_reasons.get().is_empty() {
3523            return false;
3524        }
3525
3526        let result = fonts.fulfill_ready_promise_if_needed(cx);
3527
3528        // Add a rendering update after the `fonts.ready` promise is fulfilled just for
3529        // the sake of taking screenshots. This has the effect of delaying screenshots
3530        // until layout has taken a shot at updating the rendering.
3531        if result {
3532            self.add_rendering_update_reason(RenderingUpdateReason::FontReadyPromiseFulfilled);
3533        }
3534
3535        result
3536    }
3537
3538    pub(crate) fn id_map(&self) -> &TreeOrderedIndexMap {
3539        &self.id_map
3540    }
3541
3542    /// <https://drafts.csswg.org/resize-observer/#lifetime>
3543    pub(crate) fn add_resize_observer(&self, no_gc: &NoGC, resize_observer: &ResizeObserver) {
3544        let mut resize_observers = self.resize_observers.safe_borrow_mut(no_gc);
3545        let mut insertion_index = None;
3546        for (index, existing_resize_observer) in resize_observers.iter().enumerate() {
3547            if &**existing_resize_observer == resize_observer {
3548                return;
3549            }
3550            if existing_resize_observer.created_after(resize_observer) {
3551                insertion_index = Some(index);
3552                break;
3553            }
3554        }
3555
3556        match insertion_index {
3557            Some(index) => resize_observers.insert(index, Dom::from_ref(resize_observer)),
3558            None => resize_observers.push(Dom::from_ref(resize_observer)),
3559        }
3560    }
3561
3562    pub(crate) fn remove_resize_observer(&self, no_gc: &NoGC, resize_observer: &ResizeObserver) {
3563        self.resize_observers
3564            .safe_borrow_mut(no_gc)
3565            .retain(|existing_resize_observer| &**existing_resize_observer != resize_observer);
3566    }
3567
3568    /// <https://drafts.csswg.org/resize-observer/#gather-active-observations-h>
3569    /// <https://drafts.csswg.org/resize-observer/#has-active-resize-observations>
3570    pub(crate) fn gather_active_resize_observations_at_depth(
3571        &self,
3572        cx: &mut JSContext,
3573        depth: &ResizeObservationDepth,
3574    ) -> bool {
3575        // This does not trigger a creation of ResizeObserver, hence, we can take a simple borrow.
3576        let mut has_active_resize_observations = false;
3577        for observer in self.resize_observers.borrow().iter() {
3578            observer.gather_active_resize_observations_at_depth(
3579                cx,
3580                depth,
3581                &mut has_active_resize_observations,
3582            );
3583        }
3584        has_active_resize_observations
3585    }
3586
3587    /// <https://drafts.csswg.org/resize-observer/#broadcast-active-resize-observations>
3588    pub(crate) fn broadcast_active_resize_observations(
3589        &self,
3590        cx: &mut JSContext,
3591    ) -> ResizeObservationDepth {
3592        // As the interior of the loop can trigger creation of new ResizeObservers (which mutably borrows `resize_observers`, we have to clone the fields.
3593        let mut shallowest = ResizeObservationDepth::max();
3594        rooted_vec!(let observers <- self.resize_observers.borrow().iter().cloned());
3595        for observer in &*observers {
3596            observer.broadcast_active_resize_observations(cx, &mut shallowest);
3597        }
3598        shallowest
3599    }
3600
3601    /// <https://drafts.csswg.org/resize-observer/#has-skipped-observations-h>
3602    pub(crate) fn has_skipped_resize_observations(&self) -> bool {
3603        self.resize_observers
3604            .borrow()
3605            .iter()
3606            .any(|observer| observer.has_skipped_resize_observations())
3607    }
3608
3609    /// <https://drafts.csswg.org/resize-observer/#deliver-resize-loop-error-notification>
3610    pub(crate) fn deliver_resize_loop_error_notification(&self, cx: &mut JSContext) {
3611        let error_info: ErrorInfo = crate::dom::bindings::error::ErrorInfo {
3612            message: "ResizeObserver loop completed with undelivered notifications.".to_string(),
3613            ..Default::default()
3614        };
3615        self.window
3616            .as_global_scope()
3617            .report_an_error(cx, error_info, HandleValue::null());
3618    }
3619
3620    pub(crate) fn status_code(&self) -> Option<u16> {
3621        self.status_code
3622    }
3623
3624    /// <https://html.spec.whatwg.org/multipage/#encoding-parsing-a-url>
3625    pub(crate) fn encoding_parse_a_url(&self, url: &str) -> Result<ServoUrl, url::ParseError> {
3626        // Step 4. Let baseURL be environment's base URL, if environment is a Document object;
3627        // otherwise environment's API base URL.
3628        self.encoding_parse_a_url_with_base(url, &self.base_url())
3629    }
3630
3631    /// <https://html.spec.whatwg.org/multipage/#encoding-parsing-a-url>
3632    ///
3633    /// Like [`Self::encoding_parse_a_url`], but resolves relative to the given base URL
3634    /// instead of the document's current one. This is for callers that must use the
3635    /// document's base URL from an earlier point in time.
3636    pub(crate) fn encoding_parse_a_url_with_base(
3637        &self,
3638        url: &str,
3639        base_url: &ServoUrl,
3640    ) -> Result<ServoUrl, url::ParseError> {
3641        // NOTE: This algorithm is defined for both Document and environment settings objects.
3642        // This implementation is only for documents.
3643
3644        // Step 1. Let encoding be UTF-8.
3645        // Step 2. If environment is a Document object, then set encoding to environment's character encoding.
3646        let encoding = self.encoding.get();
3647
3648        // Step 3. Otherwise, if environment's relevant global object is a Window object, set encoding to environment's
3649        // relevant global object's associated Document's character encoding.
3650
3651        // Step 5. Return the result of applying the URL parser to url, with baseURL and encoding.
3652        url::Url::options()
3653            .base_url(Some(base_url.as_url()))
3654            .encoding_override(Some(&|input| {
3655                servo_url::encoding::encode_as_url_query_string(input, encoding)
3656            }))
3657            .parse(url)
3658            .map(ServoUrl::from)
3659    }
3660
3661    /// <https://html.spec.whatwg.org/multipage/#allowed-to-use>
3662    pub(crate) fn allowed_to_use_feature(&self, _feature: PermissionName) -> bool {
3663        // Step 1. If document's browsing context is null, then return false.
3664        if !self.has_browsing_context {
3665            return false;
3666        }
3667
3668        // Step 2. If document is not fully active, then return false.
3669        if !self.is_fully_active() {
3670            return false;
3671        }
3672
3673        // Step 3. If the result of running is feature enabled in document for origin on
3674        // feature, document, and document's origin is "Enabled", then return true.
3675        // Step 4. Return false.
3676        // TODO: All features are currently enabled for `Document`s because we do not
3677        // implement the Permissions Policy specification.
3678        true
3679    }
3680
3681    /// Add an [`IntersectionObserver`] to the [`Document`], to be processed in the [`Document`]'s event loop.
3682    /// <https://github.com/w3c/IntersectionObserver/issues/525>
3683    pub(crate) fn add_intersection_observer(&self, intersection_observer: &IntersectionObserver) {
3684        self.intersection_observers
3685            .borrow_mut()
3686            .push(Dom::from_ref(intersection_observer));
3687    }
3688
3689    /// Remove an [`IntersectionObserver`] from [`Document`], ommiting it from the event loop.
3690    /// An observer without any target, ideally should be removed to be conformant with
3691    /// <https://w3c.github.io/IntersectionObserver/#lifetime>.
3692    pub(crate) fn remove_intersection_observer(
3693        &self,
3694        intersection_observer: &IntersectionObserver,
3695    ) {
3696        self.intersection_observers
3697            .borrow_mut()
3698            .retain(|observer| *observer != intersection_observer)
3699    }
3700
3701    /// <https://html.spec.whatwg.org/multipage/#start-intersection-observing-a-lazy-loading-element>
3702    pub(crate) fn start_intersection_observing_a_lazy_loading_element(
3703        &self,
3704        cx: &mut JSContext,
3705        element: &Element,
3706    ) {
3707        // Step 2: create the observer if it is still null.
3708        let observer = self
3709            .lazy_load_intersection_observer
3710            .or_init(|| IntersectionObserver::new_lazy_load(cx, &self.window));
3711        observer.Observe(cx.no_gc(), element);
3712    }
3713
3714    /// <https://html.spec.whatwg.org/multipage/#stop-intersection-observing-a-lazy-loading-element>
3715    pub(crate) fn stop_intersection_observing_a_lazy_loading_element(
3716        &self,
3717        no_gc: &NoGC,
3718        element: &Element,
3719    ) {
3720        // The spec asserts the observer is not null. We skip quietly instead,
3721        // because navigation code may call this for iframes that were
3722        // never observed (for example ones with a `src` attribute).
3723        if let Some(observer) = self.lazy_load_intersection_observer.get() {
3724            observer.Unobserve(no_gc, element);
3725        }
3726    }
3727
3728    /// <https://w3c.github.io/IntersectionObserver/#update-intersection-observations-algo>
3729    pub(crate) fn update_intersection_observer_steps(
3730        &self,
3731        cx: &mut JSContext,
3732        time: CrossProcessInstant,
3733    ) {
3734        if self.intersection_observers.borrow().is_empty() {
3735            return;
3736        }
3737        // Ensure that any layout changes are flushed for subsequent queries.
3738        self.window()
3739            .reflow_for_non_flushing_update_the_rendering_queries(cx);
3740
3741        // Step 1-2
3742        for intersection_observer in &*self.intersection_observers.borrow() {
3743            self.update_single_intersection_observer_steps(cx, intersection_observer, time);
3744        }
3745    }
3746
3747    /// Step 2.1-2.2 of <https://w3c.github.io/IntersectionObserver/#update-intersection-observations-algo>
3748    fn update_single_intersection_observer_steps(
3749        &self,
3750        cx: &mut JSContext,
3751        intersection_observer: &IntersectionObserver,
3752        time: CrossProcessInstant,
3753    ) {
3754        // Step 1
3755        // > Let rootBounds be observer’s root intersection rectangle.
3756        let root_bounds = intersection_observer.root_intersection_rectangle();
3757
3758        // Step 2
3759        // > For each target in observer’s internal [[ObservationTargets]] slot,
3760        // > processed in the same order that observe() was called on each target:
3761        intersection_observer.update_intersection_observations_steps(cx, self, time, root_bounds);
3762    }
3763
3764    /// <https://w3c.github.io/IntersectionObserver/#notify-intersection-observers-algo>
3765    pub(crate) fn notify_intersection_observers(&self, cx: &mut JSContext) {
3766        // Step 1
3767        // > Set document’s IntersectionObserverTaskQueued flag to false.
3768        self.intersection_observer_task_queued.set(false);
3769
3770        // Step 2
3771        // > Let notify list be a list of all IntersectionObservers whose root is in the DOM tree of document.
3772        // We will copy the observers because callback could modify the current list.
3773        // It will rooted to prevent GC in the iteration.
3774        rooted_vec!(let notify_list <- self.intersection_observers.clone().take().into_iter());
3775
3776        // Step 3
3777        // > For each IntersectionObserver object observer in notify list, run these steps:
3778        for intersection_observer in notify_list.iter() {
3779            // Step 3.1-3.5
3780            intersection_observer.invoke_callback_if_necessary(cx);
3781        }
3782    }
3783
3784    /// <https://w3c.github.io/IntersectionObserver/#queue-intersection-observer-task>
3785    pub(crate) fn queue_an_intersection_observer_task(&self) {
3786        // Step 1
3787        // > If document’s IntersectionObserverTaskQueued flag is set to true, return.
3788        if self.intersection_observer_task_queued.get() {
3789            return;
3790        }
3791
3792        // Step 2
3793        // > Set document’s IntersectionObserverTaskQueued flag to true.
3794        self.intersection_observer_task_queued.set(true);
3795
3796        // Step 3
3797        // > Queue a task on the IntersectionObserver task source associated with
3798        // > the document's event loop to notify intersection observers.
3799        let document = Trusted::new(self);
3800        self.owner_global()
3801            .task_manager()
3802            .intersection_observer_task_source()
3803            .queue(task!(notify_intersection_observers: move |cx| {
3804                document.root().notify_intersection_observers(cx);
3805            }));
3806    }
3807
3808    pub(crate) fn store_lcp_candidate(&self, candidate: LCPCandidate, element: Option<&Element>) {
3809        self.lcp_candidates.borrow_mut().insert(
3810            candidate.id,
3811            LCPCandidateAndElement {
3812                element: element.map(Dom::from_ref),
3813                candidate,
3814            },
3815        );
3816    }
3817
3818    pub(crate) fn store_container_timing_record(
3819        &self,
3820        record: ContainerTimingRecord,
3821        identifier: DOMString,
3822        root_element: &Element,
3823        last_painted_element: Option<&Element>,
3824    ) {
3825        self.container_timing_records.borrow_mut().insert(
3826            record.id,
3827            ContainerTimingRecordAndElements {
3828                identifier,
3829                root_element: Dom::from_ref(root_element),
3830                last_painted_element: last_painted_element.map(Dom::from_ref),
3831                record,
3832            },
3833        );
3834    }
3835
3836    /// Build the `PerformanceContainerTiming` entries for the Container Timing updates
3837    /// that were presented in the frame composited at `paint_time`.
3838    #[cfg_attr(crown, expect(crown::unrooted_must_root))]
3839    fn container_timing_entries(
3840        &self,
3841        cx: &mut JSContext,
3842        paint_time: CrossProcessInstant,
3843        ids: Vec<ContainerTimingID>,
3844    ) -> Vec<DomRoot<PerformanceEntry>> {
3845        ids.into_iter()
3846            .filter_map(|id| {
3847                let stored = self
3848                    .container_timing_records
3849                    .safe_borrow_mut(cx)
3850                    .remove(&id)?;
3851                // The first frame that painted anything for this container fixes its
3852                // `firstRenderTime`; every later update to the same container carries
3853                // that same value forward.
3854                let first_render_time = *self
3855                    .container_first_render_times
3856                    .safe_borrow_mut(cx)
3857                    .entry(stored.record.root_element)
3858                    .or_insert(paint_time);
3859                Some(DomRoot::upcast::<PerformanceEntry>(
3860                    PerformanceContainerTiming::new(
3861                        cx,
3862                        self.window.as_global_scope(),
3863                        stored.identifier,
3864                        stored.record.intersection_rect,
3865                        stored.record.size,
3866                        first_render_time,
3867                        paint_time,
3868                        stored.last_painted_element.as_deref(),
3869                        Some(&stored.root_element),
3870                    ),
3871                ))
3872            })
3873            .collect()
3874    }
3875
3876    #[cfg_attr(crown, expect(crown::unrooted_must_root))]
3877    pub(crate) fn handle_paint_metric(&self, cx: &mut JSContext, event: PaintMetricEvent) {
3878        let metrics = self.interactive_time.borrow();
3879        let entry = match event {
3880            PaintMetricEvent::FirstPaint(paint_timing_info, first_reflow) => {
3881                metrics.set_first_paint(paint_timing_info.default_paint_timestamp(), first_reflow);
3882                DomRoot::upcast::<PerformanceEntry>(PerformancePaintTiming::new(
3883                    cx,
3884                    self.window.as_global_scope(),
3885                    ProgressiveWebMetricType::FirstPaint,
3886                    paint_timing_info,
3887                ))
3888            },
3889            PaintMetricEvent::FirstContentfulPaint(paint_timing_info, first_reflow) => {
3890                metrics.set_first_contentful_paint(
3891                    paint_timing_info.default_paint_timestamp(),
3892                    first_reflow,
3893                );
3894                DomRoot::upcast::<PerformanceEntry>(PerformancePaintTiming::new(
3895                    cx,
3896                    self.window.as_global_scope(),
3897                    ProgressiveWebMetricType::FirstContentfulPaint,
3898                    paint_timing_info,
3899                ))
3900            },
3901            PaintMetricEvent::LargestContentfulPaint(paint_timing_info, id) => {
3902                let Some(stored_candidate) = self.lcp_candidates.borrow_mut().remove(&id) else {
3903                    warn!("Received LCP paint metric for unknown candidate: {id:?}");
3904                    return;
3905                };
3906                metrics
3907                    .set_largest_contentful_paint(id, paint_timing_info.default_paint_timestamp());
3908                DomRoot::upcast::<PerformanceEntry>(LargestContentfulPaint::new(
3909                    cx,
3910                    self.window.as_global_scope(),
3911                    &stored_candidate.candidate,
3912                    stored_candidate.element.as_deref(),
3913                    stored_candidate.candidate.load_time,
3914                    paint_timing_info,
3915                ))
3916            },
3917            // Unlike the other paint metrics, a single composited frame can present
3918            // several Container Timing updates at once, so this queues its own entries
3919            // rather than producing one.
3920            PaintMetricEvent::ContainerTiming(paint_time, ids) => {
3921                drop(metrics);
3922                for entry in self.container_timing_entries(cx, paint_time, ids) {
3923                    self.window.Performance(cx).queue_entry(&entry);
3924                }
3925                return;
3926            },
3927        };
3928        self.window.Performance(cx).queue_entry(&entry);
3929    }
3930
3931    /// <https://html.spec.whatwg.org/multipage/#document-write-steps>
3932    fn write(
3933        &self,
3934        cx: &mut JSContext,
3935        text: Vec<TrustedHTMLOrString>,
3936        line_feed: bool,
3937        containing_class: &str,
3938        field: &str,
3939    ) -> ErrorResult {
3940        // Step 1: Let string be the empty string.
3941        let mut strings: Vec<String> = Vec::with_capacity(text.len());
3942        // Step 2: Let isTrusted be false if text contains a string; otherwise true.
3943        let mut is_trusted = true;
3944        // Step 3: For each value of text:
3945        for value in text {
3946            match value {
3947                // Step 3.1: If value is a TrustedHTML object, then append value's associated data to string.
3948                TrustedHTMLOrString::TrustedHTML(trusted_html) => {
3949                    strings.push(trusted_html.to_string());
3950                },
3951                TrustedHTMLOrString::String(str_) => {
3952                    // Step 2: Let isTrusted be false if text contains a string; otherwise true.
3953                    is_trusted = false;
3954                    // Step 3.2: Otherwise, append value to string.
3955                    strings.push(str_.into());
3956                },
3957            };
3958        }
3959        let mut string = itertools::join(strings, "");
3960        // Step 4: If isTrusted is false, set string to the result of invoking the
3961        // Get Trusted Type compliant string algorithm with TrustedHTML,
3962        // this's relevant global object, string, sink, and "script".
3963        if !is_trusted {
3964            string = TrustedHTML::get_trusted_type_compliant_string(
3965                cx,
3966                &self.global(),
3967                TrustedHTMLOrString::String(string.into()),
3968                &format!("{} {}", containing_class, field),
3969            )?
3970            .str()
3971            .to_owned();
3972        }
3973        // Step 5: If lineFeed is true, append U+000A LINE FEED to string.
3974        if line_feed {
3975            string.push('\n');
3976        }
3977        // Step 6: If document is an XML document, then throw an "InvalidStateError" DOMException.
3978        if !self.is_html_document() {
3979            return Err(Error::InvalidState(Some(
3980                "Document must be a HTML document".into(),
3981            )));
3982        }
3983
3984        // Step 7: If document's throw-on-dynamic-markup-insertion counter is greater than 0,
3985        // then throw an "InvalidStateError" DOMException.
3986        if self.throw_on_dynamic_markup_insertion_counter.get() > 0 {
3987            return Err(Error::InvalidState(Some(
3988                "A custom element constructor attempted to open, close or write to this document"
3989                    .into(),
3990            )));
3991        }
3992
3993        // Step 8: If document's active parser was aborted is true, then return.
3994        if self.active_parser_was_aborted.get() {
3995            return Ok(());
3996        }
3997
3998        let parser = match self.get_current_parser() {
3999            Some(ref parser) if parser.can_write() => DomRoot::from_ref(&**parser),
4000            // Step 9: If the insertion point is undefined, then:
4001            _ => {
4002                // Step 9.1: If document's unload counter is greater than 0 or
4003                // document's ignore-destructive-writes counter is greater than 0, then return.
4004                if self.is_prompting_or_unloading() ||
4005                    self.ignore_destructive_writes_counter.get() > 0
4006                {
4007                    return Ok(());
4008                }
4009                // Step 9.2: Run the document open steps with document.
4010                self.Open(cx, None, None)?;
4011                self.get_current_parser().unwrap()
4012            },
4013        };
4014
4015        // Steps 10-11.
4016        parser.write(cx, string.into());
4017
4018        Ok(())
4019    }
4020
4021    pub(crate) fn details_name_groups<'a: 'b, 'b>(
4022        &'a self,
4023        no_gc: &'b NoGC,
4024    ) -> RefMut<'b, DetailsNameGroups> {
4025        RefMut::map(
4026            self.details_name_groups.safe_borrow_mut(no_gc),
4027            |details_name_groups| details_name_groups.get_or_insert_default(),
4028        )
4029    }
4030
4031    pub(crate) fn accessibility_data_mut(&self) -> RefMut<'_, AccessibilityData> {
4032        self.accessibility_data.borrow_mut()
4033    }
4034
4035    pub(crate) fn accessibility_active(&self) -> bool {
4036        self.window().layout().accessibility_active()
4037    }
4038
4039    pub(crate) fn rooted_nodes_for_accessibility_integrity_check(
4040        &self,
4041    ) -> Option<FxHashSet<OpaqueNode>> {
4042        if !self.accessibility_active() {
4043            return None;
4044        }
4045
4046        let mut accessibility_data = self.accessibility_data_mut();
4047
4048        if pref!(expensive_accessibility_test_assertions_enabled) {
4049            return Some(accessibility_data.unroot_and_drain_all_removed_nodes());
4050        }
4051
4052        accessibility_data.unroot_all_removed_nodes();
4053        None
4054    }
4055
4056    pub(crate) fn get_document_element_unrooted<'a>(
4057        &self,
4058        no_gc: &'a NoGC,
4059    ) -> Option<UnrootedDom<'a, Element>> {
4060        self.upcast::<Node>().child_elements_unrooted(no_gc).next()
4061    }
4062
4063    pub(crate) fn collect_reports(
4064        &self,
4065        reports: &mut Vec<Report>,
4066        ops: &mut MallocSizeOfOps,
4067    ) -> HashSet<*const JSObject> {
4068        let mut computed_objects = HashSet::new();
4069        let mut sizes = DocumentSizes::default();
4070
4071        for node in self
4072            .upcast::<Node>()
4073            .traverse_preorder(ShadowIncluding::Yes)
4074        {
4075            let size = compute_size(node.jsobject(), ops, &computed_objects, None);
4076
4077            match node.type_id() {
4078                NodeTypeId::Element(_) => {
4079                    sizes.element_nodes_size += size;
4080
4081                    let element = node.downcast::<Element>().expect("node must be Element");
4082                    for attr in element.attrs().borrow().iter() {
4083                        if let Some(attr) = attr.as_attr() {
4084                            let size = compute_size(
4085                                attr.upcast::<Node>().jsobject(),
4086                                ops,
4087                                &computed_objects,
4088                                None,
4089                            );
4090                            sizes.attribute_nodes_size += size;
4091                            computed_objects.insert(attr.upcast::<Node>().jsobject());
4092                        }
4093                    }
4094                },
4095                NodeTypeId::CharacterData(_) => sizes.text_nodes_size += size,
4096                _ => sizes.other_nodes_size += size,
4097            };
4098
4099            computed_objects.insert(node.jsobject());
4100        }
4101
4102        let prefix = format!("url({})", self.url());
4103        reports.push(Report {
4104            path: path![prefix, "js", "dom", "element-nodes"],
4105            kind: ReportKind::ExplicitJemallocHeapSize,
4106            size: sizes.element_nodes_size,
4107        });
4108        reports.push(Report {
4109            path: path![prefix, "js", "dom", "text-nodes"],
4110            kind: ReportKind::ExplicitJemallocHeapSize,
4111            size: sizes.text_nodes_size,
4112        });
4113        reports.push(Report {
4114            path: path![prefix, "js", "dom", "attribute-nodes"],
4115            kind: ReportKind::ExplicitJemallocHeapSize,
4116            size: sizes.attribute_nodes_size,
4117        });
4118        reports.push(Report {
4119            path: path![prefix, "js", "dom", "other-nodes"],
4120            kind: ReportKind::ExplicitJemallocHeapSize,
4121            size: sizes.other_nodes_size,
4122        });
4123
4124        computed_objects
4125    }
4126
4127    /// Get a reference to this [`Document`]'s vector of weak live ranges.
4128    pub(crate) fn live_ranges(&self) -> &WeakRangeVec {
4129        &self.live_ranges
4130    }
4131
4132    pub(crate) fn gained_or_lost_system_focus(&self, cx: &mut JSContext, gained_focus: bool) {
4133        let focus_handler = self.focus_handler();
4134        if !self.is_fully_active() || !focus_handler.has_focus() {
4135            return;
4136        }
4137        focus_handler.gained_or_lost_system_focus(cx, gained_focus);
4138        self.refresh_focus_rendering();
4139    }
4140
4141    pub(crate) fn refresh_focus_rendering(&self) {
4142        self.window().layout().set_needs_new_display_list();
4143    }
4144}
4145
4146/// Holds DOM object memory sizes for fine-grained memory reports.
4147#[derive(Default)]
4148struct DocumentSizes {
4149    element_nodes_size: usize,
4150    text_nodes_size: usize,
4151    attribute_nodes_size: usize,
4152    other_nodes_size: usize,
4153}
4154
4155impl<'dom> LayoutDom<'dom, Document> {
4156    #[inline]
4157    pub(crate) fn is_html_document_for_layout(&self) -> bool {
4158        self.unsafe_get().is_html_document
4159    }
4160
4161    #[inline]
4162    pub(crate) fn encoding_for_layout(&self) -> &'static Encoding {
4163        self.unsafe_get().encoding.get()
4164    }
4165
4166    #[inline]
4167    pub(crate) fn quirks_mode(self) -> QuirksMode {
4168        self.unsafe_get().quirks_mode.get()
4169    }
4170
4171    #[inline]
4172    pub(crate) fn shared_style_locks(self) -> &'dom SharedRwLocks {
4173        self.unsafe_get().shared_style_locks()
4174    }
4175
4176    #[inline]
4177    pub(crate) fn flush_shadow_root_stylesheets_if_necessary(
4178        self,
4179        stylist: &mut Stylist,
4180        guard: &SharedRwLockReadGuard,
4181    ) {
4182        (*self.unsafe_get()).flush_shadow_root_stylesheets_if_necessary_for_layout(stylist, guard)
4183    }
4184
4185    pub(crate) fn elements_with_id(self, id: &Atom) -> &[LayoutDom<'dom, Element>] {
4186        self.unsafe_get().id_map.get_all_for_layout(id)
4187    }
4188
4189    pub(crate) fn url_for_layout(self) -> ServoUrl {
4190        self.unsafe_get().url.borrow().clone()
4191    }
4192
4193    #[expect(unsafe_code)]
4194    pub(crate) fn visible_selection_for_layout(&self) -> Option<LayoutDom<'dom, Selection>> {
4195        unsafe { self.unsafe_get().selection.to_layout() }
4196    }
4197
4198    pub(crate) fn default_language_for_layout(&self) -> AtomicRef<'dom, Option<String>> {
4199        self.unsafe_get().default_language.borrow()
4200    }
4201}
4202
4203// https://html.spec.whatwg.org/multipage/#is-a-registrable-domain-suffix-of-or-is-equal-to
4204// The spec says to return a bool, we actually return an Option<Host> containing
4205// the parsed host in the successful case, to avoid having to re-parse the host.
4206pub(crate) fn get_registrable_domain_suffix_of_or_is_equal_to(
4207    host_suffix_string: &str,
4208    original_host: Host,
4209) -> Option<Host> {
4210    // Step 1
4211    if host_suffix_string.is_empty() {
4212        return None;
4213    }
4214
4215    // Step 2-3.
4216    let host = match Host::parse(host_suffix_string) {
4217        Ok(host) => host,
4218        Err(_) => return None,
4219    };
4220
4221    // Step 4.
4222    if host != original_host {
4223        // Step 4.1
4224        let host = match host {
4225            Host::Domain(ref host) => host,
4226            _ => return None,
4227        };
4228        let original_host = match original_host {
4229            Host::Domain(ref original_host) => original_host,
4230            _ => return None,
4231        };
4232
4233        // Step 4.2
4234        let index = original_host.len().checked_sub(host.len())?;
4235        let (prefix, suffix) = original_host.split_at(index);
4236
4237        if !prefix.ends_with('.') {
4238            return None;
4239        }
4240        if suffix != host {
4241            return None;
4242        }
4243
4244        // Step 4.3
4245        if is_pub_domain(host) {
4246            return None;
4247        }
4248    }
4249
4250    // Step 5
4251    Some(host)
4252}
4253
4254/// <https://url.spec.whatwg.org/#network-scheme>
4255fn url_has_network_scheme(url: &ServoUrl) -> bool {
4256    matches!(url.scheme(), "ftp" | "http" | "https")
4257}
4258
4259#[derive(Clone, Copy, Eq, JSTraceable, MallocSizeOf, PartialEq)]
4260pub(crate) enum HasBrowsingContext {
4261    No,
4262    Yes,
4263}
4264
4265impl Document {
4266    #[expect(clippy::too_many_arguments)]
4267    pub(crate) fn new_inherited(
4268        window: &Window,
4269        has_browsing_context: HasBrowsingContext,
4270        url: Option<ServoUrl>,
4271        about_base_url: Option<ServoUrl>,
4272        origin: MutableOrigin,
4273        is_html_document: IsHTMLDocument,
4274        content_type: Option<Mime>,
4275        last_modified: Option<String>,
4276        activity: DocumentActivity,
4277        doc_loader: DocumentLoader,
4278        referrer: Option<String>,
4279        status_code: Option<u16>,
4280        is_initial_about_blank: bool,
4281        allow_declarative_shadow_roots: bool,
4282        inherited_insecure_requests_policy: Option<InsecureRequestsPolicy>,
4283        has_trustworthy_ancestor_origin: bool,
4284        custom_element_reaction_stack: Rc<CustomElementReactionStack>,
4285        creation_sandboxing_flag_set: SandboxingFlagSet,
4286        timeline: &DocumentTimeline,
4287        pipeline_id: PipelineId,
4288        image_cache: StdArc<dyn ImageCache>,
4289    ) -> Document {
4290        let url = url.unwrap_or_else(|| ServoUrl::parse("about:blank").unwrap());
4291
4292        let frame_type = match window.is_top_level() {
4293            true => TimerMetadataFrameType::RootWindow,
4294            false => TimerMetadataFrameType::IFrame,
4295        };
4296        let interactive_time = ProgressiveWebMetrics::new(
4297            window.time_profiler_chan().clone(),
4298            url.clone(),
4299            frame_type,
4300        );
4301
4302        let content_type = content_type.unwrap_or_else(|| {
4303            match is_html_document {
4304                // https://dom.spec.whatwg.org/#dom-domimplementation-createhtmldocument
4305                IsHTMLDocument::HTMLDocument => "text/html",
4306                // https://dom.spec.whatwg.org/#concept-document-content-type
4307                IsHTMLDocument::NonHTMLDocument => "application/xml",
4308            }
4309            .parse()
4310            .unwrap()
4311        });
4312
4313        let encoding = content_type
4314            .get_parameter(CHARSET)
4315            .and_then(|charset| Encoding::for_label(charset.as_bytes()))
4316            .unwrap_or(UTF_8);
4317
4318        let has_focus = window.parent_info().is_none();
4319        let has_browsing_context = has_browsing_context == HasBrowsingContext::Yes;
4320        let shared_style_locks = window.script_thread().shared_style_locks().clone();
4321        // <https://html.spec.whatwg.org/multipage/#creating-a-new-browsing-context>
4322        // Step 15. Let document be a new Document, with:
4323        // - mode: "quirks"
4324        let quirks_mode = if is_initial_about_blank {
4325            QuirksMode::Quirks
4326        } else {
4327            // <https://dom.spec.whatwg.org/#concept-document-quirks>
4328            QuirksMode::NoQuirks
4329        };
4330
4331        Document {
4332            node: Node::new_document_node(),
4333            document_or_shadow_root: DocumentOrShadowRoot::new(window),
4334            window: Dom::from_ref(window),
4335            has_browsing_context,
4336            implementation: Default::default(),
4337            content_type,
4338            last_modified,
4339            url: AtomicRefCell::new(url),
4340            about_base_url: DomRefCell::new(about_base_url),
4341            quirks_mode: Cell::new(quirks_mode),
4342            event_handler: DocumentEventHandler::new(window),
4343            focus_handler: DocumentFocusHandler::new(window, has_focus),
4344            overlay_handler: Default::default(),
4345            embedder_controls: DocumentEmbedderControls::new(window),
4346            id_map: TreeOrderedIndexMap::id(),
4347            name_map: TreeOrderedIndexMap::name(),
4348            // https://dom.spec.whatwg.org/#concept-document-encoding
4349            encoding: Cell::new(encoding),
4350            is_html_document: is_html_document == IsHTMLDocument::HTMLDocument,
4351            activity: Cell::new(activity),
4352            tag_map: DomRefCell::new(HashMapTracedValues::new_fx()),
4353            tagns_map: DomRefCell::new(HashMapTracedValues::new_fx()),
4354            classes_map: DomRefCell::new(HashMapTracedValues::new()),
4355            images: Default::default(),
4356            embeds: Default::default(),
4357            links: Default::default(),
4358            forms: Default::default(),
4359            scripts: Default::default(),
4360            anchors: Default::default(),
4361            applets: Default::default(),
4362            iframes: IFrameCollection::new(),
4363            shared_style_locks,
4364            stylesheets: DomRefCell::new(DocumentStylesheetSet::new()),
4365            stylesheet_list: MutNullableDom::new(None),
4366            // https://html.spec.whatwg.org/multipage/#current-document-readiness
4367            // > Each Document has a current document readiness, a string, initially "complete".
4368            ready_state: Cell::new(DocumentReadyState::Complete),
4369            current_script: Default::default(),
4370            current_the_end_loading_phase: Default::default(),
4371            pending_parsing_blocking_script: Default::default(),
4372            script_blocking_stylesheet_set: Default::default(),
4373            render_blocking_element_count: Default::default(),
4374            deferred_scripts: Default::default(),
4375            asap_in_order_scripts_list: Default::default(),
4376            asap_scripts_set: Default::default(),
4377            animation_frame_ident: Cell::new(0),
4378            animation_frame_list: DomRefCell::new(VecDeque::new()),
4379            running_animation_callbacks: Cell::new(false),
4380            loader: DomRefCell::new(doc_loader),
4381            current_parser: Default::default(),
4382            base_element: Default::default(),
4383            target_base_element: Default::default(),
4384            ancestor_origins_list: Default::default(),
4385            internal_ancestor_origin_objects_list: Default::default(),
4386            appropriate_template_contents_owner_document: Default::default(),
4387            pending_restyles: DomRefCell::new(FxHashMap::default()),
4388            needs_restyle: Cell::new(RestyleReason::DOMChanged),
4389            origin: DomRefCell::new(origin),
4390            referrer,
4391            target_element: MutNullableDom::new(None),
4392            policy_container: DomRefCell::new(StdArc::new(PolicyContainer::default())),
4393            preloaded_resources: Default::default(),
4394            ignore_destructive_writes_counter: Default::default(),
4395            ignore_opens_during_unload_counter: Default::default(),
4396            spurious_animation_frames: Cell::new(0),
4397            form_id_listener_map: Default::default(),
4398            interactive_time: DomRefCell::new(interactive_time),
4399            tti_window: DomRefCell::new(InteractiveWindow::default()),
4400            throw_on_dynamic_markup_insertion_counter: Cell::new(0),
4401            page_showing: Cell::new(false),
4402            salvageable: Cell::new(true),
4403            active_parser_was_aborted: Cell::new(false),
4404            fired_unload: Cell::new(false),
4405            responsive_images: Default::default(),
4406            navigation_timing: Default::default(),
4407            resource_fetch_timing: RefCell::new(None),
4408            completely_loaded: Cell::new(false),
4409            script_and_layout_blockers: Cell::new(0),
4410            delayed_tasks: Default::default(),
4411            shadow_roots: Default::default(),
4412            shadow_roots_styles_changed: Cell::new(false),
4413            media_controls: DomRefCell::new(HashMap::new()),
4414            dirty_canvases: DomRefCell::new(Default::default()),
4415            has_pending_animated_image_update: Cell::new(false),
4416            selection: MutNullableDom::new(None),
4417            timeline: Dom::from_ref(timeline),
4418            animation_manager: AnimationManager::new(),
4419            dirty_root: Default::default(),
4420            declarative_refresh: Default::default(),
4421            resize_observers: Default::default(),
4422            fonts: Default::default(),
4423            // TODO: This is intended to workaround the issue where `visibilityState`
4424            // is always hidden. This should really be hooked with system visibility
4425            // which involves more work.
4426            visibility_state: Cell::new(DocumentVisibilityState::Visible),
4427            status_code,
4428            is_initial_about_blank: Cell::new(is_initial_about_blank),
4429            allow_declarative_shadow_roots: Cell::new(allow_declarative_shadow_roots),
4430            inherited_insecure_requests_policy: Cell::new(inherited_insecure_requests_policy),
4431            has_trustworthy_ancestor_origin: Cell::new(has_trustworthy_ancestor_origin),
4432            intersection_observer_task_queued: Cell::new(false),
4433            intersection_observers: Default::default(),
4434            lazy_load_intersection_observer: Default::default(),
4435            highlighted_dom_node: Default::default(),
4436            lcp_candidates: DomRefCell::new(Default::default()),
4437            paint_timing_info: Cell::new(PaintTimingInfo::now()),
4438            container_timing_records: DomRefCell::new(Default::default()),
4439            container_first_render_times: DomRefCell::new(Default::default()),
4440            adopted_stylesheets: Default::default(),
4441            pending_scroll_events: Default::default(),
4442            rendering_update_reasons: Default::default(),
4443            waiting_on_canvas_image_updates: Cell::new(false),
4444            root_removal_noted: Cell::new(true),
4445            current_rendering_epoch: Default::default(),
4446            custom_element_reaction_stack,
4447            active_sandboxing_flag_set: Cell::new(creation_sandboxing_flag_set),
4448            creation_sandboxing_flag_set: Cell::new(creation_sandboxing_flag_set),
4449            favicon: RefCell::new(None),
4450            ever_had_favicon_link: Cell::new(false),
4451            websockets: DOMTracker::new(),
4452            active_media_elements: Default::default(),
4453            details_name_groups: Default::default(),
4454            protocol_handler_automation_mode: Default::default(),
4455            layout_animations_test_enabled: pref!(layout_animations_test_enabled),
4456            state_override: Default::default(),
4457            value_override: Default::default(),
4458            default_single_line_container_name: Default::default(),
4459            css_styling_flag: Default::default(),
4460            accessibility_data: Default::default(),
4461            iframe_load_in_progress: Default::default(),
4462            mute_iframe_load: Default::default(),
4463            timers: OneshotTimers::new(window.upcast()),
4464            pipeline_id,
4465            task_manager: Rc::new(TaskManager::new(
4466                Some(window.event_loop_sender()),
4467                pipeline_id,
4468                None,
4469            )),
4470            image_cache,
4471            history: Default::default(),
4472            theme: Default::default(),
4473            theme_override: Default::default(),
4474            default_language: Default::default(),
4475            window_detached: Default::default(),
4476            live_ranges: Default::default(),
4477            module_map: Default::default(),
4478        }
4479    }
4480
4481    pub(crate) fn detach_window(&self) {
4482        self.window_detached.set(true);
4483
4484        // Note: This is step 7 of "destroy a document"
4485        // <https://html.spec.whatwg.org/multipage/#destroy-a-document>. Eventually
4486        // document replacement should call `Document::destroy` via step 20 in
4487        // "unload" <https://html.spec.whatwg.org/multipage/#unload-a-document>.
4488        self.task_manager()
4489            .cancel_all_tasks_and_ignore_future_tasks();
4490    }
4491
4492    pub(crate) fn window_detached(&self) -> bool {
4493        self.window_detached.get()
4494    }
4495
4496    /// Returns a policy value that should be used for fetches initiated by this document.
4497    pub(crate) fn insecure_requests_policy(&self) -> InsecureRequestsPolicy {
4498        if let Some(csp_list) = self.get_csp_list().as_ref() {
4499            for policy in &csp_list.0 {
4500                if policy.contains_a_directive_whose_name_is("upgrade-insecure-requests") &&
4501                    policy.disposition == PolicyDisposition::Enforce
4502                {
4503                    return InsecureRequestsPolicy::Upgrade;
4504                }
4505            }
4506        }
4507
4508        self.inherited_insecure_requests_policy
4509            .get()
4510            .unwrap_or(InsecureRequestsPolicy::DoNotUpgrade)
4511    }
4512
4513    /// Get the [`Document`]'s [`DocumentEventHandler`].
4514    pub(crate) fn event_handler(&self) -> &DocumentEventHandler {
4515        &self.event_handler
4516    }
4517
4518    /// Get the [`Document`]'s [`DocumentFocusHandler`].
4519    pub(crate) fn focus_handler(&self) -> &DocumentFocusHandler {
4520        &self.focus_handler
4521    }
4522
4523    /// Get the [`Document`]'s [`DocumentOverlayHandler`].
4524    pub(crate) fn overlay_handler(&self) -> &DocumentOverlayHandler {
4525        self.overlay_handler
4526            .get_or_init(|| DocumentOverlayHandler::new(self))
4527    }
4528
4529    /// Get the [`Document`]'s [`DocumentEmbedderControls`].
4530    pub(crate) fn embedder_controls(&self) -> &DocumentEmbedderControls {
4531        &self.embedder_controls
4532    }
4533
4534    /// Whether or not this [`Document`] has any pending scroll events to be processed during
4535    /// "update the rendering."
4536    fn has_pending_scroll_events(&self) -> bool {
4537        !self.pending_scroll_events.borrow().is_empty()
4538    }
4539
4540    /// Add a [`RenderingUpdateReason`] to this [`Document`] which will trigger a
4541    /// rendering update at a later time.
4542    pub(crate) fn add_rendering_update_reason(&self, reason: RenderingUpdateReason) {
4543        self.rendering_update_reasons
4544            .set(self.rendering_update_reasons.get().union(reason));
4545    }
4546
4547    /// Clear all [`RenderingUpdateReason`]s from this [`Document`].
4548    pub(crate) fn clear_rendering_update_reasons(&self) {
4549        self.rendering_update_reasons
4550            .set(RenderingUpdateReason::empty())
4551    }
4552
4553    /// Prevent any JS or layout from running until the corresponding call to
4554    /// `remove_script_and_layout_blocker`. Used to isolate periods in which
4555    /// the DOM is in an unstable state and should not be exposed to arbitrary
4556    /// web content. Any attempts to invoke content JS or query layout during
4557    /// that time will trigger a panic. `add_delayed_task` will cause the
4558    /// provided task to be executed as soon as the last blocker is removed.
4559    pub(crate) fn add_script_and_layout_blocker(&self) {
4560        self.script_and_layout_blockers
4561            .set(self.script_and_layout_blockers.get() + 1);
4562    }
4563
4564    /// Terminate the period in which JS or layout is disallowed from running.
4565    /// If no further blockers remain, any delayed tasks in the queue will
4566    /// be executed in queue order until the queue is empty.
4567    pub(crate) fn remove_script_and_layout_blocker(&self, cx: &mut JSContext) {
4568        assert!(self.script_and_layout_blockers.get() > 0);
4569        self.script_and_layout_blockers
4570            .set(self.script_and_layout_blockers.get() - 1);
4571        while self.script_and_layout_blockers.get() == 0 {
4572            let Some(task) = self.delayed_tasks.borrow_mut().pop_front() else {
4573                return;
4574            };
4575            task.run_box(cx);
4576        }
4577    }
4578
4579    /// Enqueue a task to run as soon as any JS and layout blockers are removed.
4580    pub(crate) fn add_delayed_task<T: 'static + NonSendTaskBox>(&self, task: T) {
4581        self.delayed_tasks.borrow_mut().push_back(Box::new(task));
4582    }
4583
4584    /// Returns true if the DOM is in a state that will allow running content JS or
4585    /// performing a layout operation.
4586    pub(crate) fn is_safe_to_run_script_or_layout(&self) -> bool {
4587        self.script_and_layout_blockers.get() == 0
4588    }
4589
4590    /// Assert that the DOM is in a state that will allow running content JS or
4591    /// performing a layout operation.
4592    pub(crate) fn ensure_safe_to_run_script_or_layout(&self) {
4593        assert!(
4594            self.is_safe_to_run_script_or_layout(),
4595            "Attempt to use script or layout while DOM not in a stable state"
4596        );
4597    }
4598
4599    #[expect(clippy::too_many_arguments)]
4600    pub(crate) fn new(
4601        cx: &mut JSContext,
4602        window: &Window,
4603        has_browsing_context: HasBrowsingContext,
4604        url: Option<ServoUrl>,
4605        about_base_url: Option<ServoUrl>,
4606        origin: MutableOrigin,
4607        doctype: IsHTMLDocument,
4608        content_type: Option<Mime>,
4609        last_modified: Option<String>,
4610        activity: DocumentActivity,
4611        doc_loader: DocumentLoader,
4612        referrer: Option<String>,
4613        status_code: Option<u16>,
4614        is_initial_about_blank: bool,
4615        allow_declarative_shadow_roots: bool,
4616        inherited_insecure_requests_policy: Option<InsecureRequestsPolicy>,
4617        has_trustworthy_ancestor_origin: bool,
4618        custom_element_reaction_stack: Rc<CustomElementReactionStack>,
4619        creation_sandboxing_flag_set: SandboxingFlagSet,
4620        pipeline_id: PipelineId,
4621        image_cache: StdArc<dyn ImageCache>,
4622    ) -> DomRoot<Document> {
4623        Self::new_with_proto(
4624            cx,
4625            window,
4626            None,
4627            has_browsing_context,
4628            url,
4629            about_base_url,
4630            origin,
4631            doctype,
4632            content_type,
4633            last_modified,
4634            activity,
4635            doc_loader,
4636            referrer,
4637            status_code,
4638            is_initial_about_blank,
4639            allow_declarative_shadow_roots,
4640            inherited_insecure_requests_policy,
4641            has_trustworthy_ancestor_origin,
4642            custom_element_reaction_stack,
4643            creation_sandboxing_flag_set,
4644            pipeline_id,
4645            image_cache,
4646        )
4647    }
4648
4649    #[expect(clippy::too_many_arguments)]
4650    fn new_with_proto(
4651        cx: &mut JSContext,
4652        window: &Window,
4653        proto: Option<HandleObject>,
4654        has_browsing_context: HasBrowsingContext,
4655        url: Option<ServoUrl>,
4656        about_base_url: Option<ServoUrl>,
4657        origin: MutableOrigin,
4658        doctype: IsHTMLDocument,
4659        content_type: Option<Mime>,
4660        last_modified: Option<String>,
4661        activity: DocumentActivity,
4662        doc_loader: DocumentLoader,
4663        referrer: Option<String>,
4664        status_code: Option<u16>,
4665        is_initial_about_blank: bool,
4666        allow_declarative_shadow_roots: bool,
4667        inherited_insecure_requests_policy: Option<InsecureRequestsPolicy>,
4668        has_trustworthy_ancestor_origin: bool,
4669        custom_element_reaction_stack: Rc<CustomElementReactionStack>,
4670        creation_sandboxing_flag_set: SandboxingFlagSet,
4671        pipeline_id: PipelineId,
4672        image_cache: StdArc<dyn ImageCache>,
4673    ) -> DomRoot<Document> {
4674        let timeline = DocumentTimeline::new(cx, window);
4675        let document = reflect_dom_object_with_proto(
4676            cx,
4677            Box::new(Document::new_inherited(
4678                window,
4679                has_browsing_context,
4680                url,
4681                about_base_url,
4682                origin,
4683                doctype,
4684                content_type,
4685                last_modified,
4686                activity,
4687                doc_loader,
4688                referrer,
4689                status_code,
4690                is_initial_about_blank,
4691                allow_declarative_shadow_roots,
4692                inherited_insecure_requests_policy,
4693                has_trustworthy_ancestor_origin,
4694                custom_element_reaction_stack,
4695                creation_sandboxing_flag_set,
4696                &timeline,
4697                pipeline_id,
4698                image_cache,
4699            )),
4700            window,
4701            proto,
4702        );
4703        {
4704            let node = document.upcast::<Node>();
4705            node.set_owner_doc(&document);
4706        }
4707        document
4708    }
4709
4710    pub(crate) fn get_redirect_count(&self) -> u16 {
4711        self.resource_fetch_timing()
4712            .as_ref()
4713            .map_or(0, |resource_fetch_timing| {
4714                resource_fetch_timing.redirect_count
4715            })
4716    }
4717
4718    pub(crate) fn set_resource_fetch_timing(&self, timing: ResourceFetchTiming) {
4719        self.resource_fetch_timing.replace(Some(timing));
4720    }
4721
4722    pub(crate) fn resource_fetch_timing(&self) -> Ref<'_, Option<ResourceFetchTiming>> {
4723        self.resource_fetch_timing.borrow()
4724    }
4725
4726    pub(crate) fn navigation_timing(&self) -> Rc<NavigationTiming> {
4727        self.navigation_timing.clone()
4728    }
4729
4730    pub(crate) fn performance_timing_attribute(
4731        &self,
4732        name: &str,
4733    ) -> Fallible<Option<CrossProcessInstant>> {
4734        Ok(match name {
4735            "unloadEventStart" => self.navigation_timing().unload_event_start.get(),
4736            "unloadEventEnd" => self.navigation_timing().unload_event_end.get(),
4737            "domInteractive" => self.navigation_timing().dom_interactive.get(),
4738            "domContentLoadedEventStart" => self
4739                .navigation_timing()
4740                .dom_content_loaded_event_start
4741                .get(),
4742            "domContentLoadedEventEnd" => {
4743                self.navigation_timing().dom_content_loaded_event_end.get()
4744            },
4745            "domComplete" => self.navigation_timing().dom_complete.get(),
4746            "loadEventStart" => self.navigation_timing().load_event_start.get(),
4747            "loadEventEnd" => self.navigation_timing().load_event_end.get(),
4748            "redirectStart" | "redirectEnd" | "secureConnectionStart" | "responseEnd" => self
4749                .resource_fetch_timing()
4750                .as_ref()
4751                .and_then(|resource_fetch_timing| match name {
4752                    "redirectStart" => resource_fetch_timing.redirect_start,
4753                    "redirectEnd" => resource_fetch_timing.redirect_end,
4754                    "secureConnectionStart" => resource_fetch_timing.secure_connection_start,
4755                    "responseEnd" => resource_fetch_timing.response_end,
4756                    _ => None,
4757                }),
4758            _ => {
4759                return Err(Error::Operation(Some(format!(
4760                    "{name} hasn't been implemented."
4761                ))));
4762            },
4763        })
4764    }
4765
4766    pub(crate) fn elements_by_name_count(&self, name: &TracedDOMString) -> u32 {
4767        if name.is_empty() {
4768            return 0;
4769        }
4770        self.count_node_list(|n| Document::is_element_in_get_by_name(n, name))
4771    }
4772
4773    pub(crate) fn elements_by_name_iter<'a>(
4774        &self,
4775        no_gc: &'a NoGC,
4776        name: &'a TracedDOMString,
4777    ) -> impl Iterator<Item = UnrootedDom<'a, Node>> + 'a {
4778        self.get_document_element_unrooted(no_gc)
4779            .into_iter()
4780            .flat_map(|element| {
4781                element
4782                    .upcast::<Node>()
4783                    .traverse_preorder_unrooted(no_gc, ShadowIncluding::No)
4784            })
4785            .filter(move |node| Document::is_element_in_get_by_name(node, name))
4786    }
4787
4788    // Note that document.getByName does not match on the same conditions
4789    // as the document named getter.
4790    fn is_element_in_get_by_name(node: &Node, name: &TracedDOMString) -> bool {
4791        let element = match node.downcast::<Element>() {
4792            Some(element) => element,
4793            None => return false,
4794        };
4795        if element.namespace() != &ns!(html) {
4796            return false;
4797        }
4798        element.get_name().is_some_and(|n| &*n == name)
4799    }
4800
4801    fn count_node_list<F: Fn(&Node) -> bool>(&self, callback: F) -> u32 {
4802        let doc = self.GetDocumentElement();
4803        let maybe_node = doc.as_deref().map(Castable::upcast::<Node>);
4804        maybe_node
4805            .iter()
4806            .flat_map(|node| node.traverse_preorder(ShadowIncluding::No))
4807            .filter(|node| callback(node))
4808            .count() as u32
4809    }
4810
4811    fn get_html_element(&self) -> Option<DomRoot<HTMLHtmlElement>> {
4812        self.GetDocumentElement().and_then(DomRoot::downcast)
4813    }
4814
4815    /// Return a reference to the per-ScriptThread shared locks used for stylesheets.
4816    pub(crate) fn shared_style_locks(&self) -> &SharedRwLocks {
4817        &self.shared_style_locks
4818    }
4819
4820    /// Return a reference to the per-ScriptThread shared lock used for author stylesheets.
4821    pub(crate) fn style_shared_author_lock(&self) -> &SharedRwLock {
4822        &self.shared_style_locks.author
4823    }
4824
4825    /// Flushes the stylesheet list, and returns whether any stylesheet changed.
4826    pub(crate) fn flush_stylesheets_for_reflow(&self) -> bool {
4827        // NOTE(emilio): The invalidation machinery is used on the replicated
4828        // list in layout.
4829        //
4830        // FIXME(emilio): This really should differentiate between CSSOM changes
4831        // and normal stylesheets additions / removals, because in the last case
4832        // layout already has that information and we could avoid dirtying the whole thing.
4833        let mut stylesheets = self.stylesheets.borrow_mut();
4834        let have_changed = stylesheets.has_changed();
4835        stylesheets.flush_without_invalidation();
4836        have_changed
4837    }
4838
4839    pub(crate) fn salvageable(&self) -> bool {
4840        self.salvageable.get()
4841    }
4842
4843    /// <https://html.spec.whatwg.org/multipage/#make-document-unsalvageable>
4844    pub(crate) fn make_document_unsalvageable(&self) {
4845        // Step 1. Let details be a new not restored reason details whose reason is reason.
4846        // TODO
4847        // Step 2. Append details to document's bfcache blocking details.
4848        // TODO
4849        // Step 3. Set document's salvageable state to false.
4850        self.salvageable.set(false);
4851    }
4852
4853    /// <https://html.spec.whatwg.org/multipage/#appropriate-template-contents-owner-document>
4854    pub(crate) fn appropriate_template_contents_owner_document(
4855        &self,
4856        cx: &mut JSContext,
4857    ) -> DomRoot<Document> {
4858        self.appropriate_template_contents_owner_document
4859            .or_init(|| {
4860                let doctype = if self.is_html_document {
4861                    IsHTMLDocument::HTMLDocument
4862                } else {
4863                    IsHTMLDocument::NonHTMLDocument
4864                };
4865                let new_doc = Document::new(
4866                    cx,
4867                    self.window(),
4868                    HasBrowsingContext::No,
4869                    None,
4870                    None,
4871                    // https://github.com/whatwg/html/issues/2109
4872                    MutableOrigin::new(ImmutableOrigin::new_opaque()),
4873                    doctype,
4874                    None,
4875                    None,
4876                    DocumentActivity::Inactive,
4877                    DocumentLoader::new(&self.loader()),
4878                    None,
4879                    None,
4880                    false,
4881                    self.allow_declarative_shadow_roots(),
4882                    Some(self.insecure_requests_policy()),
4883                    self.has_trustworthy_ancestor_or_current_origin(),
4884                    self.custom_element_reaction_stack.clone(),
4885                    self.creation_sandboxing_flag_set(),
4886                    self.pipeline_id(),
4887                    self.image_cache.clone(),
4888                );
4889                new_doc
4890                    .appropriate_template_contents_owner_document
4891                    .set(Some(&new_doc));
4892                new_doc
4893            })
4894    }
4895
4896    pub(crate) fn get_element_by_id(&self, no_gc: &NoGC, id: &Atom) -> Option<DomRoot<Element>> {
4897        self.id_map.get(no_gc, self.upcast(), id)
4898    }
4899
4900    pub(crate) fn ensure_pending_restyle(&self, el: &Element) -> RefMut<'_, PendingRestyle> {
4901        let map = self.pending_restyles.borrow_mut();
4902        RefMut::map(map, |m| {
4903            &mut m
4904                .entry(Dom::from_ref(el))
4905                .or_insert_with(|| NoTrace(PendingRestyle::default()))
4906                .0
4907        })
4908    }
4909
4910    pub(crate) fn element_attr_will_change(&self, el: &Element, attr: AttrRef<'_>) {
4911        if !el.upcast::<Node>().is_connected() {
4912            // Disconnected elements don’t need styling, and will get a full restyle when/if
4913            // connected later. For elements created by scripts, it is common to set attributes
4914            // before inserting them.
4915            return;
4916        }
4917
4918        // FIXME(emilio): Kind of a shame we have to duplicate this.
4919        //
4920        // I'm getting rid of the whole hashtable soon anyway, since all it does
4921        // right now is populate the element restyle data in layout, and we
4922        // could in theory do it in the DOM I think.
4923        let mut entry = self.ensure_pending_restyle(el);
4924        if entry.snapshot.is_none() {
4925            entry.snapshot = Some(Snapshot::new());
4926        }
4927        if attr.local_name() == &local_name!("style") {
4928            entry.hint.insert(RestyleHint::RESTYLE_STYLE_ATTRIBUTE);
4929        }
4930
4931        let affects_presentational_hints =
4932            vtable_for(el.upcast()).attribute_affects_presentational_hints(attr);
4933        if affects_presentational_hints {
4934            el.dirty_presentational_hints();
4935        }
4936        if affects_presentational_hints ||
4937            el.check_style_on_self_or_eager_pseudos(|style| {
4938                if let Some(ref attribute_references) = style.attribute_references {
4939                    return attribute_references.contains_key(attr.local_name());
4940                }
4941                false
4942            })
4943        {
4944            entry.hint.insert(RestyleHint::RESTYLE_SELF);
4945        }
4946
4947        let snapshot = entry.snapshot.as_mut().unwrap();
4948        if attr.local_name() == &local_name!("id") {
4949            if snapshot.id_changed {
4950                return;
4951            }
4952            snapshot.id_changed = true;
4953        } else if attr.local_name() == &local_name!("class") {
4954            if snapshot.class_changed {
4955                return;
4956            }
4957            snapshot.class_changed = true;
4958        } else {
4959            snapshot.other_attributes_changed = true;
4960        }
4961        let local_name = style::LocalName::cast(attr.local_name());
4962        if !snapshot.changed_attrs.contains(local_name) {
4963            snapshot.changed_attrs.push(local_name.clone());
4964        }
4965        if snapshot.attrs.is_none() {
4966            let attrs = el
4967                .attrs()
4968                .borrow()
4969                .iter()
4970                .map(|attr| (attr.as_identifier(), attr.value().clone()))
4971                .collect();
4972            snapshot.attrs = Some(attrs);
4973        }
4974    }
4975
4976    pub(crate) fn set_referrer_policy(&self, policy: ReferrerPolicy) {
4977        StdArc::make_mut(&mut *self.policy_container.borrow_mut()).set_referrer_policy(policy);
4978    }
4979
4980    pub(crate) fn get_referrer_policy(&self) -> ReferrerPolicy {
4981        self.policy_container.borrow().get_referrer_policy()
4982    }
4983
4984    pub(crate) fn set_target_element(&self, no_gc: &NoGC, node: Option<&Element>) {
4985        if let Some(ref element) = self.target_element.get() {
4986            element.set_target_state(no_gc, false);
4987        }
4988
4989        self.target_element.set(node);
4990
4991        if let Some(ref element) = self.target_element.get() {
4992            element.set_target_state(no_gc, true);
4993        }
4994    }
4995
4996    pub(crate) fn incr_ignore_destructive_writes_counter(&self) {
4997        self.ignore_destructive_writes_counter
4998            .set(self.ignore_destructive_writes_counter.get() + 1);
4999    }
5000
5001    pub(crate) fn decr_ignore_destructive_writes_counter(&self) {
5002        self.ignore_destructive_writes_counter
5003            .set(self.ignore_destructive_writes_counter.get() - 1);
5004    }
5005
5006    pub(crate) fn is_prompting_or_unloading(&self) -> bool {
5007        self.ignore_opens_during_unload_counter.get() > 0
5008    }
5009
5010    fn incr_ignore_opens_during_unload_counter(&self) {
5011        self.ignore_opens_during_unload_counter
5012            .set(self.ignore_opens_during_unload_counter.get() + 1);
5013    }
5014
5015    fn decr_ignore_opens_during_unload_counter(&self) {
5016        self.ignore_opens_during_unload_counter
5017            .set(self.ignore_opens_during_unload_counter.get() - 1);
5018    }
5019
5020    fn reset_form_owner_for_listeners(&self, cx: &mut JSContext, id: &Atom) {
5021        let map = self.form_id_listener_map.borrow();
5022        if let Some(listeners) = map.get(id) {
5023            for listener in listeners {
5024                listener
5025                    .as_maybe_form_control()
5026                    .expect("Element must be a form control")
5027                    .reset_form_owner(cx);
5028            }
5029        }
5030    }
5031
5032    pub(crate) fn register_shadow_root(&self, shadow_root: &ShadowRoot) {
5033        self.shadow_roots
5034            .borrow_mut()
5035            .insert(Dom::from_ref(shadow_root));
5036        self.invalidate_shadow_roots_stylesheets();
5037    }
5038
5039    pub(crate) fn unregister_shadow_root(&self, shadow_root: &ShadowRoot) {
5040        let mut shadow_roots = self.shadow_roots.borrow_mut();
5041        shadow_roots.remove(&Dom::from_ref(shadow_root));
5042    }
5043
5044    pub(crate) fn invalidate_shadow_roots_stylesheets(&self) {
5045        self.shadow_roots_styles_changed.set(true);
5046    }
5047
5048    pub(crate) fn flush_shadow_root_stylesheets_if_necessary_for_layout(
5049        &self,
5050        stylist: &mut Stylist,
5051        guard: &SharedRwLockReadGuard,
5052    ) {
5053        if !self.shadow_roots_styles_changed.get() {
5054            return;
5055        }
5056        #[expect(unsafe_code)]
5057        unsafe {
5058            for shadow_root in self.shadow_roots.borrow_for_layout().iter() {
5059                let layout: LayoutDom<'_, _> = shadow_root.to_layout();
5060                layout.flush_stylesheets_for_layout(stylist, guard);
5061            }
5062        }
5063        self.shadow_roots_styles_changed.set(false);
5064    }
5065
5066    pub(crate) fn stylesheet_count(&self) -> usize {
5067        self.stylesheets.borrow().len()
5068    }
5069
5070    pub(crate) fn stylesheet_at(
5071        &self,
5072        cx: &mut JSContext,
5073        index: usize,
5074    ) -> Option<DomRoot<CSSStyleSheet>> {
5075        let stylesheets = self.stylesheets.borrow();
5076
5077        stylesheets
5078            .get(Origin::Author, index)
5079            .and_then(|s| s.owner.get_cssom_object(cx))
5080    }
5081
5082    /// Add a stylesheet owned by `owner_node` to the list of document sheets, in the
5083    /// correct tree position. Additionally, ensure that the owned stylesheet is inserted
5084    /// before any constructed stylesheet.
5085    ///
5086    /// <https://drafts.csswg.org/cssom/#documentorshadowroot-final-css-style-sheets>
5087    #[cfg_attr(crown, expect(crown::unrooted_must_root))] // Owner needs to be rooted already necessarily.
5088    pub(crate) fn add_owned_stylesheet(
5089        &self,
5090        no_gc: &NoGC,
5091        owner_node: &Element,
5092        sheet: Arc<Stylesheet>,
5093    ) {
5094        let insertion_point = {
5095            let stylesheets = &mut *self.stylesheets.borrow_mut();
5096
5097            // FIXME(stevennovaryo): This is almost identical with the one in ShadowRoot::add_stylesheet.
5098            stylesheets
5099                .iter()
5100                .map(|(sheet, _origin)| sheet)
5101                .find(|sheet_in_doc| {
5102                    match &sheet_in_doc.owner {
5103                        StylesheetSource::Element(other_node) => owner_node
5104                            .upcast::<Node>()
5105                            .is_before(no_gc, other_node.upcast()),
5106                        // Non-constructed stylesheet should be ordered before the
5107                        // constructed ones.
5108                        StylesheetSource::Constructed(_) => true,
5109                    }
5110                })
5111                .cloned()
5112        };
5113
5114        if self.has_browsing_context() {
5115            self.add_stylesheet_to_stylist(
5116                sheet.clone(),
5117                insertion_point.as_ref().map(|s| s.sheet.clone()),
5118            );
5119        }
5120
5121        let stylesheets = &mut *self.stylesheets.borrow_mut();
5122        DocumentOrShadowRoot::add_stylesheet(
5123            StylesheetSource::Element(Dom::from_ref(owner_node)),
5124            StylesheetSetRef::Document(stylesheets),
5125            sheet,
5126            insertion_point,
5127            self.style_shared_author_lock(),
5128        );
5129    }
5130
5131    /// Append a constructed stylesheet to the back of document stylesheet set. Because
5132    /// it would be the last element, we therefore would not mess with the ordering.
5133    ///
5134    /// <https://drafts.csswg.org/cssom/#documentorshadowroot-final-css-style-sheets>
5135    pub(crate) fn append_constructed_stylesheet(&self, cssom_stylesheet: &CSSStyleSheet) {
5136        debug_assert!(cssom_stylesheet.is_constructed());
5137
5138        let sheet = cssom_stylesheet.style_stylesheet().clone();
5139
5140        if self.has_browsing_context() {
5141            self.add_stylesheet_to_stylist(sheet.clone(), None);
5142        }
5143
5144        let stylesheets = &mut *self.stylesheets.borrow_mut();
5145        DocumentOrShadowRoot::add_stylesheet(
5146            StylesheetSource::Constructed(Dom::from_ref(cssom_stylesheet)),
5147            StylesheetSetRef::Document(stylesheets),
5148            sheet,
5149            None,
5150            self.style_shared_author_lock(),
5151        );
5152    }
5153
5154    pub(crate) fn add_stylesheet_to_stylist(
5155        &self,
5156        stylesheet: Arc<Stylesheet>,
5157        before_stylesheet: Option<Arc<Stylesheet>>,
5158    ) {
5159        self.window
5160            .layout_mut()
5161            .add_stylesheet(stylesheet, before_stylesheet);
5162    }
5163
5164    /// Remove a stylesheet owned by `owner` from the list of document sheets.
5165    #[cfg_attr(crown, expect(crown::unrooted_must_root))] // Owner needs to be rooted already necessarily.
5166    pub(crate) fn remove_stylesheet(&self, owner: StylesheetSource, stylesheet: &Arc<Stylesheet>) {
5167        if self.has_browsing_context() {
5168            self.window
5169                .layout_mut()
5170                .remove_stylesheet(stylesheet.clone());
5171        }
5172
5173        DocumentOrShadowRoot::remove_stylesheet(
5174            owner,
5175            stylesheet,
5176            StylesheetSetRef::Document(&mut *self.stylesheets.borrow_mut()),
5177        )
5178    }
5179
5180    pub(crate) fn get_elements_with_id(
5181        &self,
5182        cx: &mut JSContext,
5183        id: &Atom,
5184    ) -> Ref<'_, [Dom<Element>]> {
5185        self.id_map.get_all(cx.no_gc(), self.upcast(), id)
5186    }
5187
5188    pub(crate) fn get_elements_with_name(
5189        &self,
5190        cx: &mut JSContext,
5191        name: &Atom,
5192    ) -> Ref<'_, [Dom<Element>]> {
5193        self.name_map.get_all(cx.no_gc(), self.upcast(), name)
5194    }
5195
5196    pub(crate) fn drain_pending_restyles(
5197        &self,
5198        no_gc: &NoGC,
5199    ) -> Vec<(TrustedNodeAddress, PendingRestyle)> {
5200        self.pending_restyles
5201            .borrow_mut()
5202            .drain()
5203            .filter_map(|(element, restyle)| {
5204                let node = element.upcast::<Node>();
5205                if !node.get_flag(NodeFlags::IS_CONNECTED) {
5206                    return None;
5207                }
5208                element.note_dirty_descendants(no_gc);
5209                Some((node.to_trusted_node_address(), restyle.0))
5210            })
5211            .collect()
5212    }
5213
5214    pub(crate) fn advance_animation_timeline_for_testing(&self, delta: TimeDuration) {
5215        self.timeline.advance_specific(delta);
5216        let current_timeline_value = self.current_animation_timeline_value();
5217        self.animation_manager
5218            .update_for_new_timeline_value(&self.window, current_timeline_value);
5219    }
5220
5221    pub(crate) fn maybe_mark_animating_nodes_as_dirty(&self, no_gc: &NoGC) {
5222        let current_timeline_value = self.current_animation_timeline_value();
5223        self.animation_manager
5224            .mark_animating_nodes_as_dirty(no_gc, current_timeline_value);
5225    }
5226
5227    pub(crate) fn current_animation_timeline_value(&self) -> f64 {
5228        self.timeline
5229            .upcast::<AnimationTimeline>()
5230            .current_time_in_seconds()
5231    }
5232
5233    pub(crate) fn animation_manager(&self) -> &AnimationManager {
5234        &self.animation_manager
5235    }
5236
5237    pub(crate) fn update_animations_post_reflow(&self) {
5238        let current_timeline_value = self.current_animation_timeline_value();
5239        self.animation_manager
5240            .do_post_reflow_update(&self.window, current_timeline_value);
5241    }
5242
5243    pub(crate) fn cancel_animations_for_node(&self, node: &Node) {
5244        self.animation_manager.cancel_animations_for_node(node);
5245    }
5246
5247    /// Clear style and layout data on this [`Node`] and all descendants. This is used to clean
5248    /// up the data when a [`Node`] becomes detached from the flat tree. Note that this
5249    /// operates on shadow-including descendants.
5250    pub(crate) fn remove_style_and_layout_data_from_subtree(
5251        &self,
5252        no_gc: &NoGC,
5253        subtree_root: &Node,
5254    ) {
5255        for node in subtree_root.traverse_preorder_unrooted(no_gc, ShadowIncluding::Yes) {
5256            self.clean_up_style_and_layout_data_for_node(&node);
5257        }
5258    }
5259
5260    pub(crate) fn clean_up_style_and_layout_data_for_node(&self, node: &Node) {
5261        node.clear_layout_data();
5262        if let Some(element) = node.downcast::<Element>() {
5263            element.clean_up_style_data();
5264
5265            // If this element no longer has any layout or style data, nothing underneath it
5266            // can either, and it no longer needs to serve as a layout root. This method is
5267            // generally called when a node is leaving the flat tree and no longer takes part
5268            // in layout.
5269            if self.dirty_root == Some(element) {
5270                self.dirty_root.clear();
5271            }
5272        }
5273
5274        node.set_flag(NodeFlags::OVERLAPS_DOCUMENT_SELECTION, false);
5275        node.set_flag(NodeFlags::SELECTION_INHIBITED, false);
5276        node.set_flag(NodeFlags::HAS_DIRTY_DESCENDANTS, false);
5277    }
5278
5279    /// An implementation of <https://drafts.csswg.org/web-animations-1/#update-animations-and-send-events>.
5280    pub(crate) fn update_animations_and_send_events(&self, cx: &mut CurrentRealm) {
5281        // Only update the time if it isn't being managed by a test.
5282        if !self.layout_animations_test_enabled {
5283            self.timeline.update(self.window());
5284        }
5285
5286        // > 1. Update the current time of all timelines associated with doc passing now
5287        // > as the timestamp.
5288        // > 2. Remove replaced animations for doc.
5289        //
5290        // We still want to update the animations, because our timeline
5291        // value might have been advanced previously via the TestBinding.
5292        let current_timeline_value = self.current_animation_timeline_value();
5293        self.animation_manager
5294            .update_for_new_timeline_value(&self.window, current_timeline_value);
5295        self.maybe_mark_animating_nodes_as_dirty(cx.no_gc());
5296
5297        // > 3. Perform a microtask checkpoint.
5298        self.window().perform_a_microtask_checkpoint(cx);
5299
5300        // Steps 4 through 7 occur inside `send_pending_events().`
5301        self.animation_manager()
5302            .send_pending_events(self.window(), cx);
5303    }
5304
5305    pub(crate) fn set_has_pending_animated_image_update(&self) {
5306        self.has_pending_animated_image_update.set(true);
5307    }
5308
5309    /// <https://html.spec.whatwg.org/multipage/#shared-declarative-refresh-steps>
5310    pub(crate) fn shared_declarative_refresh_steps(&self, content: &[u8], from_meta_element: bool) {
5311        // 1. If document's will declaratively refresh is true, then return.
5312        if self.will_declaratively_refresh() {
5313            return;
5314        }
5315
5316        // 2-11 Parsing
5317        static REFRESH_REGEX: LazyLock<Regex> = LazyLock::new(|| {
5318            // s flag is used to match . on newlines since the only places we use . in the
5319            // regex is to go "to end of the string"
5320            // (?s-u:.) is used to consume invalid unicode bytes
5321            Regex::new(
5322                r#"(?xs)
5323                    ^
5324                    \s* # 3
5325                    ((?<time>[0-9]+)|\.) # 5-6
5326                    [0-9.]* # 8
5327                    (
5328                        (
5329                            (\s*;|\s*,|\s) # 10.3
5330                            \s* # 10.4
5331                        )
5332                        (
5333                            (
5334                                (U|u)(R|r)(L|l) # 11.2-11.4
5335                                \s*=\s* # 11.5-11.7
5336                            )?
5337                        ('(?<url1>[^']*)'(?s-u:.)*|"(?<url2>[^"]*)"(?s-u:.)*|['"]?(?<url3>(?s-u:.)*)) # 11.8 - 11.10
5338                        |
5339                        (?<url4>(?s-u:.)*)
5340                    )
5341                )?
5342                $
5343            "#,
5344            )
5345            .unwrap()
5346        });
5347
5348        // 9. Let urlRecord be document's URL.
5349        let mut url_record = self.url();
5350        let captures = if let Some(captures) = REFRESH_REGEX.captures(content) {
5351            captures
5352        } else {
5353            return;
5354        };
5355        let time = if let Some(time_string) = captures.name("time") {
5356            u64::from_str(&String::from_utf8_lossy(time_string.as_bytes())).unwrap_or(0)
5357        } else {
5358            0
5359        };
5360        let captured_url = captures.name("url1").or(captures
5361            .name("url2")
5362            .or(captures.name("url3").or(captures.name("url4"))));
5363
5364        // 11.11 Parse: Set urlRecord to the result of encoding-parsing a URL given urlString, relative to document.
5365        if let Some(url_match) = captured_url {
5366            url_record = if let Ok(url) = ServoUrl::parse_with_base(
5367                Some(&url_record),
5368                &String::from_utf8_lossy(url_match.as_bytes()),
5369            ) {
5370                info!("Refresh to {}", url.debug_compact());
5371                url
5372            } else {
5373                // 11.12 If urlRecord is failure, then return.
5374                return;
5375            };
5376            // 11.13 If urlRecord's scheme is "javascript", then return.
5377            if url_record.scheme() == "javascript" {
5378                return;
5379            }
5380        }
5381        // 12. Set document's will declaratively refresh to true.
5382        if self.completely_loaded() {
5383            self.window.as_global_scope().schedule_callback(
5384                OneshotTimerCallback::RefreshRedirectDue(RefreshRedirectDue {
5385                    url: url_record,
5386                    from_meta_element,
5387                }),
5388                Duration::from_secs(time),
5389            );
5390            self.set_declarative_refresh(DeclarativeRefresh::CreatedAfterLoad);
5391        } else {
5392            self.set_declarative_refresh(DeclarativeRefresh::PendingLoad {
5393                url: url_record,
5394                time,
5395                from_meta_element,
5396            });
5397        }
5398    }
5399
5400    pub(crate) fn will_declaratively_refresh(&self) -> bool {
5401        self.declarative_refresh.borrow().is_some()
5402    }
5403    pub(crate) fn set_declarative_refresh(&self, refresh: DeclarativeRefresh) {
5404        *self.declarative_refresh.borrow_mut() = Some(refresh);
5405    }
5406
5407    /// <https://html.spec.whatwg.org/multipage/#visibility-state>
5408    fn update_visibility_state(
5409        &self,
5410        cx: &mut JSContext,
5411        visibility_state: DocumentVisibilityState,
5412    ) {
5413        // Step 1 If document's visibility state equals visibilityState, then return.
5414        if self.visibility_state.get() == visibility_state {
5415            return;
5416        }
5417        // Step 2 Set document's visibility state to visibilityState.
5418        self.visibility_state.set(visibility_state);
5419        // Step 3 Queue a new VisibilityStateEntry whose visibility state is visibilityState and whose timestamp is
5420        // the current high resolution time given document's relevant global object.
5421        let entry = VisibilityStateEntry::new(
5422            cx,
5423            &self.global(),
5424            visibility_state,
5425            CrossProcessInstant::now(),
5426        );
5427        self.window
5428            .Performance(cx)
5429            .queue_entry(entry.upcast::<PerformanceEntry>());
5430
5431        // Step 4 Run the screen orientation change steps with document.
5432        // TODO ScreenOrientation hasn't implemented yet
5433
5434        // Step 5 Run the view transition page visibility change steps with document.
5435        // TODO ViewTransition hasn't implemented yet
5436
5437        // Step 6 Run any page visibility change steps which may be defined in other specifications, with visibility
5438        // state and document. Any other specs' visibility steps will go here.
5439
5440        // <https://www.w3.org/TR/geolocation/#dfn-request-a-position>
5441        // Position requests made while the document was hidden resume once it becomes visible.
5442        if let Some(geolocation) = self.window.maybe_geolocation() {
5443            geolocation.handle_visibility_change(visibility_state);
5444        }
5445
5446        // <https://www.w3.org/TR/gamepad/#handling-visibility-change>
5447        #[cfg(feature = "gamepad")]
5448        if visibility_state == DocumentVisibilityState::Hidden {
5449            self.window
5450                .Navigator(cx)
5451                .GetGamepads(cx)
5452                .unwrap_or_default()
5453                .iter_mut()
5454                .for_each(|gamepad| {
5455                    if let Some(g) = gamepad {
5456                        g.vibration_actuator().handle_visibility_change();
5457                    }
5458                });
5459        }
5460
5461        // Step 7 Fire an event named visibilitychange at document, with its bubbles attribute initialized to true.
5462        self.upcast::<EventTarget>()
5463            .fire_bubbling_event(cx, atom!("visibilitychange"));
5464    }
5465
5466    /// <https://html.spec.whatwg.org/multipage/#is-initial-about:blank>
5467    pub(crate) fn is_initial_about_blank(&self) -> bool {
5468        self.is_initial_about_blank.get()
5469    }
5470
5471    /// <https://dom.spec.whatwg.org/#document-allow-declarative-shadow-roots>
5472    pub(crate) fn allow_declarative_shadow_roots(&self) -> bool {
5473        self.allow_declarative_shadow_roots.get()
5474    }
5475
5476    pub(crate) fn has_trustworthy_ancestor_origin(&self) -> bool {
5477        self.has_trustworthy_ancestor_origin.get()
5478    }
5479
5480    pub(crate) fn has_trustworthy_ancestor_or_current_origin(&self) -> bool {
5481        self.has_trustworthy_ancestor_origin.get() ||
5482            self.origin().immutable().is_potentially_trustworthy()
5483    }
5484
5485    /// <https://fetch.spec.whatwg.org/#determine-the-network-partition-key>
5486    pub(crate) fn determine_the_network_partition_key(&self) -> Option<Site> {
5487        // Step 1. Let topLevelOrigin be environment’s top-level origin.
5488        // https://html.spec.whatwg.org/multipage/#concept-environment-top-level-origin
5489        let top_level_origin = if self.window().is_top_level() {
5490            Some(self.origin().immutable().clone())
5491        } else if let Some(top_level_document) = self.window().top_level_document_if_local() {
5492            Some(top_level_document.origin().immutable().clone())
5493        } else if let Ok(ancestor_origins) = self.internal_ancestor_origin_objects_list.try_borrow()
5494        {
5495            ancestor_origins
5496                .as_ref()
5497                .and_then(|ancestors| ancestors.last().cloned())
5498        } else {
5499            None
5500        };
5501
5502        // Step 2. If topLevelOrigin is null, then set topLevelOrigin to environment’s
5503        // top-level creation URL’s origin.
5504        let top_level_origin = top_level_origin.or_else(|| {
5505            self.window()
5506                .as_global_scope()
5507                .top_level_creation_url()
5508                .map(|url| url.origin())
5509        });
5510
5511        // Step 3. Assert: topLevelOrigin is an origin.
5512        let top_level_origin = top_level_origin.expect("topLevelOrigin must be an origin");
5513
5514        // Step 4. Let topLevelSite be the result of obtaining a site, given topLevelOrigin.
5515        let top_level_site = Site::from_origin(&top_level_origin);
5516
5517        // Step 5. Let secondKey be null or an implementation-defined value.
5518        //
5519        // We choose to do nothing here
5520
5521        // Step 6. Return (topLevelSite, secondKey).
5522        Some(top_level_site)
5523    }
5524
5525    #[cfg(feature = "devtools")]
5526    pub(crate) fn highlight_dom_node(&self, node: Option<&Node>) {
5527        self.highlighted_dom_node.set(node);
5528        self.add_restyle_reason(RestyleReason::HighlightedDOMNodeChanged);
5529    }
5530
5531    pub(crate) fn highlighted_dom_node(&self) -> Option<DomRoot<Node>> {
5532        self.highlighted_dom_node.get()
5533    }
5534
5535    pub(crate) fn custom_element_reaction_stack(&self) -> Rc<CustomElementReactionStack> {
5536        self.custom_element_reaction_stack.clone()
5537    }
5538
5539    pub(crate) fn active_sandboxing_flag_set(&self) -> SandboxingFlagSet {
5540        self.active_sandboxing_flag_set.get()
5541    }
5542
5543    pub(crate) fn has_active_sandboxing_flag(&self, flag: SandboxingFlagSet) -> bool {
5544        self.active_sandboxing_flag_set.get().contains(flag)
5545    }
5546
5547    pub(crate) fn set_active_sandboxing_flag_set(&self, flags: SandboxingFlagSet) {
5548        self.active_sandboxing_flag_set.set(flags)
5549    }
5550
5551    pub(crate) fn creation_sandboxing_flag_set(&self) -> SandboxingFlagSet {
5552        self.creation_sandboxing_flag_set.get()
5553    }
5554
5555    pub(crate) fn creation_sandboxing_flag_set_considering_parent_iframe(
5556        &self,
5557    ) -> SandboxingFlagSet {
5558        self.window()
5559            .window_proxy()
5560            .frame_element()
5561            .and_then(|element| element.downcast::<HTMLIFrameElement>())
5562            .map(HTMLIFrameElement::sandboxing_flag_set)
5563            .unwrap_or_else(|| self.creation_sandboxing_flag_set())
5564    }
5565
5566    pub(crate) fn viewport_scrolling_box(&self, flags: ScrollContainerQueryFlags) -> ScrollingBox {
5567        self.window()
5568            .scrolling_box_query(None, flags)
5569            .expect("We should always have a ScrollingBox for the Viewport")
5570    }
5571
5572    pub(crate) fn notify_embedder_favicon(&self) {
5573        if !self.window.is_top_level() {
5574            return;
5575        }
5576        self.send_to_embedder(EmbedderMsg::SetFavicon(
5577            self.webview_id(),
5578            self.favicon.borrow().clone(),
5579        ));
5580    }
5581
5582    pub(crate) fn set_favicon(&self, favicon: Image) {
5583        *self.favicon.borrow_mut() = Some(favicon);
5584        self.notify_embedder_favicon();
5585    }
5586
5587    pub(crate) fn favicon(&self) -> Option<Image> {
5588        self.favicon.borrow().clone()
5589    }
5590
5591    pub(crate) fn ever_had_favicon_link(&self) -> bool {
5592        self.ever_had_favicon_link.get()
5593    }
5594
5595    pub(crate) fn set_ever_had_favicon_link(&self, value: bool) {
5596        self.ever_had_favicon_link.set(value);
5597    }
5598
5599    /// <https://w3c.github.io/editing/docs/execCommand/#state-override>
5600    pub(crate) fn state_override(&self, command_name: &CommandName) -> Option<bool> {
5601        self.state_override.borrow().get(command_name).copied()
5602    }
5603
5604    /// <https://w3c.github.io/editing/docs/execCommand/#state-override>
5605    pub(crate) fn set_state_override(&self, command_name: CommandName, state: Option<bool>) {
5606        if let Some(state) = state {
5607            self.state_override.borrow_mut().insert(command_name, state);
5608        } else {
5609            self.value_override.borrow_mut().remove(&command_name);
5610        }
5611    }
5612
5613    /// <https://w3c.github.io/editing/docs/execCommand/#value-override>
5614    pub(crate) fn value_override(&self, command_name: &CommandName) -> Option<DOMString> {
5615        self.value_override.borrow().get(command_name).cloned()
5616    }
5617
5618    /// <https://w3c.github.io/editing/docs/execCommand/#value-override>
5619    pub(crate) fn set_value_override(&self, command_name: CommandName, value: Option<DOMString>) {
5620        if let Some(value) = value {
5621            self.value_override.borrow_mut().insert(command_name, value);
5622        } else {
5623            self.value_override.borrow_mut().remove(&command_name);
5624        }
5625    }
5626
5627    /// <https://w3c.github.io/editing/docs/execCommand/#value-override>
5628    /// and <https://w3c.github.io/editing/docs/execCommand/#state-override>
5629    pub(crate) fn clear_command_overrides(&self) {
5630        self.state_override.borrow_mut().clear();
5631        self.value_override.borrow_mut().clear();
5632    }
5633
5634    /// <https://w3c.github.io/editing/docs/execCommand/#default-single-line-container-name>
5635    pub(crate) fn default_single_line_container_name(&self) -> DefaultSingleLineContainerName {
5636        self.default_single_line_container_name.get()
5637    }
5638
5639    /// <https://w3c.github.io/editing/docs/execCommand/#default-single-line-container-name>
5640    pub(crate) fn set_default_single_line_container_name(
5641        &self,
5642        value: DefaultSingleLineContainerName,
5643    ) {
5644        self.default_single_line_container_name.set(value)
5645    }
5646
5647    /// <https://w3c.github.io/editing/docs/execCommand/#css-styling-flag>
5648    pub(crate) fn css_styling_flag(&self) -> bool {
5649        self.css_styling_flag.get()
5650    }
5651
5652    /// <https://w3c.github.io/editing/docs/execCommand/#css-styling-flag>
5653    pub(crate) fn set_css_styling_flag(&self, value: bool) {
5654        self.css_styling_flag.set(value)
5655    }
5656
5657    pub(crate) fn mute_iframe_load_flag(&self) -> bool {
5658        self.mute_iframe_load.get()
5659    }
5660
5661    pub(crate) fn set_iframe_load_in_progress(&self, value: bool) {
5662        self.iframe_load_in_progress.set(value)
5663    }
5664
5665    pub(crate) fn theme(&self) -> Option<Theme> {
5666        self.theme.get()
5667    }
5668
5669    pub(crate) fn set_theme(&self, new_theme: Option<Theme>) {
5670        self.theme.set(new_theme);
5671        self.window.refresh_theme();
5672    }
5673
5674    pub(crate) fn theme_override(&self) -> Option<Theme> {
5675        self.theme_override.get()
5676    }
5677
5678    #[cfg(feature = "devtools")]
5679    pub(crate) fn set_theme_override(&self, new_theme: Option<Theme>) {
5680        self.theme_override.set(new_theme);
5681        self.window.refresh_theme();
5682    }
5683
5684    pub(crate) fn default_language(&self) -> Option<String> {
5685        self.default_language.borrow().clone()
5686    }
5687
5688    pub(crate) fn set_default_language(&self, new_language: Option<String>) {
5689        *self.default_language.borrow_mut() = new_language;
5690    }
5691
5692    pub(crate) fn create_element(&self, cx: &mut JSContext, name: &str) -> DomRoot<Element> {
5693        let element_options =
5694            StringOrElementCreationOptions::ElementCreationOptions(ElementCreationOptions {
5695                is: None,
5696            });
5697        self.CreateElement(cx, name.into(), element_options)
5698            .expect("Must always be able to create element")
5699    }
5700
5701    /// Queue `online` or `offline` events on this `Document`'s `Window` and on its
5702    /// dedicated workers.
5703    pub(crate) fn queue_online_offline_events(&self, online: bool) {
5704        let event_name = Atom::from(if online { "online" } else { "offline" });
5705        let window = self.window();
5706        let global_scope = window.as_global_scope();
5707
5708        // From <https://html.spec.whatwg.org/multipage/#dom-navigator-online>:
5709        // > When the value that would be returned by the navigator.onLine attribute of a
5710        // > Window or WorkerGlobalScope global changes from true to false, the user agent
5711        // > must queue a global task on the networking task source given global to fire an
5712        // > event named offline at global.
5713        // >
5714        // > On the other hand, when the value that would be returned by the
5715        // > navigator.onLine attribute of a Window or WorkerGlobalScope global changes from
5716        // > false to true, the user agent must queue a global task on the networking task
5717        // > source given global to fire an event named online at the Window or
5718        // > WorkerGlobalScope object.
5719        global_scope
5720            .task_manager()
5721            .networking_task_source()
5722            .queue_simple_event(window.upcast::<EventTarget>(), event_name);
5723        global_scope.set_network_online_state_on_dedicated_workers(online);
5724    }
5725}
5726
5727impl DocumentMethods<crate::DomTypeHolder> for Document {
5728    /// <https://dom.spec.whatwg.org/#dom-document-document>
5729    fn Constructor(
5730        cx: &mut JSContext,
5731        window: &Window,
5732        proto: Option<HandleObject>,
5733    ) -> Fallible<DomRoot<Document>> {
5734        // The new Document() constructor steps are to set this’s origin to the origin of current global object’s associated Document. [HTML]
5735        let doc = window.Document();
5736        let docloader = DocumentLoader::new(&doc.loader());
5737        Ok(Document::new_with_proto(
5738            cx,
5739            window,
5740            proto,
5741            HasBrowsingContext::No,
5742            None,
5743            None,
5744            doc.origin().clone(),
5745            IsHTMLDocument::NonHTMLDocument,
5746            None,
5747            None,
5748            DocumentActivity::Inactive,
5749            docloader,
5750            None,
5751            None,
5752            false,
5753            doc.allow_declarative_shadow_roots(),
5754            Some(doc.insecure_requests_policy()),
5755            doc.has_trustworthy_ancestor_or_current_origin(),
5756            doc.custom_element_reaction_stack(),
5757            doc.active_sandboxing_flag_set.get(),
5758            doc.pipeline_id(),
5759            doc.image_cache(),
5760        ))
5761    }
5762
5763    /// <https://html.spec.whatwg.org/multipage/#dom-parsehtmlunsafe>
5764    fn ParseHTMLUnsafe(
5765        cx: &mut JSContext,
5766        window: &Window,
5767        s: TrustedHTMLOrString,
5768        options: &SetHTMLUnsafeOptions,
5769    ) -> Fallible<DomRoot<Self>> {
5770        // Step 1. Let compliantHTML be the result of invoking the
5771        // Get Trusted Type compliant string algorithm with TrustedHTML, the current global object,
5772        // html, "Document parseHTMLUnsafe", and "script".
5773        let compliant_html = TrustedHTML::get_trusted_type_compliant_string(
5774            cx,
5775            window.as_global_scope(),
5776            s,
5777            "Document parseHTMLUnsafe",
5778        )?;
5779
5780        let url = window.get_url();
5781        let doc = window.Document();
5782        let loader = DocumentLoader::new(&doc.loader());
5783
5784        let content_type = "text/html"
5785            .parse()
5786            .expect("Supported type is not a MIME type");
5787        // Step 2. Let document be a new Document, whose content type is "text/html".
5788        // Step 3. Set document's allow declarative shadow roots to true.
5789        let document = Document::new(
5790            cx,
5791            window,
5792            HasBrowsingContext::No,
5793            Some(ServoUrl::parse("about:blank").unwrap()),
5794            None,
5795            doc.origin().clone(),
5796            IsHTMLDocument::HTMLDocument,
5797            Some(content_type),
5798            None,
5799            DocumentActivity::Inactive,
5800            loader,
5801            None,
5802            None,
5803            false,
5804            true,
5805            Some(doc.insecure_requests_policy()),
5806            doc.has_trustworthy_ancestor_or_current_origin(),
5807            doc.custom_element_reaction_stack(),
5808            doc.creation_sandboxing_flag_set(),
5809            doc.pipeline_id(),
5810            doc.image_cache(),
5811        );
5812        // Step 4. Parse HTML from string given document and compliantHTML.
5813        ServoParser::parse_html_document(cx, &document, Some(compliant_html), url, None, None);
5814
5815        // Step 5. Let sanitizer be the result of calling get a sanitizer instance from options with
5816        // options and false.
5817        let sanitizer = Sanitizer::get_sanitizer_instance_from_options(cx, window, options, false)?;
5818
5819        // Step 6. Call sanitize on document with sanitizer and false.
5820        sanitizer.sanitize(cx, document.upcast(), false)?;
5821
5822        // Step 7. Return document.
5823        document.update_the_current_document_readiness(cx, DocumentReadyState::Complete);
5824        Ok(document)
5825    }
5826
5827    /// <https://wicg.github.io/sanitizer-api/#dom-document-parsehtml>
5828    fn ParseHTML(
5829        cx: &mut JSContext,
5830        window: &Window,
5831        html: DOMString,
5832        options: &SetHTMLOptions,
5833    ) -> Fallible<DomRoot<Document>> {
5834        // Step 1. Let document be a new Document, whose content type is "text/html".
5835        // Step 2. Set document's allow declarative shadow roots to true.
5836        let url = window.get_url();
5837        let doc = window.Document();
5838        let loader = DocumentLoader::new(&doc.loader());
5839        let content_type = "text/html"
5840            .parse()
5841            .expect("Supported type is not a MIME type");
5842        let document = Document::new(
5843            cx,
5844            window,
5845            HasBrowsingContext::No,
5846            Some(ServoUrl::parse("about:blank").unwrap()),
5847            None,
5848            doc.origin().clone(),
5849            IsHTMLDocument::HTMLDocument,
5850            Some(content_type),
5851            None,
5852            DocumentActivity::Inactive,
5853            loader,
5854            None,
5855            None,
5856            false,
5857            true,
5858            Some(doc.insecure_requests_policy()),
5859            doc.has_trustworthy_ancestor_or_current_origin(),
5860            doc.custom_element_reaction_stack(),
5861            doc.creation_sandboxing_flag_set(),
5862            doc.pipeline_id(),
5863            doc.image_cache(),
5864        );
5865
5866        // Step 3. Parse HTML from a string given document and html.
5867        ServoParser::parse_html_document(cx, &document, Some(html), url, None, None);
5868
5869        // Step 4. Let sanitizer be the result of calling get a sanitizer instance from options with
5870        // options and true.
5871        let sanitizer = Sanitizer::get_sanitizer_instance_from_options(cx, window, options, true)?;
5872
5873        // Step 5. Call sanitize on document with sanitizer and true.
5874        sanitizer.sanitize(cx, document.upcast(), true)?;
5875
5876        // Step 6. Return document.
5877        Ok(document)
5878    }
5879
5880    /// <https://drafts.csswg.org/cssom/#dom-document-stylesheets>
5881    fn StyleSheets(&self, cx: &mut JSContext) -> DomRoot<StyleSheetList> {
5882        self.stylesheet_list.or_init(|| {
5883            StyleSheetList::new(
5884                cx,
5885                &self.window,
5886                StyleSheetListOwner::Document(Dom::from_ref(self)),
5887            )
5888        })
5889    }
5890
5891    /// <https://dom.spec.whatwg.org/#dom-document-implementation>
5892    fn Implementation(&self, cx: &mut JSContext) -> DomRoot<DOMImplementation> {
5893        self.implementation
5894            .or_init(|| DOMImplementation::new(cx, self))
5895    }
5896
5897    /// <https://dom.spec.whatwg.org/#dom-document-url>
5898    fn URL(&self) -> USVString {
5899        USVString(String::from(self.url().as_str()))
5900    }
5901
5902    /// <https://html.spec.whatwg.org/multipage/#dom-document-activeelement>
5903    fn GetActiveElement(&self) -> Option<DomRoot<Element>> {
5904        self.document_or_shadow_root.active_element(self.upcast())
5905    }
5906
5907    /// <https://dom.spec.whatwg.org/#dom-documentorshadowroot-customelementregistry>
5908    fn GetCustomElementRegistry(&self) -> Option<DomRoot<CustomElementRegistry>> {
5909        self.custom_element_registry()
5910    }
5911
5912    /// <https://html.spec.whatwg.org/multipage/#dom-document-hasfocus>
5913    fn HasFocus(&self) -> bool {
5914        // <https://html.spec.whatwg.org/multipage/#has-focus-steps>
5915        //
5916        // > The has focus steps, given a `Document` object `target`, are as
5917        // > follows:
5918        // >
5919        // > 1. If `target`'s browsing context's top-level browsing context does
5920        // >    not have system focus, then return false.
5921        if !self.window().webview_state().has_system_focus.get() {
5922            return false;
5923        }
5924
5925        // > 2. Let `candidate` be `target`'s browsing context's top-level
5926        // >    browsing context's active document.
5927        // >
5928        // > 3. While true:
5929        // >
5930        // >    3.1. If `candidate` is target, then return true.
5931        // >
5932        // >    3.2. If the focused area of `candidate` is a browsing context
5933        // >         container with a non-null nested browsing context, then set
5934        // >         `candidate` to the active document of that browsing context
5935        // >         container's nested browsing context.
5936        // >
5937        // >    3.3. Otherwise, return false.
5938        if self.window().parent_info().is_none() {
5939            // 2 → 3 → (3.1 || ⋯ → 3.3)
5940            self.is_fully_active()
5941        } else {
5942            // 2 → 3 → 3.2 → (⋯ → 3.1 || ⋯ → 3.3)
5943            self.is_fully_active() && self.focus_handler.has_focus()
5944        }
5945    }
5946
5947    /// <https://html.spec.whatwg.org/multipage/#dom-document-domain>
5948    fn Domain(&self) -> DOMString {
5949        // Step 1. Let effectiveDomain be this's origin's effective domain.
5950        match self.origin().effective_domain() {
5951            // Step 2. If effectiveDomain is null, then return the empty string.
5952            None => DOMString::new(),
5953            // Step 3. Return effectiveDomain, serialized.
5954            Some(Host::Domain(domain)) => DOMString::from(domain),
5955            Some(host) => DOMString::from(host.to_string()),
5956        }
5957    }
5958
5959    /// <https://html.spec.whatwg.org/multipage/#dom-document-domain>
5960    fn SetDomain(&self, value: DOMString) -> ErrorResult {
5961        // Step 1. If this's browsing context is null, then throw a "SecurityError" DOMException.
5962        if !self.has_browsing_context {
5963            return Err(Error::Security(Some(
5964                "Document has no browsing context".into(),
5965            )));
5966        }
5967
5968        // Step 2. If this Document object's active sandboxing flag set has its sandboxed
5969        // document.domain browsing context flag set, then throw a "SecurityError" DOMException.
5970        if self.has_active_sandboxing_flag(
5971            SandboxingFlagSet::SANDBOXED_DOCUMENT_DOMAIN_BROWSING_CONTEXT_FLAG,
5972        ) {
5973            return Err(Error::Security(Some(
5974                "Sandboxed document cannot set its domain".into(),
5975            )));
5976        }
5977
5978        // Step 3. Let effectiveDomain be this's origin's effective domain.
5979        let effective_domain = match self.origin().effective_domain() {
5980            Some(effective_domain) => effective_domain,
5981            // Step 4. If effectiveDomain is null, then throw a "SecurityError" DOMException.
5982            None => return Err(Error::Security(Some("Document's origin is opaque".into()))),
5983        };
5984
5985        // Step 5. If the given value is not a registrable domain suffix of and is not equal to effectiveDomain, then throw a "SecurityError" DOMException.
5986        let host =
5987            match get_registrable_domain_suffix_of_or_is_equal_to(&value.str(), effective_domain) {
5988                None => return Err(Error::Security(Some("Provided domain is not a registrable domain suffix and is not equal to document's effective domain".into()))),
5989                Some(host) => host,
5990            };
5991
5992        // Step 6. If the surrounding agent's agent cluster's is origin-keyed is true, then return.
5993        // TODO
5994
5995        // Step 7. Set this's origin's domain to the result of parsing the given value.
5996        self.origin().set_domain(host);
5997
5998        Ok(())
5999    }
6000
6001    /// <https://html.spec.whatwg.org/multipage/#dom-document-referrer>
6002    fn Referrer(&self) -> DOMString {
6003        match self.referrer {
6004            Some(ref referrer) => DOMString::from(referrer.to_string()),
6005            None => DOMString::new(),
6006        }
6007    }
6008
6009    /// <https://dom.spec.whatwg.org/#dom-document-documenturi>
6010    fn DocumentURI(&self) -> USVString {
6011        self.URL()
6012    }
6013
6014    /// <https://dom.spec.whatwg.org/#dom-document-compatmode>
6015    fn CompatMode(&self) -> DOMString {
6016        DOMString::from(match self.quirks_mode.get() {
6017            QuirksMode::LimitedQuirks | QuirksMode::NoQuirks => "CSS1Compat",
6018            QuirksMode::Quirks => "BackCompat",
6019        })
6020    }
6021
6022    /// <https://dom.spec.whatwg.org/#dom-document-characterset>
6023    fn CharacterSet(&self) -> DOMString {
6024        DOMString::from_static(self.encoding.get().name())
6025    }
6026
6027    /// <https://dom.spec.whatwg.org/#dom-document-charset>
6028    fn Charset(&self) -> DOMString {
6029        self.CharacterSet()
6030    }
6031
6032    /// <https://dom.spec.whatwg.org/#dom-document-inputencoding>
6033    fn InputEncoding(&self) -> DOMString {
6034        self.CharacterSet()
6035    }
6036
6037    /// <https://dom.spec.whatwg.org/#dom-document-content_type>
6038    fn ContentType(&self) -> DOMString {
6039        DOMString::from(format!(
6040            "{}/{}",
6041            self.content_type.type_, self.content_type.subtype
6042        ))
6043    }
6044
6045    /// <https://dom.spec.whatwg.org/#dom-document-doctype>
6046    fn GetDoctype(&self) -> Option<DomRoot<DocumentType>> {
6047        self.upcast::<Node>().children().find_map(DomRoot::downcast)
6048    }
6049
6050    /// <https://dom.spec.whatwg.org/#dom-document-documentelement>
6051    fn GetDocumentElement(&self) -> Option<DomRoot<Element>> {
6052        self.upcast::<Node>().child_elements().next()
6053    }
6054
6055    /// <https://dom.spec.whatwg.org/#dom-document-getelementsbytagname>
6056    fn GetElementsByTagName(
6057        &self,
6058        cx: &mut JSContext,
6059        qualified_name: DOMString,
6060    ) -> DomRoot<HTMLCollection> {
6061        let qualified_name = LocalName::from(qualified_name);
6062        if let Some(entry) = self.tag_map.borrow_mut().get(&qualified_name) {
6063            return DomRoot::from_ref(entry);
6064        }
6065        let result = HTMLCollection::by_qualified_name(
6066            cx,
6067            &self.window,
6068            self.upcast(),
6069            qualified_name.clone(),
6070        );
6071        self.tag_map
6072            .borrow_mut()
6073            .insert(qualified_name, Dom::from_ref(&*result));
6074        result
6075    }
6076
6077    /// <https://dom.spec.whatwg.org/#dom-document-getelementsbytagnamens>
6078    fn GetElementsByTagNameNS(
6079        &self,
6080        cx: &mut JSContext,
6081        maybe_ns: Option<DOMString>,
6082        tag_name: DOMString,
6083    ) -> DomRoot<HTMLCollection> {
6084        let ns = namespace_from_domstring(maybe_ns);
6085        let local = LocalName::from(tag_name);
6086        let qname = QualName::new(None, ns, local);
6087        if let Some(collection) = self.tagns_map.borrow().get(&qname) {
6088            return DomRoot::from_ref(collection);
6089        }
6090        let result =
6091            HTMLCollection::by_qual_tag_name(cx, &self.window, self.upcast(), qname.clone());
6092        self.tagns_map
6093            .borrow_mut()
6094            .insert(qname, Dom::from_ref(&*result));
6095        result
6096    }
6097
6098    /// <https://dom.spec.whatwg.org/#dom-document-getelementsbyclassname>
6099    fn GetElementsByClassName(
6100        &self,
6101        cx: &mut JSContext,
6102        classes: DOMString,
6103    ) -> DomRoot<HTMLCollection> {
6104        let class_atoms: Vec<Atom> = split_html_space_chars(&classes.str())
6105            .map(Atom::from)
6106            .collect();
6107        if let Some(collection) = self.classes_map.borrow().get(&class_atoms) {
6108            return DomRoot::from_ref(collection);
6109        }
6110        let result = HTMLCollection::by_atomic_class_name(
6111            cx,
6112            &self.window,
6113            self.upcast(),
6114            class_atoms.clone(),
6115        );
6116        self.classes_map
6117            .borrow_mut()
6118            .insert(class_atoms, Dom::from_ref(&*result));
6119        result
6120    }
6121
6122    /// <https://dom.spec.whatwg.org/#dom-nonelementparentnode-getelementbyid>
6123    fn GetElementById(
6124        &self,
6125        cx: &js::context::JSContext,
6126        id: DOMString,
6127    ) -> Option<DomRoot<Element>> {
6128        self.get_element_by_id(cx, &Atom::from(id))
6129    }
6130
6131    /// <https://dom.spec.whatwg.org/#dom-document-createelement>
6132    fn CreateElement(
6133        &self,
6134        cx: &mut JSContext,
6135        mut local_name: DOMString,
6136        options: StringOrElementCreationOptions,
6137    ) -> Fallible<DomRoot<Element>> {
6138        // Step 1. If localName is not a valid element local name, then throw an "InvalidCharacterError" DOMException.
6139        if !is_valid_element_local_name(&local_name.str()) {
6140            return Err(Error::InvalidCharacter(Some(
6141                "Provided element local name is invalid".into(),
6142            )));
6143        }
6144
6145        // Step 2. If this is an HTML document, then set localName to localName in ASCII lowercase.
6146        if self.is_html_document {
6147            local_name.make_ascii_lowercase();
6148        }
6149
6150        // Step 4. Let namespace be the HTML namespace, if this is an HTML document or this’s content type is "application/xhtml+xml"; otherwise null.
6151        let ns = if self.is_html_document || self.is_xhtml_document() {
6152            ns!(html)
6153        } else {
6154            ns!()
6155        };
6156        let name = QualName::new(None, ns, LocalName::from(local_name));
6157
6158        let is = match options {
6159            StringOrElementCreationOptions::String(_) => None,
6160            StringOrElementCreationOptions::ElementCreationOptions(options) => {
6161                options.is.as_ref().map(LocalName::from)
6162            },
6163        };
6164        Ok(Element::create(
6165            cx,
6166            name,
6167            is,
6168            self,
6169            ElementCreator::ScriptCreated,
6170            CustomElementCreationMode::Synchronous,
6171            None,
6172        ))
6173    }
6174
6175    /// <https://dom.spec.whatwg.org/#dom-document-createelementns>
6176    fn CreateElementNS(
6177        &self,
6178        cx: &mut JSContext,
6179        namespace: Option<DOMString>,
6180        qualified_name: DOMString,
6181        options: StringOrElementCreationOptions,
6182    ) -> Fallible<DomRoot<Element>> {
6183        // Step 1. Let (namespace, prefix, localName) be the result of
6184        //      validating and extracting namespace and qualifiedName given "element".
6185        let context = domname::Context::Element;
6186        let (namespace, prefix, local_name) =
6187            domname::validate_and_extract(namespace, &qualified_name, context)?;
6188
6189        // Step 2. Let is be null.
6190        // Step 3. If options is a dictionary and options["is"] exists, then set is to it.
6191        let name = QualName::new(prefix, namespace, local_name);
6192        let is = match options {
6193            StringOrElementCreationOptions::String(_) => None,
6194            StringOrElementCreationOptions::ElementCreationOptions(options) => {
6195                options.is.as_ref().map(LocalName::from)
6196            },
6197        };
6198
6199        // Step 4. Return the result of creating an element given document, localName, namespace, prefix, is, and true.
6200        Ok(Element::create(
6201            cx,
6202            name,
6203            is,
6204            self,
6205            ElementCreator::ScriptCreated,
6206            CustomElementCreationMode::Synchronous,
6207            None,
6208        ))
6209    }
6210
6211    /// <https://dom.spec.whatwg.org/#dom-document-createattribute>
6212    fn CreateAttribute(
6213        &self,
6214        cx: &mut JSContext,
6215        mut local_name: DOMString,
6216    ) -> Fallible<DomRoot<Attr>> {
6217        // Step 1. If localName is not a valid attribute local name, then throw an "InvalidCharacterError" DOMException
6218        if !is_valid_attribute_local_name(&local_name.str()) {
6219            return Err(Error::InvalidCharacter(Some(
6220                "Provided local name is invalid".into(),
6221            )));
6222        }
6223
6224        // Step 2. If this is an HTML document, then set localName to localName in ASCII lowercase.
6225        if self.is_html_document {
6226            local_name.make_ascii_lowercase();
6227        }
6228        let name = LocalName::from(local_name);
6229        let value = AttrValue::String(String::new());
6230
6231        Ok(Attr::new(
6232            cx,
6233            self,
6234            name.clone(),
6235            value,
6236            name,
6237            ns!(),
6238            None,
6239            None,
6240        ))
6241    }
6242
6243    /// <https://dom.spec.whatwg.org/#dom-document-createattributens>
6244    fn CreateAttributeNS(
6245        &self,
6246        cx: &mut JSContext,
6247        namespace: Option<DOMString>,
6248        qualified_name: DOMString,
6249    ) -> Fallible<DomRoot<Attr>> {
6250        // Step 1. Let (namespace, prefix, localName) be the result of validating and
6251        //      extracting namespace and qualifiedName given "attribute".
6252        let context = domname::Context::Attribute;
6253        let (namespace, prefix, local_name) =
6254            domname::validate_and_extract(namespace, &qualified_name, context)?;
6255        let value = AttrValue::String(String::new());
6256        let qualified_name = LocalName::from(qualified_name);
6257        Ok(Attr::new(
6258            cx,
6259            self,
6260            local_name,
6261            value,
6262            qualified_name,
6263            namespace,
6264            prefix,
6265            None,
6266        ))
6267    }
6268
6269    /// <https://dom.spec.whatwg.org/#dom-document-createdocumentfragment>
6270    fn CreateDocumentFragment(&self, cx: &mut JSContext) -> DomRoot<DocumentFragment> {
6271        DocumentFragment::new(cx, self)
6272    }
6273
6274    /// <https://dom.spec.whatwg.org/#dom-document-createtextnode>
6275    fn CreateTextNode(&self, cx: &mut JSContext, data: DOMString) -> DomRoot<Text> {
6276        Text::new(cx, data, self)
6277    }
6278
6279    /// <https://dom.spec.whatwg.org/#dom-document-createcdatasection>
6280    fn CreateCDATASection(
6281        &self,
6282        cx: &mut JSContext,
6283        data: DOMString,
6284    ) -> Fallible<DomRoot<CDATASection>> {
6285        // Step 1
6286        if self.is_html_document {
6287            return Err(Error::NotSupported(Some(
6288                "Document must be an XML document".into(),
6289            )));
6290        }
6291
6292        // Step 2
6293        if data.contains("]]>") {
6294            return Err(Error::InvalidCharacter(Some(
6295                "CDATA section cannot include `]]>`".into(),
6296            )));
6297        }
6298
6299        // Step 3
6300        Ok(CDATASection::new(cx, data, self))
6301    }
6302
6303    /// <https://dom.spec.whatwg.org/#dom-document-createcomment>
6304    fn CreateComment(&self, cx: &mut JSContext, data: DOMString) -> DomRoot<Comment> {
6305        Comment::new(cx, data, self, None)
6306    }
6307
6308    /// <https://dom.spec.whatwg.org/#dom-document-createprocessinginstruction>
6309    fn CreateProcessingInstruction(
6310        &self,
6311        cx: &mut JSContext,
6312        target: DOMString,
6313        data: DOMString,
6314    ) -> Fallible<DomRoot<ProcessingInstruction>> {
6315        // Step 1. If target does not match the Name production, then throw an "InvalidCharacterError" DOMException.
6316        if !matches_name_production(&target.str()) {
6317            return Err(Error::InvalidCharacter(Some(
6318                "Target name provided is invalid".into(),
6319            )));
6320        }
6321
6322        // Step 2. If data contains the string "?>", then throw an "InvalidCharacterError" DOMException.
6323        if data.contains("?>") {
6324            return Err(Error::InvalidCharacter(Some(
6325                "Processing instruction's data cannot contain `>?`".into(),
6326            )));
6327        }
6328
6329        // Step 3.
6330        Ok(ProcessingInstruction::new(cx, target, data, self))
6331    }
6332
6333    /// <https://dom.spec.whatwg.org/#dom-document-importnode>
6334    fn ImportNode(
6335        &self,
6336        cx: &mut JSContext,
6337        node: &Node,
6338        options: BooleanOrImportNodeOptions,
6339    ) -> Fallible<DomRoot<Node>> {
6340        // Step 1. If node is a document or shadow root, then throw a "NotSupportedError" DOMException.
6341        if node.is::<Document>() || node.is::<ShadowRoot>() {
6342            return Err(Error::NotSupported(Some(
6343                "Node cannot be a document or shadow root".into(),
6344            )));
6345        }
6346        // Step 2. Let subtree be false.
6347        let (subtree, registry) = match options {
6348            // Step 3. Let registry be null.
6349            // Step 4. If options is a boolean, then set subtree to options.
6350            BooleanOrImportNodeOptions::Boolean(boolean) => (boolean.into(), None),
6351            // Step 5. Otherwise:
6352            BooleanOrImportNodeOptions::ImportNodeOptions(options) => {
6353                // Step 5.1. Set subtree to the negation of options["selfOnly"].
6354                let subtree = (!options.selfOnly).into();
6355                // Step 5.2. If options["customElementRegistry"] exists, then set registry to it.
6356                let registry = options.customElementRegistry.as_ref().map(Dom::as_rooted);
6357
6358                // Step 5.3. If registry's is scoped is false and registry is not
6359                // this's custom element registry, then throw a "NotSupportedError" DOMException.
6360                if registry.as_ref().is_some_and(|registry| {
6361                    let this_registry = self
6362                        .custom_element_registry()
6363                        .expect("Document must have a custom element registry");
6364
6365                    !registry.is_scoped() && *registry != this_registry
6366                }) {
6367                    return Err(Error::NotSupported(Some(
6368                            "Imported customElementRegistry is not scoped and does not match existing registry.".into()
6369                        )));
6370                }
6371                (subtree, registry)
6372            },
6373        };
6374        // Step 6. If registry is null, then set registry to the
6375        // result of looking up a custom element registry given this.
6376        let registry = registry
6377            .or_else(|| CustomElementRegistry::lookup_a_custom_element_registry(self.upcast()));
6378
6379        // Step 7. Return the result of cloning a node given node with
6380        // document set to this, subtree set to subtree, and fallbackRegistry set to registry.
6381        Ok(Node::clone(cx, node, Some(self), subtree, registry))
6382    }
6383
6384    /// <https://dom.spec.whatwg.org/#dom-document-adoptnode>
6385    fn AdoptNode(&self, cx: &mut JSContext, node: &Node) -> Fallible<DomRoot<Node>> {
6386        // Step 1.
6387        if node.is::<Document>() {
6388            return Err(Error::NotSupported(Some(
6389                "Node cannot be a document".into(),
6390            )));
6391        }
6392
6393        // Step 2.
6394        if node.is::<ShadowRoot>() {
6395            return Err(Error::HierarchyRequest(Some(
6396                "Node cannot be a shadow root".into(),
6397            )));
6398        }
6399
6400        // Step 3.
6401        Node::adopt(cx, node, self);
6402
6403        // Step 4.
6404        Ok(DomRoot::from_ref(node))
6405    }
6406
6407    /// <https://dom.spec.whatwg.org/#dom-document-createevent>
6408    fn CreateEvent(
6409        &self,
6410        cx: &mut JSContext,
6411        mut interface: DOMString,
6412    ) -> Fallible<DomRoot<Event>> {
6413        interface.make_ascii_lowercase();
6414        match &*interface.str() {
6415            "beforeunloadevent" => Ok(DomRoot::upcast(BeforeUnloadEvent::new_uninitialized(
6416                cx,
6417                &self.window,
6418            ))),
6419            "compositionevent" => Ok(DomRoot::upcast(CompositionEvent::new_uninitialized(
6420                cx,
6421                &self.window,
6422            ))),
6423            "customevent" => Ok(DomRoot::upcast(CustomEvent::new_uninitialized(
6424                cx,
6425                self.window.upcast(),
6426            ))),
6427            // FIXME(#25136): devicemotionevent, deviceorientationevent
6428            // FIXME(#7529): dragevent
6429            "events" | "event" | "htmlevents" | "svgevents" => {
6430                Ok(Event::new_uninitialized(cx, self.window.upcast()))
6431            },
6432            "focusevent" => Ok(DomRoot::upcast(FocusEvent::new_uninitialized(
6433                cx,
6434                &self.window,
6435            ))),
6436            "hashchangeevent" => Ok(DomRoot::upcast(HashChangeEvent::new_uninitialized(
6437                cx,
6438                &self.window,
6439            ))),
6440            "keyboardevent" => Ok(DomRoot::upcast(KeyboardEvent::new_uninitialized(
6441                cx,
6442                &self.window,
6443            ))),
6444            "messageevent" => Ok(DomRoot::upcast(MessageEvent::new_uninitialized(
6445                cx,
6446                self.window.upcast(),
6447            ))),
6448            "mouseevent" | "mouseevents" => Ok(DomRoot::upcast(MouseEvent::new_uninitialized(
6449                cx,
6450                &self.window,
6451            ))),
6452            "storageevent" => Ok(DomRoot::upcast(StorageEvent::new_uninitialized(
6453                cx,
6454                &self.window,
6455                DOMString::new(),
6456            ))),
6457            "textevent" => Ok(DomRoot::upcast(TextEvent::new_uninitialized(
6458                cx,
6459                &self.window,
6460            ))),
6461            "touchevent" => {
6462                let touches = TouchList::new(cx, &self.window, &[]);
6463                let changed_touches = TouchList::new(cx, &self.window, &[]);
6464                let target_touches = TouchList::new(cx, &self.window, &[]);
6465
6466                Ok(DomRoot::upcast(DomTouchEvent::new_uninitialized(
6467                    cx,
6468                    &self.window,
6469                    &touches,
6470                    &changed_touches,
6471                    &target_touches,
6472                )))
6473            },
6474            "uievent" | "uievents" => Ok(DomRoot::upcast(UIEvent::new_uninitialized(
6475                cx,
6476                &self.window,
6477            ))),
6478            _ => Err(Error::NotSupported(Some(
6479                "Interface is not supported".into(),
6480            ))),
6481        }
6482    }
6483
6484    /// <https://html.spec.whatwg.org/multipage/#dom-document-lastmodified>
6485    fn LastModified(&self) -> DOMString {
6486        DOMString::from(self.last_modified.as_ref().cloned().unwrap_or_else(|| {
6487            // Ideally this would get the local time using `time`, but `time` always fails to get the local
6488            // timezone on Unix unless the application is single threaded unless the library is explicitly
6489            // set to "unsound" mode. Maybe that's fine, but it needs more investigation. see
6490            // https://nvd.nist.gov/vuln/detail/CVE-2020-26235
6491            // When `time` supports a thread-safe way of getting the local time zone we could use it here.
6492            Local::now().format("%m/%d/%Y %H:%M:%S").to_string()
6493        }))
6494    }
6495
6496    /// <https://dom.spec.whatwg.org/#dom-document-createrange>
6497    fn CreateRange(&self, cx: &mut JSContext) -> DomRoot<Range> {
6498        Range::new_with_doc(cx, self, None)
6499    }
6500
6501    /// <https://dom.spec.whatwg.org/#dom-document-createnodeiteratorroot-whattoshow-filter>
6502    fn CreateNodeIterator(
6503        &self,
6504        cx: &mut js::context::JSContext,
6505        root: &Node,
6506        what_to_show: u32,
6507        filter: Option<RootedCallback<NodeFilter>>,
6508    ) -> DomRoot<NodeIterator> {
6509        NodeIterator::new(cx, self, root, what_to_show, filter)
6510    }
6511
6512    /// <https://dom.spec.whatwg.org/#dom-document-createtreewalker>
6513    fn CreateTreeWalker(
6514        &self,
6515        cx: &mut JSContext,
6516        root: &Node,
6517        what_to_show: u32,
6518        filter: Option<RootedCallback<NodeFilter>>,
6519    ) -> DomRoot<TreeWalker> {
6520        TreeWalker::new(cx, self, root, what_to_show, filter)
6521    }
6522
6523    /// <https://html.spec.whatwg.org/multipage/#document.title>
6524    fn Title(&self) -> DOMString {
6525        self.title().unwrap_or_default()
6526    }
6527
6528    /// <https://html.spec.whatwg.org/multipage/#document.title>
6529    fn SetTitle(&self, cx: &mut JSContext, title: DOMString) {
6530        let root = match self.GetDocumentElement() {
6531            Some(root) => root,
6532            None => return,
6533        };
6534
6535        // > On setting, the steps corresponding to the first matching condition in the following list must be run:
6536        // ↪ If the document element is an SVG svg element
6537        let node = if root.namespace() == &ns!(svg) && root.local_name() == &local_name!("svg") {
6538            // Step 1. If there is an SVG title element that is a child of the document element,
6539            // let element be the first such element.
6540            let elem = root
6541                .upcast::<Node>()
6542                .child_elements_unrooted(cx.no_gc())
6543                .find(|node| {
6544                    node.namespace() == &ns!(svg) && node.local_name() == &local_name!("title")
6545                });
6546            match elem {
6547                Some(elem) => UnrootedDom::upcast::<Node>(elem).as_rooted(),
6548                // Step 2. Otherwise:
6549                None => {
6550                    // Step 2.1 Let element be the result of creating an element given the document element's
6551                    // node document, "title", and the SVG namespace.
6552                    let name = QualName::new(None, ns!(svg), local_name!("title"));
6553                    let elem = Element::create(
6554                        cx,
6555                        name,
6556                        None,
6557                        self,
6558                        ElementCreator::ScriptCreated,
6559                        CustomElementCreationMode::Synchronous,
6560                        None,
6561                    );
6562
6563                    // Step 2.2 Insert element as the first child of the document element.
6564                    let parent = root.upcast::<Node>();
6565                    let child = elem.upcast::<Node>();
6566                    parent
6567                        .InsertBefore(cx, child, parent.GetFirstChild().as_deref())
6568                        .unwrap()
6569                },
6570            }
6571        }
6572        // ↪ If the document element is in the HTML namespace
6573        else if root.namespace() == &ns!(html) {
6574            let elem = root
6575                .upcast::<Node>()
6576                .traverse_preorder_unrooted(cx.no_gc(), ShadowIncluding::No)
6577                .find(|node| node.is::<HTMLTitleElement>());
6578            match elem {
6579                // Step 2. If the title element is non-null, let element be the title element.
6580                Some(elem) => elem.as_rooted(),
6581                // Step 3. Otherwise:
6582                None => match self.GetHead() {
6583                    Some(head) => {
6584                        // Step 3.1 Let element be the result of creating an element given the
6585                        // document element's node document, "title", and the HTML namespace.
6586                        let name = QualName::new(None, ns!(html), local_name!("title"));
6587                        let elem = Element::create(
6588                            cx,
6589                            name,
6590                            None,
6591                            self,
6592                            ElementCreator::ScriptCreated,
6593                            CustomElementCreationMode::Synchronous,
6594                            None,
6595                        );
6596
6597                        // Step 3.2 Append element to the head element.
6598                        head.upcast::<Node>()
6599                            .AppendChild(cx, elem.upcast())
6600                            .unwrap()
6601                    },
6602                    // Step 1. If the title element is null and the head element is null, then return.
6603                    None => return,
6604                },
6605            }
6606        }
6607        // ↪ Otherwise
6608        else {
6609            // Do nothing.
6610            return;
6611        };
6612
6613        // Step 3. of "↪ If the document element is an SVG svg element"
6614        // Step 4. of "↪ If the document element is in the HTML namespace"
6615        //
6616        // > String replace all with the given value within element.
6617        node.set_text_content_for_element(cx, Some(title));
6618    }
6619
6620    /// <https://html.spec.whatwg.org/multipage/#dom-document-dir>
6621    fn Dir(&self) -> DOMString {
6622        self.get_html_element()
6623            .map(|html| html.upcast::<HTMLElement>().Dir())
6624            .unwrap_or_default()
6625    }
6626
6627    /// <https://html.spec.whatwg.org/multipage/#dom-document-dir>
6628    fn SetDir(&self, cx: &mut JSContext, dir: DOMString) {
6629        if let Some(html) = self.get_html_element() {
6630            html.upcast::<HTMLElement>().SetDir(cx, dir);
6631        }
6632    }
6633
6634    /// <https://html.spec.whatwg.org/multipage/#dom-document-head>
6635    fn GetHead(&self) -> Option<DomRoot<HTMLHeadElement>> {
6636        self.get_html_element()
6637            .and_then(|root| root.upcast::<Node>().children().find_map(DomRoot::downcast))
6638    }
6639
6640    /// <https://html.spec.whatwg.org/multipage/#dom-document-currentscript>
6641    fn GetCurrentScript(&self) -> Option<DomRoot<HTMLScriptElement>> {
6642        self.current_script.get()
6643    }
6644
6645    /// <https://html.spec.whatwg.org/multipage/#dom-document-body>
6646    fn GetBody(&self) -> Option<DomRoot<HTMLElement>> {
6647        // > The body element of a document is the first of the html element's children
6648        // > that is either a body element or a frameset element, or null if there is no such element.
6649        self.get_html_element().and_then(|root| {
6650            let node = root.upcast::<Node>();
6651            node.children()
6652                .find(|child| {
6653                    matches!(
6654                        child.type_id(),
6655                        NodeTypeId::Element(ElementTypeId::HTMLElement(
6656                            HTMLElementTypeId::HTMLBodyElement,
6657                        )) | NodeTypeId::Element(ElementTypeId::HTMLElement(
6658                            HTMLElementTypeId::HTMLFrameSetElement,
6659                        ))
6660                    )
6661                })
6662                .map(|node| DomRoot::downcast(node).unwrap())
6663        })
6664    }
6665
6666    /// <https://html.spec.whatwg.org/multipage/#dom-document-body>
6667    fn SetBody(&self, cx: &mut JSContext, new_body: Option<&HTMLElement>) -> ErrorResult {
6668        // Step 1. If the new value is not a body or frameset element, then throw a "HierarchyRequestError" DOMException.
6669        let new_body = match new_body {
6670            Some(new_body) => new_body,
6671            None => {
6672                return Err(Error::HierarchyRequest(Some(
6673                    "HTML element provided is neither a body nor a frameset element".into(),
6674                )));
6675            },
6676        };
6677
6678        let node = new_body.upcast::<Node>();
6679        match node.type_id() {
6680            NodeTypeId::Element(ElementTypeId::HTMLElement(HTMLElementTypeId::HTMLBodyElement)) |
6681            NodeTypeId::Element(ElementTypeId::HTMLElement(
6682                HTMLElementTypeId::HTMLFrameSetElement,
6683            )) => {},
6684            _ => {
6685                return Err(Error::HierarchyRequest(Some(
6686                    "HTML element provided is neither a body nor a frameset element".into(),
6687                )));
6688            },
6689        }
6690
6691        // Step 2. Otherwise, if the new value is the same as the body element, return.
6692        let old_body = self.GetBody();
6693        if old_body.as_deref() == Some(new_body) {
6694            return Ok(());
6695        }
6696
6697        match (self.GetDocumentElement(), &old_body) {
6698            // Step 3. Otherwise, if the body element is not null,
6699            // then replace the body element with the new value within the body element's parent and return.
6700            (Some(ref root), Some(child)) => {
6701                let root = root.upcast::<Node>();
6702                root.ReplaceChild(cx, new_body.upcast(), child.upcast())
6703                    .map(|_| ())
6704            },
6705
6706            // Step 4. Otherwise, if there is no document element, throw a "HierarchyRequestError" DOMException.
6707            (None, _) => Err(Error::HierarchyRequest(Some(
6708                "Document element is missing".into(),
6709            ))),
6710
6711            // Step 5. Otherwise, the body element is null, but there's a document element.
6712            // Append the new value to the document element.
6713            (Some(ref root), &None) => {
6714                let root = root.upcast::<Node>();
6715                root.AppendChild(cx, new_body.upcast()).map(|_| ())
6716            },
6717        }
6718    }
6719
6720    /// <https://html.spec.whatwg.org/multipage/#dom-document-getelementsbyname>
6721    fn GetElementsByName(&self, cx: &mut JSContext, name: DOMString) -> DomRoot<NodeList> {
6722        NodeList::new_elements_by_name_list(cx, self.window(), self, name)
6723    }
6724
6725    /// <https://html.spec.whatwg.org/multipage/#dom-document-images>
6726    fn Images(&self, cx: &mut JSContext) -> DomRoot<HTMLCollection> {
6727        self.images.or_init(|| {
6728            HTMLCollection::new_with_filter_fn(cx, &self.window, self.upcast(), |element, _| {
6729                element.is::<HTMLImageElement>()
6730            })
6731        })
6732    }
6733
6734    /// <https://html.spec.whatwg.org/multipage/#dom-document-embeds>
6735    fn Embeds(&self, cx: &mut JSContext) -> DomRoot<HTMLCollection> {
6736        self.embeds.or_init(|| {
6737            HTMLCollection::new_with_filter_fn(cx, &self.window, self.upcast(), |element, _| {
6738                element.is::<HTMLEmbedElement>()
6739            })
6740        })
6741    }
6742
6743    /// <https://html.spec.whatwg.org/multipage/#dom-document-plugins>
6744    fn Plugins(&self, cx: &mut JSContext) -> DomRoot<HTMLCollection> {
6745        self.Embeds(cx)
6746    }
6747
6748    /// <https://html.spec.whatwg.org/multipage/#dom-document-links>
6749    fn Links(&self, cx: &mut JSContext) -> DomRoot<HTMLCollection> {
6750        self.links.or_init(|| {
6751            HTMLCollection::new_with_filter_fn(cx, &self.window, self.upcast(), |element, _| {
6752                (element.is::<HTMLAnchorElement>() || element.is::<HTMLAreaElement>()) &&
6753                    element.has_attribute(&local_name!("href"))
6754            })
6755        })
6756    }
6757
6758    /// <https://html.spec.whatwg.org/multipage/#dom-document-forms>
6759    fn Forms(&self, cx: &mut JSContext) -> DomRoot<HTMLCollection> {
6760        self.forms.or_init(|| {
6761            HTMLCollection::new_with_filter_fn(cx, &self.window, self.upcast(), |element, _| {
6762                element.is::<HTMLFormElement>()
6763            })
6764        })
6765    }
6766
6767    /// <https://html.spec.whatwg.org/multipage/#dom-document-scripts>
6768    fn Scripts(&self, cx: &mut JSContext) -> DomRoot<HTMLCollection> {
6769        self.scripts.or_init(|| {
6770            HTMLCollection::new_with_filter_fn(cx, &self.window, self.upcast(), |element, _| {
6771                element.is::<HTMLScriptElement>()
6772            })
6773        })
6774    }
6775
6776    /// <https://html.spec.whatwg.org/multipage/#dom-document-anchors>
6777    fn Anchors(&self, cx: &mut JSContext) -> DomRoot<HTMLCollection> {
6778        self.anchors.or_init(|| {
6779            HTMLCollection::new_with_filter_fn(cx, &self.window, self.upcast(), |element, _| {
6780                element.is::<HTMLAnchorElement>() && element.has_attribute(&local_name!("href"))
6781            })
6782        })
6783    }
6784
6785    /// <https://html.spec.whatwg.org/multipage/#dom-document-applets>
6786    fn Applets(&self, cx: &mut JSContext) -> DomRoot<HTMLCollection> {
6787        self.applets
6788            .or_init(|| HTMLCollection::always_empty(cx, &self.window, self.upcast()))
6789    }
6790
6791    /// <https://html.spec.whatwg.org/multipage/#dom-document-location>
6792    fn GetLocation(&self, cx: &mut JSContext) -> Option<DomRoot<Location>> {
6793        if self.is_fully_active() {
6794            Some(self.window.Location(cx))
6795        } else {
6796            None
6797        }
6798    }
6799
6800    /// <https://dom.spec.whatwg.org/#dom-parentnode-children>
6801    fn Children(&self, cx: &mut JSContext) -> DomRoot<HTMLCollection> {
6802        HTMLCollection::children(cx, &self.window, self.upcast())
6803    }
6804
6805    /// <https://dom.spec.whatwg.org/#dom-parentnode-firstelementchild>
6806    fn GetFirstElementChild(&self) -> Option<DomRoot<Element>> {
6807        self.upcast::<Node>().child_elements().next()
6808    }
6809
6810    /// <https://dom.spec.whatwg.org/#dom-parentnode-lastelementchild>
6811    fn GetLastElementChild(&self) -> Option<DomRoot<Element>> {
6812        self.upcast::<Node>()
6813            .rev_children()
6814            .find_map(DomRoot::downcast)
6815    }
6816
6817    /// <https://dom.spec.whatwg.org/#dom-parentnode-childelementcount>
6818    fn ChildElementCount(&self) -> u32 {
6819        self.upcast::<Node>().child_elements().count() as u32
6820    }
6821
6822    /// <https://dom.spec.whatwg.org/#dom-parentnode-prepend>
6823    fn Prepend(&self, cx: &mut JSContext, nodes: Vec<NodeOrString>) -> ErrorResult {
6824        self.upcast::<Node>().prepend(cx, nodes)
6825    }
6826
6827    /// <https://dom.spec.whatwg.org/#dom-parentnode-append>
6828    fn Append(&self, cx: &mut JSContext, nodes: Vec<NodeOrString>) -> ErrorResult {
6829        self.upcast::<Node>().append(cx, nodes)
6830    }
6831
6832    /// <https://dom.spec.whatwg.org/#dom-parentnode-replacechildren>
6833    fn ReplaceChildren(&self, cx: &mut JSContext, nodes: Vec<NodeOrString>) -> ErrorResult {
6834        self.upcast::<Node>().replace_children(cx, nodes)
6835    }
6836
6837    /// <https://dom.spec.whatwg.org/#dom-parentnode-movebefore>
6838    fn MoveBefore(&self, cx: &mut JSContext, node: &Node, child: Option<&Node>) -> ErrorResult {
6839        self.upcast::<Node>().move_before(cx, node, child)
6840    }
6841
6842    /// <https://dom.spec.whatwg.org/#dom-parentnode-queryselector>
6843    fn QuerySelector(
6844        &self,
6845        cx: &mut JSContext,
6846        selectors: DOMString,
6847    ) -> Fallible<Option<DomRoot<Element>>> {
6848        self.upcast::<Node>().query_selector(cx.no_gc(), selectors)
6849    }
6850
6851    /// <https://dom.spec.whatwg.org/#dom-parentnode-queryselectorall>
6852    fn QuerySelectorAll(
6853        &self,
6854        cx: &mut JSContext,
6855        selectors: DOMString,
6856    ) -> Fallible<DomRoot<NodeList>> {
6857        self.upcast::<Node>().query_selector_all(cx, selectors)
6858    }
6859
6860    /// <https://html.spec.whatwg.org/multipage/#dom-document-readystate>
6861    fn ReadyState(&self) -> DocumentReadyState {
6862        self.ready_state.get()
6863    }
6864
6865    /// <https://html.spec.whatwg.org/multipage/#dom-document-defaultview>
6866    fn GetDefaultView(&self) -> Option<DomRoot<Window>> {
6867        if self.has_browsing_context {
6868            Some(DomRoot::from_ref(&*self.window))
6869        } else {
6870            None
6871        }
6872    }
6873
6874    /// <https://html.spec.whatwg.org/multipage/#dom-document-cookie>
6875    fn GetCookie(&self) -> Fallible<DOMString> {
6876        if self.is_cookie_averse() {
6877            return Ok(DOMString::new());
6878        }
6879
6880        if !self.origin().is_tuple() {
6881            return Err(Error::Security(Some("Document's origin is opaque".into())));
6882        }
6883
6884        let url = self.url();
6885        let (tx, rx) =
6886            profile_generic_channel::channel(self.global().time_profiler_chan().clone()).unwrap();
6887        let _ = self
6888            .window
6889            .as_global_scope()
6890            .resource_threads()
6891            .send(GetCookieStringForUrl(url, tx, NonHTTP));
6892        let cookies = rx.recv().unwrap();
6893        Ok(cookies.map_or(DOMString::new(), DOMString::from))
6894    }
6895
6896    /// <https://html.spec.whatwg.org/multipage/#dom-document-cookie>
6897    fn SetCookie(&self, cookie: DOMString) -> ErrorResult {
6898        if self.is_cookie_averse() {
6899            return Ok(());
6900        }
6901
6902        if !self.origin().is_tuple() {
6903            return Err(Error::Security(Some("Document's origin is opaque".into())));
6904        }
6905
6906        if !cookie.is_valid_for_cookie() {
6907            return Ok(());
6908        }
6909
6910        let cookies = if let Some(cookie) = Cookie::parse(cookie.to_string()).ok().map(Serde) {
6911            vec![cookie]
6912        } else {
6913            vec![]
6914        };
6915
6916        let _ = self
6917            .window
6918            .as_global_scope()
6919            .resource_threads()
6920            .send(SetCookiesForUrl(self.url(), cookies, NonHTTP));
6921        Ok(())
6922    }
6923
6924    /// <https://html.spec.whatwg.org/multipage/#dom-document-bgcolor>
6925    fn BgColor(&self) -> DOMString {
6926        self.get_body_attribute(&local_name!("bgcolor"))
6927    }
6928
6929    /// <https://html.spec.whatwg.org/multipage/#dom-document-bgcolor>
6930    fn SetBgColor(&self, cx: &mut JSContext, value: DOMString) {
6931        self.set_body_attribute(cx, &local_name!("bgcolor"), value)
6932    }
6933
6934    /// <https://html.spec.whatwg.org/multipage/#dom-document-fgcolor>
6935    fn FgColor(&self) -> DOMString {
6936        self.get_body_attribute(&local_name!("text"))
6937    }
6938
6939    /// <https://html.spec.whatwg.org/multipage/#dom-document-fgcolor>
6940    fn SetFgColor(&self, cx: &mut JSContext, value: DOMString) {
6941        self.set_body_attribute(cx, &local_name!("text"), value)
6942    }
6943
6944    /// <https://html.spec.whatwg.org/multipage/#dom-tree-accessors:dom-document-nameditem-filter>
6945    fn NamedGetter(&self, cx: &mut JSContext, name: DOMString) -> Option<NamedPropertyValue> {
6946        if name.is_empty() {
6947            return None;
6948        }
6949        let name = Atom::from(name);
6950
6951        // Step 1. Let elements be the list of named elements with the name name that are in a document tree
6952        // with the Document as their root.
6953        let elements_with_name = self.get_elements_with_name(cx, &name);
6954        let name_iter = elements_with_name
6955            .iter()
6956            .filter(|elem| is_named_element_with_name_attribute(elem));
6957        let elements_with_id = self.id_map.get_all(cx.no_gc(), self.upcast(), &name);
6958        let id_iter = elements_with_id
6959            .iter()
6960            .filter(|elem| is_named_element_with_id_attribute(elem));
6961        let mut elements = name_iter.chain(id_iter);
6962
6963        // Step 2. If elements has only one element, and that element is an iframe element,
6964        // and that iframe element's content navigable is not null, then return the active
6965        // WindowProxy of the element's content navigable.
6966
6967        // NOTE: We have to check if all remaining elements are equal to the first, since
6968        // the same element may appear in both lists.
6969        let first = elements.next()?;
6970        if elements.all(|other| first == other) {
6971            if let Some(nested_window_proxy) = first
6972                .downcast::<HTMLIFrameElement>()
6973                .and_then(|iframe| iframe.GetContentWindow())
6974            {
6975                return Some(NamedPropertyValue::WindowProxy(nested_window_proxy));
6976            }
6977
6978            // Step 3. Otherwise, if elements has only one element, return that element.
6979            return Some(NamedPropertyValue::Element(DomRoot::from_ref(first)));
6980        }
6981
6982        // Step 4. Otherwise, return an HTMLCollection rooted at the Document node,
6983        // whose filter matches only named elements with the name name.
6984        #[derive(JSTraceable, MallocSizeOf)]
6985        struct DocumentNamedGetter {
6986            #[no_trace]
6987            name: Atom,
6988        }
6989        impl CollectionFilter for DocumentNamedGetter {
6990            fn filter(&self, elem: &Element, _root: &Node) -> bool {
6991                let type_ = match elem.upcast::<Node>().type_id() {
6992                    NodeTypeId::Element(ElementTypeId::HTMLElement(type_)) => type_,
6993                    _ => return false,
6994                };
6995                match type_ {
6996                    HTMLElementTypeId::HTMLFormElement | HTMLElementTypeId::HTMLIFrameElement => {
6997                        elem.get_name().as_ref() == Some(&self.name)
6998                    },
6999                    HTMLElementTypeId::HTMLImageElement => elem.get_name().is_some_and(|name| {
7000                        name == *self.name ||
7001                            !name.is_empty() && elem.get_id().as_ref() == Some(&self.name)
7002                    }),
7003                    // TODO handle <embed> and <object>; these depend on whether the element is
7004                    // “exposed”, a concept that doesn’t fully make sense until embed/object
7005                    // behaviour is actually implemented
7006                    _ => false,
7007                }
7008            }
7009        }
7010        let collection = HTMLCollection::create(
7011            cx,
7012            self.window(),
7013            self.upcast(),
7014            Box::new(DocumentNamedGetter { name }),
7015        );
7016        Some(NamedPropertyValue::HTMLCollection(collection))
7017    }
7018
7019    /// <https://html.spec.whatwg.org/multipage/#dom-tree-accessors:supported-property-names>
7020    fn SupportedPropertyNames(&self, no_gc: &NoGC) -> Vec<DOMString> {
7021        let mut names_with_first_named_element_map = HashMap::new();
7022        self.name_map
7023            .for_each(no_gc, self.upcast(), |name, elements| {
7024                if name.is_empty() {
7025                    return;
7026                }
7027                let mut name_iter = elements
7028                    .iter()
7029                    .filter(|elem| is_named_element_with_name_attribute(elem));
7030                if let Some(first) = name_iter.next() {
7031                    names_with_first_named_element_map.insert(name.clone(), first.as_rooted());
7032                }
7033            });
7034
7035        self.id_map.for_each(no_gc, self.upcast(), |id, elements| {
7036            if id.is_empty() {
7037                return;
7038            }
7039            let mut id_iter = elements
7040                .iter()
7041                .filter(|elem| is_named_element_with_id_attribute(elem));
7042            if let Some(first) = id_iter.next() {
7043                match names_with_first_named_element_map.entry(id.clone()) {
7044                    Vacant(entry) => drop(entry.insert(first.as_rooted())),
7045                    Occupied(mut entry) => {
7046                        if first
7047                            .upcast::<Node>()
7048                            .is_before(no_gc, entry.get().upcast())
7049                        {
7050                            *entry.get_mut() = first.as_rooted();
7051                        }
7052                    },
7053                }
7054            }
7055        });
7056
7057        let mut names_with_first_named_element_vec: Vec<_> =
7058            names_with_first_named_element_map.into_iter().collect();
7059        names_with_first_named_element_vec.sort_unstable_by(|a, b| {
7060            if a.1 == b.1 {
7061                // This can happen if an img has an id different from its name,
7062                // spec does not say which string to put first.
7063                a.0.cmp(&b.0)
7064            } else if a.1.upcast::<Node>().is_before(no_gc, b.1.upcast::<Node>()) {
7065                Ordering::Less
7066            } else {
7067                Ordering::Greater
7068            }
7069        });
7070
7071        names_with_first_named_element_vec
7072            .into_iter()
7073            .map(|(k, _)| TracedDOMString::from(k).root())
7074            .collect()
7075    }
7076
7077    /// <https://html.spec.whatwg.org/multipage/#dom-document-clear>
7078    fn Clear(&self) {
7079        // This method intentionally does nothing
7080    }
7081
7082    /// <https://html.spec.whatwg.org/multipage/#dom-document-captureevents>
7083    fn CaptureEvents(&self) {
7084        // This method intentionally does nothing
7085    }
7086
7087    /// <https://html.spec.whatwg.org/multipage/#dom-document-releaseevents>
7088    fn ReleaseEvents(&self) {
7089        // This method intentionally does nothing
7090    }
7091
7092    // https://html.spec.whatwg.org/multipage/#globaleventhandlers
7093    global_event_handlers!();
7094
7095    // https://html.spec.whatwg.org/multipage/#handler-onreadystatechange
7096    event_handler!(
7097        readystatechange,
7098        GetOnreadystatechange,
7099        SetOnreadystatechange
7100    );
7101
7102    /// <https://drafts.csswg.org/cssom-view/#dom-document-elementfrompoint>
7103    fn ElementFromPoint(
7104        &self,
7105        cx: &mut JSContext,
7106        x: Finite<f64>,
7107        y: Finite<f64>,
7108    ) -> Option<DomRoot<Element>> {
7109        self.document_or_shadow_root.element_from_point(
7110            cx,
7111            self.upcast(),
7112            x,
7113            y,
7114            self.GetDocumentElement(),
7115            self.has_browsing_context,
7116        )
7117    }
7118
7119    /// <https://drafts.csswg.org/cssom-view/#dom-document-elementsfrompoint>
7120    fn ElementsFromPoint(
7121        &self,
7122        cx: &mut JSContext,
7123        x: Finite<f64>,
7124        y: Finite<f64>,
7125    ) -> Vec<DomRoot<Element>> {
7126        self.document_or_shadow_root.elements_from_point(
7127            cx,
7128            self.upcast(),
7129            x,
7130            y,
7131            self.GetDocumentElement(),
7132            self.has_browsing_context,
7133        )
7134    }
7135
7136    /// <https://drafts.csswg.org/cssom-view/#dom-document-scrollingelement>
7137    fn GetScrollingElement(&self, cx: &mut JSContext) -> Option<DomRoot<Element>> {
7138        // Step 1. If the Document is in quirks mode, follow these steps:
7139        if self.quirks_mode() == QuirksMode::Quirks {
7140            // Step 1.1. If the body element exists,
7141            if let Some(ref body) = self.GetBody() {
7142                let e = body.upcast::<Element>();
7143                // and it is not potentially scrollable, return the body element and abort these steps.
7144                // For this purpose, a value of overflow:clip on the body element’s parent element
7145                // must be treated as overflow:hidden.
7146                if !e.is_potentially_scrollable_body_for_scrolling_element(cx) {
7147                    return Some(DomRoot::from_ref(e));
7148                }
7149            }
7150
7151            // Step 1.2. Return null and abort these steps.
7152            return None;
7153        }
7154
7155        // Step 2. If there is a root element, return the root element and abort these steps.
7156        // Step 3. Return null.
7157        self.GetDocumentElement()
7158    }
7159
7160    /// <https://html.spec.whatwg.org/multipage/#dom-document-open>
7161    fn Open(
7162        &self,
7163        cx: &mut JSContext,
7164        _unused1: Option<DOMString>,
7165        _unused2: Option<DOMString>,
7166    ) -> Fallible<DomRoot<Document>> {
7167        // Step 1. If document is an XML document, then throw an "InvalidStateError" DOMException.
7168        if !self.is_html_document() {
7169            return Err(Error::InvalidState(Some(
7170                "Document must be a HTML document".into(),
7171            )));
7172        }
7173
7174        // Step 2. If document's throw-on-dynamic-markup-insertion counter is greater than 0,
7175        // then throw an "InvalidStateError" DOMException.
7176        if self.throw_on_dynamic_markup_insertion_counter.get() > 0 {
7177            return Err(Error::InvalidState(Some(
7178                "A custom element constructor attempted to open, close or write to this document"
7179                    .into(),
7180            )));
7181        }
7182
7183        // Step 3. Let entryDocument be the entry global object's associated Document.
7184        let entry_responsible_document = GlobalScope::entry().as_window().Document();
7185
7186        // Step 4. If document's origin is not same origin to entryDocument's origin,
7187        // then throw a "SecurityError" DOMException.
7188        if !self
7189            .origin()
7190            .same_origin(&entry_responsible_document.origin())
7191        {
7192            return Err(Error::Security(Some(
7193                "Document's origin is not the same as entry global's document origin".into(),
7194            )));
7195        }
7196
7197        // Step 5. If document has an active parser whose script nesting level is greater than 0,
7198        // then return document.
7199        if self
7200            .active_parser()
7201            .is_some_and(|parser| parser.script_nesting_level() > 0)
7202        {
7203            return Ok(DomRoot::from_ref(self));
7204        }
7205
7206        // Step 6. Similarly, if document's unload counter is greater than 0, then return document.
7207        if self.is_prompting_or_unloading() {
7208            return Ok(DomRoot::from_ref(self));
7209        }
7210
7211        // Step 7. If document's active parser was aborted is true, then return document.
7212        if self.active_parser_was_aborted.get() {
7213            return Ok(DomRoot::from_ref(self));
7214        }
7215
7216        // TODO: prompt to unload.
7217        // TODO: set unload_event_start and unload_event_end
7218
7219        self.window().set_navigation_start();
7220
7221        // Step 8. If document's node navigable is non-null and document's node navigable's
7222        // ongoing navigation is a navigation ID, then stop loading document's node navigable.
7223        // TODO: https://github.com/servo/servo/issues/21937
7224        if self.has_browsing_context() {
7225            // spec says "stop document loading",
7226            // which is a process that does more than just abort
7227            self.abort(cx, AbortReason::DocumentOpen);
7228        }
7229
7230        // Step 9. For each shadow-including inclusive descendant node of document,
7231        // erase all event listeners and handlers given node.
7232        for node in self
7233            .upcast::<Node>()
7234            .traverse_preorder_unrooted(cx.no_gc(), ShadowIncluding::Yes)
7235        {
7236            node.upcast::<EventTarget>().remove_all_listeners(cx);
7237        }
7238
7239        // Step 10. If document is the associated Document of document's relevant global object,
7240        // then erase all event listeners and handlers given document's relevant global object.
7241        if self.window.Document() == DomRoot::from_ref(self) {
7242            self.window.upcast::<EventTarget>().remove_all_listeners(cx);
7243        }
7244
7245        // Step 11. Replace all with null within document.
7246        Node::replace_all(cx, None, self.upcast::<Node>());
7247
7248        // Specs and tests are in a state of flux about whether
7249        // we want to clear the selection when we remove the contents;
7250        // WPT selection/Document-open.html wants us to not clear it
7251        // as of Feb 1 2020
7252
7253        // Step 12. If document is fully active, then:
7254        if self.is_fully_active() {
7255            // Step 12.1. Let newURL be a copy of entryDocument's URL.
7256            let mut new_url = entry_responsible_document.url();
7257
7258            // Step 12.2. If entryDocument is not document, then set newURL's fragment to null.
7259            if entry_responsible_document != DomRoot::from_ref(self) {
7260                new_url.set_fragment(None);
7261            }
7262
7263            // Step 12.3. Run the URL and history update steps with document and newURL.
7264            // TODO: https://github.com/servo/servo/issues/21939
7265            self.set_url(new_url);
7266        }
7267
7268        // Step 13. Set document's is initial about:blank to false.
7269        self.is_initial_about_blank.set(false);
7270
7271        // Step 14. If document's iframe load in progress flag is set, then set document's mute
7272        // iframe load flag.
7273        if self.iframe_load_in_progress.get() {
7274            self.mute_iframe_load.set(true);
7275        }
7276
7277        // Step 15: Set document to no-quirks mode.
7278        self.set_quirks_mode(QuirksMode::NoQuirks);
7279
7280        // Step 16. Create a new HTML parser and associate it with document. This is a
7281        // script-created parser (meaning that it can be closed by the document.open() and
7282        // document.close() methods, and that the tokenizer will wait for an explicit call to
7283        // document.close() before emitting an end-of-file token). The encoding confidence is
7284        // irrelevant.
7285        let resource_threads = self.window.as_global_scope().resource_threads().clone();
7286        *self.loader.borrow_mut() =
7287            DocumentLoader::new_with_threads(resource_threads, Some(self.url()));
7288        ServoParser::parse_html_script_input(cx, self, self.url());
7289
7290        // Step 17. Set the insertion point to point at just before the end of the input stream
7291        // (which at this point will be empty).
7292        // Handled when creating the parser in step 16
7293
7294        // Step 18. Update the current document readiness of document to "loading".
7295        self.update_the_current_document_readiness(cx, DocumentReadyState::Loading);
7296
7297        // Step 19. Return document.
7298        Ok(DomRoot::from_ref(self))
7299    }
7300
7301    /// <https://html.spec.whatwg.org/multipage/#dom-document-open-window>
7302    fn Open_(
7303        &self,
7304        cx: &mut JSContext,
7305        url: USVString,
7306        target: DOMString,
7307        features: DOMString,
7308    ) -> Fallible<Option<DomRoot<WindowProxy>>> {
7309        if self.is_fully_active() {
7310            self.browsing_context()
7311                .ok_or(Error::InvalidAccess(Some(
7312                    "Failed to get browsing context".into(),
7313                )))?
7314                .open(cx, url, target, features)
7315        } else {
7316            Err(Error::InvalidAccess(Some(
7317                "Document is not fully active".into(),
7318            )))
7319        }
7320    }
7321
7322    /// <https://html.spec.whatwg.org/multipage/#dom-document-write>
7323    fn Write(&self, cx: &mut JSContext, text: Vec<TrustedHTMLOrString>) -> ErrorResult {
7324        // The document.write(...text) method steps are to run the document write steps
7325        // with this, text, false, and "Document write".
7326        self.write(cx, text, false, "Document", "write")
7327    }
7328
7329    /// <https://html.spec.whatwg.org/multipage/#dom-document-writeln>
7330    fn Writeln(&self, cx: &mut JSContext, text: Vec<TrustedHTMLOrString>) -> ErrorResult {
7331        // The document.writeln(...text) method steps are to run the document write steps
7332        // with this, text, true, and "Document writeln".
7333        self.write(cx, text, true, "Document", "writeln")
7334    }
7335
7336    /// <https://html.spec.whatwg.org/multipage/#dom-document-close>
7337    fn Close(&self, cx: &mut JSContext) -> ErrorResult {
7338        if !self.is_html_document() {
7339            // Step 1. If this is an XML document, then throw an "InvalidStateError" DOMException.
7340            return Err(Error::InvalidState(Some(
7341                "Document must be a HTML document".into(),
7342            )));
7343        }
7344
7345        // Step 2. If this's throw-on-dynamic-markup-insertion counter is greater than zero,
7346        // then throw an "InvalidStateError" DOMException.
7347        if self.throw_on_dynamic_markup_insertion_counter.get() > 0 {
7348            return Err(Error::InvalidState(Some(
7349                "A custom element constructor attempted to open, close or write to this document"
7350                    .into(),
7351            )));
7352        }
7353
7354        // Step 3. If there is no script-created parser associated with this, then return.
7355        let parser = match self.get_current_parser() {
7356            Some(ref parser) if parser.is_script_created() => DomRoot::from_ref(&**parser),
7357            _ => {
7358                return Ok(());
7359            },
7360        };
7361
7362        // parser.close implements the remainder of this algorithm
7363        parser.close(cx);
7364
7365        Ok(())
7366    }
7367
7368    /// <https://w3c.github.io/editing/docs/execCommand/#execcommand()>
7369    fn ExecCommand(
7370        &self,
7371        cx: &mut JSContext,
7372        command_id: DOMString,
7373        _show_ui: bool,
7374        value: TrustedHTMLOrString,
7375    ) -> Fallible<bool> {
7376        let value = if command_id == "insertHTML" {
7377            TrustedHTML::get_trusted_type_compliant_string(
7378                cx,
7379                self.window.as_global_scope(),
7380                value,
7381                "Document execCommand",
7382            )?
7383        } else {
7384            match value {
7385                TrustedHTMLOrString::TrustedHTML(trusted_html) => {
7386                    trusted_html.data().clone().root()
7387                },
7388                TrustedHTMLOrString::String(value) => value,
7389            }
7390        };
7391
7392        Ok(self.exec_command_for_command_id(cx, command_id, value))
7393    }
7394
7395    /// <https://w3c.github.io/editing/docs/execCommand/#querycommandenabled()>
7396    fn QueryCommandEnabled(&self, cx: &mut JSContext, command_id: DOMString) -> bool {
7397        // Step 2. Return true if command is both supported and enabled, false otherwise.
7398        self.check_support_and_enabled(cx, &command_id).is_some()
7399    }
7400
7401    /// <https://w3c.github.io/editing/docs/execCommand/#querycommandsupported()>
7402    fn QueryCommandSupported(&self, command_id: DOMString) -> bool {
7403        // > When the queryCommandSupported(command) method on the Document interface is invoked,
7404        // the user agent must return true if command is supported and available
7405        // within the current script on the current site, and false otherwise.
7406        self.is_command_supported(command_id)
7407    }
7408
7409    /// <https://w3c.github.io/editing/docs/execCommand/#querycommandindeterm()>
7410    fn QueryCommandIndeterm(&self, cx: &mut JSContext, command_id: DOMString) -> bool {
7411        self.is_command_indeterminate(cx, command_id)
7412    }
7413
7414    /// <https://w3c.github.io/editing/docs/execCommand/#querycommandstate()>
7415    fn QueryCommandState(&self, cx: &mut JSContext, command_id: DOMString) -> bool {
7416        self.command_state_for_command(cx, command_id)
7417    }
7418
7419    /// <https://w3c.github.io/editing/docs/execCommand/#querycommandvalue()>
7420    fn QueryCommandValue(&self, cx: &mut JSContext, command_id: DOMString) -> DOMString {
7421        self.command_value_for_command(cx, command_id)
7422    }
7423
7424    // https://fullscreen.spec.whatwg.org/#handler-document-onfullscreenerror
7425    event_handler!(fullscreenerror, GetOnfullscreenerror, SetOnfullscreenerror);
7426
7427    // https://fullscreen.spec.whatwg.org/#handler-document-onfullscreenchange
7428    event_handler!(
7429        fullscreenchange,
7430        GetOnfullscreenchange,
7431        SetOnfullscreenchange
7432    );
7433
7434    /// <https://fullscreen.spec.whatwg.org/#dom-document-fullscreenenabled>
7435    fn FullscreenEnabled(&self) -> bool {
7436        self.overlay_handler().get_allow_fullscreen()
7437    }
7438
7439    /// <https://fullscreen.spec.whatwg.org/#dom-document-fullscreen>
7440    fn Fullscreen(&self) -> bool {
7441        self.overlay_handler().fullscreen_element().is_some()
7442    }
7443
7444    /// <https://fullscreen.spec.whatwg.org/#dom-document-fullscreenelement>
7445    fn GetFullscreenElement(&self) -> Option<DomRoot<Element>> {
7446        DocumentOrShadowRoot::get_fullscreen_element(
7447            &self.node,
7448            self.overlay_handler().fullscreen_element(),
7449        )
7450    }
7451
7452    /// <https://fullscreen.spec.whatwg.org/#dom-document-exitfullscreen>
7453    fn ExitFullscreen(&self, cx: &mut CurrentRealm) -> RootedPromise {
7454        self.overlay_handler().exit_fullscreen(cx)
7455    }
7456
7457    // check-tidy: no specs after this line
7458    // Servo only API to get an instance of the controls of a specific
7459    // media element matching the given id.
7460    fn ServoGetMediaControls(&self, id: DOMString) -> Fallible<DomRoot<ShadowRoot>> {
7461        match self.media_controls.borrow().get(&*id.str()) {
7462            Some(m) => Ok(DomRoot::from_ref(m)),
7463            None => Err(Error::InvalidAccess(Some(
7464                "No registered media controls exist with provided id".into(),
7465            ))),
7466        }
7467    }
7468
7469    /// <https://w3c.github.io/selection-api/#dom-document-getselection>
7470    fn GetSelection(&self, cx: &mut JSContext) -> Option<DomRoot<Selection>> {
7471        if self.has_browsing_context {
7472            Some(self.selection.or_init(|| Selection::new(cx, self)))
7473        } else {
7474            None
7475        }
7476    }
7477
7478    /// <https://drafts.csswg.org/css-font-loading/#font-face-source>
7479    fn Fonts(&self, cx: &mut JSContext) -> DomRoot<FontFaceSet> {
7480        self.fonts
7481            .or_init(|| FontFaceSet::new(cx, &self.global(), None))
7482    }
7483
7484    /// <https://html.spec.whatwg.org/multipage/#dom-document-hidden>
7485    fn Hidden(&self) -> bool {
7486        self.visibility_state.get() == DocumentVisibilityState::Hidden
7487    }
7488
7489    /// <https://html.spec.whatwg.org/multipage/#dom-document-visibilitystate>
7490    fn VisibilityState(&self) -> DocumentVisibilityState {
7491        self.visibility_state.get()
7492    }
7493
7494    fn CreateExpression(
7495        &self,
7496        cx: &mut JSContext,
7497        expression: DOMString,
7498        resolver: Option<RootedCallback<XPathNSResolver>>,
7499    ) -> Fallible<DomRoot<crate::dom::types::XPathExpression>> {
7500        let parsed_expression =
7501            parse_expression(cx, &expression.str(), resolver, self.is_html_document())?;
7502        Ok(XPathExpression::new(
7503            cx,
7504            &self.window,
7505            None,
7506            parsed_expression,
7507        ))
7508    }
7509
7510    fn CreateNSResolver(&self, cx: &mut JSContext, node_resolver: &Node) -> DomRoot<Node> {
7511        let global = self.global();
7512        let window = global.as_window();
7513        let evaluator = XPathEvaluator::new(cx, window, None);
7514        XPathEvaluatorMethods::<crate::DomTypeHolder>::CreateNSResolver(&*evaluator, node_resolver)
7515    }
7516
7517    fn Evaluate(
7518        &self,
7519        cx: &mut JSContext,
7520        expression: DOMString,
7521        context_node: &Node,
7522        resolver: Option<RootedCallback<XPathNSResolver>>,
7523        result_type: u16,
7524        result: Option<&crate::dom::types::XPathResult>,
7525    ) -> Fallible<DomRoot<crate::dom::types::XPathResult>> {
7526        let parsed_expression =
7527            parse_expression(cx, &expression.str(), resolver, self.is_html_document())?;
7528        XPathExpression::new(cx, &self.window, None, parsed_expression).evaluate_internal(
7529            cx,
7530            context_node,
7531            result_type,
7532            result,
7533        )
7534    }
7535
7536    /// <https://drafts.csswg.org/cssom/#dom-documentorshadowroot-adoptedstylesheets>
7537    ///
7538    /// To react to an ObservableArray indexed write:
7539    /// 1. Convert the binding-provided context into a JS API context.
7540    /// 2. Insert `value` at `index` in the DOM-side list.
7541    /// 3. Reconcile the effective constructed stylesheets for this document.
7542    fn OnSetAdoptedStyleSheets(
7543        &self,
7544        cx: &mut JSContext,
7545        value: DomRoot<CSSStyleSheet>,
7546        index: u32,
7547    ) -> ErrorResult {
7548        DocumentOrShadowRoot::on_set_adopted_stylesheets(
7549            self.adopted_stylesheets.safe_borrow_mut(cx).as_mut(),
7550            &value,
7551            index,
7552            &StyleSheetListOwner::Document(Dom::from_ref(self)),
7553        )
7554    }
7555
7556    /// <https://drafts.csswg.org/cssom/#dom-documentorshadowroot-adoptedstylesheets>
7557    ///
7558    /// To react to an ObservableArray deletion:
7559    /// 1. Convert the binding-provided context into a JS API context.
7560    /// 2. Remove the entry at `index` from the DOM-side list.
7561    /// 3. Reconcile the effective constructed stylesheets for this document.
7562    fn OnDeleteAdoptedStyleSheets(
7563        &self,
7564        cx: &mut JSContext,
7565        _value: DomRoot<CSSStyleSheet>,
7566        index: u32,
7567    ) -> ErrorResult {
7568        DocumentOrShadowRoot::on_delete_adopted_stylesheets(
7569            self.adopted_stylesheets.safe_borrow_mut(cx).as_mut(),
7570            index,
7571            &StyleSheetListOwner::Document(Dom::from_ref(self)),
7572        )
7573    }
7574
7575    fn Timeline(&self) -> DomRoot<DocumentTimeline> {
7576        self.timeline.as_rooted()
7577    }
7578}
7579
7580fn update_with_current_instant(marker: &Cell<Option<CrossProcessInstant>>) {
7581    if marker.get().is_none() {
7582        marker.set(Some(CrossProcessInstant::now()))
7583    }
7584}
7585
7586#[derive(JSTraceable, MallocSizeOf)]
7587pub(crate) enum AnimationFrameCallback {
7588    #[cfg(feature = "devtools")]
7589    DevtoolsFramerateTick { actor_name: String },
7590    FrameRequestCallback {
7591        callback: TracedCallback<FrameRequestCallback>,
7592    },
7593}
7594
7595impl js::gc::Rootable for AnimationFrameCallback {}
7596
7597impl AnimationFrameCallback {
7598    fn call(&self, cx: &mut JSContext, document: &Document, now: f64) {
7599        match *self {
7600            #[cfg(feature = "devtools")]
7601            AnimationFrameCallback::DevtoolsFramerateTick { ref actor_name } => {
7602                let msg = ScriptToDevtoolsControlMsg::FramerateTick(actor_name.clone(), now);
7603                let devtools_sender = document.window().as_global_scope().devtools_chan().unwrap();
7604                devtools_sender.send(msg).unwrap();
7605            },
7606            AnimationFrameCallback::FrameRequestCallback { ref callback } => {
7607                // TODO(jdm): The spec says that any exceptions should be suppressed:
7608                // https://github.com/servo/servo/issues/6928
7609                let _ = callback.Call__(cx, Finite::wrap(now), ExceptionHandling::Report);
7610            },
7611        }
7612    }
7613}
7614
7615#[derive(Default, JSTraceable, MallocSizeOf)]
7616#[cfg_attr(crown, crown::unrooted_must_root_lint::must_root)]
7617struct PendingInOrderScriptVec {
7618    scripts: DomRefCell<VecDeque<PendingScript>>,
7619}
7620
7621impl PendingInOrderScriptVec {
7622    fn is_empty(&self) -> bool {
7623        self.scripts.borrow().is_empty()
7624    }
7625
7626    fn push(&self, element: &HTMLScriptElement) {
7627        self.scripts
7628            .borrow_mut()
7629            .push_back(PendingScript::new(element));
7630    }
7631
7632    fn loaded(&self, element: &HTMLScriptElement, result: ScriptResult) {
7633        let mut scripts = self.scripts.borrow_mut();
7634        let entry = scripts
7635            .iter_mut()
7636            .find(|entry| &*entry.element == element)
7637            .unwrap();
7638        entry.loaded(result);
7639    }
7640
7641    fn take_next_ready_to_be_executed(&self) -> Option<(DomRoot<HTMLScriptElement>, ScriptResult)> {
7642        let mut scripts = self.scripts.borrow_mut();
7643        let pair = scripts.front_mut()?.take_result()?;
7644        scripts.pop_front();
7645        Some(pair)
7646    }
7647
7648    fn clear(&self) {
7649        *self.scripts.borrow_mut() = Default::default();
7650    }
7651}
7652
7653#[derive(JSTraceable, MallocSizeOf)]
7654#[cfg_attr(crown, crown::unrooted_must_root_lint::must_root)]
7655struct PendingScript {
7656    element: Dom<HTMLScriptElement>,
7657    load: Option<TracedScriptResult>,
7658}
7659
7660impl PendingScript {
7661    fn new(element: &HTMLScriptElement) -> Self {
7662        Self {
7663            element: Dom::from_ref(element),
7664            load: None,
7665        }
7666    }
7667
7668    fn new_with_load(element: &HTMLScriptElement, load: Option<ScriptResult>) -> Self {
7669        Self {
7670            element: Dom::from_ref(element),
7671            load: load.map(|result| result.map(Into::into)),
7672        }
7673    }
7674
7675    fn loaded(&mut self, result: ScriptResult) {
7676        assert!(self.load.is_none());
7677        self.load = Some(result.map(Into::into));
7678    }
7679
7680    fn take_result(&mut self) -> Option<(DomRoot<HTMLScriptElement>, ScriptResult)> {
7681        self.load
7682            .take()
7683            .map(|result| (DomRoot::from_ref(&*self.element), result.map(Into::into)))
7684    }
7685}
7686
7687fn is_named_element_with_name_attribute(elem: &Element) -> bool {
7688    let type_ = match elem.upcast::<Node>().type_id() {
7689        NodeTypeId::Element(ElementTypeId::HTMLElement(type_)) => type_,
7690        _ => return false,
7691    };
7692    match type_ {
7693        HTMLElementTypeId::HTMLFormElement |
7694        HTMLElementTypeId::HTMLIFrameElement |
7695        HTMLElementTypeId::HTMLImageElement => true,
7696        // TODO handle <embed> and <object>; these depend on whether the element is
7697        // “exposed”, a concept that doesn’t fully make sense until embed/object
7698        // behaviour is actually implemented
7699        _ => false,
7700    }
7701}
7702
7703fn is_named_element_with_id_attribute(elem: &Element) -> bool {
7704    // TODO handle <embed> and <object>; these depend on whether the element is
7705    // “exposed”, a concept that doesn’t fully make sense until embed/object
7706    // behaviour is actually implemented
7707    elem.is::<HTMLImageElement>() && elem.get_name().is_some_and(|name| !name.is_empty())
7708}
7709
7710impl DocumentHelpers for Document {
7711    fn ensure_safe_to_run_script_or_layout(&self) {
7712        Document::ensure_safe_to_run_script_or_layout(self)
7713    }
7714}
7715
7716/// Iterator for ancestor navigables whose active document is in this script thread, returning the
7717/// active documents of the navigables. Stops at the first ancestor whose document is not local.
7718/// <https://html.spec.whatwg.org/multipage/#ancestor-navigables>
7719// TODO: Find a way for something equivalent for documents in other script threads.
7720pub(crate) struct LocalAncestorNavigablesIterator {
7721    document: DomRoot<Document>,
7722}
7723
7724impl LocalAncestorNavigablesIterator {
7725    pub(crate) fn new(document: DomRoot<Document>) -> Self {
7726        Self { document }
7727    }
7728}
7729
7730impl Iterator for LocalAncestorNavigablesIterator {
7731    type Item = DomRoot<Document>;
7732
7733    fn next(&mut self) -> Option<Self::Item> {
7734        let window_proxy = self.document.browsing_context()?;
7735        self.document = window_proxy.parent()?.document()?;
7736        Some(self.document.clone())
7737    }
7738}
7739
7740/// Iterator for descendant navigables whose active document is in this script thread, in a
7741/// shadow-including tree order, returning the active documents of the navigables.
7742/// This does not descend into navigables whose document is not local.
7743/// <https://html.spec.whatwg.org/multipage/#descendant-navigables>
7744// TODO: Find a way for something equivalent for documents in other script threads.
7745pub(crate) struct LocalDescendantNavigablesIterator {
7746    stack: Vec<Box<dyn Iterator<Item = DomRoot<HTMLIFrameElement>>>>,
7747}
7748
7749impl LocalDescendantNavigablesIterator {
7750    pub(crate) fn new(document: &Document) -> Self {
7751        let iframes: Vec<DomRoot<HTMLIFrameElement>> = document.iframes().iter().collect();
7752        Self {
7753            stack: vec![Box::new(iframes.into_iter())],
7754        }
7755    }
7756
7757    fn get_next_iframe(&mut self) -> Option<DomRoot<HTMLIFrameElement>> {
7758        let mut cur_iframe = self.stack.last_mut()?.next();
7759        while cur_iframe.is_none() {
7760            self.stack.pop();
7761            cur_iframe = self.stack.last_mut()?.next();
7762        }
7763        cur_iframe
7764    }
7765}
7766
7767impl Iterator for LocalDescendantNavigablesIterator {
7768    type Item = DomRoot<Document>;
7769
7770    fn next(&mut self) -> Option<Self::Item> {
7771        while let Some(iframe) = self.get_next_iframe() {
7772            let Some(pipeline_id) = iframe.pipeline_id() else {
7773                continue;
7774            };
7775
7776            if let Some(document) = ScriptThread::find_document(pipeline_id) {
7777                let child_iframes: Vec<DomRoot<HTMLIFrameElement>> =
7778                    document.iframes().iter().collect();
7779                self.stack.push(Box::new(child_iframes.into_iter()));
7780                return Some(document);
7781            } else {
7782                continue;
7783            };
7784        }
7785        None
7786    }
7787}