/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at https://mozilla.org/MPL/2.0/. */ use std::cell::{Cell, RefCell}; use std::cmp::Ordering; use std::collections::hash_map::Entry::{Occupied, Vacant}; use std::collections::{HashMap, HashSet, VecDeque}; use std::default::Default; use std::rc::Rc; use std::str::FromStr; use std::sync::{LazyLock, Mutex}; use std::time::Duration; use base::cross_process_instant::CrossProcessInstant; use base::id::WebViewId; use base::{Epoch, IpcSend, generic_channel}; use canvas_traits::canvas::CanvasId; use canvas_traits::webgl::{WebGLContextId, WebGLMsg}; use chrono::Local; use constellation_traits::{NavigationHistoryBehavior, ScriptToConstellationMessage}; use content_security_policy::sandboxing_directive::SandboxingFlagSet; use content_security_policy::{CspList, PolicyDisposition}; use cookie::Cookie; use cssparser::match_ignore_ascii_case; use data_url::mime::Mime; use devtools_traits::ScriptToDevtoolsControlMsg; use dom_struct::dom_struct; use embedder_traits::{AllowOrDeny, AnimationState, EmbedderMsg, FocusSequenceNumber, LoadStatus}; use encoding_rs::{Encoding, UTF_8}; use euclid::Point2D; use euclid::default::{Rect, Size2D}; use html5ever::{LocalName, Namespace, QualName, local_name, ns}; use hyper_serde::Serde; use js::rust::{HandleObject, HandleValue, MutableHandleValue}; use layout_api::{ PendingRestyle, ReflowGoal, ReflowPhasesRun, RestyleReason, ScrollContainerQueryFlags, TrustedNodeAddress, }; use metrics::{InteractiveFlag, InteractiveWindow, ProgressiveWebMetrics}; use net_traits::CookieSource::NonHTTP; use net_traits::CoreResourceMsg::{GetCookiesForUrl, SetCookiesForUrl}; use net_traits::policy_container::PolicyContainer; use net_traits::pub_domains::is_pub_domain; use net_traits::request::{InsecureRequestsPolicy, RequestBuilder}; use net_traits::response::HttpsState; use net_traits::{FetchResponseListener, ReferrerPolicy}; use percent_encoding::percent_decode; use profile_traits::ipc as profile_ipc; use profile_traits::time::TimerMetadataFrameType; use regex::bytes::Regex; use rustc_hash::{FxBuildHasher, FxHashMap}; use script_bindings::codegen::GenericBindings::ElementBinding::ElementMethods; use script_bindings::interfaces::DocumentHelpers; use script_bindings::script_runtime::JSContext; use script_traits::{DocumentActivity, ProgressiveWebMetricType}; use servo_arc::Arc; use servo_config::pref; use servo_media::{ClientContextId, ServoMedia}; use servo_url::{ImmutableOrigin, MutableOrigin, ServoUrl}; use style::attr::AttrValue; use style::context::QuirksMode; use style::invalidation::element::restyle_hints::RestyleHint; use style::selector_parser::Snapshot; use style::shared_lock::SharedRwLock as StyleSharedRwLock; use style::str::{split_html_space_chars, str_join}; use style::stylesheet_set::DocumentStylesheetSet; use style::stylesheets::{Origin, OriginSet, Stylesheet}; use stylo_atoms::Atom; use url::Host; use uuid::Uuid; #[cfg(feature = "webgpu")] use webgpu_traits::WebGPUContextId; use webrender_api::units::DeviceIntRect; use crate::animation_timeline::AnimationTimeline; use crate::animations::Animations; use crate::canvas_context::CanvasContext as _; use crate::document_loader::{DocumentLoader, LoadType}; use crate::dom::attr::Attr; use crate::dom::beforeunloadevent::BeforeUnloadEvent; use crate::dom::bindings::callback::ExceptionHandling; use crate::dom::bindings::cell::{DomRefCell, Ref, RefMut}; use crate::dom::bindings::codegen::Bindings::BeforeUnloadEventBinding::BeforeUnloadEvent_Binding::BeforeUnloadEventMethods; use crate::dom::bindings::codegen::Bindings::DocumentBinding::{ DocumentMethods, DocumentReadyState, DocumentVisibilityState, NamedPropertyValue, }; use crate::dom::bindings::codegen::Bindings::ElementBinding::{ ScrollIntoViewContainer, ScrollIntoViewOptions, ScrollLogicalPosition, }; use crate::dom::bindings::codegen::Bindings::EventBinding::Event_Binding::EventMethods; use crate::dom::bindings::codegen::Bindings::HTMLIFrameElementBinding::HTMLIFrameElement_Binding::HTMLIFrameElementMethods; use crate::dom::bindings::codegen::Bindings::HTMLInputElementBinding::HTMLInputElementMethods; use crate::dom::bindings::codegen::Bindings::HTMLOrSVGElementBinding::FocusOptions; use crate::dom::bindings::codegen::Bindings::HTMLTextAreaElementBinding::HTMLTextAreaElementMethods; use crate::dom::bindings::codegen::Bindings::NavigatorBinding::Navigator_Binding::NavigatorMethods; use crate::dom::bindings::codegen::Bindings::NodeBinding::NodeMethods; use crate::dom::bindings::codegen::Bindings::NodeFilterBinding::NodeFilter; use crate::dom::bindings::codegen::Bindings::PerformanceBinding::PerformanceMethods; use crate::dom::bindings::codegen::Bindings::PermissionStatusBinding::PermissionName; use crate::dom::bindings::codegen::Bindings::WindowBinding::{ FrameRequestCallback, ScrollBehavior, ScrollOptions, WindowMethods, }; use crate::dom::bindings::codegen::Bindings::XPathEvaluatorBinding::XPathEvaluatorMethods; use crate::dom::bindings::codegen::Bindings::XPathNSResolverBinding::XPathNSResolver; use crate::dom::bindings::codegen::UnionTypes::{ BooleanOrScrollIntoViewOptions, NodeOrString, StringOrElementCreationOptions, TrustedHTMLOrString, }; use crate::dom::bindings::domname::{ self, is_valid_attribute_local_name, is_valid_element_local_name, namespace_from_domstring, }; use crate::dom::bindings::error::{Error, ErrorInfo, ErrorResult, Fallible}; use crate::dom::bindings::frozenarray::CachedFrozenArray; use crate::dom::bindings::inheritance::{Castable, ElementTypeId, HTMLElementTypeId, NodeTypeId}; use crate::dom::bindings::num::Finite; use crate::dom::bindings::refcounted::{Trusted, TrustedPromise}; use crate::dom::bindings::reflector::{DomGlobal, reflect_dom_object_with_proto}; use crate::dom::bindings::root::{Dom, DomRoot, LayoutDom, MutNullableDom, ToLayout}; use crate::dom::bindings::str::{DOMString, USVString}; use crate::dom::bindings::trace::{HashMapTracedValues, NoTrace}; use crate::dom::bindings::xmlname::matches_name_production; use crate::dom::canvasrenderingcontext2d::CanvasRenderingContext2D; use crate::dom::cdatasection::CDATASection; use crate::dom::comment::Comment; use crate::dom::compositionevent::CompositionEvent; use crate::dom::cssstylesheet::CSSStyleSheet; use crate::dom::customelementregistry::{CustomElementDefinition, CustomElementReactionStack}; use crate::dom::customevent::CustomEvent; use crate::dom::document_event_handler::DocumentEventHandler; use crate::dom::documentfragment::DocumentFragment; use crate::dom::documentorshadowroot::{ DocumentOrShadowRoot, ServoStylesheetInDocument, StylesheetSource, }; use crate::dom::documenttype::DocumentType; use crate::dom::domimplementation::DOMImplementation; use crate::dom::element::{ CustomElementCreationMode, Element, ElementCreator, ElementPerformFullscreenEnter, ElementPerformFullscreenExit, }; use crate::dom::event::{Event, EventBubbles, EventCancelable}; use crate::dom::eventtarget::EventTarget; use crate::dom::focusevent::FocusEvent; use crate::dom::fontfaceset::FontFaceSet; use crate::dom::globalscope::GlobalScope; use crate::dom::hashchangeevent::HashChangeEvent; use crate::dom::html::htmlanchorelement::HTMLAnchorElement; use crate::dom::html::htmlareaelement::HTMLAreaElement; use crate::dom::html::htmlbaseelement::HTMLBaseElement; use crate::dom::html::htmlcollection::{CollectionFilter, HTMLCollection}; use crate::dom::html::htmlelement::HTMLElement; use crate::dom::html::htmlembedelement::HTMLEmbedElement; use crate::dom::html::htmlformelement::{FormControl, FormControlElementHelpers, HTMLFormElement}; use crate::dom::html::htmlheadelement::HTMLHeadElement; use crate::dom::html::htmlhtmlelement::HTMLHtmlElement; use crate::dom::html::htmliframeelement::HTMLIFrameElement; use crate::dom::html::htmlimageelement::HTMLImageElement; use crate::dom::html::htmlinputelement::HTMLInputElement; use crate::dom::html::htmlscriptelement::{HTMLScriptElement, ScriptResult}; use crate::dom::html::htmltextareaelement::HTMLTextAreaElement; use crate::dom::html::htmltitleelement::HTMLTitleElement; use crate::dom::intersectionobserver::IntersectionObserver; use crate::dom::keyboardevent::KeyboardEvent; use crate::dom::location::{Location, NavigationType}; use crate::dom::messageevent::MessageEvent; use crate::dom::mouseevent::MouseEvent; use crate::dom::node::{ CloneChildrenFlag, Node, NodeDamage, NodeFlags, NodeTraits, ShadowIncluding, }; use crate::dom::nodeiterator::NodeIterator; use crate::dom::nodelist::NodeList; use crate::dom::pagetransitionevent::PageTransitionEvent; use crate::dom::performanceentry::PerformanceEntry; use crate::dom::performancepainttiming::PerformancePaintTiming; use crate::dom::processinginstruction::ProcessingInstruction; use crate::dom::promise::Promise; use crate::dom::range::Range; use crate::dom::resizeobserver::{ResizeObservationDepth, ResizeObserver}; use crate::dom::scrolling_box::ScrollingBox; use crate::dom::selection::Selection; use crate::dom::servoparser::ServoParser; use crate::dom::shadowroot::ShadowRoot; use crate::dom::storageevent::StorageEvent; use crate::dom::stylesheetlist::{StyleSheetList, StyleSheetListOwner}; use crate::dom::text::Text; use crate::dom::touchevent::TouchEvent as DomTouchEvent; use crate::dom::touchlist::TouchList; use crate::dom::treewalker::TreeWalker; use crate::dom::trustedhtml::TrustedHTML; use crate::dom::types::VisibilityStateEntry; use crate::dom::uievent::UIEvent; use crate::dom::virtualmethods::vtable_for; use crate::dom::webgl::webglrenderingcontext::WebGLRenderingContext; #[cfg(feature = "webgpu")] use crate::dom::webgpu::gpucanvascontext::GPUCanvasContext; use crate::dom::window::Window; use crate::dom::windowproxy::WindowProxy; use crate::dom::xpathevaluator::XPathEvaluator; use crate::fetch::FetchCanceller; use crate::iframe_collection::IFrameCollection; use crate::image_animation::ImageAnimationManager; use crate::messaging::{CommonScriptMsg, MainThreadScriptMsg}; use crate::mime::{APPLICATION, CHARSET}; use crate::network_listener::{NetworkListener, PreInvoke}; use crate::realms::{AlreadyInRealm, InRealm, enter_realm}; use crate::script_runtime::{CanGc, ScriptThreadEventCategory}; use crate::script_thread::ScriptThread; use crate::stylesheet_set::StylesheetSetRef; use crate::task::NonSendTaskBox; use crate::task_source::TaskSourceName; use crate::timers::OneshotTimerCallback; pub(crate) enum TouchEventResult { Processed(bool), Forwarded, } #[derive(Clone, Copy, PartialEq)] pub(crate) enum FireMouseEventType { Move, Over, Out, Enter, Leave, } impl FireMouseEventType { pub(crate) fn as_str(&self) -> &str { match *self { FireMouseEventType::Move => "mousemove", FireMouseEventType::Over => "mouseover", FireMouseEventType::Out => "mouseout", FireMouseEventType::Enter => "mouseenter", FireMouseEventType::Leave => "mouseleave", } } } #[derive(JSTraceable, MallocSizeOf)] pub(crate) struct RefreshRedirectDue { #[no_trace] pub(crate) url: ServoUrl, #[ignore_malloc_size_of = "non-owning"] pub(crate) window: DomRoot, } impl RefreshRedirectDue { pub(crate) fn invoke(self, can_gc: CanGc) { self.window.Location().navigate( self.url.clone(), NavigationHistoryBehavior::Replace, NavigationType::DeclarativeRefresh, can_gc, ); } } #[derive(Clone, Copy, Debug, JSTraceable, MallocSizeOf, PartialEq)] pub(crate) enum IsHTMLDocument { HTMLDocument, NonHTMLDocument, } #[derive(JSTraceable, MallocSizeOf)] #[cfg_attr(crown, crown::unrooted_must_root_lint::must_root)] struct FocusTransaction { /// The focused element of this document. element: Option>, /// See [`Document::has_focus`]. has_focus: bool, /// Focus options for the transaction focus_options: FocusOptions, } /// Information about a declarative refresh #[derive(JSTraceable, MallocSizeOf)] pub(crate) enum DeclarativeRefresh { PendingLoad { #[no_trace] url: ServoUrl, time: u64, }, CreatedAfterLoad, } /// #[dom_struct] pub(crate) struct Document { node: Node, document_or_shadow_root: DocumentOrShadowRoot, window: Dom, implementation: MutNullableDom, #[ignore_malloc_size_of = "type from external crate"] #[no_trace] content_type: Mime, last_modified: Option, #[no_trace] encoding: Cell<&'static Encoding>, has_browsing_context: bool, is_html_document: bool, #[no_trace] activity: Cell, #[no_trace] url: DomRefCell, #[ignore_malloc_size_of = "defined in selectors"] #[no_trace] quirks_mode: Cell, /// A helper used to process and store data related to input event handling. event_handler: DocumentEventHandler, /// Caches for the getElement methods. It is safe to use FxHash for these maps /// as Atoms are `string_cache` items that will have the hash computed from a u32. id_map: DomRefCell>, FxBuildHasher>>, name_map: DomRefCell>, FxBuildHasher>>, tag_map: DomRefCell, FxBuildHasher>>, tagns_map: DomRefCell, FxBuildHasher>>, classes_map: DomRefCell, Dom>>, images: MutNullableDom, embeds: MutNullableDom, links: MutNullableDom, forms: MutNullableDom, scripts: MutNullableDom, anchors: MutNullableDom, applets: MutNullableDom, /// Information about the `` in this [`Document`]. iframes: RefCell, /// Lock use for style attributes and author-origin stylesheet objects in this document. /// Can be acquired once for accessing many objects. #[no_trace] style_shared_lock: StyleSharedRwLock, /// List of stylesheets associated with nodes in this document. |None| if the list needs to be refreshed. #[custom_trace] stylesheets: DomRefCell>, stylesheet_list: MutNullableDom, ready_state: Cell, /// Whether the DOMContentLoaded event has already been dispatched. domcontentloaded_dispatched: Cell, /// The state of this document's focus transaction. focus_transaction: DomRefCell>, /// The element that currently has the document focus context. focused: MutNullableDom, /// The last sequence number sent to the constellation. #[no_trace] focus_sequence: Cell, /// Indicates whether the container is included in the top-level browsing /// context's focus chain (not considering system focus). Permanently `true` /// for a top-level document. has_focus: Cell, /// The script element that is currently executing. current_script: MutNullableDom, /// pending_parsing_blocking_script: DomRefCell>, /// Number of stylesheets that block executing the next parser-inserted script script_blocking_stylesheets_count: Cell, /// deferred_scripts: PendingInOrderScriptVec, /// asap_in_order_scripts_list: PendingInOrderScriptVec, /// asap_scripts_set: DomRefCell>>, /// /// Current identifier of animation frame callback animation_frame_ident: Cell, /// /// List of animation frame callbacks animation_frame_list: DomRefCell)>>, /// Whether we're in the process of running animation callbacks. /// /// Tracking this is not necessary for correctness. Instead, it is an optimization to avoid /// sending needless `ChangeRunningAnimationsState` messages to the compositor. running_animation_callbacks: Cell, /// Tracks all outstanding loads related to this document. loader: DomRefCell, /// The current active HTML parser, to allow resuming after interruptions. current_parser: MutNullableDom, /// The cached first `base` element with an `href` attribute. base_element: MutNullableDom, /// This field is set to the document itself for inert documents. /// appropriate_template_contents_owner_document: MutNullableDom, /// Information on elements needing restyle to ship over to layout when the /// time comes. pending_restyles: DomRefCell, NoTrace>>, /// A collection of reasons that the [`Document`] needs to be restyled at the next /// opportunity for a reflow. If this is empty, then the [`Document`] does not need to /// be restyled. #[no_trace] needs_restyle: Cell, /// Navigation Timing properties: /// #[no_trace] dom_interactive: Cell>, #[no_trace] dom_content_loaded_event_start: Cell>, #[no_trace] dom_content_loaded_event_end: Cell>, #[no_trace] dom_complete: Cell>, #[no_trace] top_level_dom_complete: Cell>, #[no_trace] load_event_start: Cell>, #[no_trace] load_event_end: Cell>, #[no_trace] unload_event_start: Cell>, #[no_trace] unload_event_end: Cell>, /// #[no_trace] https_state: Cell, /// The document's origin. #[no_trace] origin: MutableOrigin, /// referrer: Option, /// target_element: MutNullableDom, /// #[no_trace] policy_container: DomRefCell, /// ignore_destructive_writes_counter: Cell, /// ignore_opens_during_unload_counter: Cell, /// The number of spurious `requestAnimationFrame()` requests we've received. /// /// A rAF request is considered spurious if nothing was actually reflowed. spurious_animation_frames: Cell, /// Track the total number of elements in this DOM's tree. /// This is sent to layout every time a reflow is done; /// layout uses this to determine if the gains from parallel layout will be worth the overhead. /// /// See also: dom_count: Cell, /// Entry node for fullscreen. fullscreen_element: MutNullableDom, /// Map from ID to set of form control elements that have that ID as /// their 'form' content attribute. Used to reset form controls /// whenever any element with the same ID as the form attribute /// is inserted or removed from the document. /// See /// It is safe to use FxBuildHasher here as Atoms are in the string_cache form_id_listener_map: DomRefCell>, FxBuildHasher>>, #[no_trace] interactive_time: DomRefCell, #[no_trace] tti_window: DomRefCell, /// RAII canceller for Fetch canceller: FetchCanceller, /// throw_on_dynamic_markup_insertion_counter: Cell, /// page_showing: Cell, /// Whether the document is salvageable. salvageable: Cell, /// Whether the document was aborted with an active parser active_parser_was_aborted: Cell, /// Whether the unload event has already been fired. fired_unload: Cell, /// List of responsive images responsive_images: DomRefCell>>, /// Number of redirects for the document load redirect_count: Cell, /// Number of outstanding requests to prevent JS or layout from running. script_and_layout_blockers: Cell, /// List of tasks to execute as soon as last script/layout blocker is removed. #[ignore_malloc_size_of = "Measuring trait objects is hard"] delayed_tasks: DomRefCell>>, /// completely_loaded: Cell, /// Set of shadow roots connected to the document tree. shadow_roots: DomRefCell>>, /// Whether any of the shadow roots need the stylesheets flushed. shadow_roots_styles_changed: Cell, /// List of registered media controls. /// We need to keep this list to allow the media controls to /// access the "privileged" document.servoGetMediaControls(id) API, /// where `id` needs to match any of the registered ShadowRoots /// hosting the media controls UI. media_controls: DomRefCell>>, /// List of all context 2d IDs that need flushing. dirty_2d_contexts: DomRefCell, FxBuildHasher>>, /// List of all WebGL context IDs that need flushing. dirty_webgl_contexts: DomRefCell, FxBuildHasher>>, /// Whether or not animated images need to have their contents updated. has_pending_animated_image_update: Cell, /// List of all WebGPU contexts that need flushing. #[cfg(feature = "webgpu")] dirty_webgpu_contexts: DomRefCell, FxBuildHasher>>, /// selection: MutNullableDom, /// A timeline for animations which is used for synchronizing animations. /// animation_timeline: DomRefCell, /// Animations for this Document animations: DomRefCell, /// Image Animation Manager for this Document image_animation_manager: DomRefCell, /// The nearest inclusive ancestors to all the nodes that require a restyle. dirty_root: MutNullableDom, /// declarative_refresh: DomRefCell>, /// /// /// Note: we are storing, but never removing, resize observers. /// The lifetime of resize observers is specified at /// . /// But implementing it comes with known problems: /// - /// - resize_observers: DomRefCell>>, /// The set of all fonts loaded by this document. /// fonts: MutNullableDom, /// visibility_state: Cell, /// status_code: Option, /// is_initial_about_blank: Cell, /// allow_declarative_shadow_roots: Cell, /// #[no_trace] inherited_insecure_requests_policy: Cell>, //// has_trustworthy_ancestor_origin: Cell, /// intersection_observer_task_queued: Cell, /// Active intersection observers that should be processed by this document in /// the update intersection observation steps. /// /// > Let observer list be a list of all IntersectionObservers whose root is in the DOM tree of document. /// > For the top-level browsing context, this includes implicit root observers. /// /// Details of which document that should process an observers is discussed further at /// . /// /// The lifetime of an intersection observer is specified at /// . intersection_observers: DomRefCell>>, /// The node that is currently highlighted by the devtools highlighted_dom_node: MutNullableDom, /// The constructed stylesheet that is adopted by this [Document]. /// adopted_stylesheets: DomRefCell>>, /// Cached frozen array of [`Self::adopted_stylesheets`] #[ignore_malloc_size_of = "mozjs"] adopted_stylesheets_frozen_types: CachedFrozenArray, /// pending_scroll_event_targets: DomRefCell>>, /// When a `ResizeObserver` starts observing a target, this becomes true, which in turn is a /// signal to the [`ScriptThread`] that a rendering update should happen. resize_observer_started_observing_target: Cell, /// Whether or not this [`Document`] is waiting on canvas image updates. If it is /// waiting it will not do any new layout until the canvas images are up-to-date in /// the renderer. waiting_on_canvas_image_updates: Cell, /// The current canvas epoch, which is used to track when canvas images have been /// uploaded to the renderer after a rendering update. Until those images are uploaded /// this `Document` will not perform any more rendering updates. #[no_trace] current_canvas_epoch: RefCell, /// The global custom element reaction stack for this script thread. #[conditional_malloc_size_of] custom_element_reaction_stack: Rc, #[no_trace] #[ignore_malloc_size_of = "type from external crate"] /// , active_sandboxing_flag_set: Cell, } #[allow(non_snake_case)] impl Document { pub(crate) fn note_node_with_dirty_descendants(&self, node: &Node) { debug_assert!(*node.owner_doc() == *self); if !node.is_connected() { return; } let parent = match node.parent_in_flat_tree() { Some(parent) => parent, None => { // There is no parent so this is the Document node, so we // behave as if we were called with the document element. let document_element = match self.GetDocumentElement() { Some(element) => element, None => return, }; if let Some(dirty_root) = self.dirty_root.get() { // There was an existing dirty root so we mark its // ancestors as dirty until the document element. for ancestor in dirty_root .upcast::() .inclusive_ancestors_in_flat_tree() { if ancestor.is::() { ancestor.set_flag(NodeFlags::HAS_DIRTY_DESCENDANTS, true); } } } self.dirty_root.set(Some(&document_element)); return; }, }; if parent.is::() { if !parent.is_styled() { return; } if parent.is_display_none() { return; } } let element_parent: DomRoot; let element = match node.downcast::() { Some(element) => element, None => { // Current node is not an element, it's probably a text node, // we try to get its element parent. match DomRoot::downcast::(parent) { Some(parent) => { element_parent = parent; &element_parent }, None => { // Parent is not an element so it must be a document, // and this is not an element either, so there is // nothing to do. return; }, } }, }; let dirty_root = match self.dirty_root.get() { None => { element .upcast::() .set_flag(NodeFlags::HAS_DIRTY_DESCENDANTS, true); self.dirty_root.set(Some(element)); return; }, Some(root) => root, }; for ancestor in element.upcast::().inclusive_ancestors_in_flat_tree() { if ancestor.get_flag(NodeFlags::HAS_DIRTY_DESCENDANTS) { return; } if ancestor.is::() { ancestor.set_flag(NodeFlags::HAS_DIRTY_DESCENDANTS, true); } } let new_dirty_root = element .upcast::() .common_ancestor_in_flat_tree(dirty_root.upcast()) .expect("Couldn't find common ancestor"); let mut has_dirty_descendants = true; for ancestor in dirty_root .upcast::() .inclusive_ancestors_in_flat_tree() { ancestor.set_flag(NodeFlags::HAS_DIRTY_DESCENDANTS, has_dirty_descendants); has_dirty_descendants &= *ancestor != *new_dirty_root; } self.dirty_root .set(Some(new_dirty_root.downcast::().unwrap())); } pub(crate) fn take_dirty_root(&self) -> Option> { self.dirty_root.take() } #[inline] pub(crate) fn loader(&self) -> Ref<'_, DocumentLoader> { self.loader.borrow() } #[inline] pub(crate) fn loader_mut(&self) -> RefMut<'_, DocumentLoader> { self.loader.borrow_mut() } #[inline] pub(crate) fn has_browsing_context(&self) -> bool { self.has_browsing_context } /// #[inline] pub(crate) fn browsing_context(&self) -> Option> { if self.has_browsing_context { self.window.undiscarded_window_proxy() } else { None } } pub(crate) fn webview_id(&self) -> WebViewId { self.window.webview_id() } #[inline] pub(crate) fn window(&self) -> &Window { &self.window } #[inline] pub(crate) fn is_html_document(&self) -> bool { self.is_html_document } pub(crate) fn is_xhtml_document(&self) -> bool { self.content_type.matches(APPLICATION, "xhtml+xml") } pub(crate) fn set_https_state(&self, https_state: HttpsState) { self.https_state.set(https_state); } pub(crate) fn is_fully_active(&self) -> bool { self.activity.get() == DocumentActivity::FullyActive } pub(crate) fn is_active(&self) -> bool { self.activity.get() != DocumentActivity::Inactive } pub(crate) fn set_activity(&self, activity: DocumentActivity, can_gc: CanGc) { // This function should only be called on documents with a browsing context assert!(self.has_browsing_context); if activity == self.activity.get() { return; } // Set the document's activity level, reflow if necessary, and suspend or resume timers. self.activity.set(activity); let media = ServoMedia::get(); let pipeline_id = self.window().pipeline_id(); let client_context_id = ClientContextId::build(pipeline_id.namespace_id.0, pipeline_id.index.0.get()); if activity != DocumentActivity::FullyActive { self.window().suspend(can_gc); media.suspend(&client_context_id); return; } self.title_changed(); self.dirty_all_nodes(); self.window().resume(can_gc); media.resume(&client_context_id); if self.ready_state.get() != DocumentReadyState::Complete { return; } // This step used to be Step 4.6 in html.spec.whatwg.org/multipage/#history-traversal // But it's now Step 4 in https://html.spec.whatwg.org/multipage/#reactivate-a-document // TODO: See #32687 for more information. let document = Trusted::new(self); self.owner_global() .task_manager() .dom_manipulation_task_source() .queue(task!(fire_pageshow_event: move || { let document = document.root(); let window = document.window(); // Step 4.6.1 if document.page_showing.get() { return; } // Step 4.6.2 Set document's page showing flag to true. document.page_showing.set(true); // Step 4.6.3 Update the visibility state of document to "visible". document.update_visibility_state(DocumentVisibilityState::Visible, CanGc::note()); // Step 4.6.4 Fire a page transition event named pageshow at document's relevant // global object with true. let event = PageTransitionEvent::new( window, atom!("pageshow"), false, // bubbles false, // cancelable true, // persisted CanGc::note(), ); let event = event.upcast::(); event.set_trusted(true); window.dispatch_event_with_target_override(event, CanGc::note()); })) } pub(crate) fn origin(&self) -> &MutableOrigin { &self.origin } /// pub(crate) fn url(&self) -> ServoUrl { self.url.borrow().clone() } pub(crate) fn set_url(&self, url: ServoUrl) { *self.url.borrow_mut() = url; } /// pub(crate) fn fallback_base_url(&self) -> ServoUrl { let document_url = self.url(); if let Some(browsing_context) = self.browsing_context() { // Step 1: If document is an iframe srcdoc document, then return the // document base URL of document's browsing context's container document. let container_base_url = browsing_context .parent() .and_then(|parent| parent.document()) .map(|document| document.base_url()); if document_url.as_str() == "about:srcdoc" { if let Some(base_url) = container_base_url { return base_url; } } // Step 2: If document's URL is about:blank, and document's browsing // context's creator base URL is non-null, then return that creator base URL. if document_url.as_str() == "about:blank" && browsing_context.has_creator_base_url() { return browsing_context.creator_base_url().unwrap(); } } // Step 3: Return document's URL. document_url } /// pub(crate) fn base_url(&self) -> ServoUrl { match self.base_element() { // Step 1. None => self.fallback_base_url(), // Step 2. Some(base) => base.frozen_base_url(), } } pub(crate) fn add_restyle_reason(&self, reason: RestyleReason) { self.needs_restyle.set(self.needs_restyle.get() | reason) } pub(crate) fn clear_restyle_reasons(&self) { self.needs_restyle.set(RestyleReason::empty()); } pub(crate) fn restyle_reason(&self) -> RestyleReason { let mut condition = self.needs_restyle.get(); if self.stylesheets.borrow().has_changed() { condition.insert(RestyleReason::StylesheetsChanged); } // FIXME: This should check the dirty bit on the document, // not the document element. Needs some layout changes to make // that workable. if let Some(root) = self.GetDocumentElement() { if root.upcast::().has_dirty_descendants() { condition.insert(RestyleReason::DOMChanged); } } if !self.pending_restyles.borrow().is_empty() { condition.insert(RestyleReason::PendingRestyles); } condition } /// Returns the first `base` element in the DOM that has an `href` attribute. pub(crate) fn base_element(&self) -> Option> { self.base_element.get() } /// Refresh the cached first base element in the DOM. /// pub(crate) fn refresh_base_element(&self) { let base = self .upcast::() .traverse_preorder(ShadowIncluding::No) .filter_map(DomRoot::downcast::) .find(|element| { element .upcast::() .has_attribute(&local_name!("href")) }); self.base_element.set(base.as_deref()); } pub(crate) fn dom_count(&self) -> u32 { self.dom_count.get() } /// This is called by `bind_to_tree` when a node is added to the DOM. /// The internal count is used by layout to determine whether to be sequential or parallel. /// (it's sequential for small DOMs) pub(crate) fn increment_dom_count(&self) { self.dom_count.set(self.dom_count.get() + 1); } /// This is called by `unbind_from_tree` when a node is removed from the DOM. pub(crate) fn decrement_dom_count(&self) { self.dom_count.set(self.dom_count.get() - 1); } pub(crate) fn quirks_mode(&self) -> QuirksMode { self.quirks_mode.get() } pub(crate) fn set_quirks_mode(&self, new_mode: QuirksMode) { let old_mode = self.quirks_mode.replace(new_mode); if old_mode != new_mode { self.window.layout_mut().set_quirks_mode(new_mode); } } pub(crate) fn encoding(&self) -> &'static Encoding { self.encoding.get() } pub(crate) fn set_encoding(&self, encoding: &'static Encoding) { self.encoding.set(encoding); } pub(crate) fn content_and_heritage_changed(&self, node: &Node) { if node.is_connected() { node.note_dirty_descendants(); } // FIXME(emilio): This is very inefficient, ideally the flag above would // be enough and incremental layout could figure out from there. node.dirty(NodeDamage::ContentOrHeritage); } /// Remove any existing association between the provided id and any elements in this document. pub(crate) fn unregister_element_id(&self, to_unregister: &Element, id: Atom, can_gc: CanGc) { self.document_or_shadow_root .unregister_named_element(&self.id_map, to_unregister, &id); self.reset_form_owner_for_listeners(&id, can_gc); } /// Associate an element present in this document with the provided id. pub(crate) fn register_element_id(&self, element: &Element, id: Atom, can_gc: CanGc) { let root = self.GetDocumentElement().expect( "The element is in the document, so there must be a document \ element.", ); self.document_or_shadow_root.register_named_element( &self.id_map, element, &id, DomRoot::from_ref(root.upcast::()), ); self.reset_form_owner_for_listeners(&id, can_gc); } /// Remove any existing association between the provided name and any elements in this document. pub(crate) fn unregister_element_name(&self, to_unregister: &Element, name: Atom) { self.document_or_shadow_root .unregister_named_element(&self.name_map, to_unregister, &name); } /// Associate an element present in this document with the provided name. pub(crate) fn register_element_name(&self, element: &Element, name: Atom) { let root = self.GetDocumentElement().expect( "The element is in the document, so there must be a document \ element.", ); self.document_or_shadow_root.register_named_element( &self.name_map, element, &name, DomRoot::from_ref(root.upcast::()), ); } pub(crate) fn register_form_id_listener( &self, id: DOMString, listener: &T, ) { let mut map = self.form_id_listener_map.borrow_mut(); let listener = listener.to_element(); let set = map.entry(Atom::from(id)).or_default(); set.insert(Dom::from_ref(listener)); } pub(crate) fn unregister_form_id_listener( &self, id: DOMString, listener: &T, ) { let mut map = self.form_id_listener_map.borrow_mut(); if let Occupied(mut entry) = map.entry(Atom::from(id)) { entry .get_mut() .remove(&Dom::from_ref(listener.to_element())); if entry.get().is_empty() { entry.remove(); } } } /// Attempt to find a named element in this page's document. /// pub(crate) fn find_fragment_node(&self, fragid: &str) -> Option> { // Step 1 is not handled here; the fragid is already obtained by the calling function // Step 2: Simply use None to indicate the top of the document. // Step 3 & 4 percent_decode(fragid.as_bytes()) .decode_utf8() .ok() // Step 5 .and_then(|decoded_fragid| self.get_element_by_id(&Atom::from(decoded_fragid))) // Step 6 .or_else(|| self.get_anchor_by_name(fragid)) // Step 7 & 8 } /// Scroll to the target element, and when we do not find a target /// and the fragment is empty or "top", scroll to the top. /// pub(crate) fn check_and_scroll_fragment(&self, fragment: &str) { let target = self.find_fragment_node(fragment); // Step 1 self.set_target_element(target.as_deref()); let point = target .as_ref() .map(|element| { // TODO: This strategy is completely wrong if the element we are scrolling to in // inside other scrollable containers. Ideally this should use an implementation of // `scrollIntoView` when that is available: // See https://github.com/servo/servo/issues/24059. let rect = element.upcast::().border_box().unwrap_or_default(); // In order to align with element edges, we snap to unscaled pixel boundaries, since // the paint thread currently does the same for drawing elements. This is important // for pages that require pixel perfect scroll positioning for proper display // (like Acid2). let device_pixel_ratio = self.window.device_pixel_ratio().get(); ( rect.origin.x.to_nearest_pixel(device_pixel_ratio), rect.origin.y.to_nearest_pixel(device_pixel_ratio), ) }) .or_else(|| { if fragment.is_empty() || fragment.eq_ignore_ascii_case("top") { // FIXME(stshine): this should be the origin of the stacking context space, // which may differ under the influence of writing mode. Some((0.0, 0.0)) } else { None } }); if let Some((x, y)) = point { self.window.scroll(x, y, ScrollBehavior::Instant) } } fn get_anchor_by_name(&self, name: &str) -> Option> { let name = Atom::from(name); self.name_map.borrow().get(&name).and_then(|elements| { elements .iter() .find(|e| e.is::()) .map(|e| DomRoot::from_ref(&**e)) }) } // https://html.spec.whatwg.org/multipage/#current-document-readiness pub(crate) fn set_ready_state(&self, state: DocumentReadyState, can_gc: CanGc) { match state { DocumentReadyState::Loading => { if self.window().is_top_level() { self.send_to_embedder(EmbedderMsg::NotifyLoadStatusChanged( self.webview_id(), LoadStatus::Started, )); self.send_to_embedder(EmbedderMsg::Status(self.webview_id(), None)); } }, DocumentReadyState::Complete => { if self.window().is_top_level() { self.send_to_embedder(EmbedderMsg::NotifyLoadStatusChanged( self.webview_id(), LoadStatus::Complete, )); } update_with_current_instant(&self.dom_complete); }, DocumentReadyState::Interactive => update_with_current_instant(&self.dom_interactive), }; self.ready_state.set(state); self.upcast::() .fire_event(atom!("readystatechange"), can_gc); } /// Return whether scripting is enabled or not /// pub(crate) fn scripting_enabled(&self) -> bool { // Scripting is enabled for a node node if node's node document's browsing context is non-null, // and scripting is enabled for node's relevant settings object. self.has_browsing_context() && // Either settings's global object is not a Window object, // or settings's global object's associated Document's active sandboxing flag // set does not have its sandboxed scripts browsing context flag set. !self.has_active_sandboxing_flag( SandboxingFlagSet::SANDBOXED_SCRIPTS_BROWSING_CONTEXT_FLAG, ) } /// Return the element that currently has focus. // https://w3c.github.io/uievents/#events-focusevent-doc-focus pub(crate) fn get_focused_element(&self) -> Option> { self.focused.get() } /// Get the last sequence number sent to the constellation. /// /// Received focus-related messages with sequence numbers less than the one /// returned by this method must be discarded. pub fn get_focus_sequence(&self) -> FocusSequenceNumber { self.focus_sequence.get() } /// Generate the next sequence number for focus-related messages. fn increment_fetch_focus_sequence(&self) -> FocusSequenceNumber { self.focus_sequence.set(FocusSequenceNumber( self.focus_sequence .get() .0 .checked_add(1) .expect("too many focus messages have been sent"), )); self.focus_sequence.get() } pub(crate) fn has_focus_transaction(&self) -> bool { self.focus_transaction.borrow().is_some() } /// Initiate a new round of checking for elements requesting focus. The last element to call /// `request_focus` before `commit_focus_transaction` is called will receive focus. pub(crate) fn begin_focus_transaction(&self) { // Initialize it with the current state *self.focus_transaction.borrow_mut() = Some(FocusTransaction { element: self.focused.get().as_deref().map(Dom::from_ref), has_focus: self.has_focus.get(), focus_options: FocusOptions { preventScroll: true, }, }); } /// pub(crate) fn perform_focus_fixup_rule(&self, not_focusable: &Element, can_gc: CanGc) { // Return if `not_focusable` is not the designated focused area of the // `Document`. if Some(not_focusable) != self.focused.get().as_deref() { return; } let implicit_transaction = self.focus_transaction.borrow().is_none(); if implicit_transaction { self.begin_focus_transaction(); } // Designate the viewport as the new focused area of the `Document`, but // do not run the focusing steps. { let mut focus_transaction = self.focus_transaction.borrow_mut(); focus_transaction.as_mut().unwrap().element = None; } if implicit_transaction { self.commit_focus_transaction(FocusInitiator::Local, can_gc); } } /// Request that the given element receive focus with default options. /// See [`Self::request_focus_with_options`] for the details. pub(crate) fn request_focus( &self, elem: Option<&Element>, focus_initiator: FocusInitiator, can_gc: CanGc, ) { self.request_focus_with_options( elem, focus_initiator, FocusOptions { preventScroll: true, }, can_gc, ); } /// Request that the given element receive focus once the current /// transaction is complete. `None` specifies to focus the document. /// /// If there's no ongoing transaction, this method automatically starts and /// commits an implicit transaction. pub(crate) fn request_focus_with_options( &self, elem: Option<&Element>, focus_initiator: FocusInitiator, focus_options: FocusOptions, can_gc: CanGc, ) { // If an element is specified, and it's non-focusable, ignore the // request. if elem.is_some_and(|e| !e.is_focusable_area()) { return; } let implicit_transaction = self.focus_transaction.borrow().is_none(); if implicit_transaction { self.begin_focus_transaction(); } { let mut focus_transaction = self.focus_transaction.borrow_mut(); let focus_transaction = focus_transaction.as_mut().unwrap(); focus_transaction.element = elem.map(Dom::from_ref); focus_transaction.has_focus = true; focus_transaction.focus_options = focus_options; } if implicit_transaction { self.commit_focus_transaction(focus_initiator, can_gc); } } /// Update the local focus state accordingly after being notified that the /// document's container is removed from the top-level browsing context's /// focus chain (not considering system focus). pub(crate) fn handle_container_unfocus(&self, can_gc: CanGc) { if self.window().parent_info().is_none() { warn!("Top-level document cannot be unfocused"); return; } // Since this method is called from an event loop, there mustn't be // an in-progress focus transaction assert!( self.focus_transaction.borrow().is_none(), "there mustn't be an in-progress focus transaction at this point" ); // Start an implicit focus transaction self.begin_focus_transaction(); // Update the transaction { let mut focus_transaction = self.focus_transaction.borrow_mut(); focus_transaction.as_mut().unwrap().has_focus = false; } // Commit the implicit focus transaction self.commit_focus_transaction(FocusInitiator::Remote, can_gc); } /// Reassign the focus context to the element that last requested focus during this /// transaction, or the document if no elements requested it. pub(crate) fn commit_focus_transaction(&self, focus_initiator: FocusInitiator, can_gc: CanGc) { let (mut new_focused, new_focus_state, prevent_scroll) = { let focus_transaction = self.focus_transaction.borrow(); let focus_transaction = focus_transaction .as_ref() .expect("no focus transaction in progress"); ( focus_transaction .element .as_ref() .map(|e| DomRoot::from_ref(&**e)), focus_transaction.has_focus, focus_transaction.focus_options.preventScroll, ) }; *self.focus_transaction.borrow_mut() = None; if !new_focus_state { // In many browsers, a document forgets its focused area when the // document is removed from the top-level BC's focus chain if new_focused.take().is_some() { trace!( "Forgetting the document's focused area because the \ document's container was removed from the top-level BC's \ focus chain" ); } } let old_focused = self.focused.get(); let old_focus_state = self.has_focus.get(); debug!( "Committing focus transaction: {:?} → {:?}", (&old_focused, old_focus_state), (&new_focused, new_focus_state), ); // `*_focused_filtered` indicates the local element (if any) included in // the top-level BC's focus chain. let old_focused_filtered = old_focused.as_ref().filter(|_| old_focus_state); let new_focused_filtered = new_focused.as_ref().filter(|_| new_focus_state); let trace_focus_chain = |name, element, doc| { trace!( "{} local focus chain: {}", name, match (element, doc) { (Some(e), _) => format!("[{:?}, document]", e), (None, true) => "[document]".to_owned(), (None, false) => "[]".to_owned(), } ); }; trace_focus_chain("Old", old_focused_filtered, old_focus_state); trace_focus_chain("New", new_focused_filtered, new_focus_state); if old_focused_filtered != new_focused_filtered { if let Some(elem) = &old_focused_filtered { let node = elem.upcast::(); elem.set_focus_state(false); // FIXME: pass appropriate relatedTarget if node.is_connected() { self.fire_focus_event(FocusEventType::Blur, node.upcast(), None, can_gc); } // Notify the embedder to hide the input method. if elem.input_method_type().is_some() { self.send_to_embedder(EmbedderMsg::HideIME(self.webview_id())); } } } if old_focus_state != new_focus_state && !new_focus_state { self.fire_focus_event(FocusEventType::Blur, self.global().upcast(), None, can_gc); } self.focused.set(new_focused.as_deref()); self.has_focus.set(new_focus_state); if old_focus_state != new_focus_state && new_focus_state { self.fire_focus_event(FocusEventType::Focus, self.global().upcast(), None, can_gc); } if old_focused_filtered != new_focused_filtered { if let Some(elem) = &new_focused_filtered { elem.set_focus_state(true); let node = elem.upcast::(); // FIXME: pass appropriate relatedTarget self.fire_focus_event(FocusEventType::Focus, node.upcast(), None, can_gc); // Notify the embedder to display an input method. if let Some(kind) = elem.input_method_type() { let rect = elem.upcast::().border_box().unwrap_or_default(); let rect = Rect::new( Point2D::new(rect.origin.x.to_px(), rect.origin.y.to_px()), Size2D::new(rect.size.width.to_px(), rect.size.height.to_px()), ); let (text, multiline) = if let Some(input) = elem.downcast::() { ( Some(( (input.Value()).to_string(), input.GetSelectionEnd().unwrap_or(0) as i32, )), false, ) } else if let Some(textarea) = elem.downcast::() { ( Some(( (textarea.Value()).to_string(), textarea.GetSelectionEnd().unwrap_or(0) as i32, )), true, ) } else { (None, false) }; self.send_to_embedder(EmbedderMsg::ShowIME( self.webview_id(), kind, text, multiline, DeviceIntRect::from_untyped(&rect.to_box2d()), )); } // Scroll operation to happen after element gets focus. // This is needed to ensure that the focused element is visible. // Only scroll if preventScroll was not specified if !prevent_scroll { elem.ScrollIntoView(BooleanOrScrollIntoViewOptions::ScrollIntoViewOptions( ScrollIntoViewOptions { parent: ScrollOptions { behavior: ScrollBehavior::Smooth, }, block: ScrollLogicalPosition::Center, inline: ScrollLogicalPosition::Center, container: ScrollIntoViewContainer::All, }, )); } } } if focus_initiator != FocusInitiator::Local { return; } // We are the initiator of the focus operation, so we must broadcast // the change we intend to make. match (old_focus_state, new_focus_state) { (_, true) => { // Advertise the change in the focus chain. // // // // If the top-level BC doesn't have system focus, this won't // have an immediate effect, but it will when we gain system // focus again. Therefore we still have to send `ScriptMsg:: // Focus`. // // When a container with a non-null nested browsing context is // focused, its active document becomes the focused area of the // top-level browsing context instead. Therefore we need to let // the constellation know if such a container is focused. // // > The focusing steps for an object `new focus target` [...] // > // > 3. If `new focus target` is a browsing context container // > with non-null nested browsing context, then set // > `new focus target` to the nested browsing context's // > active document. let child_browsing_context_id = new_focused .as_ref() .and_then(|elem| elem.downcast::()) .and_then(|iframe| iframe.browsing_context_id()); let sequence = self.increment_fetch_focus_sequence(); debug!( "Advertising the focus request to the constellation \ with sequence number {} and child BC ID {}", sequence, child_browsing_context_id .as_ref() .map(|id| id as &dyn std::fmt::Display) .unwrap_or(&"(none)"), ); self.window() .send_to_constellation(ScriptToConstellationMessage::Focus( child_browsing_context_id, sequence, )); }, (false, false) => { // Our `Document` doesn't have focus, and we intend to keep it // this way. }, (true, false) => { unreachable!( "Can't lose the document's focus without specifying \ another one to focus" ); }, } } /// Handles any updates when the document's title has changed. pub(crate) fn title_changed(&self) { if self.browsing_context().is_some() { self.send_title_to_embedder(); let title = String::from(self.Title()); self.window .send_to_constellation(ScriptToConstellationMessage::TitleChanged( self.window.pipeline_id(), title.clone(), )); if let Some(chan) = self.window.as_global_scope().devtools_chan() { let _ = chan.send(ScriptToDevtoolsControlMsg::TitleChanged( self.window.pipeline_id(), title, )); } } } /// Determine the title of the [`Document`] according to the specification at: /// . The difference /// here is that when the title isn't specified `None` is returned. fn title(&self) -> Option { let title = self.GetDocumentElement().and_then(|root| { if root.namespace() == &ns!(svg) && root.local_name() == &local_name!("svg") { // Step 1. root.upcast::() .child_elements() .find(|node| { node.namespace() == &ns!(svg) && node.local_name() == &local_name!("title") }) .map(DomRoot::upcast::) } else { // Step 2. root.upcast::() .traverse_preorder(ShadowIncluding::No) .find(|node| node.is::()) } }); title.map(|title| { // Steps 3-4. let value = title.child_text_content(); DOMString::from(str_join(split_html_space_chars(&value), " ")) }) } /// Sends this document's title to the constellation. pub(crate) fn send_title_to_embedder(&self) { let window = self.window(); if window.is_top_level() { let title = self.title().map(String::from); self.send_to_embedder(EmbedderMsg::ChangePageTitle(self.webview_id(), title)); } } pub(crate) fn send_to_embedder(&self, msg: EmbedderMsg) { let window = self.window(); window.send_to_embedder(msg); } pub(crate) fn dirty_all_nodes(&self) { let root = match self.GetDocumentElement() { Some(root) => root, None => return, }; for node in root .upcast::() .traverse_preorder(ShadowIncluding::Yes) { node.dirty(NodeDamage::Other) } } /// pub(crate) fn run_the_scroll_steps(&self, can_gc: CanGc) { // Step 1. // > Run the steps to dispatch pending scrollsnapchanging events for doc. // TODO(#7673): Implement scroll snapping // Step 2 // > For each item target in doc’s pending scroll event targets, in the order they // > were added to the list, run these substeps: // Step 3. // > Empty doc’s pending scroll event targets. // Since the scroll event callback could trigger another scroll event, we are taking all of the // current scroll event to avoid borrow checking error. rooted_vec!(let notify_list <- self.pending_scroll_event_targets.take().into_iter()); for target in notify_list.iter() { if target.downcast::().is_some() { // Step 2.1 // > If target is a Document, fire an event named scroll that bubbles at target. target.fire_bubbling_event(Atom::from("scroll"), can_gc); } else if target.downcast::().is_some() { // Step 2.2 // > Otherwise, fire an event named scroll at target. target.fire_event(Atom::from("scroll"), can_gc); } } // Step 4. // > Run the steps to dispatch pending scrollsnapchange events for doc. // TODO(#7673): Implement scroll snapping } /// Whenever a viewport gets scrolled (whether in response to user interaction or by an /// API), the user agent must run these steps: /// pub(crate) fn handle_viewport_scroll_event(&self) { // Step 2. // > If doc is a snap container, run the steps to update scrollsnapchanging targets // > for doc with doc’s eventual snap target in the block axis as newBlockTarget and // > doc’s eventual snap target in the inline axis as newInlineTarget. // TODO(#7673): Implement scroll snapping // Step 3. // > If doc is already in doc’s pending scroll event targets, abort these steps. let target = self.upcast::(); if self .pending_scroll_event_targets .borrow() .iter() .any(|other_target| *other_target == target) { return; } // Step 4. // > Append doc to doc’s pending scroll event targets. self.pending_scroll_event_targets .borrow_mut() .push(Dom::from_ref(target)); } /// Whenever an element gets scrolled (whether in response to user interaction or by an /// API), the user agent must run these steps: /// pub(crate) fn handle_element_scroll_event(&self, element: &Element) { // Step 2. // > If the element is a snap container, run the steps to update scrollsnapchanging // > targets for the element with the element’s eventual snap target in the block // > axis as newBlockTarget and the element’s eventual snap target in the inline axis // > as newInlineTarget. // TODO(#7673): Implement scroll snapping // Step 3. // > If the element is already in doc’s pending scroll event targets, abort these steps. let target = element.upcast::(); if self .pending_scroll_event_targets .borrow() .iter() .any(|other_target| *other_target == target) { return; } // Step 4. // > Append the element to doc’s pending scroll event targets. self.pending_scroll_event_targets .borrow_mut() .push(Dom::from_ref(target)); } // https://dom.spec.whatwg.org/#converting-nodes-into-a-node pub(crate) fn node_from_nodes_and_strings( &self, mut nodes: Vec, can_gc: CanGc, ) -> Fallible> { if nodes.len() == 1 { Ok(match nodes.pop().unwrap() { NodeOrString::Node(node) => node, NodeOrString::String(string) => { DomRoot::upcast(self.CreateTextNode(string, can_gc)) }, }) } else { let fragment = DomRoot::upcast::(self.CreateDocumentFragment(can_gc)); for node in nodes { match node { NodeOrString::Node(node) => { fragment.AppendChild(&node, can_gc)?; }, NodeOrString::String(string) => { let node = DomRoot::upcast::(self.CreateTextNode(string, can_gc)); // No try!() here because appending a text node // should not fail. fragment.AppendChild(&node, can_gc).unwrap(); }, } } Ok(fragment) } } pub(crate) fn get_body_attribute(&self, local_name: &LocalName) -> DOMString { match self.GetBody() { Some(ref body) if body.is_body_element() => { body.upcast::().get_string_attribute(local_name) }, _ => DOMString::new(), } } pub(crate) fn set_body_attribute( &self, local_name: &LocalName, value: DOMString, can_gc: CanGc, ) { if let Some(ref body) = self.GetBody().filter(|elem| elem.is_body_element()) { let body = body.upcast::(); let value = body.parse_attribute(&ns!(), local_name, value); body.set_attribute(local_name, value, can_gc); } } pub(crate) fn set_current_script(&self, script: Option<&HTMLScriptElement>) { self.current_script.set(script); } pub(crate) fn get_script_blocking_stylesheets_count(&self) -> u32 { self.script_blocking_stylesheets_count.get() } pub(crate) fn increment_script_blocking_stylesheet_count(&self) { let count_cell = &self.script_blocking_stylesheets_count; count_cell.set(count_cell.get() + 1); } pub(crate) fn decrement_script_blocking_stylesheet_count(&self) { let count_cell = &self.script_blocking_stylesheets_count; assert!(count_cell.get() > 0); count_cell.set(count_cell.get() - 1); } pub(crate) fn invalidate_stylesheets(&self) { self.stylesheets.borrow_mut().force_dirty(OriginSet::all()); // Mark the document element dirty so a reflow will be performed. // // FIXME(emilio): Use the DocumentStylesheetSet invalidation stuff. if let Some(element) = self.GetDocumentElement() { element.upcast::().dirty(NodeDamage::Style); } } /// Whether or not this `Document` has any active requestAnimationFrame callbacks /// registered. pub(crate) fn has_active_request_animation_frame_callbacks(&self) -> bool { !self.animation_frame_list.borrow().is_empty() } /// pub(crate) fn request_animation_frame(&self, callback: AnimationFrameCallback) -> u32 { let ident = self.animation_frame_ident.get() + 1; self.animation_frame_ident.set(ident); let had_animation_frame_callbacks; { let mut animation_frame_list = self.animation_frame_list.borrow_mut(); had_animation_frame_callbacks = !animation_frame_list.is_empty(); animation_frame_list.push_back((ident, Some(callback))); } // No need to send a `ChangeRunningAnimationsState` if we're running animation callbacks: // we're guaranteed to already be in the "animation callbacks present" state. // // This reduces CPU usage by avoiding needless thread wakeups in the common case of // repeated rAF. if !self.running_animation_callbacks.get() && !had_animation_frame_callbacks { self.window().send_to_constellation( ScriptToConstellationMessage::ChangeRunningAnimationsState( AnimationState::AnimationCallbacksPresent, ), ); } ident } /// pub(crate) fn cancel_animation_frame(&self, ident: u32) { let mut list = self.animation_frame_list.borrow_mut(); if let Some(pair) = list.iter_mut().find(|pair| pair.0 == ident) { pair.1 = None; } } /// pub(crate) fn run_the_animation_frame_callbacks(&self, can_gc: CanGc) { let _realm = enter_realm(self); self.running_animation_callbacks.set(true); let timing = self.global().performance().Now(); let num_callbacks = self.animation_frame_list.borrow().len(); for _ in 0..num_callbacks { let (_, maybe_callback) = self.animation_frame_list.borrow_mut().pop_front().unwrap(); if let Some(callback) = maybe_callback { callback.call(self, *timing, can_gc); } } self.running_animation_callbacks.set(false); if self.animation_frame_list.borrow().is_empty() { self.window().send_to_constellation( ScriptToConstellationMessage::ChangeRunningAnimationsState( AnimationState::NoAnimationCallbacksPresent, ), ); } } pub(crate) fn policy_container(&self) -> Ref<'_, PolicyContainer> { self.policy_container.borrow() } pub(crate) fn set_policy_container(&self, policy_container: PolicyContainer) { *self.policy_container.borrow_mut() = policy_container; } pub(crate) fn set_csp_list(&self, csp_list: Option) { self.policy_container.borrow_mut().set_csp_list(csp_list); } pub(crate) fn get_csp_list(&self) -> Option { self.policy_container.borrow().csp_list.clone() } /// Add the policy container and HTTPS state to a given request. /// /// TODO: Can this hapen for all requests that go through the document? pub(crate) fn prepare_request(&self, request: RequestBuilder) -> RequestBuilder { request .policy_container(self.policy_container().to_owned()) .https_state(self.https_state.get()) } pub(crate) fn fetch( &self, load: LoadType, mut request: RequestBuilder, listener: Listener, ) { request = request .insecure_requests_policy(self.insecure_requests_policy()) .has_trustworthy_ancestor_origin(self.has_trustworthy_ancestor_or_current_origin()); let callback = NetworkListener { context: std::sync::Arc::new(Mutex::new(listener)), task_source: self .owner_global() .task_manager() .networking_task_source() .into(), } .into_callback(); self.loader_mut() .fetch_async_with_callback(load, request, callback); } pub(crate) fn fetch_background( &self, mut request: RequestBuilder, listener: Listener, ) { request = request .insecure_requests_policy(self.insecure_requests_policy()) .has_trustworthy_ancestor_origin(self.has_trustworthy_ancestor_or_current_origin()); let callback = NetworkListener { context: std::sync::Arc::new(Mutex::new(listener)), task_source: self .owner_global() .task_manager() .networking_task_source() .into(), } .into_callback(); self.loader_mut().fetch_async_background(request, callback); } // https://html.spec.whatwg.org/multipage/#the-end // https://html.spec.whatwg.org/multipage/#delay-the-load-event pub(crate) fn finish_load(&self, load: LoadType, can_gc: CanGc) { // This does not delay the load event anymore. debug!("Document got finish_load: {:?}", load); self.loader.borrow_mut().finish_load(&load); match load { LoadType::Stylesheet(_) => { // A stylesheet finishing to load may unblock any pending // parsing-blocking script or deferred script. self.process_pending_parsing_blocking_script(can_gc); // Step 3. self.process_deferred_scripts(can_gc); }, LoadType::PageSource(_) => { // We finished loading the page, so if the `Window` is still waiting for // the first layout, allow it. if self.has_browsing_context && self.is_fully_active() { self.window().allow_layout_if_necessary(); } // Deferred scripts have to wait for page to finish loading, // this is the first opportunity to process them. // Step 3. self.process_deferred_scripts(can_gc); }, _ => {}, } // Step 4 is in another castle, namely at the end of // process_deferred_scripts. // Step 5 can be found in asap_script_loaded and // asap_in_order_script_loaded. let loader = self.loader.borrow(); // Servo measures when the top-level content (not iframes) is loaded. if self.top_level_dom_complete.get().is_none() && loader.is_only_blocked_by_iframes() { update_with_current_instant(&self.top_level_dom_complete); } if loader.is_blocked() || loader.events_inhibited() { // Step 6. return; } ScriptThread::mark_document_with_no_blocked_loads(self); } // https://html.spec.whatwg.org/multipage/#prompt-to-unload-a-document pub(crate) fn prompt_to_unload(&self, recursive_flag: bool, can_gc: CanGc) -> bool { // TODO: Step 1, increase the event loop's termination nesting level by 1. // Step 2 self.incr_ignore_opens_during_unload_counter(); // Step 3-5. let beforeunload_event = BeforeUnloadEvent::new( &self.window, atom!("beforeunload"), EventBubbles::Bubbles, EventCancelable::Cancelable, can_gc, ); let event = beforeunload_event.upcast::(); event.set_trusted(true); let event_target = self.window.upcast::(); let has_listeners = event_target.has_listeners_for(&atom!("beforeunload")); self.window .dispatch_event_with_target_override(event, can_gc); // TODO: Step 6, decrease the event loop's termination nesting level by 1. // Step 7 if has_listeners { self.salvageable.set(false); } let mut can_unload = true; // TODO: Step 8, also check sandboxing modals flag. let default_prevented = event.DefaultPrevented(); let return_value_not_empty = !event .downcast::() .unwrap() .ReturnValue() .is_empty(); if default_prevented || return_value_not_empty { let (chan, port) = generic_channel::channel().expect("Failed to create IPC channel!"); let msg = EmbedderMsg::AllowUnload(self.webview_id(), chan); self.send_to_embedder(msg); can_unload = port.recv().unwrap() == AllowOrDeny::Allow; } // Step 9 if !recursive_flag { // `prompt_to_unload` might cause futher modifications to the DOM so collecting here prevents // a double borrow if the `IFrameCollection` needs to be validated again. let iframes: Vec<_> = self.iframes().iter().collect(); for iframe in &iframes { // TODO: handle the case of cross origin iframes. let document = iframe.owner_document(); can_unload = document.prompt_to_unload(true, can_gc); if !document.salvageable() { self.salvageable.set(false); } if !can_unload { break; } } } // Step 10 self.decr_ignore_opens_during_unload_counter(); can_unload } // https://html.spec.whatwg.org/multipage/#unload-a-document pub(crate) fn unload(&self, recursive_flag: bool, can_gc: CanGc) { // TODO: Step 1, increase the event loop's termination nesting level by 1. // Step 2 self.incr_ignore_opens_during_unload_counter(); // Step 3-6 If oldDocument's page showing is true: if self.page_showing.get() { // Set oldDocument's page showing to false. self.page_showing.set(false); // Fire a page transition event named pagehide at oldDocument's relevant global object with oldDocument's // salvageable state. let event = PageTransitionEvent::new( &self.window, atom!("pagehide"), false, // bubbles false, // cancelable self.salvageable.get(), // persisted can_gc, ); let event = event.upcast::(); event.set_trusted(true); self.window .dispatch_event_with_target_override(event, can_gc); // Step 6 Update the visibility state of oldDocument to "hidden". self.update_visibility_state(DocumentVisibilityState::Hidden, can_gc); } // Step 7 if !self.fired_unload.get() { let event = Event::new( self.window.upcast(), atom!("unload"), EventBubbles::Bubbles, EventCancelable::Cancelable, can_gc, ); event.set_trusted(true); let event_target = self.window.upcast::(); let has_listeners = event_target.has_listeners_for(&atom!("unload")); self.window .dispatch_event_with_target_override(&event, can_gc); self.fired_unload.set(true); // Step 9 if has_listeners { self.salvageable.set(false); } } // TODO: Step 8, decrease the event loop's termination nesting level by 1. // Step 13 if !recursive_flag { // `unload` might cause futher modifications to the DOM so collecting here prevents // a double borrow if the `IFrameCollection` needs to be validated again. let iframes: Vec<_> = self.iframes().iter().collect(); for iframe in &iframes { // TODO: handle the case of cross origin iframes. let document = iframe.owner_document(); document.unload(true, can_gc); if !document.salvageable() { self.salvageable.set(false); } } } let global_scope = self.window.as_global_scope(); // Step 10, 14 // https://html.spec.whatwg.org/multipage/#unloading-document-cleanup-steps if !self.salvageable.get() { // Step 1 of clean-up steps. global_scope.close_event_sources(); let msg = ScriptToConstellationMessage::DiscardDocument; let _ = global_scope.script_to_constellation_chan().send(msg); } // https://w3c.github.io/FileAPI/#lifeTime global_scope.clean_up_all_file_resources(); // Step 15, End self.decr_ignore_opens_during_unload_counter(); } // https://html.spec.whatwg.org/multipage/#the-end pub(crate) fn maybe_queue_document_completion(&self) { // https://html.spec.whatwg.org/multipage/#delaying-load-events-mode let is_in_delaying_load_events_mode = match self.window.undiscarded_window_proxy() { Some(window_proxy) => window_proxy.is_delaying_load_events_mode(), None => false, }; // Note: if the document is not fully active, layout will have exited already, // and this method will panic. // The underlying problem might actually be that layout exits while it should be kept alive. // See https://github.com/servo/servo/issues/22507 let not_ready_for_load = self.loader.borrow().is_blocked() || !self.is_fully_active() || is_in_delaying_load_events_mode; if not_ready_for_load { // Step 6. return; } assert!(!self.loader.borrow().events_inhibited()); self.loader.borrow_mut().inhibit_events(); // The rest will ever run only once per document. // Step 7. debug!("Document loads are complete."); let document = Trusted::new(self); self.owner_global() .task_manager() .dom_manipulation_task_source() .queue(task!(fire_load_event: move || { let document = document.root(); let window = document.window(); if !window.is_alive() { return; } // Step 7.1. document.set_ready_state(DocumentReadyState::Complete, CanGc::note()); // Step 7.2. if document.browsing_context().is_none() { return; } let event = Event::new( window.upcast(), atom!("load"), EventBubbles::DoesNotBubble, EventCancelable::NotCancelable, CanGc::note(), ); event.set_trusted(true); // http://w3c.github.io/navigation-timing/#widl-PerformanceNavigationTiming-loadEventStart update_with_current_instant(&document.load_event_start); debug!("About to dispatch load for {:?}", document.url()); window.dispatch_event_with_target_override(&event, CanGc::note()); // http://w3c.github.io/navigation-timing/#widl-PerformanceNavigationTiming-loadEventEnd update_with_current_instant(&document.load_event_end); if let Some(fragment) = document.url().fragment() { document.check_and_scroll_fragment(fragment); } })); // Step 8. let document = Trusted::new(self); if document.root().browsing_context().is_some() { self.owner_global() .task_manager() .dom_manipulation_task_source() .queue(task!(fire_pageshow_event: move || { let document = document.root(); let window = document.window(); if document.page_showing.get() || !window.is_alive() { return; } document.page_showing.set(true); let event = PageTransitionEvent::new( window, atom!("pageshow"), false, // bubbles false, // cancelable false, // persisted CanGc::note(), ); let event = event.upcast::(); event.set_trusted(true); window.dispatch_event_with_target_override(event, CanGc::note()); })); } // Step 9. // TODO: pending application cache download process tasks. // Step 10. // TODO: printing steps. // Step 11. // TODO: ready for post-load tasks. // The dom.webxr.sessionavailable pref allows webxr // content to immediately begin a session without waiting for a user gesture. // TODO: should this only happen on the first document loaded? // https://immersive-web.github.io/webxr/#user-intention // https://github.com/immersive-web/navigation/issues/10 #[cfg(feature = "webxr")] if pref!(dom_webxr_sessionavailable) && self.window.is_top_level() { self.window.Navigator().Xr().dispatch_sessionavailable(); } // Step 12: completely loaded. // https://html.spec.whatwg.org/multipage/#completely-loaded // TODO: fully implement "completely loaded". let document = Trusted::new(self); if document.root().browsing_context().is_some() { self.owner_global() .task_manager() .dom_manipulation_task_source() .queue(task!(completely_loaded: move || { let document = document.root(); document.completely_loaded.set(true); if let Some(DeclarativeRefresh::PendingLoad { url, time }) = &*document.declarative_refresh.borrow() { // https://html.spec.whatwg.org/multipage/#shared-declarative-refresh-steps document.window.as_global_scope().schedule_callback( OneshotTimerCallback::RefreshRedirectDue(RefreshRedirectDue { window: DomRoot::from_ref(document.window()), url: url.clone(), }), Duration::from_secs(*time), ); } // Note: this will, among others, result in the "iframe-load-event-steps" being run. // https://html.spec.whatwg.org/multipage/#iframe-load-event-steps document.notify_constellation_load(); })); } } pub(crate) fn completely_loaded(&self) -> bool { self.completely_loaded.get() } // https://html.spec.whatwg.org/multipage/#pending-parsing-blocking-script pub(crate) fn set_pending_parsing_blocking_script( &self, script: &HTMLScriptElement, load: Option, ) { assert!(!self.has_pending_parsing_blocking_script()); *self.pending_parsing_blocking_script.borrow_mut() = Some(PendingScript::new_with_load(script, load)); } // https://html.spec.whatwg.org/multipage/#pending-parsing-blocking-script pub(crate) fn has_pending_parsing_blocking_script(&self) -> bool { self.pending_parsing_blocking_script.borrow().is_some() } /// step 22.d. pub(crate) fn pending_parsing_blocking_script_loaded( &self, element: &HTMLScriptElement, result: ScriptResult, can_gc: CanGc, ) { { let mut blocking_script = self.pending_parsing_blocking_script.borrow_mut(); let entry = blocking_script.as_mut().unwrap(); assert!(&*entry.element == element); entry.loaded(result); } self.process_pending_parsing_blocking_script(can_gc); } fn process_pending_parsing_blocking_script(&self, can_gc: CanGc) { if self.script_blocking_stylesheets_count.get() > 0 { return; } let pair = self .pending_parsing_blocking_script .borrow_mut() .as_mut() .and_then(PendingScript::take_result); if let Some((element, result)) = pair { *self.pending_parsing_blocking_script.borrow_mut() = None; self.get_current_parser() .unwrap() .resume_with_pending_parsing_blocking_script(&element, result, can_gc); } } // https://html.spec.whatwg.org/multipage/#set-of-scripts-that-will-execute-as-soon-as-possible pub(crate) fn add_asap_script(&self, script: &HTMLScriptElement) { self.asap_scripts_set .borrow_mut() .push(Dom::from_ref(script)); } /// step 5. /// step 22.d. pub(crate) fn asap_script_loaded( &self, element: &HTMLScriptElement, result: ScriptResult, can_gc: CanGc, ) { { let mut scripts = self.asap_scripts_set.borrow_mut(); let idx = scripts .iter() .position(|entry| &**entry == element) .unwrap(); scripts.swap_remove(idx); } element.execute(result, can_gc); } // https://html.spec.whatwg.org/multipage/#list-of-scripts-that-will-execute-in-order-as-soon-as-possible pub(crate) fn push_asap_in_order_script(&self, script: &HTMLScriptElement) { self.asap_in_order_scripts_list.push(script); } /// step 5. /// step> 22.c. pub(crate) fn asap_in_order_script_loaded( &self, element: &HTMLScriptElement, result: ScriptResult, can_gc: CanGc, ) { self.asap_in_order_scripts_list.loaded(element, result); while let Some((element, result)) = self .asap_in_order_scripts_list .take_next_ready_to_be_executed() { element.execute(result, can_gc); } } // https://html.spec.whatwg.org/multipage/#list-of-scripts-that-will-execute-when-the-document-has-finished-parsing pub(crate) fn add_deferred_script(&self, script: &HTMLScriptElement) { self.deferred_scripts.push(script); } /// step 3. /// step 22.d. pub(crate) fn deferred_script_loaded( &self, element: &HTMLScriptElement, result: ScriptResult, can_gc: CanGc, ) { self.deferred_scripts.loaded(element, result); self.process_deferred_scripts(can_gc); } /// step 3. fn process_deferred_scripts(&self, can_gc: CanGc) { if self.ready_state.get() != DocumentReadyState::Interactive { return; } // Part of substep 1. loop { if self.script_blocking_stylesheets_count.get() > 0 { return; } if let Some((element, result)) = self.deferred_scripts.take_next_ready_to_be_executed() { element.execute(result, can_gc); } else { break; } } if self.deferred_scripts.is_empty() { // https://html.spec.whatwg.org/multipage/#the-end step 4. self.maybe_dispatch_dom_content_loaded(); } } // https://html.spec.whatwg.org/multipage/#the-end step 4. pub(crate) fn maybe_dispatch_dom_content_loaded(&self) { if self.domcontentloaded_dispatched.get() { return; } self.domcontentloaded_dispatched.set(true); assert_ne!( self.ReadyState(), DocumentReadyState::Complete, "Complete before DOMContentLoaded?" ); update_with_current_instant(&self.dom_content_loaded_event_start); // Step 4.1. let document = Trusted::new(self); self.owner_global() .task_manager() .dom_manipulation_task_source() .queue( task!(fire_dom_content_loaded_event: move || { let document = document.root(); document.upcast::().fire_bubbling_event(atom!("DOMContentLoaded"), CanGc::note()); update_with_current_instant(&document.dom_content_loaded_event_end); }) ); // html parsing has finished - set dom content loaded self.interactive_time .borrow() .maybe_set_tti(InteractiveFlag::DOMContentLoaded); // Step 4.2. // TODO: client message queue. } // https://html.spec.whatwg.org/multipage/#abort-a-document pub(crate) fn abort(&self, can_gc: CanGc) { // We need to inhibit the loader before anything else. self.loader.borrow_mut().inhibit_events(); // Step 1. for iframe in self.iframes().iter() { if let Some(document) = iframe.GetContentDocument() { // TODO: abort the active documents of every child browsing context. document.abort(can_gc); // TODO: salvageable flag. } } // Step 2. self.script_blocking_stylesheets_count.set(0); *self.pending_parsing_blocking_script.borrow_mut() = None; *self.asap_scripts_set.borrow_mut() = vec![]; self.asap_in_order_scripts_list.clear(); self.deferred_scripts.clear(); let loads_cancelled = self.loader.borrow_mut().cancel_all_loads(); let event_sources_canceled = self.window.as_global_scope().close_event_sources(); if loads_cancelled || event_sources_canceled { // If any loads were canceled. self.salvageable.set(false); }; // Also Step 2. // Note: the spec says to discard any tasks queued for fetch. // This cancels all tasks on the networking task source, which might be too broad. // See https://github.com/whatwg/html/issues/3837 self.owner_global() .task_manager() .cancel_pending_tasks_for_source(TaskSourceName::Networking); // Step 3. if let Some(parser) = self.get_current_parser() { self.active_parser_was_aborted.set(true); parser.abort(can_gc); self.salvageable.set(false); } } pub(crate) fn notify_constellation_load(&self) { self.window() .send_to_constellation(ScriptToConstellationMessage::LoadComplete); } pub(crate) fn set_current_parser(&self, script: Option<&ServoParser>) { self.current_parser.set(script); } pub(crate) fn get_current_parser(&self) -> Option> { self.current_parser.get() } /// A reference to the [`IFrameCollection`] of this [`Document`], holding information about /// `