1#![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 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 Abort(AbortReason),
292 ParsingBytesChunk,
293 FinishingParser,
294}
295
296#[derive(JSTraceable, MallocSizeOf)]
300#[cfg_attr(crown, crown::unrooted_must_root_lint::must_root)]
301struct LCPCandidateAndElement {
302 element: Option<Dom<Element>>,
304 #[no_trace]
305 candidate: LCPCandidate,
306}
307
308#[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 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 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#[derive(JSTraceable, MallocSizeOf)]
371pub(crate) enum DeclarativeRefresh {
372 PendingLoad {
373 #[no_trace]
374 url: ServoUrl,
375 time: u64,
376 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 target: Dom<EventTarget>,
387 #[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#[derive(Clone, Copy, Debug, Default, JSTraceable, MallocSizeOf)]
401pub(crate) struct RenderingUpdateReason(u8);
402
403bitflags! {
404 impl RenderingUpdateReason: u8 {
405 const ResizeObserverStartedObservingTarget = 1 << 0;
408 const IntersectionObserverStartedObservingTarget = 1 << 1;
411 const FontReadyPromiseFulfilled = 1 << 2;
415 }
416}
417
418#[derive(Clone, Debug, Default, MallocSizeOf)]
420pub(crate) struct NavigationTiming {
421 pub(crate) dom_loading: Cell<Option<CrossProcessInstant>>,
422 pub(crate) navigation_start: Cell<Option<CrossProcessInstant>>,
424 pub(crate) unload_event_start: Cell<Option<CrossProcessInstant>>,
426 pub(crate) unload_event_end: Cell<Option<CrossProcessInstant>>,
428 pub(crate) dom_interactive: Cell<Option<CrossProcessInstant>>,
430 pub(crate) dom_content_loaded_event_start: Cell<Option<CrossProcessInstant>>,
432 pub(crate) dom_content_loaded_event_end: Cell<Option<CrossProcessInstant>>,
434 pub(crate) dom_complete: Cell<Option<CrossProcessInstant>>,
436 pub(crate) load_event_start: Cell<Option<CrossProcessInstant>>,
438 pub(crate) load_event_end: Cell<Option<CrossProcessInstant>>,
440 pub(crate) top_level_dom_complete: Cell<Option<CrossProcessInstant>>,
442}
443
444#[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 #[no_trace]
462 url: AtomicRefCell<ServoUrl>,
463 #[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 event_handler: DocumentEventHandler,
471 focus_handler: DocumentFocusHandler,
473 overlay_handler: OnceCell<DocumentOverlayHandler>,
475 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 iframes: IFrameCollection,
491 #[no_trace]
495 shared_style_locks: SharedRwLocks,
496 #[custom_trace]
498 stylesheets: DomRefCell<DocumentStylesheetSet<ServoStylesheetInDocument>>,
499 stylesheet_list: MutNullableDom<StyleSheetList>,
500 ready_state: Cell<DocumentReadyState>,
501 current_script: MutNullableDom<HTMLScriptElement>,
503 #[no_trace]
504 current_the_end_loading_phase: Cell<TheEndLoadingPhase>,
505 pending_parsing_blocking_script: DomRefCell<Option<PendingScript>>,
507 script_blocking_stylesheet_set: DomRefCell<IndexSet<StylesheetContextId>>,
510 render_blocking_element_count: Cell<u32>,
513 deferred_scripts: PendingInOrderScriptVec,
515 asap_in_order_scripts_list: PendingInOrderScriptVec,
517 asap_scripts_set: DomRefCell<Vec<Dom<HTMLScriptElement>>>,
519 animation_frame_ident: Cell<u32>,
522 animation_frame_list: DomRefCell<VecDeque<(u32, Option<AnimationFrameCallback>)>>,
525 running_animation_callbacks: Cell<bool>,
530 loader: DomRefCell<DocumentLoader>,
532 current_parser: MutNullableDom<ServoParser>,
534 base_element: MutNullableDom<HTMLBaseElement>,
536 target_base_element: MutNullableDom<HTMLBaseElement>,
538 appropriate_template_contents_owner_document: MutNullableDom<Document>,
541 pending_restyles: DomRefCell<FxHashMap<Dom<Element>, NoTrace<PendingRestyle>>>,
544 #[no_trace]
548 needs_restyle: Cell<RestyleReason>,
549 #[no_trace]
551 origin: DomRefCell<MutableOrigin>,
552 referrer: Option<String>,
554 target_element: MutNullableDom<Element>,
556 #[no_trace]
558 #[conditional_malloc_size_of]
559 policy_container: DomRefCell<StdArc<PolicyContainer>>,
560 #[no_trace]
562 preloaded_resources: DomRefCell<PreloadedResources>,
563 ignore_destructive_writes_counter: Cell<u32>,
565 ignore_opens_during_unload_counter: Cell<u32>,
567 spurious_animation_frames: Cell<u8>,
571
572 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 throw_on_dynamic_markup_insertion_counter: Cell<u64>,
586 page_showing: Cell<bool>,
588 salvageable: Cell<bool>,
590 active_parser_was_aborted: Cell<bool>,
592 fired_unload: Cell<bool>,
594 responsive_images: DomRefCell<Vec<Dom<HTMLImageElement>>>,
596
597 #[no_trace]
600 #[conditional_malloc_size_of]
601 navigation_timing: Rc<NavigationTiming>,
602
603 #[no_trace]
605 resource_fetch_timing: RefCell<Option<ResourceFetchTiming>>,
606
607 script_and_layout_blockers: Cell<u32>,
609 #[ignore_malloc_size_of = "Measuring trait objects is hard"]
611 delayed_tasks: DomRefCell<VecDeque<Box<dyn NonSendTaskBox>>>,
612 completely_loaded: Cell<bool>,
614 shadow_roots: DomRefCell<FxHashSet<Dom<ShadowRoot>>>,
616 shadow_roots_styles_changed: Cell<bool>,
618 media_controls: DomRefCell<HashMap<String, Dom<ShadowRoot>>>,
624 dirty_canvases: DomRefCell<Vec<Dom<HTMLCanvasElement>>>,
627 has_pending_animated_image_update: Cell<bool>,
629 selection: MutNullableDom<Selection>,
631 timeline: Dom<DocumentTimeline>,
634 animation_manager: AnimationManager,
636 dirty_root: MutNullableDom<Element>,
638 declarative_refresh: DomRefCell<Option<DeclarativeRefresh>>,
640 resize_observers: DomRefCell<Vec<Dom<ResizeObserver>>>,
649 fonts: MutNullableDom<FontFaceSet>,
652 visibility_state: Cell<DocumentVisibilityState>,
654 status_code: Option<u16>,
656 is_initial_about_blank: Cell<bool>,
658 allow_declarative_shadow_roots: Cell<bool>,
660 #[no_trace]
662 inherited_insecure_requests_policy: Cell<Option<InsecureRequestsPolicy>>,
663 has_trustworthy_ancestor_origin: Cell<bool>,
665 intersection_observer_task_queued: Cell<bool>,
667 intersection_observers: DomRefCell<Vec<Dom<IntersectionObserver>>>,
679 lazy_load_intersection_observer: MutNullableDom<IntersectionObserver>,
681 highlighted_dom_node: MutNullableDom<Node>,
683 lcp_candidates: DomRefCell<HashMapTracedValues<LCPCandidateID, LCPCandidateAndElement>>,
685 #[no_trace]
688 paint_timing_info: Cell<PaintTimingInfo>,
689 container_timing_records:
691 DomRefCell<HashMapTracedValues<ContainerTimingID, ContainerTimingRecordAndElements>>,
692 #[no_trace]
698 container_first_render_times: DomRefCell<HashMap<OpaqueNode, CrossProcessInstant>>,
699 adopted_stylesheets: DomRefCell<Vec<Dom<CSSStyleSheet>>>,
703 pending_scroll_events: DomRefCell<Vec<PendingScrollEvent>>,
707 rendering_update_reasons: Cell<RenderingUpdateReason>,
709 waiting_on_canvas_image_updates: Cell<bool>,
713 root_removal_noted: Cell<bool>,
715 #[no_trace]
723 current_rendering_epoch: Cell<Epoch>,
724 #[conditional_malloc_size_of]
726 custom_element_reaction_stack: Rc<CustomElementReactionStack>,
727 #[no_trace]
728 active_sandboxing_flag_set: Cell<SandboxingFlagSet>,
730 #[no_trace]
731 creation_sandboxing_flag_set: Cell<SandboxingFlagSet>,
738 #[no_trace]
740 favicon: RefCell<Option<Image>>,
741 ever_had_favicon_link: Cell<bool>,
743
744 websockets: DOMTracker<WebSocket>,
746
747 active_media_elements: DomRefCell<FxHashSet<Dom<HTMLMediaElement>>>,
750
751 details_name_groups: DomRefCell<Option<DetailsNameGroups>>,
753
754 #[no_trace]
756 protocol_handler_automation_mode: RefCell<CustomHandlersAutomationMode>,
757
758 layout_animations_test_enabled: bool,
760
761 #[no_trace]
763 state_override: DomRefCell<FxHashMap<CommandName, bool>>,
764
765 #[no_trace]
767 value_override: DomRefCell<FxHashMap<CommandName, DOMString>>,
768
769 #[no_trace]
771 default_single_line_container_name: Cell<DefaultSingleLineContainerName>,
772
773 css_styling_flag: Cell<bool>,
775
776 accessibility_data: DomRefCell<AccessibilityData>,
778
779 iframe_load_in_progress: Cell<bool>,
781 mute_iframe_load: Cell<bool>,
783
784 timers: OneshotTimers,
787
788 #[no_trace]
789 pipeline_id: PipelineId,
790
791 #[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 history: MutNullableDom<History>,
801
802 #[no_trace]
804 theme: Cell<Option<Theme>>,
805
806 #[no_trace]
808 theme_override: Cell<Option<Theme>>,
809
810 #[no_trace]
812 default_language: AtomicRefCell<Option<String>>,
813
814 window_detached: Cell<bool>,
817
818 ancestor_origins_list: MutNullableDom<DOMStringList>,
820
821 #[no_trace]
823 internal_ancestor_origin_objects_list: RefCell<Option<Vec<ImmutableOrigin>>>,
824
825 live_ranges: WeakRangeVec,
828
829 #[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 fn unloading_cleanup_steps(&self, cx: &mut JSContext) {
864 self.overlay_handler().fully_exit_fullscreen(cx);
867
868 if self.close_outstanding_websockets() {
871 self.salvageable.set(false);
873 }
874
875 self.clean_up_media_elements(cx.no_gc());
876
877 if !self.salvageable.get() && !self.window_detached() {
882 let global_scope = self.window.as_global_scope();
883
884 global_scope.close_event_sources();
886
887 self.timers.clear();
889
890 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 self.root_removal_noted.set(false);
940 } else if !self.root_removal_noted.get() {
941 self.add_restyle_reason(RestyleReason::DOMChanged);
944 self.root_removal_noted.set(true);
945 }
946 }
947
948 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 if let Some(parent_element) = parent_element {
979 if !parent_element.is_styled() {
982 return;
983 }
984 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 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 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) .find_map(|ancestor| {
1025 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 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 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 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 #[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 pub(crate) fn is_fully_active(&self) -> bool {
1123 self.is_active() &&
1127 (self.window.is_top_level() || self.activity.get() == DocumentActivity::FullyActive)
1128 }
1129
1130 pub(crate) fn is_active(&self) -> bool {
1132 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 #[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 assert!(self.has_browsing_context);
1156 if activity == self.activity.get() {
1157 return;
1158 }
1159
1160 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 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 if document.page_showing.get() {
1201 return;
1202 }
1203 document.page_showing.set(true);
1205 document.update_visibility_state(cx, DocumentVisibilityState::Visible);
1207 let event = PageTransitionEvent::new(
1210 cx,
1211 window,
1212 atom!("pageshow"),
1213 false, false, true, );
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 pub(crate) fn paint_timing_eligible(&self) -> bool {
1229 if self.window().is_top_level() {
1233 return true;
1234 }
1235 if let Some(top_level_document) = self.window().top_level_document_if_local() {
1238 return self.origin().same_origin(&top_level_document.origin());
1242 };
1243 false
1244 }
1245
1246 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 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 pub(crate) fn fallback_base_url(&self) -> ServoUrl {
1276 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 document_url
1287 }
1288
1289 pub(crate) fn base_url(&self) -> ServoUrl {
1291 match self.base_element() {
1292 None => self.fallback_base_url(),
1294 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 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 pub(crate) fn base_element(&self) -> Option<DomRoot<HTMLBaseElement>> {
1335 self.base_element.get()
1336 }
1337
1338 pub(crate) fn target_base_element(&self) -> Option<DomRoot<HTMLBaseElement>> {
1340 self.target_base_element.get()
1341 }
1342
1343 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 node.dirty(no_gc, NodeDamage::ContentOrHeritage);
1401 }
1402
1403 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 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 pub(crate) fn unregister_element_name(&self, name: &Atom) {
1417 self.name_map.remove(name);
1418 }
1419
1420 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 fn find_a_potential_indicated_element(
1454 &self,
1455 cx: &mut JSContext,
1456 fragment: &str,
1457 ) -> Option<DomRoot<Element>> {
1458 self.get_element_by_id(cx.no_gc(), &Atom::from(fragment))
1462 .or_else(|| self.get_anchor_by_name(cx, fragment))
1466 }
1467
1468 fn select_indicated_part(&self, cx: &mut JSContext, fragment: &str) -> Option<DomRoot<Node>> {
1471 if fragment.is_empty() {
1481 return Some(DomRoot::from_ref(self.upcast()));
1482 }
1483 if let Some(potential_indicated_element) =
1485 self.find_a_potential_indicated_element(cx, fragment)
1486 {
1487 return Some(DomRoot::upcast(potential_indicated_element));
1489 }
1490 let fragment_bytes = percent_decode(fragment.as_bytes());
1492 let Ok(decoded_fragment) = fragment_bytes.decode_utf8() else {
1494 return None;
1495 };
1496 if let Some(potential_indicated_element) =
1498 self.find_a_potential_indicated_element(cx, &decoded_fragment)
1499 {
1500 return Some(DomRoot::upcast(potential_indicated_element));
1502 }
1503 if decoded_fragment.eq_ignore_ascii_case("top") {
1505 return Some(DomRoot::from_ref(self.upcast()));
1506 }
1507 None
1509 }
1510
1511 pub(crate) fn scroll_to_the_fragment(&self, cx: &mut JSContext, fragment: &str) {
1513 let Some(indicated_part) = self.select_indicated_part(cx, fragment) else {
1518 self.set_target_element(cx.no_gc(), None);
1519 return;
1520 };
1521 if *indicated_part == *self.upcast() {
1523 self.set_target_element(cx.no_gc(), None);
1525 self.window.scroll(cx, 0.0, 0.0, ScrollBehavior::Instant);
1530 return;
1532 }
1533 let Some(target) = indicated_part.downcast::<Element>() else {
1536 unreachable!("Indicated part should always be an element");
1538 };
1539 self.set_target_element(cx.no_gc(), Some(target));
1541 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 indicated_part.run_the_focusing_steps(
1556 cx,
1557 Some(FocusableArea::Viewport),
1558 FocusTrigger::Script,
1559 );
1560
1561 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 pub(crate) fn set_document_readiness_to_loading_for_initialization(&self) {
1590 if self.is_initial_about_blank() {
1594 return;
1595 }
1596
1597 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 pub(crate) fn update_the_current_document_readiness(
1617 &self,
1618 cx: &mut JSContext,
1619 state: DocumentReadyState,
1620 ) {
1621 if self.ready_state.get() == state {
1623 return;
1624 }
1625
1626 self.ready_state.set(state);
1628
1629 match state {
1634 DocumentReadyState::Loading => {},
1635 DocumentReadyState::Complete => {
1636 self.notify_embedder_of_load_completion();
1639
1640 update_with_current_instant(&self.navigation_timing.dom_complete);
1645 },
1646 DocumentReadyState::Interactive => {
1647 update_with_current_instant(&self.navigation_timing.dom_interactive)
1652 },
1653 };
1654
1655 self.upcast::<EventTarget>()
1657 .fire_event(cx, atom!("readystatechange"));
1658 }
1659
1660 pub(crate) fn scripting_enabled(&self) -> bool {
1663 self.has_browsing_context() &&
1666 !self.has_active_sandboxing_flag(
1670 SandboxingFlagSet::SANDBOXED_SCRIPTS_BROWSING_CONTEXT_FLAG,
1671 )
1672 }
1673
1674 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 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 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 root.upcast::<Node>()
1710 .traverse_preorder(ShadowIncluding::No)
1711 .find(|node| node.is::<HTMLTitleElement>())
1712 }
1713 });
1714
1715 title.map(|title| {
1716 let value = title.child_text_content();
1718 DOMString::from(str_join(value.str().split_html_space_characters(), " "))
1719 })
1720 }
1721
1722 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 pub(crate) fn run_the_scroll_steps(&self, cx: &mut JSContext) {
1751 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 let Some(element) = target.downcast::<Element>() else {
1778 continue;
1779 };
1780 let document = element.owner_document();
1781
1782 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 pending_scroll_events.push(PendingScrollEvent {
1799 target: target.as_traced(),
1800 event: "scrollend".into(),
1801 });
1802 }
1803
1804 rooted_vec!(let pending_scroll_events <- self.pending_scroll_events.take().into_iter());
1807 for pending_event in pending_scroll_events.iter() {
1808 let event = pending_event.event.clone();
1811 if pending_event.target.is::<Document>() {
1812 pending_event.target.fire_bubbling_event(cx, event);
1813 }
1814 else {
1823 pending_event.target.fire_event(cx, event);
1824 }
1825 }
1826
1827 }
1830
1831 pub(crate) fn handle_viewport_scroll_event(&self) {
1836 self.finish_handle_scroll_event(self.upcast());
1848 }
1849
1850 pub(crate) fn finish_handle_scroll_event(&self, event_target: &EventTarget) {
1855 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 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 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 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 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 pub(crate) fn increment_render_blocking_element_count(&self) {
1954 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 pub(crate) fn decrement_render_blocking_element_count(&self) {
1967 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 pub(crate) fn allows_adding_render_blocking_elements(&self) -> bool {
1979 self.is_html_document && self.GetBody().is_none()
1982 }
1983
1984 pub(crate) fn is_render_blocked(&self) -> bool {
1986 self.render_blocking_element_count() > 0
1990 }
1995
1996 pub(crate) fn invalidate_stylesheets(&self, no_gc: &NoGC) {
1997 self.stylesheets.borrow_mut().force_dirty(OriginSet::all());
1998
1999 if let Some(element) = self.GetDocumentElement() {
2003 element.upcast::<Node>().dirty(no_gc, NodeDamage::Style);
2004 }
2005 }
2006
2007 pub(crate) fn has_active_request_animation_frame_callbacks(&self) -> bool {
2010 !self.animation_frame_list.borrow().is_empty()
2011 }
2012
2013 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 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 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 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 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 pub(crate) fn enforce_csp_policy(&self, policy: CspPolicy) {
2121 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 fn deferred_fetch_control_document(&self) -> DomRoot<Document> {
2187 match self.window().window_proxy().frame_element() {
2188 None => DomRoot::from_ref(self),
2191 Some(container) => container.owner_document().deferred_fetch_control_document(),
2193 }
2194 }
2195
2196 pub(crate) fn available_deferred_fetch_quota(&self, origin: ImmutableOrigin) -> isize {
2198 let control_document = self.deferred_fetch_control_document();
2200 let navigable = control_document.window();
2202 let is_top_level = navigable.is_top_level();
2205 let deferred_fetch_allowed = true;
2209 let deferred_fetch_minimal_allowed = true;
2213 let mut quota = match is_top_level {
2215 true if !deferred_fetch_allowed => 0,
2217 true if !deferred_fetch_minimal_allowed => 640 * 1024,
2219 true => 512 * 1024,
2221 _ if deferred_fetch_allowed => 0,
2225 _ if deferred_fetch_minimal_allowed => 8 * 1024,
2229 _ => 0,
2231 } as isize;
2232 let mut quota_for_request_origin = 64 * 1024_isize;
2234 let deferred_fetches = navigable.as_global_scope().fetch_group().deferred_fetches();
2243 for deferred_fetch in deferred_fetches {
2244 if deferred_fetch.invoke_state.get() != DeferredFetchRecordInvokeState::Pending {
2246 continue;
2247 }
2248 let request_length = deferred_fetch.request.total_request_length();
2250 quota -= request_length as isize;
2252 if deferred_fetch.request.url().origin() == origin {
2255 quota_for_request_origin -= request_length as isize;
2256 }
2257 }
2258 if quota <= 0 {
2260 return 0;
2261 }
2262 if quota < quota_for_request_origin {
2264 return quota;
2265 }
2266 quota_for_request_origin
2268 }
2269
2270 pub(crate) fn update_document_for_history_step_application(
2272 &self,
2273 old_url: &ServoUrl,
2274 new_url: &ServoUrl,
2275 ) {
2276 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 pub(crate) fn finish_load(&self, load: LoadType, cx: &mut JSContext) {
2344 debug!("Document {:?} got finish_load: {:?}", self.url(), load);
2346 self.loader.borrow_mut().finish_load(&load);
2347
2348 match load {
2349 LoadType::Stylesheet(_) => {
2350 self.process_pending_parsing_blocking_script(cx);
2353
2354 self.process_deferred_scripts(cx);
2356 },
2357 LoadType::PageSource(_) => {
2358 if self.has_browsing_context && self.is_fully_active() {
2361 self.window().allow_layout_if_necessary(cx);
2362 }
2363
2364 self.process_deferred_scripts(cx);
2369 },
2370 _ => {},
2371 }
2372
2373 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 pub(crate) fn check_if_unloading_is_cancelled(
2385 &self,
2386 cx: &mut JSContext,
2387 recursive_flag: bool,
2388 ) -> bool {
2389 self.incr_ignore_opens_during_unload_counter();
2392 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 if has_listeners {
2408 self.salvageable.set(false);
2409 }
2410 let mut can_unload = true;
2411 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 if !recursive_flag {
2426 let iframes: Vec<_> = self.iframes().iter().collect();
2429 for iframe in &iframes {
2430 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 self.decr_ignore_opens_during_unload_counter();
2443 can_unload
2444 }
2445
2446 pub(crate) fn unload(&self, cx: &mut JSContext, recursive_flag: bool) {
2448 if self.window_detached() {
2449 return;
2450 }
2451
2452 self.incr_ignore_opens_during_unload_counter();
2455 if self.page_showing.get() {
2457 self.page_showing.set(false);
2459 let event = PageTransitionEvent::new(
2462 cx,
2463 &self.window,
2464 atom!("pagehide"),
2465 false, false, self.salvageable.get(), );
2469 let event = event.upcast::<Event>();
2470 event.set_trusted(true);
2471 self.window.dispatch_event_with_target_override(cx, event);
2472 self.update_visibility_state(cx, DocumentVisibilityState::Hidden);
2474 }
2475 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 if has_listeners {
2491 self.salvageable.set(false);
2492 }
2493 }
2494 if !recursive_flag {
2498 let iframes: Vec<_> = self.iframes().iter().collect();
2501 for iframe in &iframes {
2502 let document = iframe.owner_document();
2504 document.unload(cx, true);
2505 if !document.salvageable() {
2506 self.salvageable.set(false);
2507 }
2508 }
2509 }
2510
2511 self.unloading_cleanup_steps(cx);
2513
2514 self.window.as_global_scope().clean_up_all_file_resources();
2516
2517 self.decr_ignore_opens_during_unload_counter();
2519
2520 }
2523
2524 fn completely_finish_loading(&self) {
2526 self.completely_loaded.set(true);
2531 self.notify_constellation_that_load_finished(false );
2540
2541 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 fn queue_document_completion(&self, cx: &mut JSContext) {
2567 assert!(!self.is_initial_about_blank());
2571
2572 self.loader.borrow_mut().inhibit_events();
2573
2574 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 let window = document.window();
2587 if !window.is_alive() || document.window_detached() {
2588 return;
2589 }
2590
2591 document.update_the_current_document_readiness(cx, DocumentReadyState::Complete);
2594
2595 if document.loader().aborted() {
2603 return;
2604 }
2605
2606 if document.browsing_context().is_none() {
2608 return;
2609 }
2610
2611 update_with_current_instant(&document.navigation_timing.load_event_start);
2613
2614 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 update_with_current_instant(&document.navigation_timing.load_event_end);
2636
2637 document.page_showing.set(true);
2642
2643 let page_show_event = PageTransitionEvent::new(
2645 cx,
2646 window,
2647 atom!("pageshow"),
2648 false, false, false, );
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 document.completely_finish_loading();
2658
2659 if let Some(fragment) = document.url().fragment() {
2663 document.scroll_to_the_fragment(cx, fragment);
2664 }
2665 }));
2666
2667 #[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 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 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 pub(crate) fn has_pending_parsing_blocking_script(&self) -> bool {
2715 self.pending_parsing_blocking_script.borrow().is_some()
2716 }
2717
2718 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 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 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 pub(crate) fn push_asap_in_order_script(&self, script: &HTMLScriptElement) {
2780 self.asap_in_order_scripts_list.push(script);
2781 }
2782
2783 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 pub(crate) fn add_deferred_script(&self, script: &HTMLScriptElement) {
2804 self.deferred_scripts.push(script);
2805 }
2806
2807 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 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 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 if let Some((element, result)) = self.deferred_scripts.take_next_ready_to_be_executed()
2841 {
2842 element.execute(cx, result);
2845 } else {
2846 break;
2847 }
2848 }
2849
2850 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 fn dispatch_dom_content_loaded(&self) {
2861 assert_ne!(
2862 self.ReadyState(),
2863 DocumentReadyState::Complete,
2864 "Complete before DOMContentLoaded?"
2865 );
2866
2867 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 let document = document.root();
2877 update_with_current_instant(&document.navigation_timing.dom_content_loaded_event_start);
2878 document.upcast::<EventTarget>().fire_bubbling_event(cx, atom!("DOMContentLoaded"));
2880 update_with_current_instant(&document.navigation_timing.dom_content_loaded_event_end);
2883 }));
2892
2893 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 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 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 if document.current_the_end_loading_phase.get() !=
2924 TheEndLoadingPhase::ProcessingAsSoonAsPossibleScripts
2925 {
2926 return;
2927 }
2928 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 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 {
2948 let loader = self.loader.borrow();
2949
2950 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 pub(crate) fn destroy_document_and_its_descendants(&self, cx: &mut JSContext) {
2974 if !self.is_fully_active() {
2976 self.salvageable.set(false);
2981 }
2985 for exited_iframe in self.iframes().iter() {
2998 debug!("Destroying nested iframe document");
2999 exited_iframe.destroy_document_and_its_descendants(cx);
3000 }
3001 self.destroy(cx);
3006 }
3009
3010 pub(crate) fn destroy(&self, cx: &mut JSContext) {
3012 let exited_window = self.window();
3013 self.abort(cx, AbortReason::Destroy);
3015 self.salvageable.set(false);
3017 self.unloading_cleanup_steps(cx);
3027
3028 exited_window
3031 .as_global_scope()
3032 .task_manager()
3033 .cancel_all_tasks_and_ignore_future_tasks();
3034
3035 exited_window.discard_browsing_context();
3037
3038 exited_window
3045 .as_global_scope()
3046 .disable_owned_worker_animation_frame_providers();
3047
3048 exited_window.as_global_scope().tear_down();
3055 }
3056
3057 fn active_parser(&self) -> Option<DomRoot<ServoParser>> {
3059 self.get_current_parser()
3062 .filter(|parser| !(parser.has_stopped() || parser.has_aborted()))
3063 }
3064
3065 pub(crate) fn abort(&self, cx: &mut JSContext, reason: AbortReason) {
3067 self.loader.borrow_mut().abort();
3070 self.current_the_end_loading_phase
3071 .set(TheEndLoadingPhase::Done);
3072
3073 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 self.salvageable.set(false);
3094 };
3095
3096 self.owner_global()
3101 .task_manager()
3102 .cancel_pending_tasks_for_source(TaskSourceName::Networking);
3103
3104 if let Some(parser) = self.active_parser() {
3109 self.active_parser_was_aborted.set(true);
3111 parser.abort(cx, reason);
3113 self.salvageable.set(false);
3115 } else if self.ready_state.get() != DocumentReadyState::Complete {
3116 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 pub(crate) fn abort_a_document_and_its_descendants(
3136 &self,
3137 cx: &mut JSContext,
3138 reason: AbortReason,
3139 ) {
3140 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 descendant_document.abort(cx, reason);
3159 if !descendant_document.salvageable.get() {
3161 document.root().salvageable.set(false);
3162 }
3163 }));
3164 }
3165 }
3166
3167 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 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 pub(crate) fn ancestor_origins_list(&self) -> Option<DomRoot<DOMStringList>> {
3207 self.ancestor_origins_list.get()
3208 }
3209
3210 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 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 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 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 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 pub(crate) fn effective_global_custom_element_registry(
3283 &self,
3284 ) -> Option<DomRoot<CustomElementRegistry>> {
3285 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 None
3295 }
3296
3297 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 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 pub(crate) fn mark_paint_timing(&self) {
3414 self.paint_timing_info.set(PaintTimingInfo::now());
3418 }
3419
3420 pub(crate) fn paint_timing_info(&self) -> PaintTimingInfo {
3422 self.paint_timing_info.get()
3423 }
3424
3425 pub(crate) fn update_the_rendering(
3430 &self,
3431 cx: &mut JSContext,
3432 ) -> (ReflowPhasesRun, ReflowStatistics) {
3433 assert!(!self.is_render_blocked());
3434 self.mark_paint_timing();
3436
3437 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 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 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 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 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 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 pub(crate) fn gather_active_resize_observations_at_depth(
3571 &self,
3572 cx: &mut JSContext,
3573 depth: &ResizeObservationDepth,
3574 ) -> bool {
3575 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 pub(crate) fn broadcast_active_resize_observations(
3589 &self,
3590 cx: &mut JSContext,
3591 ) -> ResizeObservationDepth {
3592 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 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 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 pub(crate) fn encoding_parse_a_url(&self, url: &str) -> Result<ServoUrl, url::ParseError> {
3626 self.encoding_parse_a_url_with_base(url, &self.base_url())
3629 }
3630
3631 pub(crate) fn encoding_parse_a_url_with_base(
3637 &self,
3638 url: &str,
3639 base_url: &ServoUrl,
3640 ) -> Result<ServoUrl, url::ParseError> {
3641 let encoding = self.encoding.get();
3647
3648 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 pub(crate) fn allowed_to_use_feature(&self, _feature: PermissionName) -> bool {
3663 if !self.has_browsing_context {
3665 return false;
3666 }
3667
3668 if !self.is_fully_active() {
3670 return false;
3671 }
3672
3673 true
3679 }
3680
3681 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 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 pub(crate) fn start_intersection_observing_a_lazy_loading_element(
3703 &self,
3704 cx: &mut JSContext,
3705 element: &Element,
3706 ) {
3707 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 pub(crate) fn stop_intersection_observing_a_lazy_loading_element(
3716 &self,
3717 no_gc: &NoGC,
3718 element: &Element,
3719 ) {
3720 if let Some(observer) = self.lazy_load_intersection_observer.get() {
3724 observer.Unobserve(no_gc, element);
3725 }
3726 }
3727
3728 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 self.window()
3739 .reflow_for_non_flushing_update_the_rendering_queries(cx);
3740
3741 for intersection_observer in &*self.intersection_observers.borrow() {
3743 self.update_single_intersection_observer_steps(cx, intersection_observer, time);
3744 }
3745 }
3746
3747 fn update_single_intersection_observer_steps(
3749 &self,
3750 cx: &mut JSContext,
3751 intersection_observer: &IntersectionObserver,
3752 time: CrossProcessInstant,
3753 ) {
3754 let root_bounds = intersection_observer.root_intersection_rectangle();
3757
3758 intersection_observer.update_intersection_observations_steps(cx, self, time, root_bounds);
3762 }
3763
3764 pub(crate) fn notify_intersection_observers(&self, cx: &mut JSContext) {
3766 self.intersection_observer_task_queued.set(false);
3769
3770 rooted_vec!(let notify_list <- self.intersection_observers.clone().take().into_iter());
3775
3776 for intersection_observer in notify_list.iter() {
3779 intersection_observer.invoke_callback_if_necessary(cx);
3781 }
3782 }
3783
3784 pub(crate) fn queue_an_intersection_observer_task(&self) {
3786 if self.intersection_observer_task_queued.get() {
3789 return;
3790 }
3791
3792 self.intersection_observer_task_queued.set(true);
3795
3796 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 #[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 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 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 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 let mut strings: Vec<String> = Vec::with_capacity(text.len());
3942 let mut is_trusted = true;
3944 for value in text {
3946 match value {
3947 TrustedHTMLOrString::TrustedHTML(trusted_html) => {
3949 strings.push(trusted_html.to_string());
3950 },
3951 TrustedHTMLOrString::String(str_) => {
3952 is_trusted = false;
3954 strings.push(str_.into());
3956 },
3957 };
3958 }
3959 let mut string = itertools::join(strings, "");
3960 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 if line_feed {
3975 string.push('\n');
3976 }
3977 if !self.is_html_document() {
3979 return Err(Error::InvalidState(Some(
3980 "Document must be a HTML document".into(),
3981 )));
3982 }
3983
3984 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 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 _ => {
4002 if self.is_prompting_or_unloading() ||
4005 self.ignore_destructive_writes_counter.get() > 0
4006 {
4007 return Ok(());
4008 }
4009 self.Open(cx, None, None)?;
4011 self.get_current_parser().unwrap()
4012 },
4013 };
4014
4015 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 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#[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
4203pub(crate) fn get_registrable_domain_suffix_of_or_is_equal_to(
4207 host_suffix_string: &str,
4208 original_host: Host,
4209) -> Option<Host> {
4210 if host_suffix_string.is_empty() {
4212 return None;
4213 }
4214
4215 let host = match Host::parse(host_suffix_string) {
4217 Ok(host) => host,
4218 Err(_) => return None,
4219 };
4220
4221 if host != original_host {
4223 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 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 if is_pub_domain(host) {
4246 return None;
4247 }
4248 }
4249
4250 Some(host)
4252}
4253
4254fn 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 IsHTMLDocument::HTMLDocument => "text/html",
4306 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 let quirks_mode = if is_initial_about_blank {
4325 QuirksMode::Quirks
4326 } else {
4327 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 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 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 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 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 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 pub(crate) fn event_handler(&self) -> &DocumentEventHandler {
4515 &self.event_handler
4516 }
4517
4518 pub(crate) fn focus_handler(&self) -> &DocumentFocusHandler {
4520 &self.focus_handler
4521 }
4522
4523 pub(crate) fn overlay_handler(&self) -> &DocumentOverlayHandler {
4525 self.overlay_handler
4526 .get_or_init(|| DocumentOverlayHandler::new(self))
4527 }
4528
4529 pub(crate) fn embedder_controls(&self) -> &DocumentEmbedderControls {
4531 &self.embedder_controls
4532 }
4533
4534 fn has_pending_scroll_events(&self) -> bool {
4537 !self.pending_scroll_events.borrow().is_empty()
4538 }
4539
4540 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 pub(crate) fn clear_rendering_update_reasons(&self) {
4549 self.rendering_update_reasons
4550 .set(RenderingUpdateReason::empty())
4551 }
4552
4553 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 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 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 pub(crate) fn is_safe_to_run_script_or_layout(&self) -> bool {
4587 self.script_and_layout_blockers.get() == 0
4588 }
4589
4590 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 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 pub(crate) fn shared_style_locks(&self) -> &SharedRwLocks {
4817 &self.shared_style_locks
4818 }
4819
4820 pub(crate) fn style_shared_author_lock(&self) -> &SharedRwLock {
4822 &self.shared_style_locks.author
4823 }
4824
4825 pub(crate) fn flush_stylesheets_for_reflow(&self) -> bool {
4827 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 pub(crate) fn make_document_unsalvageable(&self) {
4845 self.salvageable.set(false);
4851 }
4852
4853 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 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 return;
4916 }
4917
4918 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 #[cfg_attr(crown, expect(crown::unrooted_must_root))] 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 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 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 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 #[cfg_attr(crown, expect(crown::unrooted_must_root))] 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 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 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 pub(crate) fn update_animations_and_send_events(&self, cx: &mut CurrentRealm) {
5281 if !self.layout_animations_test_enabled {
5283 self.timeline.update(self.window());
5284 }
5285
5286 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 self.window().perform_a_microtask_checkpoint(cx);
5299
5300 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 pub(crate) fn shared_declarative_refresh_steps(&self, content: &[u8], from_meta_element: bool) {
5311 if self.will_declaratively_refresh() {
5313 return;
5314 }
5315
5316 static REFRESH_REGEX: LazyLock<Regex> = LazyLock::new(|| {
5318 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 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 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 return;
5375 };
5376 if url_record.scheme() == "javascript" {
5378 return;
5379 }
5380 }
5381 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 fn update_visibility_state(
5409 &self,
5410 cx: &mut JSContext,
5411 visibility_state: DocumentVisibilityState,
5412 ) {
5413 if self.visibility_state.get() == visibility_state {
5415 return;
5416 }
5417 self.visibility_state.set(visibility_state);
5419 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 if let Some(geolocation) = self.window.maybe_geolocation() {
5443 geolocation.handle_visibility_change(visibility_state);
5444 }
5445
5446 #[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 self.upcast::<EventTarget>()
5463 .fire_bubbling_event(cx, atom!("visibilitychange"));
5464 }
5465
5466 pub(crate) fn is_initial_about_blank(&self) -> bool {
5468 self.is_initial_about_blank.get()
5469 }
5470
5471 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 pub(crate) fn determine_the_network_partition_key(&self) -> Option<Site> {
5487 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 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 let top_level_origin = top_level_origin.expect("topLevelOrigin must be an origin");
5513
5514 let top_level_site = Site::from_origin(&top_level_origin);
5516
5517 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 pub(crate) fn state_override(&self, command_name: &CommandName) -> Option<bool> {
5601 self.state_override.borrow().get(command_name).copied()
5602 }
5603
5604 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 pub(crate) fn value_override(&self, command_name: &CommandName) -> Option<DOMString> {
5615 self.value_override.borrow().get(command_name).cloned()
5616 }
5617
5618 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 pub(crate) fn clear_command_overrides(&self) {
5630 self.state_override.borrow_mut().clear();
5631 self.value_override.borrow_mut().clear();
5632 }
5633
5634 pub(crate) fn default_single_line_container_name(&self) -> DefaultSingleLineContainerName {
5636 self.default_single_line_container_name.get()
5637 }
5638
5639 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 pub(crate) fn css_styling_flag(&self) -> bool {
5649 self.css_styling_flag.get()
5650 }
5651
5652 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 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 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 fn Constructor(
5730 cx: &mut JSContext,
5731 window: &Window,
5732 proto: Option<HandleObject>,
5733 ) -> Fallible<DomRoot<Document>> {
5734 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 fn ParseHTMLUnsafe(
5765 cx: &mut JSContext,
5766 window: &Window,
5767 s: TrustedHTMLOrString,
5768 options: &SetHTMLUnsafeOptions,
5769 ) -> Fallible<DomRoot<Self>> {
5770 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 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 ServoParser::parse_html_document(cx, &document, Some(compliant_html), url, None, None);
5814
5815 let sanitizer = Sanitizer::get_sanitizer_instance_from_options(cx, window, options, false)?;
5818
5819 sanitizer.sanitize(cx, document.upcast(), false)?;
5821
5822 document.update_the_current_document_readiness(cx, DocumentReadyState::Complete);
5824 Ok(document)
5825 }
5826
5827 fn ParseHTML(
5829 cx: &mut JSContext,
5830 window: &Window,
5831 html: DOMString,
5832 options: &SetHTMLOptions,
5833 ) -> Fallible<DomRoot<Document>> {
5834 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 ServoParser::parse_html_document(cx, &document, Some(html), url, None, None);
5868
5869 let sanitizer = Sanitizer::get_sanitizer_instance_from_options(cx, window, options, true)?;
5872
5873 sanitizer.sanitize(cx, document.upcast(), true)?;
5875
5876 Ok(document)
5878 }
5879
5880 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 fn Implementation(&self, cx: &mut JSContext) -> DomRoot<DOMImplementation> {
5893 self.implementation
5894 .or_init(|| DOMImplementation::new(cx, self))
5895 }
5896
5897 fn URL(&self) -> USVString {
5899 USVString(String::from(self.url().as_str()))
5900 }
5901
5902 fn GetActiveElement(&self) -> Option<DomRoot<Element>> {
5904 self.document_or_shadow_root.active_element(self.upcast())
5905 }
5906
5907 fn GetCustomElementRegistry(&self) -> Option<DomRoot<CustomElementRegistry>> {
5909 self.custom_element_registry()
5910 }
5911
5912 fn HasFocus(&self) -> bool {
5914 if !self.window().webview_state().has_system_focus.get() {
5922 return false;
5923 }
5924
5925 if self.window().parent_info().is_none() {
5939 self.is_fully_active()
5941 } else {
5942 self.is_fully_active() && self.focus_handler.has_focus()
5944 }
5945 }
5946
5947 fn Domain(&self) -> DOMString {
5949 match self.origin().effective_domain() {
5951 None => DOMString::new(),
5953 Some(Host::Domain(domain)) => DOMString::from(domain),
5955 Some(host) => DOMString::from(host.to_string()),
5956 }
5957 }
5958
5959 fn SetDomain(&self, value: DOMString) -> ErrorResult {
5961 if !self.has_browsing_context {
5963 return Err(Error::Security(Some(
5964 "Document has no browsing context".into(),
5965 )));
5966 }
5967
5968 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 let effective_domain = match self.origin().effective_domain() {
5980 Some(effective_domain) => effective_domain,
5981 None => return Err(Error::Security(Some("Document's origin is opaque".into()))),
5983 };
5984
5985 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 self.origin().set_domain(host);
5997
5998 Ok(())
5999 }
6000
6001 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 fn DocumentURI(&self) -> USVString {
6011 self.URL()
6012 }
6013
6014 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 fn CharacterSet(&self) -> DOMString {
6024 DOMString::from_static(self.encoding.get().name())
6025 }
6026
6027 fn Charset(&self) -> DOMString {
6029 self.CharacterSet()
6030 }
6031
6032 fn InputEncoding(&self) -> DOMString {
6034 self.CharacterSet()
6035 }
6036
6037 fn ContentType(&self) -> DOMString {
6039 DOMString::from(format!(
6040 "{}/{}",
6041 self.content_type.type_, self.content_type.subtype
6042 ))
6043 }
6044
6045 fn GetDoctype(&self) -> Option<DomRoot<DocumentType>> {
6047 self.upcast::<Node>().children().find_map(DomRoot::downcast)
6048 }
6049
6050 fn GetDocumentElement(&self) -> Option<DomRoot<Element>> {
6052 self.upcast::<Node>().child_elements().next()
6053 }
6054
6055 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 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 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 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 fn CreateElement(
6133 &self,
6134 cx: &mut JSContext,
6135 mut local_name: DOMString,
6136 options: StringOrElementCreationOptions,
6137 ) -> Fallible<DomRoot<Element>> {
6138 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 if self.is_html_document {
6147 local_name.make_ascii_lowercase();
6148 }
6149
6150 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 fn CreateElementNS(
6177 &self,
6178 cx: &mut JSContext,
6179 namespace: Option<DOMString>,
6180 qualified_name: DOMString,
6181 options: StringOrElementCreationOptions,
6182 ) -> Fallible<DomRoot<Element>> {
6183 let context = domname::Context::Element;
6186 let (namespace, prefix, local_name) =
6187 domname::validate_and_extract(namespace, &qualified_name, context)?;
6188
6189 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 Ok(Element::create(
6201 cx,
6202 name,
6203 is,
6204 self,
6205 ElementCreator::ScriptCreated,
6206 CustomElementCreationMode::Synchronous,
6207 None,
6208 ))
6209 }
6210
6211 fn CreateAttribute(
6213 &self,
6214 cx: &mut JSContext,
6215 mut local_name: DOMString,
6216 ) -> Fallible<DomRoot<Attr>> {
6217 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 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 fn CreateAttributeNS(
6245 &self,
6246 cx: &mut JSContext,
6247 namespace: Option<DOMString>,
6248 qualified_name: DOMString,
6249 ) -> Fallible<DomRoot<Attr>> {
6250 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 fn CreateDocumentFragment(&self, cx: &mut JSContext) -> DomRoot<DocumentFragment> {
6271 DocumentFragment::new(cx, self)
6272 }
6273
6274 fn CreateTextNode(&self, cx: &mut JSContext, data: DOMString) -> DomRoot<Text> {
6276 Text::new(cx, data, self)
6277 }
6278
6279 fn CreateCDATASection(
6281 &self,
6282 cx: &mut JSContext,
6283 data: DOMString,
6284 ) -> Fallible<DomRoot<CDATASection>> {
6285 if self.is_html_document {
6287 return Err(Error::NotSupported(Some(
6288 "Document must be an XML document".into(),
6289 )));
6290 }
6291
6292 if data.contains("]]>") {
6294 return Err(Error::InvalidCharacter(Some(
6295 "CDATA section cannot include `]]>`".into(),
6296 )));
6297 }
6298
6299 Ok(CDATASection::new(cx, data, self))
6301 }
6302
6303 fn CreateComment(&self, cx: &mut JSContext, data: DOMString) -> DomRoot<Comment> {
6305 Comment::new(cx, data, self, None)
6306 }
6307
6308 fn CreateProcessingInstruction(
6310 &self,
6311 cx: &mut JSContext,
6312 target: DOMString,
6313 data: DOMString,
6314 ) -> Fallible<DomRoot<ProcessingInstruction>> {
6315 if !matches_name_production(&target.str()) {
6317 return Err(Error::InvalidCharacter(Some(
6318 "Target name provided is invalid".into(),
6319 )));
6320 }
6321
6322 if data.contains("?>") {
6324 return Err(Error::InvalidCharacter(Some(
6325 "Processing instruction's data cannot contain `>?`".into(),
6326 )));
6327 }
6328
6329 Ok(ProcessingInstruction::new(cx, target, data, self))
6331 }
6332
6333 fn ImportNode(
6335 &self,
6336 cx: &mut JSContext,
6337 node: &Node,
6338 options: BooleanOrImportNodeOptions,
6339 ) -> Fallible<DomRoot<Node>> {
6340 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 let (subtree, registry) = match options {
6348 BooleanOrImportNodeOptions::Boolean(boolean) => (boolean.into(), None),
6351 BooleanOrImportNodeOptions::ImportNodeOptions(options) => {
6353 let subtree = (!options.selfOnly).into();
6355 let registry = options.customElementRegistry.as_ref().map(Dom::as_rooted);
6357
6358 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 let registry = registry
6377 .or_else(|| CustomElementRegistry::lookup_a_custom_element_registry(self.upcast()));
6378
6379 Ok(Node::clone(cx, node, Some(self), subtree, registry))
6382 }
6383
6384 fn AdoptNode(&self, cx: &mut JSContext, node: &Node) -> Fallible<DomRoot<Node>> {
6386 if node.is::<Document>() {
6388 return Err(Error::NotSupported(Some(
6389 "Node cannot be a document".into(),
6390 )));
6391 }
6392
6393 if node.is::<ShadowRoot>() {
6395 return Err(Error::HierarchyRequest(Some(
6396 "Node cannot be a shadow root".into(),
6397 )));
6398 }
6399
6400 Node::adopt(cx, node, self);
6402
6403 Ok(DomRoot::from_ref(node))
6405 }
6406
6407 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 "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 fn LastModified(&self) -> DOMString {
6486 DOMString::from(self.last_modified.as_ref().cloned().unwrap_or_else(|| {
6487 Local::now().format("%m/%d/%Y %H:%M:%S").to_string()
6493 }))
6494 }
6495
6496 fn CreateRange(&self, cx: &mut JSContext) -> DomRoot<Range> {
6498 Range::new_with_doc(cx, self, None)
6499 }
6500
6501 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 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 fn Title(&self) -> DOMString {
6525 self.title().unwrap_or_default()
6526 }
6527
6528 fn SetTitle(&self, cx: &mut JSContext, title: DOMString) {
6530 let root = match self.GetDocumentElement() {
6531 Some(root) => root,
6532 None => return,
6533 };
6534
6535 let node = if root.namespace() == &ns!(svg) && root.local_name() == &local_name!("svg") {
6538 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 None => {
6550 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 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 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 Some(elem) => elem.as_rooted(),
6581 None => match self.GetHead() {
6583 Some(head) => {
6584 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 head.upcast::<Node>()
6599 .AppendChild(cx, elem.upcast())
6600 .unwrap()
6601 },
6602 None => return,
6604 },
6605 }
6606 }
6607 else {
6609 return;
6611 };
6612
6613 node.set_text_content_for_element(cx, Some(title));
6618 }
6619
6620 fn Dir(&self) -> DOMString {
6622 self.get_html_element()
6623 .map(|html| html.upcast::<HTMLElement>().Dir())
6624 .unwrap_or_default()
6625 }
6626
6627 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 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 fn GetCurrentScript(&self) -> Option<DomRoot<HTMLScriptElement>> {
6642 self.current_script.get()
6643 }
6644
6645 fn GetBody(&self) -> Option<DomRoot<HTMLElement>> {
6647 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 fn SetBody(&self, cx: &mut JSContext, new_body: Option<&HTMLElement>) -> ErrorResult {
6668 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 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 (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 (None, _) => Err(Error::HierarchyRequest(Some(
6708 "Document element is missing".into(),
6709 ))),
6710
6711 (Some(ref root), &None) => {
6714 let root = root.upcast::<Node>();
6715 root.AppendChild(cx, new_body.upcast()).map(|_| ())
6716 },
6717 }
6718 }
6719
6720 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 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 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 fn Plugins(&self, cx: &mut JSContext) -> DomRoot<HTMLCollection> {
6745 self.Embeds(cx)
6746 }
6747
6748 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 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 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 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 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 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 fn Children(&self, cx: &mut JSContext) -> DomRoot<HTMLCollection> {
6802 HTMLCollection::children(cx, &self.window, self.upcast())
6803 }
6804
6805 fn GetFirstElementChild(&self) -> Option<DomRoot<Element>> {
6807 self.upcast::<Node>().child_elements().next()
6808 }
6809
6810 fn GetLastElementChild(&self) -> Option<DomRoot<Element>> {
6812 self.upcast::<Node>()
6813 .rev_children()
6814 .find_map(DomRoot::downcast)
6815 }
6816
6817 fn ChildElementCount(&self) -> u32 {
6819 self.upcast::<Node>().child_elements().count() as u32
6820 }
6821
6822 fn Prepend(&self, cx: &mut JSContext, nodes: Vec<NodeOrString>) -> ErrorResult {
6824 self.upcast::<Node>().prepend(cx, nodes)
6825 }
6826
6827 fn Append(&self, cx: &mut JSContext, nodes: Vec<NodeOrString>) -> ErrorResult {
6829 self.upcast::<Node>().append(cx, nodes)
6830 }
6831
6832 fn ReplaceChildren(&self, cx: &mut JSContext, nodes: Vec<NodeOrString>) -> ErrorResult {
6834 self.upcast::<Node>().replace_children(cx, nodes)
6835 }
6836
6837 fn MoveBefore(&self, cx: &mut JSContext, node: &Node, child: Option<&Node>) -> ErrorResult {
6839 self.upcast::<Node>().move_before(cx, node, child)
6840 }
6841
6842 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 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 fn ReadyState(&self) -> DocumentReadyState {
6862 self.ready_state.get()
6863 }
6864
6865 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 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 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 fn BgColor(&self) -> DOMString {
6926 self.get_body_attribute(&local_name!("bgcolor"))
6927 }
6928
6929 fn SetBgColor(&self, cx: &mut JSContext, value: DOMString) {
6931 self.set_body_attribute(cx, &local_name!("bgcolor"), value)
6932 }
6933
6934 fn FgColor(&self) -> DOMString {
6936 self.get_body_attribute(&local_name!("text"))
6937 }
6938
6939 fn SetFgColor(&self, cx: &mut JSContext, value: DOMString) {
6941 self.set_body_attribute(cx, &local_name!("text"), value)
6942 }
6943
6944 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 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 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 return Some(NamedPropertyValue::Element(DomRoot::from_ref(first)));
6980 }
6981
6982 #[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 _ => 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 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 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 fn Clear(&self) {
7079 }
7081
7082 fn CaptureEvents(&self) {
7084 }
7086
7087 fn ReleaseEvents(&self) {
7089 }
7091
7092 global_event_handlers!();
7094
7095 event_handler!(
7097 readystatechange,
7098 GetOnreadystatechange,
7099 SetOnreadystatechange
7100 );
7101
7102 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 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 fn GetScrollingElement(&self, cx: &mut JSContext) -> Option<DomRoot<Element>> {
7138 if self.quirks_mode() == QuirksMode::Quirks {
7140 if let Some(ref body) = self.GetBody() {
7142 let e = body.upcast::<Element>();
7143 if !e.is_potentially_scrollable_body_for_scrolling_element(cx) {
7147 return Some(DomRoot::from_ref(e));
7148 }
7149 }
7150
7151 return None;
7153 }
7154
7155 self.GetDocumentElement()
7158 }
7159
7160 fn Open(
7162 &self,
7163 cx: &mut JSContext,
7164 _unused1: Option<DOMString>,
7165 _unused2: Option<DOMString>,
7166 ) -> Fallible<DomRoot<Document>> {
7167 if !self.is_html_document() {
7169 return Err(Error::InvalidState(Some(
7170 "Document must be a HTML document".into(),
7171 )));
7172 }
7173
7174 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 let entry_responsible_document = GlobalScope::entry().as_window().Document();
7185
7186 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 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 if self.is_prompting_or_unloading() {
7208 return Ok(DomRoot::from_ref(self));
7209 }
7210
7211 if self.active_parser_was_aborted.get() {
7213 return Ok(DomRoot::from_ref(self));
7214 }
7215
7216 self.window().set_navigation_start();
7220
7221 if self.has_browsing_context() {
7225 self.abort(cx, AbortReason::DocumentOpen);
7228 }
7229
7230 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 if self.window.Document() == DomRoot::from_ref(self) {
7242 self.window.upcast::<EventTarget>().remove_all_listeners(cx);
7243 }
7244
7245 Node::replace_all(cx, None, self.upcast::<Node>());
7247
7248 if self.is_fully_active() {
7255 let mut new_url = entry_responsible_document.url();
7257
7258 if entry_responsible_document != DomRoot::from_ref(self) {
7260 new_url.set_fragment(None);
7261 }
7262
7263 self.set_url(new_url);
7266 }
7267
7268 self.is_initial_about_blank.set(false);
7270
7271 if self.iframe_load_in_progress.get() {
7274 self.mute_iframe_load.set(true);
7275 }
7276
7277 self.set_quirks_mode(QuirksMode::NoQuirks);
7279
7280 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 self.update_the_current_document_readiness(cx, DocumentReadyState::Loading);
7296
7297 Ok(DomRoot::from_ref(self))
7299 }
7300
7301 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 fn Write(&self, cx: &mut JSContext, text: Vec<TrustedHTMLOrString>) -> ErrorResult {
7324 self.write(cx, text, false, "Document", "write")
7327 }
7328
7329 fn Writeln(&self, cx: &mut JSContext, text: Vec<TrustedHTMLOrString>) -> ErrorResult {
7331 self.write(cx, text, true, "Document", "writeln")
7334 }
7335
7336 fn Close(&self, cx: &mut JSContext) -> ErrorResult {
7338 if !self.is_html_document() {
7339 return Err(Error::InvalidState(Some(
7341 "Document must be a HTML document".into(),
7342 )));
7343 }
7344
7345 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 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(cx);
7364
7365 Ok(())
7366 }
7367
7368 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 fn QueryCommandEnabled(&self, cx: &mut JSContext, command_id: DOMString) -> bool {
7397 self.check_support_and_enabled(cx, &command_id).is_some()
7399 }
7400
7401 fn QueryCommandSupported(&self, command_id: DOMString) -> bool {
7403 self.is_command_supported(command_id)
7407 }
7408
7409 fn QueryCommandIndeterm(&self, cx: &mut JSContext, command_id: DOMString) -> bool {
7411 self.is_command_indeterminate(cx, command_id)
7412 }
7413
7414 fn QueryCommandState(&self, cx: &mut JSContext, command_id: DOMString) -> bool {
7416 self.command_state_for_command(cx, command_id)
7417 }
7418
7419 fn QueryCommandValue(&self, cx: &mut JSContext, command_id: DOMString) -> DOMString {
7421 self.command_value_for_command(cx, command_id)
7422 }
7423
7424 event_handler!(fullscreenerror, GetOnfullscreenerror, SetOnfullscreenerror);
7426
7427 event_handler!(
7429 fullscreenchange,
7430 GetOnfullscreenchange,
7431 SetOnfullscreenchange
7432 );
7433
7434 fn FullscreenEnabled(&self) -> bool {
7436 self.overlay_handler().get_allow_fullscreen()
7437 }
7438
7439 fn Fullscreen(&self) -> bool {
7441 self.overlay_handler().fullscreen_element().is_some()
7442 }
7443
7444 fn GetFullscreenElement(&self) -> Option<DomRoot<Element>> {
7446 DocumentOrShadowRoot::get_fullscreen_element(
7447 &self.node,
7448 self.overlay_handler().fullscreen_element(),
7449 )
7450 }
7451
7452 fn ExitFullscreen(&self, cx: &mut CurrentRealm) -> RootedPromise {
7454 self.overlay_handler().exit_fullscreen(cx)
7455 }
7456
7457 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 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 fn Fonts(&self, cx: &mut JSContext) -> DomRoot<FontFaceSet> {
7480 self.fonts
7481 .or_init(|| FontFaceSet::new(cx, &self.global(), None))
7482 }
7483
7484 fn Hidden(&self) -> bool {
7486 self.visibility_state.get() == DocumentVisibilityState::Hidden
7487 }
7488
7489 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 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 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 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 _ => false,
7700 }
7701}
7702
7703fn is_named_element_with_id_attribute(elem: &Element) -> bool {
7704 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
7716pub(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
7740pub(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}