script/dom/
window.rs

1/* This Source Code Form is subject to the terms of the Mozilla Public
2 * License, v. 2.0. If a copy of the MPL was not distributed with this
3 * file, You can obtain one at https://mozilla.org/MPL/2.0/. */
4
5use std::borrow::ToOwned;
6use std::cell::{Cell, RefCell, RefMut};
7use std::cmp;
8use std::collections::hash_map::Entry;
9use std::collections::{HashMap, HashSet};
10use std::default::Default;
11use std::ffi::c_void;
12use std::io::{Write, stderr, stdout};
13use std::rc::Rc;
14use std::sync::Arc;
15use std::time::{Duration, Instant};
16
17use app_units::Au;
18use backtrace::Backtrace;
19use base::cross_process_instant::CrossProcessInstant;
20use base::generic_channel;
21use base::generic_channel::GenericSender;
22use base::id::{BrowsingContextId, PipelineId, WebViewId};
23use base64::Engine;
24#[cfg(feature = "bluetooth")]
25use bluetooth_traits::BluetoothRequest;
26use canvas_traits::webgl::WebGLChan;
27use compositing_traits::CrossProcessCompositorApi;
28use constellation_traits::{
29    LoadData, LoadOrigin, NavigationHistoryBehavior, ScreenshotReadinessResponse,
30    ScriptToConstellationChan, ScriptToConstellationMessage, StructuredSerializedData,
31    WindowSizeType,
32};
33use content_security_policy::sandboxing_directive::SandboxingFlagSet;
34use crossbeam_channel::{Sender, unbounded};
35use cssparser::SourceLocation;
36use devtools_traits::{ScriptToDevtoolsControlMsg, TimelineMarker, TimelineMarkerType};
37use dom_struct::dom_struct;
38use embedder_traits::user_content_manager::{UserContentManager, UserScript};
39use embedder_traits::{
40    AlertResponse, ConfirmResponse, EmbedderMsg, JavaScriptEvaluationError, PromptResponse,
41    ScriptToEmbedderChan, SimpleDialog, Theme, UntrustedNodeAddress, ViewportDetails,
42    WebDriverJSResult, WebDriverLoadStatus,
43};
44use euclid::default::{Point2D as UntypedPoint2D, Rect as UntypedRect};
45use euclid::{Point2D, Scale, Size2D, Vector2D};
46use fonts::FontContext;
47use ipc_channel::ipc::IpcSender;
48use js::glue::DumpJSStack;
49use js::jsapi::{
50    GCReason, Heap, JS_GC, JSAutoRealm, JSContext as RawJSContext, JSObject, JSPROP_ENUMERATE,
51};
52use js::jsval::{NullValue, UndefinedValue};
53use js::rust::wrappers::JS_DefineProperty;
54use js::rust::{
55    CustomAutoRooter, CustomAutoRooterGuard, HandleObject, HandleValue, MutableHandleObject,
56    MutableHandleValue,
57};
58use layout_api::{
59    BoxAreaType, ElementsFromPointFlags, ElementsFromPointResult, FragmentType, Layout,
60    LayoutImageDestination, PendingImage, PendingImageState, PendingRasterizationImage,
61    PhysicalSides, QueryMsg, ReflowGoal, ReflowPhasesRun, ReflowRequest, ReflowRequestRestyle,
62    RestyleReason, ScrollContainerQueryFlags, ScrollContainerResponse, TrustedNodeAddress,
63    combine_id_with_fragment_type,
64};
65use malloc_size_of::MallocSizeOf;
66use media::WindowGLContext;
67use net_traits::ResourceThreads;
68use net_traits::image_cache::{
69    ImageCache, ImageCacheResponseCallback, ImageCacheResponseMessage, ImageLoadListener,
70    ImageResponse, PendingImageId, PendingImageResponse, RasterizationCompleteResponse,
71};
72use num_traits::ToPrimitive;
73use profile_traits::generic_channel as ProfiledGenericChannel;
74use profile_traits::mem::ProfilerChan as MemProfilerChan;
75use profile_traits::time::ProfilerChan as TimeProfilerChan;
76use rustc_hash::{FxBuildHasher, FxHashMap};
77use script_bindings::codegen::GenericBindings::WindowBinding::ScrollToOptions;
78use script_bindings::conversions::SafeToJSValConvertible;
79use script_bindings::interfaces::WindowHelpers;
80use script_bindings::root::Root;
81use script_traits::{ConstellationInputEvent, ScriptThreadMessage};
82use selectors::attr::CaseSensitivity;
83use servo_arc::Arc as ServoArc;
84use servo_config::pref;
85use servo_geometry::DeviceIndependentIntRect;
86use servo_url::{ImmutableOrigin, MutableOrigin, ServoUrl};
87use storage_traits::StorageThreads;
88use storage_traits::webstorage_thread::StorageType;
89use style::error_reporting::{ContextualParseError, ParseErrorReporter};
90use style::properties::PropertyId;
91use style::properties::style_structs::Font;
92use style::selector_parser::PseudoElement;
93use style::str::HTML_SPACE_CHARACTERS;
94use style::stylesheets::UrlExtraData;
95use style_traits::CSSPixel;
96use stylo_atoms::Atom;
97use url::Position;
98use webrender_api::ExternalScrollId;
99use webrender_api::units::{DeviceIntSize, DevicePixel, LayoutPixel, LayoutPoint};
100
101use super::bindings::codegen::Bindings::MessagePortBinding::StructuredSerializeOptions;
102use super::bindings::trace::HashMapTracedValues;
103use super::types::SVGSVGElement;
104use crate::dom::bindings::cell::{DomRefCell, Ref};
105use crate::dom::bindings::codegen::Bindings::DocumentBinding::{
106    DocumentMethods, DocumentReadyState, NamedPropertyValue,
107};
108use crate::dom::bindings::codegen::Bindings::HTMLIFrameElementBinding::HTMLIFrameElementMethods;
109use crate::dom::bindings::codegen::Bindings::HistoryBinding::History_Binding::HistoryMethods;
110use crate::dom::bindings::codegen::Bindings::ImageBitmapBinding::{
111    ImageBitmapOptions, ImageBitmapSource,
112};
113use crate::dom::bindings::codegen::Bindings::MediaQueryListBinding::MediaQueryList_Binding::MediaQueryListMethods;
114use crate::dom::bindings::codegen::Bindings::ReportingObserverBinding::Report;
115use crate::dom::bindings::codegen::Bindings::RequestBinding::{RequestInfo, RequestInit};
116use crate::dom::bindings::codegen::Bindings::VoidFunctionBinding::VoidFunction;
117use crate::dom::bindings::codegen::Bindings::WindowBinding::{
118    self, DeferredRequestInit, FrameRequestCallback, ScrollBehavior, WindowMethods,
119    WindowPostMessageOptions,
120};
121use crate::dom::bindings::codegen::UnionTypes::{
122    RequestOrUSVString, TrustedScriptOrString, TrustedScriptOrStringOrFunction,
123};
124use crate::dom::bindings::error::{
125    Error, ErrorInfo, ErrorResult, Fallible, javascript_error_info_from_error_info,
126};
127use crate::dom::bindings::inheritance::{Castable, ElementTypeId, HTMLElementTypeId, NodeTypeId};
128use crate::dom::bindings::num::Finite;
129use crate::dom::bindings::refcounted::Trusted;
130use crate::dom::bindings::reflector::{DomGlobal, DomObject};
131use crate::dom::bindings::root::{Dom, DomRoot, MutNullableDom};
132use crate::dom::bindings::str::{DOMString, USVString};
133use crate::dom::bindings::structuredclone;
134use crate::dom::bindings::trace::{CustomTraceable, JSTraceable, RootedTraceableBox};
135use crate::dom::bindings::utils::GlobalStaticData;
136use crate::dom::bindings::weakref::DOMTracker;
137#[cfg(feature = "bluetooth")]
138use crate::dom::bluetooth::BluetoothExtraPermissionData;
139use crate::dom::cookiestore::CookieStore;
140use crate::dom::crypto::Crypto;
141use crate::dom::css::cssstyledeclaration::{
142    CSSModificationAccess, CSSStyleDeclaration, CSSStyleOwner,
143};
144use crate::dom::customelementregistry::CustomElementRegistry;
145use crate::dom::document::{AnimationFrameCallback, Document};
146use crate::dom::element::Element;
147use crate::dom::event::{Event, EventBubbles, EventCancelable};
148use crate::dom::eventtarget::EventTarget;
149use crate::dom::fetchlaterresult::FetchLaterResult;
150use crate::dom::globalscope::GlobalScope;
151use crate::dom::hashchangeevent::HashChangeEvent;
152use crate::dom::history::History;
153use crate::dom::html::htmlcollection::{CollectionFilter, HTMLCollection};
154use crate::dom::html::htmliframeelement::HTMLIFrameElement;
155use crate::dom::indexeddb::idbfactory::IDBFactory;
156use crate::dom::inputevent::HitTestResult;
157use crate::dom::location::Location;
158use crate::dom::medialist::MediaList;
159use crate::dom::mediaquerylist::{MediaQueryList, MediaQueryListMatchState};
160use crate::dom::mediaquerylistevent::MediaQueryListEvent;
161use crate::dom::messageevent::MessageEvent;
162use crate::dom::navigator::Navigator;
163use crate::dom::node::{Node, NodeDamage, NodeTraits, from_untrusted_node_address};
164use crate::dom::performance::performance::Performance;
165use crate::dom::promise::Promise;
166use crate::dom::reportingendpoint::{ReportingEndpoint, SendReportsToEndpoints};
167use crate::dom::reportingobserver::ReportingObserver;
168use crate::dom::screen::Screen;
169use crate::dom::scrolling_box::{ScrollingBox, ScrollingBoxSource};
170use crate::dom::selection::Selection;
171use crate::dom::shadowroot::ShadowRoot;
172use crate::dom::storage::Storage;
173#[cfg(feature = "bluetooth")]
174use crate::dom::testrunner::TestRunner;
175use crate::dom::trustedtypepolicyfactory::TrustedTypePolicyFactory;
176use crate::dom::types::{ImageBitmap, UIEvent};
177use crate::dom::webgl::webglrenderingcontext::WebGLCommandSender;
178#[cfg(feature = "webgpu")]
179use crate::dom::webgpu::identityhub::IdentityHub;
180use crate::dom::windowproxy::{WindowProxy, WindowProxyHandler};
181use crate::dom::worklet::Worklet;
182use crate::dom::workletglobalscope::WorkletGlobalScopeType;
183use crate::layout_image::fetch_image_for_layout;
184use crate::messaging::{MainThreadScriptMsg, ScriptEventLoopReceiver, ScriptEventLoopSender};
185use crate::microtask::{Microtask, UserMicrotask};
186use crate::realms::{InRealm, enter_realm};
187use crate::script_runtime::{CanGc, JSContext, Runtime};
188use crate::script_thread::{ScriptThread, with_script_thread};
189use crate::script_window_proxies::ScriptWindowProxies;
190use crate::timers::{IsInterval, TimerCallback};
191use crate::unminify::unminified_path;
192use crate::webdriver_handlers::{find_node_by_unique_id_in_document, jsval_to_webdriver};
193use crate::{fetch, window_named_properties};
194
195/// A callback to call when a response comes back from the `ImageCache`.
196///
197/// This is wrapped in a struct so that we can implement `MallocSizeOf`
198/// for this type.
199#[derive(MallocSizeOf)]
200pub struct PendingImageCallback(
201    #[ignore_malloc_size_of = "dyn Fn is currently impossible to measure"]
202    Box<dyn Fn(PendingImageResponse) + 'static>,
203);
204
205/// Current state of the window object
206#[derive(Clone, Copy, Debug, JSTraceable, MallocSizeOf, PartialEq)]
207enum WindowState {
208    Alive,
209    Zombie, // Pipeline is closed, but the window hasn't been GCed yet.
210}
211
212/// How long we should wait before performing the initial reflow after `<body>` is parsed,
213/// assuming that `<body>` take this long to parse.
214const INITIAL_REFLOW_DELAY: Duration = Duration::from_millis(200);
215
216/// During loading and parsing, layouts are suppressed to avoid flashing incomplete page
217/// contents.
218///
219/// Exceptions:
220///  - Parsing the body takes so long, that layouts are no longer suppressed in order
221///    to show the user that the page is loading.
222///  - Script triggers a layout query or scroll event in which case, we want to layout
223///    but not display the contents.
224///
225/// For more information see: <https://github.com/servo/servo/pull/6028>.
226#[derive(Clone, Copy, MallocSizeOf)]
227enum LayoutBlocker {
228    /// The first load event hasn't been fired and we have not started to parse the `<body>` yet.
229    WaitingForParse,
230    /// The body is being parsed the `<body>` starting at the `Instant` specified.
231    Parsing(Instant),
232    /// The body finished parsing and the `load` event has been fired or parsing took so
233    /// long, that we are going to do layout anyway. Note that subsequent changes to the body
234    /// can trigger parsing again, but the `Window` stays in this state.
235    FiredLoadEventOrParsingTimerExpired,
236}
237
238impl LayoutBlocker {
239    fn layout_blocked(&self) -> bool {
240        !matches!(self, Self::FiredLoadEventOrParsingTimerExpired)
241    }
242}
243
244/// An id used to cancel navigations; for now only used for planned form navigations.
245/// Loosely based on <https://html.spec.whatwg.org/multipage/#ongoing-navigation>.
246#[derive(Clone, Copy, Debug, Default, JSTraceable, MallocSizeOf, PartialEq)]
247pub(crate) struct OngoingNavigation(u32);
248
249type PendingImageRasterizationKey = (PendingImageId, DeviceIntSize);
250
251/// Ancillary data of pending image request that was initiated by layout during a reflow.
252/// This data is used to faciliate invalidating layout when the image data becomes available
253/// at some point in the future.
254#[cfg_attr(crown, crown::unrooted_must_root_lint::must_root)]
255#[derive(JSTraceable, MallocSizeOf)]
256struct PendingLayoutImageAncillaryData {
257    node: Dom<Node>,
258    #[no_trace]
259    destination: LayoutImageDestination,
260}
261
262#[dom_struct]
263pub(crate) struct Window {
264    globalscope: GlobalScope,
265    /// The webview that contains this [`Window`].
266    ///
267    /// This may not be the top-level [`Window`], in the case of frames.
268    #[no_trace]
269    webview_id: WebViewId,
270    script_chan: Sender<MainThreadScriptMsg>,
271    #[no_trace]
272    #[ignore_malloc_size_of = "TODO: Add MallocSizeOf support to layout"]
273    layout: RefCell<Box<dyn Layout>>,
274    navigator: MutNullableDom<Navigator>,
275    #[ignore_malloc_size_of = "ImageCache"]
276    #[no_trace]
277    image_cache: Arc<dyn ImageCache>,
278    #[no_trace]
279    image_cache_sender: Sender<ImageCacheResponseMessage>,
280    window_proxy: MutNullableDom<WindowProxy>,
281    document: MutNullableDom<Document>,
282    location: MutNullableDom<Location>,
283    history: MutNullableDom<History>,
284    indexeddb: MutNullableDom<IDBFactory>,
285    custom_element_registry: MutNullableDom<CustomElementRegistry>,
286    performance: MutNullableDom<Performance>,
287    #[no_trace]
288    navigation_start: Cell<CrossProcessInstant>,
289    screen: MutNullableDom<Screen>,
290    session_storage: MutNullableDom<Storage>,
291    local_storage: MutNullableDom<Storage>,
292    status: DomRefCell<DOMString>,
293    trusted_types: MutNullableDom<TrustedTypePolicyFactory>,
294
295    /// The start of something resembling
296    /// <https://html.spec.whatwg.org/multipage/#ongoing-navigation>
297    ongoing_navigation: Cell<OngoingNavigation>,
298
299    /// For sending timeline markers. Will be ignored if
300    /// no devtools server
301    #[no_trace]
302    devtools_markers: DomRefCell<HashSet<TimelineMarkerType>>,
303    #[no_trace]
304    devtools_marker_sender: DomRefCell<Option<IpcSender<Option<TimelineMarker>>>>,
305
306    /// Most recent unhandled resize event, if any.
307    #[no_trace]
308    unhandled_resize_event: DomRefCell<Option<(ViewportDetails, WindowSizeType)>>,
309
310    /// Platform theme.
311    #[no_trace]
312    theme: Cell<Theme>,
313
314    /// Parent id associated with this page, if any.
315    #[no_trace]
316    parent_info: Option<PipelineId>,
317
318    /// Global static data related to the DOM.
319    dom_static: GlobalStaticData,
320
321    /// The JavaScript runtime.
322    #[conditional_malloc_size_of]
323    js_runtime: DomRefCell<Option<Rc<Runtime>>>,
324
325    /// The [`ViewportDetails`] of this [`Window`]'s frame.
326    #[no_trace]
327    viewport_details: Cell<ViewportDetails>,
328
329    /// A handle for communicating messages to the bluetooth thread.
330    #[no_trace]
331    #[cfg(feature = "bluetooth")]
332    bluetooth_thread: IpcSender<BluetoothRequest>,
333
334    #[cfg(feature = "bluetooth")]
335    bluetooth_extra_permission_data: BluetoothExtraPermissionData,
336
337    /// See the documentation for [`LayoutBlocker`]. Essentially, this flag prevents
338    /// layouts from happening before the first load event, apart from a few exceptional
339    /// cases.
340    #[no_trace]
341    layout_blocker: Cell<LayoutBlocker>,
342
343    /// A channel for communicating results of async scripts back to the webdriver server
344    #[no_trace]
345    webdriver_script_chan: DomRefCell<Option<IpcSender<WebDriverJSResult>>>,
346
347    /// A channel to notify webdriver if there is a navigation
348    #[no_trace]
349    webdriver_load_status_sender: RefCell<Option<GenericSender<WebDriverLoadStatus>>>,
350
351    /// The current state of the window object
352    current_state: Cell<WindowState>,
353
354    error_reporter: CSSErrorReporter,
355
356    /// All the MediaQueryLists we need to update
357    media_query_lists: DOMTracker<MediaQueryList>,
358
359    #[cfg(feature = "bluetooth")]
360    test_runner: MutNullableDom<TestRunner>,
361
362    /// A handle for communicating messages to the WebGL thread, if available.
363    #[ignore_malloc_size_of = "channels are hard"]
364    #[no_trace]
365    webgl_chan: Option<WebGLChan>,
366
367    #[ignore_malloc_size_of = "defined in webxr"]
368    #[no_trace]
369    #[cfg(feature = "webxr")]
370    webxr_registry: Option<webxr_api::Registry>,
371
372    /// When an element triggers an image load or starts watching an image load from the
373    /// `ImageCache` it adds an entry to this list. When those loads are triggered from
374    /// layout, they also add an etry to [`Self::pending_layout_images`].
375    #[no_trace]
376    pending_image_callbacks: DomRefCell<FxHashMap<PendingImageId, Vec<PendingImageCallback>>>,
377
378    /// All of the elements that have an outstanding image request that was
379    /// initiated by layout during a reflow. They are stored in the [`ScriptThread`]
380    /// to ensure that the element can be marked dirty when the image data becomes
381    /// available at some point in the future.
382    pending_layout_images: DomRefCell<
383        HashMapTracedValues<PendingImageId, Vec<PendingLayoutImageAncillaryData>, FxBuildHasher>,
384    >,
385
386    /// Vector images for which layout has intiated rasterization at a specific size
387    /// and whose results are not yet available. They are stored in the [`ScriptThread`]
388    /// so that the element can be marked dirty once the rasterization is completed.
389    pending_images_for_rasterization: DomRefCell<
390        HashMapTracedValues<PendingImageRasterizationKey, Vec<Dom<Node>>, FxBuildHasher>,
391    >,
392
393    /// Directory to store unminified css for this window if unminify-css
394    /// opt is enabled.
395    unminified_css_dir: DomRefCell<Option<String>>,
396
397    /// Directory with stored unminified scripts
398    local_script_source: Option<String>,
399
400    /// Worklets
401    test_worklet: MutNullableDom<Worklet>,
402    /// <https://drafts.css-houdini.org/css-paint-api-1/#paint-worklet>
403    paint_worklet: MutNullableDom<Worklet>,
404
405    /// Flag to identify whether mutation observers are present(true)/absent(false)
406    exists_mut_observer: Cell<bool>,
407
408    /// Cross-process access to the compositor.
409    #[ignore_malloc_size_of = "Wraps an IpcSender"]
410    #[no_trace]
411    compositor_api: CrossProcessCompositorApi,
412
413    /// Indicate whether a SetDocumentStatus message has been sent after a reflow is complete.
414    /// It is used to avoid sending idle message more than once, which is unneccessary.
415    has_sent_idle_message: Cell<bool>,
416
417    /// Unminify Css.
418    unminify_css: bool,
419
420    /// User content manager
421    #[no_trace]
422    user_content_manager: UserContentManager,
423
424    /// Window's GL context from application
425    #[ignore_malloc_size_of = "defined in script_thread"]
426    #[no_trace]
427    player_context: WindowGLContext,
428
429    throttled: Cell<bool>,
430
431    /// A shared marker for the validity of any cached layout values. A value of true
432    /// indicates that any such values remain valid; any new layout that invalidates
433    /// those values will cause the marker to be set to false.
434    #[conditional_malloc_size_of]
435    layout_marker: DomRefCell<Rc<Cell<bool>>>,
436
437    /// <https://dom.spec.whatwg.org/#window-current-event>
438    current_event: DomRefCell<Option<Dom<Event>>>,
439
440    /// <https://w3c.github.io/reporting/#windoworworkerglobalscope-registered-reporting-observer-list>
441    reporting_observer_list: DomRefCell<Vec<DomRoot<ReportingObserver>>>,
442
443    /// <https://w3c.github.io/reporting/#windoworworkerglobalscope-reports>
444    report_list: DomRefCell<Vec<Report>>,
445
446    /// <https://w3c.github.io/reporting/#windoworworkerglobalscope-endpoints>
447    #[no_trace]
448    endpoints_list: DomRefCell<Vec<ReportingEndpoint>>,
449
450    /// The window proxies the script thread knows.
451    #[conditional_malloc_size_of]
452    script_window_proxies: Rc<ScriptWindowProxies>,
453
454    /// Whether or not this [`Window`] has a pending screenshot readiness request.
455    has_pending_screenshot_readiness_request: Cell<bool>,
456}
457
458impl Window {
459    pub(crate) fn webview_id(&self) -> WebViewId {
460        self.webview_id
461    }
462
463    pub(crate) fn as_global_scope(&self) -> &GlobalScope {
464        self.upcast::<GlobalScope>()
465    }
466
467    pub(crate) fn layout(&self) -> Ref<'_, Box<dyn Layout>> {
468        self.layout.borrow()
469    }
470
471    pub(crate) fn layout_mut(&self) -> RefMut<'_, Box<dyn Layout>> {
472        self.layout.borrow_mut()
473    }
474
475    pub(crate) fn get_exists_mut_observer(&self) -> bool {
476        self.exists_mut_observer.get()
477    }
478
479    pub(crate) fn set_exists_mut_observer(&self) {
480        self.exists_mut_observer.set(true);
481    }
482
483    #[expect(unsafe_code)]
484    pub(crate) fn clear_js_runtime_for_script_deallocation(&self) {
485        self.as_global_scope()
486            .remove_web_messaging_and_dedicated_workers_infra();
487        unsafe {
488            *self.js_runtime.borrow_for_script_deallocation() = None;
489            self.window_proxy.set(None);
490            self.current_state.set(WindowState::Zombie);
491            self.as_global_scope()
492                .task_manager()
493                .cancel_all_tasks_and_ignore_future_tasks();
494        }
495    }
496
497    /// A convenience method for
498    /// <https://html.spec.whatwg.org/multipage/#a-browsing-context-is-discarded>
499    pub(crate) fn discard_browsing_context(&self) {
500        let proxy = match self.window_proxy.get() {
501            Some(proxy) => proxy,
502            None => panic!("Discarding a BC from a window that has none"),
503        };
504        proxy.discard_browsing_context();
505        // Step 4 of https://html.spec.whatwg.org/multipage/#discard-a-document
506        // Other steps performed when the `PipelineExit` message
507        // is handled by the ScriptThread.
508        self.as_global_scope()
509            .task_manager()
510            .cancel_all_tasks_and_ignore_future_tasks();
511    }
512
513    /// Get a sender to the time profiler thread.
514    pub(crate) fn time_profiler_chan(&self) -> &TimeProfilerChan {
515        self.globalscope.time_profiler_chan()
516    }
517
518    pub(crate) fn origin(&self) -> &MutableOrigin {
519        self.globalscope.origin()
520    }
521
522    #[expect(unsafe_code)]
523    pub(crate) fn get_cx(&self) -> JSContext {
524        unsafe { JSContext::from_ptr(js::rust::Runtime::get().unwrap().as_ptr()) }
525    }
526
527    pub(crate) fn get_js_runtime(&self) -> Ref<'_, Option<Rc<Runtime>>> {
528        self.js_runtime.borrow()
529    }
530
531    pub(crate) fn main_thread_script_chan(&self) -> &Sender<MainThreadScriptMsg> {
532        &self.script_chan
533    }
534
535    pub(crate) fn parent_info(&self) -> Option<PipelineId> {
536        self.parent_info
537    }
538
539    pub(crate) fn new_script_pair(&self) -> (ScriptEventLoopSender, ScriptEventLoopReceiver) {
540        let (sender, receiver) = unbounded();
541        (
542            ScriptEventLoopSender::MainThread(sender),
543            ScriptEventLoopReceiver::MainThread(receiver),
544        )
545    }
546
547    pub(crate) fn event_loop_sender(&self) -> ScriptEventLoopSender {
548        ScriptEventLoopSender::MainThread(self.script_chan.clone())
549    }
550
551    pub(crate) fn image_cache(&self) -> Arc<dyn ImageCache> {
552        self.image_cache.clone()
553    }
554
555    /// This can panic if it is called after the browsing context has been discarded
556    pub(crate) fn window_proxy(&self) -> DomRoot<WindowProxy> {
557        self.window_proxy.get().unwrap()
558    }
559
560    pub(crate) fn append_reporting_observer(&self, reporting_observer: DomRoot<ReportingObserver>) {
561        self.reporting_observer_list
562            .borrow_mut()
563            .push(reporting_observer);
564    }
565
566    pub(crate) fn remove_reporting_observer(&self, reporting_observer: &ReportingObserver) {
567        if let Some(index) = self
568            .reporting_observer_list
569            .borrow()
570            .iter()
571            .position(|observer| &**observer == reporting_observer)
572        {
573            self.reporting_observer_list.borrow_mut().remove(index);
574        }
575    }
576
577    pub(crate) fn registered_reporting_observers(&self) -> Vec<DomRoot<ReportingObserver>> {
578        self.reporting_observer_list.borrow().clone()
579    }
580
581    pub(crate) fn append_report(&self, report: Report) {
582        self.report_list.borrow_mut().push(report);
583        let trusted_window = Trusted::new(self);
584        self.upcast::<GlobalScope>()
585            .task_manager()
586            .dom_manipulation_task_source()
587            .queue(task!(send_to_reporting_endpoints: move || {
588                let window = trusted_window.root();
589                let reports = std::mem::take(&mut *window.report_list.borrow_mut());
590                window.upcast::<GlobalScope>().send_reports_to_endpoints(
591                    reports,
592                    window.endpoints_list.borrow().clone(),
593                );
594            }));
595    }
596
597    pub(crate) fn buffered_reports(&self) -> Vec<Report> {
598        self.report_list.borrow().clone()
599    }
600
601    pub(crate) fn set_endpoints_list(&self, endpoints: Vec<ReportingEndpoint>) {
602        *self.endpoints_list.borrow_mut() = endpoints;
603    }
604
605    /// Returns the window proxy if it has not been discarded.
606    /// <https://html.spec.whatwg.org/multipage/#a-browsing-context-is-discarded>
607    pub(crate) fn undiscarded_window_proxy(&self) -> Option<DomRoot<WindowProxy>> {
608        self.window_proxy.get().and_then(|window_proxy| {
609            if window_proxy.is_browsing_context_discarded() {
610                None
611            } else {
612                Some(window_proxy)
613            }
614        })
615    }
616
617    /// Returns the window proxy of the webview, which is the top-level ancestor browsing context.
618    /// <https://html.spec.whatwg.org/multipage/#top-level-browsing-context>
619    pub(crate) fn webview_window_proxy(&self) -> Option<DomRoot<WindowProxy>> {
620        self.undiscarded_window_proxy().and_then(|window_proxy| {
621            self.script_window_proxies
622                .find_window_proxy(window_proxy.webview_id().into())
623        })
624    }
625
626    #[cfg(feature = "bluetooth")]
627    pub(crate) fn bluetooth_thread(&self) -> IpcSender<BluetoothRequest> {
628        self.bluetooth_thread.clone()
629    }
630
631    #[cfg(feature = "bluetooth")]
632    pub(crate) fn bluetooth_extra_permission_data(&self) -> &BluetoothExtraPermissionData {
633        &self.bluetooth_extra_permission_data
634    }
635
636    pub(crate) fn css_error_reporter(&self) -> Option<&dyn ParseErrorReporter> {
637        Some(&self.error_reporter)
638    }
639
640    pub(crate) fn webgl_chan(&self) -> Option<WebGLCommandSender> {
641        self.webgl_chan
642            .as_ref()
643            .map(|chan| WebGLCommandSender::new(chan.clone()))
644    }
645
646    #[cfg(feature = "webxr")]
647    pub(crate) fn webxr_registry(&self) -> Option<webxr_api::Registry> {
648        self.webxr_registry.clone()
649    }
650
651    fn new_paint_worklet(&self, can_gc: CanGc) -> DomRoot<Worklet> {
652        debug!("Creating new paint worklet.");
653        Worklet::new(self, WorkletGlobalScopeType::Paint, can_gc)
654    }
655
656    pub(crate) fn register_image_cache_listener(
657        &self,
658        id: PendingImageId,
659        callback: impl Fn(PendingImageResponse) + 'static,
660    ) -> ImageCacheResponseCallback {
661        self.pending_image_callbacks
662            .borrow_mut()
663            .entry(id)
664            .or_default()
665            .push(PendingImageCallback(Box::new(callback)));
666
667        let image_cache_sender = self.image_cache_sender.clone();
668        Box::new(move |message| {
669            let _ = image_cache_sender.send(message);
670        })
671    }
672
673    fn pending_layout_image_notification(&self, response: PendingImageResponse) {
674        let mut images = self.pending_layout_images.borrow_mut();
675        let nodes = images.entry(response.id);
676        let nodes = match nodes {
677            Entry::Occupied(nodes) => nodes,
678            Entry::Vacant(_) => return,
679        };
680        if matches!(
681            response.response,
682            ImageResponse::Loaded(_, _) | ImageResponse::FailedToLoadOrDecode
683        ) {
684            for ancillary_data in nodes.get() {
685                match ancillary_data.destination {
686                    LayoutImageDestination::BoxTreeConstruction => {
687                        ancillary_data.node.dirty(NodeDamage::Other);
688                    },
689                    LayoutImageDestination::DisplayListBuilding => {
690                        self.layout().set_needs_new_display_list();
691                    },
692                }
693            }
694        }
695
696        match response.response {
697            ImageResponse::MetadataLoaded(_) => {},
698            ImageResponse::Loaded(_, _) | ImageResponse::FailedToLoadOrDecode => {
699                nodes.remove();
700            },
701        }
702    }
703
704    pub(crate) fn handle_image_rasterization_complete_notification(
705        &self,
706        response: RasterizationCompleteResponse,
707    ) {
708        let mut images = self.pending_images_for_rasterization.borrow_mut();
709        let nodes = images.entry((response.image_id, response.requested_size));
710        let nodes = match nodes {
711            Entry::Occupied(nodes) => nodes,
712            Entry::Vacant(_) => return,
713        };
714        for node in nodes.get() {
715            node.dirty(NodeDamage::Other);
716        }
717        nodes.remove();
718    }
719
720    pub(crate) fn pending_image_notification(&self, response: PendingImageResponse) {
721        // We take the images here, in order to prevent maintaining a mutable borrow when
722        // image callbacks are called. These, in turn, can trigger garbage collection.
723        // Normally this shouldn't trigger more pending image notifications, but just in
724        // case we do not want to cause a double borrow here.
725        let mut images = std::mem::take(&mut *self.pending_image_callbacks.borrow_mut());
726        let Entry::Occupied(callbacks) = images.entry(response.id) else {
727            let _ = std::mem::replace(&mut *self.pending_image_callbacks.borrow_mut(), images);
728            return;
729        };
730
731        for callback in callbacks.get() {
732            callback.0(response.clone());
733        }
734
735        match response.response {
736            ImageResponse::MetadataLoaded(_) => {},
737            ImageResponse::Loaded(_, _) | ImageResponse::FailedToLoadOrDecode => {
738                callbacks.remove();
739            },
740        }
741
742        let _ = std::mem::replace(&mut *self.pending_image_callbacks.borrow_mut(), images);
743    }
744
745    pub(crate) fn compositor_api(&self) -> &CrossProcessCompositorApi {
746        &self.compositor_api
747    }
748
749    pub(crate) fn userscripts(&self) -> &[UserScript] {
750        self.user_content_manager.scripts()
751    }
752
753    pub(crate) fn get_player_context(&self) -> WindowGLContext {
754        self.player_context.clone()
755    }
756
757    // see note at https://dom.spec.whatwg.org/#concept-event-dispatch step 2
758    pub(crate) fn dispatch_event_with_target_override(&self, event: &Event, can_gc: CanGc) {
759        event.dispatch(self.upcast(), true, can_gc);
760    }
761
762    pub(crate) fn font_context(&self) -> &Arc<FontContext> {
763        self.as_global_scope()
764            .font_context()
765            .expect("A `Window` should always have a `FontContext`")
766    }
767
768    pub(crate) fn ongoing_navigation(&self) -> OngoingNavigation {
769        self.ongoing_navigation.get()
770    }
771
772    /// <https://html.spec.whatwg.org/multipage/#set-the-ongoing-navigation>
773    pub(crate) fn set_ongoing_navigation(&self) -> OngoingNavigation {
774        // Note: since this value, for now, is only used in a single `ScriptThread`,
775        // we just increment it (it is not a uuid), which implies not
776        // using a `newValue` variable.
777        let new_value = self.ongoing_navigation.get().0.wrapping_add(1);
778
779        // 1. If navigable's ongoing navigation is equal to newValue, then return.
780        // Note: cannot happen in the way it is currently used.
781
782        // TODO: 2. Inform the navigation API about aborting navigation given navigable.
783
784        // 3. Set navigable's ongoing navigation to newValue.
785        self.ongoing_navigation.set(OngoingNavigation(new_value));
786
787        // Note: Return the ongoing navigation for the caller to use.
788        OngoingNavigation(new_value)
789    }
790
791    /// <https://html.spec.whatwg.org/multipage/#nav-stop>
792    fn stop_loading(&self, can_gc: CanGc) {
793        // 1. Let document be navigable's active document.
794        let doc = self.Document();
795
796        // 2. If document's unload counter is 0,
797        // and navigable's ongoing navigation is a navigation ID,
798        // then set the ongoing navigation for navigable to null.
799        //
800        // Note: since the concept of `navigable` is nascent in Servo,
801        // for now we do two things:
802        // - increment the `ongoing_navigation`(preventing planned form navigations).
803        // - Send a `AbortLoadUrl` message(in case the navigation
804        // already started at the constellation).
805        self.set_ongoing_navigation();
806
807        // 3. Abort a document and its descendants given document.
808        doc.abort(can_gc);
809    }
810
811    /// <https://html.spec.whatwg.org/multipage/#cannot-show-simple-dialogs>
812    fn cannot_show_simple_dialogs(&self) -> bool {
813        // Step 1: If the active sandboxing flag set of window's associated Document has
814        // the sandboxed modals flag set, then return true.
815        if self
816            .Document()
817            .has_active_sandboxing_flag(SandboxingFlagSet::SANDBOXED_MODALS_FLAG)
818        {
819            return true;
820        }
821
822        // Step 2: If window's relevant settings object's origin and window's relevant settings
823        // object's top-level origin are not same origin-domain, then return true.
824        //
825        // TODO: This check doesn't work currently because it seems that comparing two
826        // opaque domains doesn't work between GlobalScope::top_level_creation_url and
827        // Document::origin().
828
829        // Step 3: If window's relevant agent's event loop's termination nesting level is nonzero,
830        // then optionally return true.
831        // TODO: This is unsupported currently.
832
833        // Step 4: Optionally, return true. (For example, the user agent might give the
834        // user the option to ignore all modal dialogs, and would thus abort at this step
835        // whenever the method was invoked.)
836        // TODO: The embedder currently cannot block an alert before it is sent to the embedder. This
837        // requires changes to the API.
838
839        // Step 5: Return false.
840        false
841    }
842
843    pub(crate) fn perform_a_microtask_checkpoint(&self, can_gc: CanGc) {
844        with_script_thread(|script_thread| script_thread.perform_a_microtask_checkpoint(can_gc));
845    }
846}
847
848// https://html.spec.whatwg.org/multipage/#atob
849pub(crate) fn base64_btoa(input: DOMString) -> Fallible<DOMString> {
850    // "The btoa() method must throw an InvalidCharacterError exception if
851    //  the method's first argument contains any character whose code point
852    //  is greater than U+00FF."
853    if input.str().chars().any(|c: char| c > '\u{FF}') {
854        Err(Error::InvalidCharacter(None))
855    } else {
856        // "Otherwise, the user agent must convert that argument to a
857        //  sequence of octets whose nth octet is the eight-bit
858        //  representation of the code point of the nth character of
859        //  the argument,"
860        let octets = input
861            .str()
862            .chars()
863            .map(|c: char| c as u8)
864            .collect::<Vec<u8>>();
865
866        // "and then must apply the base64 algorithm to that sequence of
867        //  octets, and return the result. [RFC4648]"
868        let config =
869            base64::engine::general_purpose::GeneralPurposeConfig::new().with_encode_padding(true);
870        let engine = base64::engine::GeneralPurpose::new(&base64::alphabet::STANDARD, config);
871        Ok(DOMString::from(engine.encode(octets)))
872    }
873}
874
875// https://html.spec.whatwg.org/multipage/#atob
876pub(crate) fn base64_atob(input: DOMString) -> Fallible<DOMString> {
877    // "Remove all space characters from input."
878    fn is_html_space(c: char) -> bool {
879        HTML_SPACE_CHARACTERS.contains(&c)
880    }
881    let without_spaces = input
882        .str()
883        .chars()
884        .filter(|&c| !is_html_space(c))
885        .collect::<String>();
886    let mut input = &*without_spaces;
887
888    // "If the length of input divides by 4 leaving no remainder, then:
889    //  if input ends with one or two U+003D EQUALS SIGN (=) characters,
890    //  remove them from input."
891    if input.len() % 4 == 0 {
892        if input.ends_with("==") {
893            input = &input[..input.len() - 2]
894        } else if input.ends_with('=') {
895            input = &input[..input.len() - 1]
896        }
897    }
898
899    // "If the length of input divides by 4 leaving a remainder of 1,
900    //  throw an InvalidCharacterError exception and abort these steps."
901    if input.len() % 4 == 1 {
902        return Err(Error::InvalidCharacter(None));
903    }
904
905    // "If input contains a character that is not in the following list of
906    //  characters and character ranges, throw an InvalidCharacterError
907    //  exception and abort these steps:
908    //
909    //  U+002B PLUS SIGN (+)
910    //  U+002F SOLIDUS (/)
911    //  Alphanumeric ASCII characters"
912    if input
913        .chars()
914        .any(|c| c != '+' && c != '/' && !c.is_alphanumeric())
915    {
916        return Err(Error::InvalidCharacter(None));
917    }
918
919    let config = base64::engine::general_purpose::GeneralPurposeConfig::new()
920        .with_decode_padding_mode(base64::engine::DecodePaddingMode::RequireNone)
921        .with_decode_allow_trailing_bits(true);
922    let engine = base64::engine::GeneralPurpose::new(&base64::alphabet::STANDARD, config);
923
924    let data = engine
925        .decode(input)
926        .map_err(|_| Error::InvalidCharacter(None))?;
927    Ok(data.iter().map(|&b| b as char).collect::<String>().into())
928}
929
930impl WindowMethods<crate::DomTypeHolder> for Window {
931    /// <https://html.spec.whatwg.org/multipage/#dom-alert>
932    fn Alert_(&self) {
933        // Step 2: If the method was invoked with no arguments, then let message be the
934        // empty string; otherwise, let message be the method's first argument.
935        self.Alert(DOMString::new());
936    }
937
938    /// <https://html.spec.whatwg.org/multipage/#dom-alert>
939    fn Alert(&self, mut message: DOMString) {
940        // Step 1: If we cannot show simple dialogs for this, then return.
941        if self.cannot_show_simple_dialogs() {
942            return;
943        }
944
945        // Step 2 is handled in the other variant of this method.
946        //
947        // Step 3: Set message to the result of normalizing newlines given message.
948        message.normalize_newlines();
949
950        // Step 4. Set message to the result of optionally truncating message.
951        // This is up to the embedder.
952
953        // Step 5: Let userPromptHandler be WebDriver BiDi user prompt opened with this,
954        // "alert", and message.
955        // TODO: Add support for WebDriver BiDi.
956
957        // Step 6: If userPromptHandler is "none", then:
958        //  1. Show message to the user, treating U+000A LF as a line break.
959        //  2. Optionally, pause while waiting for the user to acknowledge the message.
960        {
961            // Print to the console.
962            // Ensure that stderr doesn't trample through the alert() we use to
963            // communicate test results (see executorservo.py in wptrunner).
964            let stderr = stderr();
965            let mut stderr = stderr.lock();
966            let stdout = stdout();
967            let mut stdout = stdout.lock();
968            writeln!(&mut stdout, "\nALERT: {message}").unwrap();
969            stdout.flush().unwrap();
970            stderr.flush().unwrap();
971        }
972
973        let (sender, receiver) =
974            ProfiledGenericChannel::channel(self.global().time_profiler_chan().clone()).unwrap();
975        let dialog = SimpleDialog::Alert {
976            id: self.Document().embedder_controls().next_control_id(),
977            message: message.to_string(),
978            response_sender: sender,
979        };
980        self.send_to_embedder(EmbedderMsg::ShowSimpleDialog(self.webview_id(), dialog));
981        receiver.recv().unwrap_or_else(|_| {
982            // If the receiver is closed, we assume the dialog was cancelled.
983            debug!("Alert dialog was cancelled or failed to show.");
984            AlertResponse::Ok
985        });
986
987        // Step 7: Invoke WebDriver BiDi user prompt closed with this, "alert", and true.
988        // TODO: Implement support for WebDriver BiDi.
989    }
990
991    /// <https://html.spec.whatwg.org/multipage/#dom-confirm>
992    fn Confirm(&self, mut message: DOMString) -> bool {
993        // Step 1: If we cannot show simple dialogs for this, then return false.
994        if self.cannot_show_simple_dialogs() {
995            return false;
996        }
997
998        // Step 2: Set message to the result of normalizing newlines given message.
999        message.normalize_newlines();
1000
1001        // Step 3: Set message to the result of optionally truncating message.
1002        // We let the embedder handle this.
1003
1004        // Step 4: Show message to the user, treating U+000A LF as a line break, and ask
1005        // the user to respond with a positive or negative response.
1006        let (sender, receiver) =
1007            ProfiledGenericChannel::channel(self.global().time_profiler_chan().clone()).unwrap();
1008        let dialog = SimpleDialog::Confirm {
1009            id: self.Document().embedder_controls().next_control_id(),
1010            message: message.to_string(),
1011            response_sender: sender,
1012        };
1013        self.send_to_embedder(EmbedderMsg::ShowSimpleDialog(self.webview_id(), dialog));
1014
1015        // Step 5: Let userPromptHandler be WebDriver BiDi user prompt opened with this,
1016        // "confirm", and message.
1017        //
1018        // Step 6: Let accepted be false.
1019        //
1020        // Step 7: If userPromptHandler is "none", then:
1021        //  1. Pause until the user responds either positively or negatively.
1022        //  2. If the user responded positively, then set accepted to true.
1023        //
1024        // Step 8: If userPromptHandler is "accept", then set accepted to true.
1025        //
1026        // Step 9: Invoke WebDriver BiDi user prompt closed with this, "confirm", and accepted.
1027        // TODO: Implement WebDriver BiDi and handle these steps.
1028        //
1029        // Step 10: Return accepted.
1030        match receiver.recv() {
1031            Ok(ConfirmResponse::Ok) => true,
1032            Ok(ConfirmResponse::Cancel) => false,
1033            Err(_) => {
1034                warn!("Confirm dialog was cancelled or failed to show.");
1035                false
1036            },
1037        }
1038    }
1039
1040    /// <https://html.spec.whatwg.org/multipage/#dom-prompt>
1041    fn Prompt(&self, mut message: DOMString, default: DOMString) -> Option<DOMString> {
1042        // Step 1: If we cannot show simple dialogs for this, then return null.
1043        if self.cannot_show_simple_dialogs() {
1044            return None;
1045        }
1046
1047        // Step 2: Set message to the result of normalizing newlines given message.
1048        message.normalize_newlines();
1049
1050        // Step 3. Set message to the result of optionally truncating message.
1051        // Step 4: Set default to the result of optionally truncating default.
1052        // We let the embedder handle these steps.
1053
1054        // Step 5: Show message to the user, treating U+000A LF as a line break, and ask
1055        // the user to either respond with a string value or abort. The response must be
1056        // defaulted to the value given by default.
1057        let (sender, receiver) =
1058            ProfiledGenericChannel::channel(self.global().time_profiler_chan().clone()).unwrap();
1059        let dialog = SimpleDialog::Prompt {
1060            id: self.Document().embedder_controls().next_control_id(),
1061            message: message.to_string(),
1062            default: default.to_string(),
1063            response_sender: sender,
1064        };
1065        self.send_to_embedder(EmbedderMsg::ShowSimpleDialog(self.webview_id(), dialog));
1066
1067        // Step 6: Let userPromptHandler be WebDriver BiDi user prompt opened with this,
1068        // "prompt", and message.
1069        // TODO: Add support for WebDriver BiDi.
1070        //
1071        // Step 7: Let result be null.
1072        //
1073        // Step 8: If userPromptHandler is "none", then:
1074        //  1. Pause while waiting for the user's response.
1075        //  2. If the user did not abort, then set result to the string that the user responded with.
1076        //
1077        // Step 9: Otherwise, if userPromptHandler is "accept", then set result to the empty string.
1078        // TODO: Implement this.
1079        //
1080        // Step 10: Invoke WebDriver BiDi user prompt closed with this, "prompt", false if
1081        // result is null or true otherwise, and result.
1082        // TODO: Add support for WebDriver BiDi.
1083        //
1084        // Step 11: Return result.
1085        match receiver.recv() {
1086            Ok(PromptResponse::Ok(input)) => Some(input.into()),
1087            Ok(PromptResponse::Cancel) => None,
1088            Err(_) => {
1089                warn!("Prompt dialog was cancelled or failed to show.");
1090                None
1091            },
1092        }
1093    }
1094
1095    /// <https://html.spec.whatwg.org/multipage/#dom-window-stop>
1096    fn Stop(&self, can_gc: CanGc) {
1097        // 1. If this's navigable is null, then return.
1098        // Note: Servo doesn't have a concept of navigable yet.
1099
1100        // 2. Stop loading this's navigable.
1101        self.stop_loading(can_gc);
1102    }
1103
1104    /// <https://html.spec.whatwg.org/multipage/#dom-window-focus>
1105    fn Focus(&self) {
1106        // > 1. Let `current` be this `Window` object's browsing context.
1107        // >
1108        // > 2. If `current` is null, then return.
1109        let current = match self.undiscarded_window_proxy() {
1110            Some(proxy) => proxy,
1111            None => return,
1112        };
1113
1114        // > 3. Run the focusing steps with `current`.
1115        current.focus();
1116
1117        // > 4. If current is a top-level browsing context, user agents are
1118        // >    encouraged to trigger some sort of notification to indicate to
1119        // >    the user that the page is attempting to gain focus.
1120        //
1121        // TODO: Step 4
1122    }
1123
1124    /// <https://html.spec.whatwg.org/multipage/#dom-window-blur>
1125    fn Blur(&self) {
1126        // > User agents are encouraged to ignore calls to this `blur()` method
1127        // > entirely.
1128    }
1129
1130    /// <https://html.spec.whatwg.org/multipage/#dom-open>
1131    fn Open(
1132        &self,
1133        url: USVString,
1134        target: DOMString,
1135        features: DOMString,
1136        can_gc: CanGc,
1137    ) -> Fallible<Option<DomRoot<WindowProxy>>> {
1138        self.window_proxy().open(url, target, features, can_gc)
1139    }
1140
1141    /// <https://html.spec.whatwg.org/multipage/#dom-opener>
1142    fn GetOpener(
1143        &self,
1144        cx: JSContext,
1145        in_realm_proof: InRealm,
1146        mut retval: MutableHandleValue,
1147    ) -> Fallible<()> {
1148        // Step 1, Let current be this Window object's browsing context.
1149        let current = match self.window_proxy.get() {
1150            Some(proxy) => proxy,
1151            // Step 2, If current is null, then return null.
1152            None => {
1153                retval.set(NullValue());
1154                return Ok(());
1155            },
1156        };
1157        // Still step 2, since the window's BC is the associated doc's BC,
1158        // see https://html.spec.whatwg.org/multipage/#window-bc
1159        // and a doc's BC is null if it has been discarded.
1160        // see https://html.spec.whatwg.org/multipage/#concept-document-bc
1161        if current.is_browsing_context_discarded() {
1162            retval.set(NullValue());
1163            return Ok(());
1164        }
1165        // Step 3 to 5.
1166        current.opener(*cx, in_realm_proof, retval);
1167        Ok(())
1168    }
1169
1170    #[expect(unsafe_code)]
1171    /// <https://html.spec.whatwg.org/multipage/#dom-opener>
1172    fn SetOpener(&self, cx: JSContext, value: HandleValue) -> ErrorResult {
1173        // Step 1.
1174        if value.is_null() {
1175            if let Some(proxy) = self.window_proxy.get() {
1176                proxy.disown();
1177            }
1178            return Ok(());
1179        }
1180        // Step 2.
1181        let obj = self.reflector().get_jsobject();
1182        unsafe {
1183            let result =
1184                JS_DefineProperty(*cx, obj, c"opener".as_ptr(), value, JSPROP_ENUMERATE as u32);
1185
1186            if result { Ok(()) } else { Err(Error::JSFailed) }
1187        }
1188    }
1189
1190    /// <https://html.spec.whatwg.org/multipage/#dom-window-closed>
1191    fn Closed(&self) -> bool {
1192        self.window_proxy
1193            .get()
1194            .map(|ref proxy| proxy.is_browsing_context_discarded() || proxy.is_closing())
1195            .unwrap_or(true)
1196    }
1197
1198    /// <https://html.spec.whatwg.org/multipage/#dom-window-close>
1199    fn Close(&self) {
1200        // Step 1, Let current be this Window object's browsing context.
1201        // Step 2, If current is null or its is closing is true, then return.
1202        let window_proxy = match self.window_proxy.get() {
1203            Some(proxy) => proxy,
1204            None => return,
1205        };
1206        if window_proxy.is_closing() {
1207            return;
1208        }
1209        // Note: check the length of the "session history", as opposed to the joint session history?
1210        // see https://github.com/whatwg/html/issues/3734
1211        if let Ok(history_length) = self.History().GetLength() {
1212            let is_auxiliary = window_proxy.is_auxiliary();
1213
1214            // https://html.spec.whatwg.org/multipage/#script-closable
1215            let is_script_closable = (self.is_top_level() && history_length == 1) ||
1216                is_auxiliary ||
1217                pref!(dom_allow_scripts_to_close_windows);
1218
1219            // TODO: rest of Step 3:
1220            // Is the incumbent settings object's responsible browsing context familiar with current?
1221            // Is the incumbent settings object's responsible browsing context allowed to navigate current?
1222            if is_script_closable {
1223                // Step 3.1, set current's is closing to true.
1224                window_proxy.close();
1225
1226                // Step 3.2, queue a task on the DOM manipulation task source to close current.
1227                let this = Trusted::new(self);
1228                let task = task!(window_close_browsing_context: move || {
1229                    let window = this.root();
1230                    let document = window.Document();
1231                    // https://html.spec.whatwg.org/multipage/#closing-browsing-contexts
1232                    // Step 1, check if traversable is closing, was already done above.
1233                    // Steps 2 and 3, prompt to unload for all inclusive descendant navigables.
1234                    // TODO: We should be prompting for all inclusive descendant navigables,
1235                    // but we pass false here, which suggests we are not doing that. Why?
1236                    if document.prompt_to_unload(false, CanGc::note()) {
1237                        // Step 4, unload.
1238                        document.unload(false, CanGc::note());
1239
1240                        // https://html.spec.whatwg.org/multipage/#a-browsing-context-is-discarded
1241                        // which calls into https://html.spec.whatwg.org/multipage/#discard-a-document.
1242                        window.discard_browsing_context();
1243
1244                        window.send_to_constellation(ScriptToConstellationMessage::DiscardTopLevelBrowsingContext);
1245                    }
1246                });
1247                self.as_global_scope()
1248                    .task_manager()
1249                    .dom_manipulation_task_source()
1250                    .queue(task);
1251            }
1252        }
1253    }
1254
1255    /// <https://html.spec.whatwg.org/multipage/#dom-document-2>
1256    fn Document(&self) -> DomRoot<Document> {
1257        self.document
1258            .get()
1259            .expect("Document accessed before initialization.")
1260    }
1261
1262    /// <https://html.spec.whatwg.org/multipage/#dom-history>
1263    fn History(&self) -> DomRoot<History> {
1264        self.history.or_init(|| History::new(self, CanGc::note()))
1265    }
1266
1267    /// <https://w3c.github.io/IndexedDB/#factory-interface>
1268    fn IndexedDB(&self) -> DomRoot<IDBFactory> {
1269        self.indexeddb.or_init(|| {
1270            let global_scope = self.upcast::<GlobalScope>();
1271            IDBFactory::new(global_scope, CanGc::note())
1272        })
1273    }
1274
1275    /// <https://html.spec.whatwg.org/multipage/#dom-window-customelements>
1276    fn CustomElements(&self) -> DomRoot<CustomElementRegistry> {
1277        self.custom_element_registry
1278            .or_init(|| CustomElementRegistry::new(self, CanGc::note()))
1279    }
1280
1281    /// <https://html.spec.whatwg.org/multipage/#dom-location>
1282    fn Location(&self) -> DomRoot<Location> {
1283        self.location.or_init(|| Location::new(self, CanGc::note()))
1284    }
1285
1286    /// <https://html.spec.whatwg.org/multipage/#dom-sessionstorage>
1287    fn SessionStorage(&self) -> DomRoot<Storage> {
1288        self.session_storage
1289            .or_init(|| Storage::new(self, StorageType::Session, CanGc::note()))
1290    }
1291
1292    /// <https://html.spec.whatwg.org/multipage/#dom-localstorage>
1293    fn LocalStorage(&self) -> DomRoot<Storage> {
1294        self.local_storage
1295            .or_init(|| Storage::new(self, StorageType::Local, CanGc::note()))
1296    }
1297
1298    /// <https://cookiestore.spec.whatwg.org/#Window>
1299    fn CookieStore(&self, can_gc: CanGc) -> DomRoot<CookieStore> {
1300        self.global().cookie_store(can_gc)
1301    }
1302
1303    /// <https://dvcs.w3.org/hg/webcrypto-api/raw-file/tip/spec/Overview.html#dfn-GlobalCrypto>
1304    fn Crypto(&self) -> DomRoot<Crypto> {
1305        self.as_global_scope().crypto(CanGc::note())
1306    }
1307
1308    /// <https://html.spec.whatwg.org/multipage/#dom-frameelement>
1309    fn GetFrameElement(&self) -> Option<DomRoot<Element>> {
1310        // Steps 1-3.
1311        let window_proxy = self.window_proxy.get()?;
1312
1313        // Step 4-5.
1314        let container = window_proxy.frame_element()?;
1315
1316        // Step 6.
1317        let container_doc = container.owner_document();
1318        let current_doc = GlobalScope::current()
1319            .expect("No current global object")
1320            .as_window()
1321            .Document();
1322        if !current_doc
1323            .origin()
1324            .same_origin_domain(container_doc.origin())
1325        {
1326            return None;
1327        }
1328        // Step 7.
1329        Some(DomRoot::from_ref(container))
1330    }
1331
1332    /// <https://html.spec.whatwg.org/multipage/#dom-navigator>
1333    fn Navigator(&self) -> DomRoot<Navigator> {
1334        self.navigator
1335            .or_init(|| Navigator::new(self, CanGc::note()))
1336    }
1337
1338    /// <https://html.spec.whatwg.org/multipage/#dom-settimeout>
1339    fn SetTimeout(
1340        &self,
1341        _cx: JSContext,
1342        callback: TrustedScriptOrStringOrFunction,
1343        timeout: i32,
1344        args: Vec<HandleValue>,
1345        can_gc: CanGc,
1346    ) -> Fallible<i32> {
1347        let callback = match callback {
1348            TrustedScriptOrStringOrFunction::String(i) => {
1349                TimerCallback::StringTimerCallback(TrustedScriptOrString::String(i))
1350            },
1351            TrustedScriptOrStringOrFunction::TrustedScript(i) => {
1352                TimerCallback::StringTimerCallback(TrustedScriptOrString::TrustedScript(i))
1353            },
1354            TrustedScriptOrStringOrFunction::Function(i) => TimerCallback::FunctionTimerCallback(i),
1355        };
1356        self.as_global_scope().set_timeout_or_interval(
1357            callback,
1358            args,
1359            Duration::from_millis(timeout.max(0) as u64),
1360            IsInterval::NonInterval,
1361            can_gc,
1362        )
1363    }
1364
1365    /// <https://html.spec.whatwg.org/multipage/#dom-windowtimers-cleartimeout>
1366    fn ClearTimeout(&self, handle: i32) {
1367        self.as_global_scope().clear_timeout_or_interval(handle);
1368    }
1369
1370    /// <https://html.spec.whatwg.org/multipage/#dom-windowtimers-setinterval>
1371    fn SetInterval(
1372        &self,
1373        _cx: JSContext,
1374        callback: TrustedScriptOrStringOrFunction,
1375        timeout: i32,
1376        args: Vec<HandleValue>,
1377        can_gc: CanGc,
1378    ) -> Fallible<i32> {
1379        let callback = match callback {
1380            TrustedScriptOrStringOrFunction::String(i) => {
1381                TimerCallback::StringTimerCallback(TrustedScriptOrString::String(i))
1382            },
1383            TrustedScriptOrStringOrFunction::TrustedScript(i) => {
1384                TimerCallback::StringTimerCallback(TrustedScriptOrString::TrustedScript(i))
1385            },
1386            TrustedScriptOrStringOrFunction::Function(i) => TimerCallback::FunctionTimerCallback(i),
1387        };
1388        self.as_global_scope().set_timeout_or_interval(
1389            callback,
1390            args,
1391            Duration::from_millis(timeout.max(0) as u64),
1392            IsInterval::Interval,
1393            can_gc,
1394        )
1395    }
1396
1397    /// <https://html.spec.whatwg.org/multipage/#dom-windowtimers-clearinterval>
1398    fn ClearInterval(&self, handle: i32) {
1399        self.ClearTimeout(handle);
1400    }
1401
1402    /// <https://html.spec.whatwg.org/multipage/#dom-queuemicrotask>
1403    fn QueueMicrotask(&self, callback: Rc<VoidFunction>) {
1404        ScriptThread::enqueue_microtask(Microtask::User(UserMicrotask {
1405            callback,
1406            pipeline: self.pipeline_id(),
1407        }));
1408    }
1409
1410    /// <https://html.spec.whatwg.org/multipage/#dom-createimagebitmap>
1411    fn CreateImageBitmap(
1412        &self,
1413        image: ImageBitmapSource,
1414        options: &ImageBitmapOptions,
1415        can_gc: CanGc,
1416    ) -> Rc<Promise> {
1417        ImageBitmap::create_image_bitmap(
1418            self.as_global_scope(),
1419            image,
1420            0,
1421            0,
1422            None,
1423            None,
1424            options,
1425            can_gc,
1426        )
1427    }
1428
1429    /// <https://html.spec.whatwg.org/multipage/#dom-createimagebitmap>
1430    fn CreateImageBitmap_(
1431        &self,
1432        image: ImageBitmapSource,
1433        sx: i32,
1434        sy: i32,
1435        sw: i32,
1436        sh: i32,
1437        options: &ImageBitmapOptions,
1438        can_gc: CanGc,
1439    ) -> Rc<Promise> {
1440        ImageBitmap::create_image_bitmap(
1441            self.as_global_scope(),
1442            image,
1443            sx,
1444            sy,
1445            Some(sw),
1446            Some(sh),
1447            options,
1448            can_gc,
1449        )
1450    }
1451
1452    /// <https://html.spec.whatwg.org/multipage/#dom-window>
1453    fn Window(&self) -> DomRoot<WindowProxy> {
1454        self.window_proxy()
1455    }
1456
1457    /// <https://html.spec.whatwg.org/multipage/#dom-self>
1458    fn Self_(&self) -> DomRoot<WindowProxy> {
1459        self.window_proxy()
1460    }
1461
1462    /// <https://html.spec.whatwg.org/multipage/#dom-frames>
1463    fn Frames(&self) -> DomRoot<WindowProxy> {
1464        self.window_proxy()
1465    }
1466
1467    /// <https://html.spec.whatwg.org/multipage/#accessing-other-browsing-contexts>
1468    fn Length(&self) -> u32 {
1469        self.Document().iframes().iter().count() as u32
1470    }
1471
1472    /// <https://html.spec.whatwg.org/multipage/#dom-parent>
1473    fn GetParent(&self) -> Option<DomRoot<WindowProxy>> {
1474        // Steps 1-3.
1475        let window_proxy = self.undiscarded_window_proxy()?;
1476
1477        // Step 4.
1478        if let Some(parent) = window_proxy.parent() {
1479            return Some(DomRoot::from_ref(parent));
1480        }
1481        // Step 5.
1482        Some(window_proxy)
1483    }
1484
1485    /// <https://html.spec.whatwg.org/multipage/#dom-top>
1486    fn GetTop(&self) -> Option<DomRoot<WindowProxy>> {
1487        // Steps 1-3.
1488        let window_proxy = self.undiscarded_window_proxy()?;
1489
1490        // Steps 4-5.
1491        Some(DomRoot::from_ref(window_proxy.top()))
1492    }
1493
1494    // https://dvcs.w3.org/hg/webperf/raw-file/tip/specs/
1495    // NavigationTiming/Overview.html#sec-window.performance-attribute
1496    fn Performance(&self) -> DomRoot<Performance> {
1497        self.performance.or_init(|| {
1498            Performance::new(
1499                self.as_global_scope(),
1500                self.navigation_start.get(),
1501                CanGc::note(),
1502            )
1503        })
1504    }
1505
1506    // https://html.spec.whatwg.org/multipage/#globaleventhandlers
1507    global_event_handlers!();
1508
1509    // https://html.spec.whatwg.org/multipage/#windoweventhandlers
1510    window_event_handlers!();
1511
1512    /// <https://developer.mozilla.org/en-US/docs/Web/API/Window/screen>
1513    fn Screen(&self) -> DomRoot<Screen> {
1514        self.screen.or_init(|| Screen::new(self, CanGc::note()))
1515    }
1516
1517    /// <https://html.spec.whatwg.org/multipage/#dom-windowbase64-btoa>
1518    fn Btoa(&self, btoa: DOMString) -> Fallible<DOMString> {
1519        base64_btoa(btoa)
1520    }
1521
1522    /// <https://html.spec.whatwg.org/multipage/#dom-windowbase64-atob>
1523    fn Atob(&self, atob: DOMString) -> Fallible<DOMString> {
1524        base64_atob(atob)
1525    }
1526
1527    /// <https://html.spec.whatwg.org/multipage/#dom-window-requestanimationframe>
1528    fn RequestAnimationFrame(&self, callback: Rc<FrameRequestCallback>) -> u32 {
1529        self.Document()
1530            .request_animation_frame(AnimationFrameCallback::FrameRequestCallback { callback })
1531    }
1532
1533    /// <https://html.spec.whatwg.org/multipage/#dom-window-cancelanimationframe>
1534    fn CancelAnimationFrame(&self, ident: u32) {
1535        let doc = self.Document();
1536        doc.cancel_animation_frame(ident);
1537    }
1538
1539    /// <https://html.spec.whatwg.org/multipage/#dom-window-postmessage>
1540    fn PostMessage(
1541        &self,
1542        cx: JSContext,
1543        message: HandleValue,
1544        target_origin: USVString,
1545        transfer: CustomAutoRooterGuard<Vec<*mut JSObject>>,
1546    ) -> ErrorResult {
1547        let incumbent = GlobalScope::incumbent().expect("no incumbent global?");
1548        let source = incumbent.as_window();
1549        let source_origin = source.Document().origin().immutable().clone();
1550
1551        self.post_message_impl(&target_origin, source_origin, source, cx, message, transfer)
1552    }
1553
1554    /// <https://html.spec.whatwg.org/multipage/#dom-messageport-postmessage>
1555    fn PostMessage_(
1556        &self,
1557        cx: JSContext,
1558        message: HandleValue,
1559        options: RootedTraceableBox<WindowPostMessageOptions>,
1560    ) -> ErrorResult {
1561        let mut rooted = CustomAutoRooter::new(
1562            options
1563                .parent
1564                .transfer
1565                .iter()
1566                .map(|js: &RootedTraceableBox<Heap<*mut JSObject>>| js.get())
1567                .collect(),
1568        );
1569        let transfer = CustomAutoRooterGuard::new(*cx, &mut rooted);
1570
1571        let incumbent = GlobalScope::incumbent().expect("no incumbent global?");
1572        let source = incumbent.as_window();
1573
1574        let source_origin = source.Document().origin().immutable().clone();
1575
1576        self.post_message_impl(
1577            &options.targetOrigin,
1578            source_origin,
1579            source,
1580            cx,
1581            message,
1582            transfer,
1583        )
1584    }
1585
1586    /// <https://html.spec.whatwg.org/multipage/#dom-window-captureevents>
1587    fn CaptureEvents(&self) {
1588        // This method intentionally does nothing
1589    }
1590
1591    /// <https://html.spec.whatwg.org/multipage/#dom-window-releaseevents>
1592    fn ReleaseEvents(&self) {
1593        // This method intentionally does nothing
1594    }
1595
1596    // check-tidy: no specs after this line
1597    fn Debug(&self, message: DOMString) {
1598        debug!("{}", message);
1599    }
1600
1601    #[expect(unsafe_code)]
1602    fn Gc(&self) {
1603        unsafe {
1604            JS_GC(*self.get_cx(), GCReason::API);
1605        }
1606    }
1607
1608    #[expect(unsafe_code)]
1609    fn Js_backtrace(&self) {
1610        unsafe {
1611            println!("Current JS stack:");
1612            dump_js_stack(*self.get_cx());
1613            let rust_stack = Backtrace::new();
1614            println!("Current Rust stack:\n{:?}", rust_stack);
1615        }
1616    }
1617
1618    fn WebdriverCallback(&self, cx: JSContext, value: HandleValue, realm: InRealm, can_gc: CanGc) {
1619        let webdriver_script_sender = self.webdriver_script_chan.borrow_mut().take();
1620        if let Some(webdriver_script_sender) = webdriver_script_sender {
1621            let result = jsval_to_webdriver(cx, &self.globalscope, value, realm, can_gc);
1622            let _ = webdriver_script_sender.send(result);
1623        }
1624    }
1625
1626    fn WebdriverException(&self, cx: JSContext, value: HandleValue, can_gc: CanGc) {
1627        let webdriver_script_sender = self.webdriver_script_chan.borrow_mut().take();
1628        if let Some(webdriver_script_sender) = webdriver_script_sender {
1629            let _ =
1630                webdriver_script_sender.send(Err(JavaScriptEvaluationError::EvaluationFailure(
1631                    Some(javascript_error_info_from_error_info(
1632                        cx,
1633                        &ErrorInfo::from_value(value, cx, can_gc),
1634                        value,
1635                        can_gc,
1636                    )),
1637                )));
1638        }
1639    }
1640
1641    fn WebdriverElement(&self, id: DOMString) -> Option<DomRoot<Element>> {
1642        find_node_by_unique_id_in_document(&self.Document(), id.into()).and_then(Root::downcast)
1643    }
1644
1645    fn WebdriverFrame(&self, browsing_context_id: DOMString) -> Option<DomRoot<WindowProxy>> {
1646        self.Document()
1647            .iframes()
1648            .iter()
1649            .find(|iframe| {
1650                iframe
1651                    .browsing_context_id()
1652                    .as_ref()
1653                    .map(BrowsingContextId::to_string) ==
1654                    Some(browsing_context_id.to_string())
1655            })
1656            .and_then(|iframe| iframe.GetContentWindow())
1657    }
1658
1659    fn WebdriverWindow(&self, webview_id: DOMString) -> DomRoot<WindowProxy> {
1660        let window_proxy = &self
1661            .window_proxy
1662            .get()
1663            .expect("Should always have a WindowProxy when calling WebdriverWindow");
1664        // Window must be top level browsing context.
1665        assert!(window_proxy.browsing_context_id() == window_proxy.webview_id());
1666        assert!(self.webview_id().to_string() == webview_id);
1667        DomRoot::from_ref(window_proxy)
1668    }
1669
1670    fn WebdriverShadowRoot(&self, id: DOMString) -> Option<DomRoot<ShadowRoot>> {
1671        find_node_by_unique_id_in_document(&self.Document(), id.into()).and_then(Root::downcast)
1672    }
1673
1674    /// <https://drafts.csswg.org/cssom/#dom-window-getcomputedstyle>
1675    fn GetComputedStyle(
1676        &self,
1677        element: &Element,
1678        pseudo: Option<DOMString>,
1679    ) -> DomRoot<CSSStyleDeclaration> {
1680        // Step 2: Let obj be elt.
1681        // We don't store CSSStyleOwner directly because it stores a `Dom` which must be
1682        // rooted. This avoids the rooting the value temporarily.
1683        let mut is_null = false;
1684
1685        // Step 3: If pseudoElt is provided, is not the empty string, and starts with a colon, then:
1686        // Step 3.1: Parse pseudoElt as a <pseudo-element-selector>, and let type be the result.
1687        let pseudo = pseudo.map(|mut s| {
1688            s.make_ascii_lowercase();
1689            s
1690        });
1691        let pseudo = match pseudo {
1692            Some(ref pseudo) if pseudo == ":before" || pseudo == "::before" => {
1693                Some(PseudoElement::Before)
1694            },
1695            Some(ref pseudo) if pseudo == ":after" || pseudo == "::after" => {
1696                Some(PseudoElement::After)
1697            },
1698            Some(ref pseudo) if pseudo == "::selection" => Some(PseudoElement::Selection),
1699            Some(ref pseudo) if pseudo == "::marker" => Some(PseudoElement::Marker),
1700            Some(ref pseudo) if pseudo.starts_with(':') => {
1701                // Step 3.2: If type is failure, or is a ::slotted() or ::part()
1702                // pseudo-element, let obj be null.
1703                is_null = true;
1704                None
1705            },
1706            _ => None,
1707        };
1708
1709        // Step 4. Let decls be an empty list of CSS declarations.
1710        // Step 5: If obj is not null, and elt is connected, part of the flat tree, and
1711        // its shadow-including root has a browsing context which either doesn’t have a
1712        // browsing context container, or whose browsing context container is being
1713        // rendered, set decls to a list of all longhand properties that are supported CSS
1714        // properties, in lexicographical order, with the value being the resolved value
1715        // computed for obj using the style rules associated with doc.  Additionally,
1716        // append to decls all the custom properties whose computed value for obj is not
1717        // the guaranteed-invalid value.
1718        //
1719        // Note: The specification says to generate the list of declarations beforehand, yet
1720        // also says the list should be alive. This is why we do not do step 4 and 5 here.
1721        // See: https://github.com/w3c/csswg-drafts/issues/6144
1722        //
1723        // Step 6:  Return a live CSSStyleProperties object with the following properties:
1724        CSSStyleDeclaration::new(
1725            self,
1726            if is_null {
1727                CSSStyleOwner::Null
1728            } else {
1729                CSSStyleOwner::Element(Dom::from_ref(element))
1730            },
1731            pseudo,
1732            CSSModificationAccess::Readonly,
1733            CanGc::note(),
1734        )
1735    }
1736
1737    // https://drafts.csswg.org/cssom-view/#dom-window-innerheight
1738    // TODO Include Scrollbar
1739    fn InnerHeight(&self) -> i32 {
1740        self.viewport_details
1741            .get()
1742            .size
1743            .height
1744            .to_i32()
1745            .unwrap_or(0)
1746    }
1747
1748    // https://drafts.csswg.org/cssom-view/#dom-window-innerwidth
1749    // TODO Include Scrollbar
1750    fn InnerWidth(&self) -> i32 {
1751        self.viewport_details.get().size.width.to_i32().unwrap_or(0)
1752    }
1753
1754    /// <https://drafts.csswg.org/cssom-view/#dom-window-scrollx>
1755    fn ScrollX(&self) -> i32 {
1756        self.scroll_offset().x as i32
1757    }
1758
1759    /// <https://drafts.csswg.org/cssom-view/#dom-window-pagexoffset>
1760    fn PageXOffset(&self) -> i32 {
1761        self.ScrollX()
1762    }
1763
1764    /// <https://drafts.csswg.org/cssom-view/#dom-window-scrolly>
1765    fn ScrollY(&self) -> i32 {
1766        self.scroll_offset().y as i32
1767    }
1768
1769    /// <https://drafts.csswg.org/cssom-view/#dom-window-pageyoffset>
1770    fn PageYOffset(&self) -> i32 {
1771        self.ScrollY()
1772    }
1773
1774    /// <https://drafts.csswg.org/cssom-view/#dom-window-scroll>
1775    fn Scroll(&self, options: &ScrollToOptions) {
1776        // Step 1: If invoked with one argument, follow these substeps:
1777        // Step 1.1: Let options be the argument.
1778        // Step 1.2: Let x be the value of the left dictionary member of options, if
1779        // present, or the viewport’s current scroll position on the x axis otherwise.
1780        let x = options.left.unwrap_or(0.0) as f32;
1781
1782        // Step 1.3: Let y be the value of the top dictionary member of options, if
1783        // present, or the viewport’s current scroll position on the y axis otherwise.
1784        let y = options.top.unwrap_or(0.0) as f32;
1785
1786        // The rest of the specification continues from `Self::scroll`.
1787        self.scroll(x, y, options.parent.behavior);
1788    }
1789
1790    /// <https://drafts.csswg.org/cssom-view/#dom-window-scroll>
1791    fn Scroll_(&self, x: f64, y: f64) {
1792        // Step 2: If invoked with two arguments, follow these substeps:
1793        // Step 2.1 Let options be null converted to a ScrollToOptions dictionary. [WEBIDL]
1794        // Step 2.2: Let x and y be the arguments, respectively.
1795        self.scroll(x as f32, y as f32, ScrollBehavior::Auto);
1796    }
1797
1798    /// <https://drafts.csswg.org/cssom-view/#dom-window-scrollto>
1799    ///
1800    /// > When the scrollTo() method is invoked, the user agent must act as if the
1801    /// > scroll() method was invoked with the same arguments.
1802    fn ScrollTo(&self, options: &ScrollToOptions) {
1803        self.Scroll(options);
1804    }
1805
1806    /// <https://drafts.csswg.org/cssom-view/#dom-window-scrollto>:
1807    ///
1808    /// > When the scrollTo() method is invoked, the user agent must act as if the
1809    /// > scroll() method was invoked with the same arguments.
1810    fn ScrollTo_(&self, x: f64, y: f64) {
1811        self.Scroll_(x, y)
1812    }
1813
1814    /// <https://drafts.csswg.org/cssom-view/#dom-window-scrollby>
1815    fn ScrollBy(&self, options: &ScrollToOptions) {
1816        // When the scrollBy() method is invoked, the user agent must run these steps:
1817        // Step 1: If invoked with two arguments, follow these substeps:
1818        //   This doesn't apply here.
1819
1820        // Step 2: Normalize non-finite values for the left and top dictionary members of options.
1821        let mut options = options.clone();
1822        let x = options.left.unwrap_or(0.0);
1823        let x = if x.is_finite() { x } else { 0.0 };
1824        let y = options.top.unwrap_or(0.0);
1825        let y = if y.is_finite() { y } else { 0.0 };
1826
1827        // Step 3: Add the value of scrollX to the left dictionary member.
1828        options.left.replace(x + self.ScrollX() as f64);
1829
1830        // Step 4. Add the value of scrollY to the top dictionary member.
1831        options.top.replace(y + self.ScrollY() as f64);
1832
1833        // Step 5: Act as if the scroll() method was invoked with options as the only argument.
1834        self.Scroll(&options)
1835    }
1836
1837    /// <https://drafts.csswg.org/cssom-view/#dom-window-scrollby>
1838    fn ScrollBy_(&self, x: f64, y: f64) {
1839        // When the scrollBy() method is invoked, the user agent must run these steps:
1840        // Step 1: If invoked with two arguments, follow these substeps:
1841        // Step 1.1: Let options be null converted to a ScrollToOptions dictionary.
1842        let mut options = ScrollToOptions::empty();
1843
1844        // Step 1.2: Let x and y be the arguments, respectively.
1845        // Step 1.3: Let the left dictionary member of options have the value x.
1846        options.left.replace(x);
1847
1848        // Step 1.5:  Let the top dictionary member of options have the value y.
1849        options.top.replace(y);
1850
1851        // Now follow the specification for the one argument option.
1852        self.ScrollBy(&options);
1853    }
1854
1855    /// <https://drafts.csswg.org/cssom-view/#dom-window-resizeto>
1856    fn ResizeTo(&self, width: i32, height: i32) {
1857        // Step 1
1858        let window_proxy = match self.window_proxy.get() {
1859            Some(proxy) => proxy,
1860            None => return,
1861        };
1862
1863        // If target is not an auxiliary browsing context that was created by a script
1864        // (as opposed to by an action of the user), then return.
1865        if !window_proxy.is_auxiliary() {
1866            return;
1867        }
1868
1869        let dpr = self.device_pixel_ratio();
1870        let size = Size2D::new(width, height).to_f32() * dpr;
1871        self.send_to_embedder(EmbedderMsg::ResizeTo(self.webview_id(), size.to_i32()));
1872    }
1873
1874    /// <https://drafts.csswg.org/cssom-view/#dom-window-resizeby>
1875    fn ResizeBy(&self, x: i32, y: i32) {
1876        let size = self.client_window().size();
1877        // Step 1
1878        self.ResizeTo(x + size.width, y + size.height)
1879    }
1880
1881    /// <https://drafts.csswg.org/cssom-view/#dom-window-moveto>
1882    fn MoveTo(&self, x: i32, y: i32) {
1883        // Step 1
1884        // TODO determine if this operation is allowed
1885        let dpr = self.device_pixel_ratio();
1886        let point = Point2D::new(x, y).to_f32() * dpr;
1887        let msg = EmbedderMsg::MoveTo(self.webview_id(), point.to_i32());
1888        self.send_to_embedder(msg);
1889    }
1890
1891    /// <https://drafts.csswg.org/cssom-view/#dom-window-moveby>
1892    fn MoveBy(&self, x: i32, y: i32) {
1893        let origin = self.client_window().min;
1894        // Step 1
1895        self.MoveTo(x + origin.x, y + origin.y)
1896    }
1897
1898    /// <https://drafts.csswg.org/cssom-view/#dom-window-screenx>
1899    fn ScreenX(&self) -> i32 {
1900        self.client_window().min.x
1901    }
1902
1903    /// <https://drafts.csswg.org/cssom-view/#dom-window-screeny>
1904    fn ScreenY(&self) -> i32 {
1905        self.client_window().min.y
1906    }
1907
1908    /// <https://drafts.csswg.org/cssom-view/#dom-window-outerheight>
1909    fn OuterHeight(&self) -> i32 {
1910        self.client_window().height()
1911    }
1912
1913    /// <https://drafts.csswg.org/cssom-view/#dom-window-outerwidth>
1914    fn OuterWidth(&self) -> i32 {
1915        self.client_window().width()
1916    }
1917
1918    /// <https://drafts.csswg.org/cssom-view/#dom-window-devicepixelratio>
1919    fn DevicePixelRatio(&self) -> Finite<f64> {
1920        Finite::wrap(self.device_pixel_ratio().get() as f64)
1921    }
1922
1923    /// <https://html.spec.whatwg.org/multipage/#dom-window-status>
1924    fn Status(&self) -> DOMString {
1925        self.status.borrow().clone()
1926    }
1927
1928    /// <https://html.spec.whatwg.org/multipage/#dom-window-status>
1929    fn SetStatus(&self, status: DOMString) {
1930        *self.status.borrow_mut() = status
1931    }
1932
1933    /// <https://drafts.csswg.org/cssom-view/#dom-window-matchmedia>
1934    fn MatchMedia(&self, query: DOMString) -> DomRoot<MediaQueryList> {
1935        let media_query_list = MediaList::parse_media_list(&query.str(), self);
1936        let document = self.Document();
1937        let mql = MediaQueryList::new(&document, media_query_list, CanGc::note());
1938        self.media_query_lists.track(&*mql);
1939        mql
1940    }
1941
1942    /// <https://fetch.spec.whatwg.org/#dom-global-fetch>
1943    fn Fetch(
1944        &self,
1945        input: RequestOrUSVString,
1946        init: RootedTraceableBox<RequestInit>,
1947        comp: InRealm,
1948        can_gc: CanGc,
1949    ) -> Rc<Promise> {
1950        fetch::Fetch(self.upcast(), input, init, comp, can_gc)
1951    }
1952
1953    /// <https://fetch.spec.whatwg.org/#dom-window-fetchlater>
1954    fn FetchLater(
1955        &self,
1956        input: RequestInfo,
1957        init: RootedTraceableBox<DeferredRequestInit>,
1958        can_gc: CanGc,
1959    ) -> Fallible<DomRoot<FetchLaterResult>> {
1960        fetch::FetchLater(self, input, init, can_gc)
1961    }
1962
1963    #[cfg(feature = "bluetooth")]
1964    fn TestRunner(&self) -> DomRoot<TestRunner> {
1965        self.test_runner
1966            .or_init(|| TestRunner::new(self.upcast(), CanGc::note()))
1967    }
1968
1969    fn RunningAnimationCount(&self) -> u32 {
1970        self.document
1971            .get()
1972            .map_or(0, |d| d.animations().running_animation_count() as u32)
1973    }
1974
1975    /// <https://html.spec.whatwg.org/multipage/#dom-name>
1976    fn SetName(&self, name: DOMString) {
1977        if let Some(proxy) = self.undiscarded_window_proxy() {
1978            proxy.set_name(name);
1979        }
1980    }
1981
1982    /// <https://html.spec.whatwg.org/multipage/#dom-name>
1983    fn Name(&self) -> DOMString {
1984        match self.undiscarded_window_proxy() {
1985            Some(proxy) => proxy.get_name(),
1986            None => "".into(),
1987        }
1988    }
1989
1990    /// <https://html.spec.whatwg.org/multipage/#dom-origin>
1991    fn Origin(&self) -> USVString {
1992        USVString(self.origin().immutable().ascii_serialization())
1993    }
1994
1995    /// <https://w3c.github.io/selection-api/#dom-window-getselection>
1996    fn GetSelection(&self) -> Option<DomRoot<Selection>> {
1997        self.document
1998            .get()
1999            .and_then(|d| d.GetSelection(CanGc::note()))
2000    }
2001
2002    /// <https://dom.spec.whatwg.org/#dom-window-event>
2003    fn Event(&self, cx: JSContext, rval: MutableHandleValue) {
2004        if let Some(ref event) = *self.current_event.borrow() {
2005            event
2006                .reflector()
2007                .get_jsobject()
2008                .safe_to_jsval(cx, rval, CanGc::note());
2009        }
2010    }
2011
2012    fn IsSecureContext(&self) -> bool {
2013        self.as_global_scope().is_secure_context()
2014    }
2015
2016    /// <https://html.spec.whatwg.org/multipage/#dom-window-nameditem>
2017    fn NamedGetter(&self, name: DOMString) -> Option<NamedPropertyValue> {
2018        if name.is_empty() {
2019            return None;
2020        }
2021        let document = self.Document();
2022
2023        // https://html.spec.whatwg.org/multipage/#document-tree-child-browsing-context-name-property-set
2024        let iframes: Vec<_> = document
2025            .iframes()
2026            .iter()
2027            .filter(|iframe| {
2028                if let Some(window) = iframe.GetContentWindow() {
2029                    return window.get_name() == name;
2030                }
2031                false
2032            })
2033            .collect();
2034
2035        let iframe_iter = iframes.iter().map(|iframe| iframe.upcast::<Element>());
2036
2037        let name = Atom::from(name);
2038
2039        // Step 1.
2040        let elements_with_name = document.get_elements_with_name(&name);
2041        let name_iter = elements_with_name
2042            .iter()
2043            .map(|element| &**element)
2044            .filter(|elem| is_named_element_with_name_attribute(elem));
2045        let elements_with_id = document.get_elements_with_id(&name);
2046        let id_iter = elements_with_id
2047            .iter()
2048            .map(|element| &**element)
2049            .filter(|elem| is_named_element_with_id_attribute(elem));
2050
2051        // Step 2.
2052        for elem in iframe_iter.clone() {
2053            if let Some(nested_window_proxy) = elem
2054                .downcast::<HTMLIFrameElement>()
2055                .and_then(|iframe| iframe.GetContentWindow())
2056            {
2057                return Some(NamedPropertyValue::WindowProxy(nested_window_proxy));
2058            }
2059        }
2060
2061        let mut elements = iframe_iter.chain(name_iter).chain(id_iter);
2062
2063        let first = elements.next()?;
2064
2065        if elements.next().is_none() {
2066            // Step 3.
2067            return Some(NamedPropertyValue::Element(DomRoot::from_ref(first)));
2068        }
2069
2070        // Step 4.
2071        #[derive(JSTraceable, MallocSizeOf)]
2072        struct WindowNamedGetter {
2073            #[no_trace]
2074            name: Atom,
2075        }
2076        impl CollectionFilter for WindowNamedGetter {
2077            fn filter(&self, elem: &Element, _root: &Node) -> bool {
2078                let type_ = match elem.upcast::<Node>().type_id() {
2079                    NodeTypeId::Element(ElementTypeId::HTMLElement(type_)) => type_,
2080                    _ => return false,
2081                };
2082                if elem.get_id().as_ref() == Some(&self.name) {
2083                    return true;
2084                }
2085                match type_ {
2086                    HTMLElementTypeId::HTMLEmbedElement |
2087                    HTMLElementTypeId::HTMLFormElement |
2088                    HTMLElementTypeId::HTMLImageElement |
2089                    HTMLElementTypeId::HTMLObjectElement => {
2090                        elem.get_name().as_ref() == Some(&self.name)
2091                    },
2092                    _ => false,
2093                }
2094            }
2095        }
2096        let collection = HTMLCollection::create(
2097            self,
2098            document.upcast(),
2099            Box::new(WindowNamedGetter { name }),
2100            CanGc::note(),
2101        );
2102        Some(NamedPropertyValue::HTMLCollection(collection))
2103    }
2104
2105    /// <https://html.spec.whatwg.org/multipage/#dom-tree-accessors:supported-property-names>
2106    fn SupportedPropertyNames(&self) -> Vec<DOMString> {
2107        let mut names_with_first_named_element_map: HashMap<&Atom, &Element> = HashMap::new();
2108
2109        let document = self.Document();
2110        let name_map = document.name_map();
2111        for (name, elements) in &name_map.0 {
2112            if name.is_empty() {
2113                continue;
2114            }
2115            let mut name_iter = elements
2116                .iter()
2117                .filter(|elem| is_named_element_with_name_attribute(elem));
2118            if let Some(first) = name_iter.next() {
2119                names_with_first_named_element_map.insert(name, first);
2120            }
2121        }
2122        let id_map = document.id_map();
2123        for (id, elements) in &id_map.0 {
2124            if id.is_empty() {
2125                continue;
2126            }
2127            let mut id_iter = elements
2128                .iter()
2129                .filter(|elem| is_named_element_with_id_attribute(elem));
2130            if let Some(first) = id_iter.next() {
2131                match names_with_first_named_element_map.entry(id) {
2132                    Entry::Vacant(entry) => drop(entry.insert(first)),
2133                    Entry::Occupied(mut entry) => {
2134                        if first.upcast::<Node>().is_before(entry.get().upcast()) {
2135                            *entry.get_mut() = first;
2136                        }
2137                    },
2138                }
2139            }
2140        }
2141
2142        let mut names_with_first_named_element_vec: Vec<(&Atom, &Element)> =
2143            names_with_first_named_element_map
2144                .iter()
2145                .map(|(k, v)| (*k, *v))
2146                .collect();
2147        names_with_first_named_element_vec.sort_unstable_by(|a, b| {
2148            if a.1 == b.1 {
2149                // This can happen if an img has an id different from its name,
2150                // spec does not say which string to put first.
2151                a.0.cmp(b.0)
2152            } else if a.1.upcast::<Node>().is_before(b.1.upcast::<Node>()) {
2153                cmp::Ordering::Less
2154            } else {
2155                cmp::Ordering::Greater
2156            }
2157        });
2158
2159        names_with_first_named_element_vec
2160            .iter()
2161            .map(|(k, _v)| DOMString::from(&***k))
2162            .collect()
2163    }
2164
2165    /// <https://html.spec.whatwg.org/multipage/#dom-structuredclone>
2166    fn StructuredClone(
2167        &self,
2168        cx: JSContext,
2169        value: HandleValue,
2170        options: RootedTraceableBox<StructuredSerializeOptions>,
2171        can_gc: CanGc,
2172        retval: MutableHandleValue,
2173    ) -> Fallible<()> {
2174        self.as_global_scope()
2175            .structured_clone(cx, value, options, retval, can_gc)
2176    }
2177
2178    fn TrustedTypes(&self, can_gc: CanGc) -> DomRoot<TrustedTypePolicyFactory> {
2179        self.trusted_types
2180            .or_init(|| TrustedTypePolicyFactory::new(self.as_global_scope(), can_gc))
2181    }
2182}
2183
2184impl Window {
2185    pub(crate) fn scroll_offset(&self) -> Vector2D<f32, LayoutPixel> {
2186        self.scroll_offset_query_with_external_scroll_id(self.pipeline_id().root_scroll_id())
2187    }
2188
2189    // https://heycam.github.io/webidl/#named-properties-object
2190    // https://html.spec.whatwg.org/multipage/#named-access-on-the-window-object
2191    pub(crate) fn create_named_properties_object(
2192        cx: JSContext,
2193        proto: HandleObject,
2194        object: MutableHandleObject,
2195    ) {
2196        window_named_properties::create(cx, proto, object)
2197    }
2198
2199    pub(crate) fn current_event(&self) -> Option<DomRoot<Event>> {
2200        self.current_event
2201            .borrow()
2202            .as_ref()
2203            .map(|e| DomRoot::from_ref(&**e))
2204    }
2205
2206    pub(crate) fn set_current_event(&self, event: Option<&Event>) -> Option<DomRoot<Event>> {
2207        let current = self.current_event();
2208        *self.current_event.borrow_mut() = event.map(Dom::from_ref);
2209        current
2210    }
2211
2212    /// <https://html.spec.whatwg.org/multipage/#window-post-message-steps>
2213    fn post_message_impl(
2214        &self,
2215        target_origin: &USVString,
2216        source_origin: ImmutableOrigin,
2217        source: &Window,
2218        cx: JSContext,
2219        message: HandleValue,
2220        transfer: CustomAutoRooterGuard<Vec<*mut JSObject>>,
2221    ) -> ErrorResult {
2222        // Step 1-2, 6-8.
2223        let data = structuredclone::write(cx, message, Some(transfer))?;
2224
2225        // Step 3-5.
2226        let target_origin = match target_origin.0[..].as_ref() {
2227            "*" => None,
2228            "/" => Some(source_origin.clone()),
2229            url => match ServoUrl::parse(url) {
2230                Ok(url) => Some(url.origin().clone()),
2231                Err(_) => return Err(Error::Syntax(None)),
2232            },
2233        };
2234
2235        // Step 9.
2236        self.post_message(target_origin, source_origin, &source.window_proxy(), data);
2237        Ok(())
2238    }
2239
2240    // https://drafts.css-houdini.org/css-paint-api-1/#paint-worklet
2241    pub(crate) fn paint_worklet(&self) -> DomRoot<Worklet> {
2242        self.paint_worklet
2243            .or_init(|| self.new_paint_worklet(CanGc::note()))
2244    }
2245
2246    pub(crate) fn has_document(&self) -> bool {
2247        self.document.get().is_some()
2248    }
2249
2250    pub(crate) fn clear_js_runtime(&self) {
2251        self.as_global_scope()
2252            .remove_web_messaging_and_dedicated_workers_infra();
2253
2254        // Clean up any active promises
2255        // https://github.com/servo/servo/issues/15318
2256        if let Some(custom_elements) = self.custom_element_registry.get() {
2257            custom_elements.teardown();
2258        }
2259
2260        self.current_state.set(WindowState::Zombie);
2261        *self.js_runtime.borrow_mut() = None;
2262
2263        // If this is the currently active pipeline,
2264        // nullify the window_proxy.
2265        if let Some(proxy) = self.window_proxy.get() {
2266            let pipeline_id = self.pipeline_id();
2267            if let Some(currently_active) = proxy.currently_active() {
2268                if currently_active == pipeline_id {
2269                    self.window_proxy.set(None);
2270                }
2271            }
2272        }
2273
2274        if let Some(performance) = self.performance.get() {
2275            performance.clear_and_disable_performance_entry_buffer();
2276        }
2277        self.as_global_scope()
2278            .task_manager()
2279            .cancel_all_tasks_and_ignore_future_tasks();
2280    }
2281
2282    /// <https://drafts.csswg.org/cssom-view/#dom-window-scroll>
2283    pub(crate) fn scroll(&self, x: f32, y: f32, behavior: ScrollBehavior) {
2284        // Step 3: Normalize non-finite values for x and y.
2285        let xfinite = if x.is_finite() { x } else { 0.0 };
2286        let yfinite = if y.is_finite() { y } else { 0.0 };
2287
2288        // Step 4: If there is no viewport, abort these steps.
2289        // Currently every frame has a viewport in Servo.
2290
2291        // Step 5. Let `viewport width` be the width of the viewport excluding the width
2292        // of the scroll bar, if any.
2293        // Step 6. `Let viewport height` be the height of the viewport excluding the
2294        // height of the scroll bar, if any.
2295        //
2296        // TODO: Servo does not yet support scrollbars.
2297        let viewport = self.viewport_details.get().size;
2298
2299        // Step 7:
2300        // If the viewport has rightward overflow direction
2301        //    Let x be max(0, min(x, viewport scrolling area width - viewport width)).
2302        // If the viewport has leftward overflow direction
2303        //    Let x be min(0, max(x, viewport width - viewport scrolling area width)).
2304        // TODO: Implement this.
2305
2306        // Step 8:
2307        // If the viewport has downward overflow direction
2308        //    Let y be max(0, min(y, viewport scrolling area height - viewport height)).
2309        // If the viewport has upward overflow direction
2310        //    Let y be min(0, max(y, viewport height - viewport scrolling area height)).
2311        // TODO: Implement this.
2312
2313        // Step 9: Let position be the scroll position the viewport would have by aligning
2314        // the x-coordinate x of the viewport scrolling area with the left of the viewport
2315        // and aligning the y-coordinate y of the viewport scrolling area with the top of
2316        // the viewport.
2317        let scrolling_area = self.scrolling_area_query(None).to_f32();
2318        let x = xfinite.clamp(0.0, 0.0f32.max(scrolling_area.width() - viewport.width));
2319        let y = yfinite.clamp(0.0, 0.0f32.max(scrolling_area.height() - viewport.height));
2320
2321        // Step 10: If position is the same as the viewport’s current scroll position, and
2322        // the viewport does not have an ongoing smooth scroll, abort these steps.
2323        let scroll_offset = self.scroll_offset();
2324        if x == scroll_offset.x && y == scroll_offset.y {
2325            return;
2326        }
2327
2328        // Step 11: Let document be the viewport’s associated Document.
2329        // Step 12: Perform a scroll of the viewport to position, document’s root element
2330        // as the associated element, if there is one, or null otherwise, and the scroll
2331        // behavior being the value of the behavior dictionary member of options.
2332        self.perform_a_scroll(x, y, self.pipeline_id().root_scroll_id(), behavior, None);
2333    }
2334
2335    /// <https://drafts.csswg.org/cssom-view/#perform-a-scroll>
2336    pub(crate) fn perform_a_scroll(
2337        &self,
2338        x: f32,
2339        y: f32,
2340        scroll_id: ExternalScrollId,
2341        _behavior: ScrollBehavior,
2342        element: Option<&Element>,
2343    ) {
2344        // TODO Step 1
2345        // TODO(mrobinson, #18709): Add smooth scrolling support to WebRender so that we can
2346        // properly process ScrollBehavior here.
2347        let reflow_phases_run =
2348            self.reflow(ReflowGoal::UpdateScrollNode(scroll_id, Vector2D::new(x, y)));
2349        if reflow_phases_run.needs_frame() {
2350            self.compositor_api()
2351                .generate_frame(vec![self.webview_id()]);
2352        }
2353
2354        // > If the scroll position did not change as a result of the user interaction or programmatic
2355        // > invocation, where no translations were applied as a result, then no scrollend event fires
2356        // > because no scrolling occurred.
2357        // Even though the note mention the scrollend, it is relevant to the scroll as well.
2358        if reflow_phases_run.contains(ReflowPhasesRun::UpdatedScrollNodeOffset) {
2359            match element {
2360                Some(el) => self.Document().handle_element_scroll_event(el),
2361                None => self.Document().handle_viewport_scroll_event(),
2362            };
2363        }
2364    }
2365
2366    pub(crate) fn device_pixel_ratio(&self) -> Scale<f32, CSSPixel, DevicePixel> {
2367        self.viewport_details.get().hidpi_scale_factor
2368    }
2369
2370    fn client_window(&self) -> DeviceIndependentIntRect {
2371        let (sender, receiver) = generic_channel::channel().expect("Failed to create IPC channel!");
2372
2373        self.send_to_embedder(EmbedderMsg::GetWindowRect(self.webview_id(), sender));
2374
2375        receiver.recv().unwrap_or_default()
2376    }
2377
2378    /// Prepares to tick animations and then does a reflow which also advances the
2379    /// layout animation clock.
2380    pub(crate) fn advance_animation_clock(&self, delta_ms: i32) {
2381        self.Document()
2382            .advance_animation_timeline_for_testing(delta_ms as f64 / 1000.);
2383        ScriptThread::handle_tick_all_animations_for_testing(self.pipeline_id());
2384    }
2385
2386    /// Reflows the page unconditionally if possible and not suppressed. This method will wait for
2387    /// the layout to complete. If there is no window size yet, the page is presumed invisible and
2388    /// no reflow is performed. If reflow is suppressed, no reflow will be performed for ForDisplay
2389    /// goals.
2390    ///
2391    /// NOTE: This method should almost never be called directly! Layout and rendering updates should
2392    /// happen as part of the HTML event loop via *update the rendering*.
2393    pub(crate) fn reflow(&self, reflow_goal: ReflowGoal) -> ReflowPhasesRun {
2394        let document = self.Document();
2395
2396        // Never reflow inactive Documents.
2397        if !document.is_fully_active() {
2398            return ReflowPhasesRun::empty();
2399        }
2400
2401        self.Document().ensure_safe_to_run_script_or_layout();
2402
2403        // If layouts are blocked, we block all layouts that are for display only. Other
2404        // layouts (for queries and scrolling) are not blocked, as they do not display
2405        // anything and script expects the layout to be up-to-date after they run.
2406        let pipeline_id = self.pipeline_id();
2407        if reflow_goal == ReflowGoal::UpdateTheRendering &&
2408            self.layout_blocker.get().layout_blocked()
2409        {
2410            debug!("Suppressing pre-load-event reflow pipeline {pipeline_id}");
2411            return ReflowPhasesRun::empty();
2412        }
2413
2414        debug!("script: performing reflow for goal {reflow_goal:?}");
2415        let marker = if self.need_emit_timeline_marker(TimelineMarkerType::Reflow) {
2416            Some(TimelineMarker::start("Reflow".to_owned()))
2417        } else {
2418            None
2419        };
2420
2421        let restyle_reason = document.restyle_reason();
2422        document.clear_restyle_reasons();
2423        let restyle = if restyle_reason.needs_restyle() {
2424            debug!("Invalidating layout cache due to reflow condition {restyle_reason:?}",);
2425            // Invalidate any existing cached layout values.
2426            self.layout_marker.borrow().set(false);
2427            // Create a new layout caching token.
2428            *self.layout_marker.borrow_mut() = Rc::new(Cell::new(true));
2429
2430            let stylesheets_changed = document.flush_stylesheets_for_reflow();
2431            let pending_restyles = document.drain_pending_restyles();
2432            let dirty_root = document
2433                .take_dirty_root()
2434                .filter(|_| !stylesheets_changed)
2435                .or_else(|| document.GetDocumentElement())
2436                .map(|root| root.upcast::<Node>().to_trusted_node_address());
2437
2438            Some(ReflowRequestRestyle {
2439                reason: restyle_reason,
2440                dirty_root,
2441                stylesheets_changed,
2442                pending_restyles,
2443            })
2444        } else {
2445            None
2446        };
2447
2448        let reflow = ReflowRequest {
2449            document: document.upcast::<Node>().to_trusted_node_address(),
2450            epoch: document.current_rendering_epoch(),
2451            restyle,
2452            viewport_details: self.viewport_details.get(),
2453            origin: self.origin().immutable().clone(),
2454            reflow_goal,
2455            dom_count: document.dom_count(),
2456            animation_timeline_value: document.current_animation_timeline_value(),
2457            animations: document.animations().sets.clone(),
2458            animating_images: document.image_animation_manager().animating_images(),
2459            highlighted_dom_node: document.highlighted_dom_node().map(|node| node.to_opaque()),
2460        };
2461
2462        let Some(reflow_result) = self.layout.borrow_mut().reflow(reflow) else {
2463            return ReflowPhasesRun::empty();
2464        };
2465
2466        debug!("script: layout complete");
2467        if let Some(marker) = marker {
2468            self.emit_timeline_marker(marker.end());
2469        }
2470
2471        self.handle_pending_images_post_reflow(
2472            reflow_result.pending_images,
2473            reflow_result.pending_rasterization_images,
2474            reflow_result.pending_svg_elements_for_serialization,
2475        );
2476
2477        if let Some(iframe_sizes) = reflow_result.iframe_sizes {
2478            document
2479                .iframes_mut()
2480                .handle_new_iframe_sizes_after_layout(self, iframe_sizes);
2481        }
2482
2483        document.update_animations_post_reflow();
2484
2485        reflow_result.reflow_phases_run
2486    }
2487
2488    pub(crate) fn request_screenshot_readiness(&self, can_gc: CanGc) {
2489        self.has_pending_screenshot_readiness_request.set(true);
2490        self.maybe_resolve_pending_screenshot_readiness_requests(can_gc);
2491    }
2492
2493    pub(crate) fn maybe_resolve_pending_screenshot_readiness_requests(&self, can_gc: CanGc) {
2494        let pending_request = self.has_pending_screenshot_readiness_request.get();
2495        if !pending_request {
2496            return;
2497        }
2498
2499        let document = self.Document();
2500        if document.ReadyState() != DocumentReadyState::Complete {
2501            return;
2502        }
2503
2504        if document.render_blocking_element_count() > 0 {
2505            return;
2506        }
2507
2508        // Checks if the html element has reftest-wait attribute present.
2509        // See http://testthewebforward.org/docs/reftests.html
2510        // and https://web-platform-tests.org/writing-tests/crashtest.html
2511        if document.GetDocumentElement().is_some_and(|elem| {
2512            elem.has_class(&atom!("reftest-wait"), CaseSensitivity::CaseSensitive) ||
2513                elem.has_class(&Atom::from("test-wait"), CaseSensitivity::CaseSensitive)
2514        }) {
2515            return;
2516        }
2517
2518        if self.font_context().web_fonts_still_loading() != 0 {
2519            return;
2520        }
2521
2522        if self.Document().Fonts(can_gc).waiting_to_fullfill_promise() {
2523            return;
2524        }
2525
2526        if !self.pending_layout_images.borrow().is_empty() ||
2527            !self.pending_images_for_rasterization.borrow().is_empty()
2528        {
2529            return;
2530        }
2531
2532        let document = self.Document();
2533        if document.needs_rendering_update() {
2534            return;
2535        }
2536
2537        // When all these conditions are met, notify the Constellation that we are ready to
2538        // have our screenshot taken, when the given layout Epoch has been rendered.
2539        let epoch = document.current_rendering_epoch();
2540        let pipeline_id = self.pipeline_id();
2541        debug!("Ready to take screenshot of {pipeline_id:?} at epoch={epoch:?}");
2542
2543        self.send_to_constellation(
2544            ScriptToConstellationMessage::RespondToScreenshotReadinessRequest(
2545                ScreenshotReadinessResponse::Ready(epoch),
2546            ),
2547        );
2548        self.has_pending_screenshot_readiness_request.set(false);
2549    }
2550
2551    /// If parsing has taken a long time and reflows are still waiting for the `load` event,
2552    /// start allowing them. See <https://github.com/servo/servo/pull/6028>.
2553    pub(crate) fn reflow_if_reflow_timer_expired(&self) {
2554        // Only trigger a long parsing time reflow if we are in the first parse of `<body>`
2555        // and it started more than `INITIAL_REFLOW_DELAY` ago.
2556        if !matches!(
2557            self.layout_blocker.get(),
2558            LayoutBlocker::Parsing(instant) if instant + INITIAL_REFLOW_DELAY < Instant::now()
2559        ) {
2560            return;
2561        }
2562        self.allow_layout_if_necessary();
2563    }
2564
2565    /// Block layout for this `Window` until parsing is done. If parsing takes a long time,
2566    /// we want to layout anyway, so schedule a moment in the future for when layouts are
2567    /// allowed even though parsing isn't finished and we havne't sent a load event.
2568    pub(crate) fn prevent_layout_until_load_event(&self) {
2569        // If we have already started parsing or have already fired a load event, then
2570        // don't delay the first layout any longer.
2571        if !matches!(self.layout_blocker.get(), LayoutBlocker::WaitingForParse) {
2572            return;
2573        }
2574
2575        self.layout_blocker
2576            .set(LayoutBlocker::Parsing(Instant::now()));
2577    }
2578
2579    /// Inform the [`Window`] that layout is allowed either because `load` has happened
2580    /// or because parsing the `<body>` took so long that we cannot wait any longer.
2581    pub(crate) fn allow_layout_if_necessary(&self) {
2582        if matches!(
2583            self.layout_blocker.get(),
2584            LayoutBlocker::FiredLoadEventOrParsingTimerExpired
2585        ) {
2586            return;
2587        }
2588
2589        self.layout_blocker
2590            .set(LayoutBlocker::FiredLoadEventOrParsingTimerExpired);
2591
2592        // We do this immediately instead of scheduling a future task, because this can
2593        // happen if parsing is taking a very long time, which means that the
2594        // `ScriptThread` is busy doing the parsing and not doing layouts.
2595        //
2596        // TOOD(mrobinson): It's expected that this is necessary when in the process of
2597        // parsing, as we need to interrupt it to update contents, but why is this
2598        // necessary when parsing finishes? Not doing the synchronous update in that case
2599        // causes iframe tests to become flaky. It seems there's an issue with the timing of
2600        // iframe size updates.
2601        //
2602        // See <https://github.com/servo/servo/issues/14719>
2603        if self.Document().update_the_rendering().needs_frame() {
2604            self.compositor_api()
2605                .generate_frame(vec![self.webview_id()]);
2606        }
2607    }
2608
2609    pub(crate) fn layout_blocked(&self) -> bool {
2610        self.layout_blocker.get().layout_blocked()
2611    }
2612
2613    /// Trigger a reflow that is required by a certain queries.
2614    pub(crate) fn layout_reflow(&self, query_msg: QueryMsg) {
2615        self.reflow(ReflowGoal::LayoutQuery(query_msg));
2616    }
2617
2618    pub(crate) fn resolved_font_style_query(
2619        &self,
2620        node: &Node,
2621        value: String,
2622    ) -> Option<ServoArc<Font>> {
2623        self.layout_reflow(QueryMsg::ResolvedFontStyleQuery);
2624
2625        let document = self.Document();
2626        let animations = document.animations().sets.clone();
2627        self.layout.borrow().query_resolved_font_style(
2628            node.to_trusted_node_address(),
2629            &value,
2630            animations,
2631            document.current_animation_timeline_value(),
2632        )
2633    }
2634
2635    /// Query the used padding values for the given node, but do not force a reflow.
2636    /// This is used for things like `ResizeObserver` which should observe the value
2637    /// from the most recent reflow, but do not need it to reflect the current state of
2638    /// the DOM / style.
2639    pub(crate) fn padding_query_without_reflow(&self, node: &Node) -> Option<PhysicalSides> {
2640        let layout = self.layout.borrow();
2641        layout.query_padding(node.to_trusted_node_address())
2642    }
2643
2644    /// Do the same kind of query as `Self::box_area_query`, but do not force a reflow.
2645    /// This is used for things like `IntersectionObserver` which should observe the value
2646    /// from the most recent reflow, but do not need it to reflect the current state of
2647    /// the DOM / style.
2648    pub(crate) fn box_area_query_without_reflow(
2649        &self,
2650        node: &Node,
2651        area: BoxAreaType,
2652        exclude_transform_and_inline: bool,
2653    ) -> Option<UntypedRect<Au>> {
2654        let layout = self.layout.borrow();
2655        layout.ensure_stacking_context_tree(self.viewport_details.get());
2656        layout.query_box_area(
2657            node.to_trusted_node_address(),
2658            area,
2659            exclude_transform_and_inline,
2660        )
2661    }
2662
2663    pub(crate) fn box_area_query(
2664        &self,
2665        node: &Node,
2666        area: BoxAreaType,
2667        exclude_transform_and_inline: bool,
2668    ) -> Option<UntypedRect<Au>> {
2669        self.layout_reflow(QueryMsg::BoxArea);
2670        self.box_area_query_without_reflow(node, area, exclude_transform_and_inline)
2671    }
2672
2673    pub(crate) fn box_areas_query(&self, node: &Node, area: BoxAreaType) -> Vec<UntypedRect<Au>> {
2674        self.layout_reflow(QueryMsg::BoxAreas);
2675        self.layout
2676            .borrow()
2677            .query_box_areas(node.to_trusted_node_address(), area)
2678    }
2679
2680    pub(crate) fn client_rect_query(&self, node: &Node) -> UntypedRect<i32> {
2681        self.layout_reflow(QueryMsg::ClientRectQuery);
2682        self.layout
2683            .borrow()
2684            .query_client_rect(node.to_trusted_node_address())
2685    }
2686
2687    pub(crate) fn current_css_zoom_query(&self, node: &Node) -> f32 {
2688        self.layout_reflow(QueryMsg::CurrentCSSZoomQuery);
2689        self.layout
2690            .borrow()
2691            .query_current_css_zoom(node.to_trusted_node_address())
2692    }
2693
2694    /// Find the scroll area of the given node, if it is not None. If the node
2695    /// is None, find the scroll area of the viewport.
2696    pub(crate) fn scrolling_area_query(&self, node: Option<&Node>) -> UntypedRect<i32> {
2697        self.layout_reflow(QueryMsg::ScrollingAreaOrOffsetQuery);
2698        self.layout
2699            .borrow()
2700            .query_scrolling_area(node.map(Node::to_trusted_node_address))
2701    }
2702
2703    pub(crate) fn scroll_offset_query(&self, node: &Node) -> Vector2D<f32, LayoutPixel> {
2704        let external_scroll_id = ExternalScrollId(
2705            combine_id_with_fragment_type(node.to_opaque().id(), FragmentType::FragmentBody),
2706            self.pipeline_id().into(),
2707        );
2708        self.scroll_offset_query_with_external_scroll_id(external_scroll_id)
2709    }
2710
2711    fn scroll_offset_query_with_external_scroll_id(
2712        &self,
2713        external_scroll_id: ExternalScrollId,
2714    ) -> Vector2D<f32, LayoutPixel> {
2715        self.layout_reflow(QueryMsg::ScrollingAreaOrOffsetQuery);
2716        self.scroll_offset_query_with_external_scroll_id_no_reflow(external_scroll_id)
2717    }
2718
2719    fn scroll_offset_query_with_external_scroll_id_no_reflow(
2720        &self,
2721        external_scroll_id: ExternalScrollId,
2722    ) -> Vector2D<f32, LayoutPixel> {
2723        self.layout
2724            .borrow()
2725            .scroll_offset(external_scroll_id)
2726            .unwrap_or_default()
2727    }
2728
2729    /// <https://drafts.csswg.org/cssom-view/#scroll-an-element>
2730    // TODO(stevennovaryo): Need to update the scroll API to follow the spec since it is quite outdated.
2731    pub(crate) fn scroll_an_element(
2732        &self,
2733        element: &Element,
2734        x: f32,
2735        y: f32,
2736        behavior: ScrollBehavior,
2737    ) {
2738        let scroll_id = ExternalScrollId(
2739            combine_id_with_fragment_type(
2740                element.upcast::<Node>().to_opaque().id(),
2741                FragmentType::FragmentBody,
2742            ),
2743            self.pipeline_id().into(),
2744        );
2745
2746        // Step 6.
2747        // > Perform a scroll of box to position, element as the associated element and behavior as
2748        // > the scroll behavior.
2749        self.perform_a_scroll(x, y, scroll_id, behavior, Some(element));
2750    }
2751
2752    pub(crate) fn resolved_style_query(
2753        &self,
2754        element: TrustedNodeAddress,
2755        pseudo: Option<PseudoElement>,
2756        property: PropertyId,
2757    ) -> DOMString {
2758        self.layout_reflow(QueryMsg::ResolvedStyleQuery);
2759
2760        let document = self.Document();
2761        let animations = document.animations().sets.clone();
2762        DOMString::from(self.layout.borrow().query_resolved_style(
2763            element,
2764            pseudo,
2765            property,
2766            animations,
2767            document.current_animation_timeline_value(),
2768        ))
2769    }
2770
2771    /// If the given |browsing_context_id| refers to an `<iframe>` that is an element
2772    /// in this [`Window`] and that `<iframe>` has been laid out, return its size.
2773    /// Otherwise, return `None`.
2774    pub(crate) fn get_iframe_viewport_details_if_known(
2775        &self,
2776        browsing_context_id: BrowsingContextId,
2777    ) -> Option<ViewportDetails> {
2778        // Reflow might fail, but do a best effort to return the right size.
2779        self.layout_reflow(QueryMsg::InnerWindowDimensionsQuery);
2780        self.Document()
2781            .iframes()
2782            .get(browsing_context_id)
2783            .and_then(|iframe| iframe.size)
2784    }
2785
2786    #[expect(unsafe_code)]
2787    pub(crate) fn offset_parent_query(
2788        &self,
2789        node: &Node,
2790    ) -> (Option<DomRoot<Element>>, UntypedRect<Au>) {
2791        self.layout_reflow(QueryMsg::OffsetParentQuery);
2792        let response = self
2793            .layout
2794            .borrow()
2795            .query_offset_parent(node.to_trusted_node_address());
2796        let element = response.node_address.and_then(|parent_node_address| {
2797            let node = unsafe { from_untrusted_node_address(parent_node_address) };
2798            DomRoot::downcast(node)
2799        });
2800        (element, response.rect)
2801    }
2802
2803    pub(crate) fn scroll_container_query(
2804        &self,
2805        node: Option<&Node>,
2806        flags: ScrollContainerQueryFlags,
2807    ) -> Option<ScrollContainerResponse> {
2808        self.layout_reflow(QueryMsg::ScrollParentQuery);
2809        self.layout
2810            .borrow()
2811            .query_scroll_container(node.map(Node::to_trusted_node_address), flags)
2812    }
2813
2814    #[expect(unsafe_code)]
2815    pub(crate) fn scrolling_box_query(
2816        &self,
2817        node: Option<&Node>,
2818        flags: ScrollContainerQueryFlags,
2819    ) -> Option<ScrollingBox> {
2820        self.scroll_container_query(node, flags)
2821            .and_then(|response| {
2822                Some(match response {
2823                    ScrollContainerResponse::Viewport(overflow) => {
2824                        (ScrollingBoxSource::Viewport(self.Document()), overflow)
2825                    },
2826                    ScrollContainerResponse::Element(parent_node_address, overflow) => {
2827                        let node = unsafe { from_untrusted_node_address(parent_node_address) };
2828                        (
2829                            ScrollingBoxSource::Element(DomRoot::downcast(node)?),
2830                            overflow,
2831                        )
2832                    },
2833                })
2834            })
2835            .map(|(source, overflow)| ScrollingBox::new(source, overflow))
2836    }
2837
2838    pub(crate) fn text_index_query(
2839        &self,
2840        node: &Node,
2841        point_in_node: UntypedPoint2D<f32>,
2842    ) -> Option<usize> {
2843        self.layout_reflow(QueryMsg::TextIndexQuery);
2844        self.layout
2845            .borrow()
2846            .query_text_indext(node.to_opaque(), point_in_node)
2847    }
2848
2849    pub(crate) fn elements_from_point_query(
2850        &self,
2851        point: LayoutPoint,
2852        flags: ElementsFromPointFlags,
2853    ) -> Vec<ElementsFromPointResult> {
2854        self.layout_reflow(QueryMsg::ElementsFromPoint);
2855        self.layout().query_elements_from_point(point, flags)
2856    }
2857
2858    pub(crate) fn hit_test_from_input_event(
2859        &self,
2860        input_event: &ConstellationInputEvent,
2861    ) -> Option<HitTestResult> {
2862        self.hit_test_from_point_in_viewport(
2863            input_event.hit_test_result.as_ref()?.point_in_viewport,
2864        )
2865    }
2866
2867    #[expect(unsafe_code)]
2868    pub(crate) fn hit_test_from_point_in_viewport(
2869        &self,
2870        point_in_frame: Point2D<f32, CSSPixel>,
2871    ) -> Option<HitTestResult> {
2872        let result = self
2873            .elements_from_point_query(point_in_frame.cast_unit(), ElementsFromPointFlags::empty())
2874            .into_iter()
2875            .nth(0)?;
2876
2877        let point_relative_to_initial_containing_block =
2878            point_in_frame + self.scroll_offset().cast_unit();
2879
2880        // SAFETY: This is safe because `Window::query_elements_from_point` has ensured that
2881        // layout has run and any OpaqueNodes that no longer refer to real nodes are gone.
2882        let address = UntrustedNodeAddress(result.node.0 as *const c_void);
2883        Some(HitTestResult {
2884            node: unsafe { from_untrusted_node_address(address) },
2885            cursor: result.cursor,
2886            point_in_node: result.point_in_target,
2887            point_in_frame,
2888            point_relative_to_initial_containing_block,
2889        })
2890    }
2891
2892    pub(crate) fn init_window_proxy(&self, window_proxy: &WindowProxy) {
2893        assert!(self.window_proxy.get().is_none());
2894        self.window_proxy.set(Some(window_proxy));
2895    }
2896
2897    pub(crate) fn init_document(&self, document: &Document) {
2898        assert!(self.document.get().is_none());
2899        assert!(document.window() == self);
2900        self.document.set(Some(document));
2901
2902        if self.unminify_css {
2903            *self.unminified_css_dir.borrow_mut() = Some(unminified_path("unminified-css"));
2904        }
2905    }
2906
2907    /// Commence a new URL load which will either replace this window or scroll to a fragment.
2908    ///
2909    /// <https://html.spec.whatwg.org/multipage/#navigating-across-documents>
2910    pub(crate) fn load_url(
2911        &self,
2912        history_handling: NavigationHistoryBehavior,
2913        force_reload: bool,
2914        load_data: LoadData,
2915        can_gc: CanGc,
2916    ) {
2917        let doc = self.Document();
2918
2919        // Step 3. Let initiatorOriginSnapshot be sourceDocument's origin.
2920        let initiator_origin_snapshot = &load_data.load_origin;
2921
2922        // TODO: Important re security. See https://github.com/servo/servo/issues/23373
2923        // Step 5. check that the source browsing-context is "allowed to navigate" this window.
2924        if !force_reload &&
2925            load_data.url.as_url()[..Position::AfterQuery] ==
2926                doc.url().as_url()[..Position::AfterQuery]
2927        {
2928            // Step 6
2929            // TODO: Fragment handling appears to have moved to step 13
2930            if let Some(fragment) = load_data.url.fragment() {
2931                let webdriver_sender = self.webdriver_load_status_sender.borrow().clone();
2932                if let Some(ref sender) = webdriver_sender {
2933                    let _ = sender.send(WebDriverLoadStatus::NavigationStart);
2934                }
2935
2936                self.send_to_constellation(ScriptToConstellationMessage::NavigatedToFragment(
2937                    load_data.url.clone(),
2938                    history_handling,
2939                ));
2940                doc.check_and_scroll_fragment(fragment);
2941                let this = Trusted::new(self);
2942                let old_url = doc.url().into_string();
2943                let new_url = load_data.url.clone().into_string();
2944                let task = task!(hashchange_event: move || {
2945                    let this = this.root();
2946                    let event = HashChangeEvent::new(
2947                        &this,
2948                        atom!("hashchange"),
2949                        false,
2950                        false,
2951                        old_url,
2952                        new_url,
2953                        CanGc::note());
2954                    event.upcast::<Event>().fire(this.upcast::<EventTarget>(), CanGc::note());
2955                    if let Some(sender) = webdriver_sender {
2956                        let _ = sender.send(WebDriverLoadStatus::NavigationStop);
2957                    }
2958                });
2959                self.as_global_scope()
2960                    .task_manager()
2961                    .dom_manipulation_task_source()
2962                    .queue(task);
2963                doc.set_url(load_data.url.clone());
2964                return;
2965            }
2966        }
2967
2968        // Step 4 and 5
2969        let pipeline_id = self.pipeline_id();
2970        let window_proxy = self.window_proxy();
2971        if let Some(active) = window_proxy.currently_active() {
2972            if pipeline_id == active && doc.is_prompting_or_unloading() {
2973                return;
2974            }
2975        }
2976
2977        // Step 8
2978        if doc.prompt_to_unload(false, can_gc) {
2979            let window_proxy = self.window_proxy();
2980            if window_proxy.parent().is_some() {
2981                // Step 10
2982                // If browsingContext is a nested browsing context,
2983                // then put it in the delaying load events mode.
2984                window_proxy.start_delaying_load_events_mode();
2985            }
2986
2987            // Step 11. If historyHandling is "auto", then:
2988            let resolved_history_handling = if history_handling == NavigationHistoryBehavior::Auto {
2989                // Step 11.1. If url equals navigable's active document's URL, and
2990                // initiatorOriginSnapshot is same origin with targetNavigable's active document's
2991                // origin, then set historyHandling to "replace".
2992                // Note: `targetNavigable` is not actually defined in the spec, "active document" is
2993                // assumed to be the correct reference based on WPT results
2994                if let LoadOrigin::Script(initiator_origin) = initiator_origin_snapshot {
2995                    if load_data.url == doc.url() && initiator_origin.same_origin(doc.origin()) {
2996                        NavigationHistoryBehavior::Replace
2997                    } else {
2998                        NavigationHistoryBehavior::Push
2999                    }
3000                } else {
3001                    // Step 11.2. Otherwise, set historyHandling to "push".
3002                    NavigationHistoryBehavior::Push
3003                }
3004            // Step 12. If the navigation must be a replace given url and navigable's active
3005            // document, then set historyHandling to "replace".
3006            } else if load_data.url.scheme() == "javascript" || doc.is_initial_about_blank() {
3007                NavigationHistoryBehavior::Replace
3008            } else {
3009                history_handling
3010            };
3011
3012            if let Some(sender) = self.webdriver_load_status_sender.borrow().as_ref() {
3013                let _ = sender.send(WebDriverLoadStatus::NavigationStart);
3014            }
3015
3016            // Step 13
3017            ScriptThread::navigate(
3018                self.webview_id,
3019                pipeline_id,
3020                load_data,
3021                resolved_history_handling,
3022            );
3023        };
3024    }
3025
3026    /// Handle a potential change to the [`ViewportDetails`] of this [`Window`],
3027    /// triggering a reflow if any change occurred.
3028    pub(crate) fn set_viewport_details(&self, viewport_details: ViewportDetails) {
3029        self.viewport_details.set(viewport_details);
3030        if !self.layout_mut().set_viewport_details(viewport_details) {
3031            return;
3032        }
3033        self.Document()
3034            .add_restyle_reason(RestyleReason::ViewportChanged);
3035    }
3036
3037    pub(crate) fn viewport_details(&self) -> ViewportDetails {
3038        self.viewport_details.get()
3039    }
3040
3041    /// Get the theme of this [`Window`].
3042    pub(crate) fn theme(&self) -> Theme {
3043        self.theme.get()
3044    }
3045
3046    /// Handle a theme change request, triggering a reflow is any actual change occured.
3047    pub(crate) fn set_theme(&self, new_theme: Theme) {
3048        self.theme.set(new_theme);
3049        if !self.layout_mut().set_theme(new_theme) {
3050            return;
3051        }
3052        self.Document()
3053            .add_restyle_reason(RestyleReason::ThemeChanged);
3054    }
3055
3056    pub(crate) fn get_url(&self) -> ServoUrl {
3057        self.Document().url()
3058    }
3059
3060    pub(crate) fn windowproxy_handler(&self) -> &'static WindowProxyHandler {
3061        self.dom_static.windowproxy_handler
3062    }
3063
3064    pub(crate) fn add_resize_event(&self, event: ViewportDetails, event_type: WindowSizeType) {
3065        // Whenever we receive a new resize event we forget about all the ones that came before
3066        // it, to avoid unnecessary relayouts
3067        *self.unhandled_resize_event.borrow_mut() = Some((event, event_type))
3068    }
3069
3070    pub(crate) fn take_unhandled_resize_event(&self) -> Option<(ViewportDetails, WindowSizeType)> {
3071        self.unhandled_resize_event.borrow_mut().take()
3072    }
3073
3074    /// Whether or not this [`Window`] has any resize events that have not been processed.
3075    pub(crate) fn has_unhandled_resize_event(&self) -> bool {
3076        self.unhandled_resize_event.borrow().is_some()
3077    }
3078
3079    pub(crate) fn suspend(&self, can_gc: CanGc) {
3080        // Suspend timer events.
3081        self.as_global_scope().suspend();
3082
3083        // Set the window proxy to be a cross-origin window.
3084        if self.window_proxy().currently_active() == Some(self.global().pipeline_id()) {
3085            self.window_proxy().unset_currently_active(can_gc);
3086        }
3087
3088        // A hint to the JS runtime that now would be a good time to
3089        // GC any unreachable objects generated by user script,
3090        // or unattached DOM nodes. Attached DOM nodes can't be GCd yet,
3091        // as the document might be reactivated later.
3092        self.Gc();
3093    }
3094
3095    pub(crate) fn resume(&self, can_gc: CanGc) {
3096        // Resume timer events.
3097        self.as_global_scope().resume();
3098
3099        // Set the window proxy to be this object.
3100        self.window_proxy().set_currently_active(self, can_gc);
3101
3102        // Push the document title to the compositor since we are
3103        // activating this document due to a navigation.
3104        self.Document().title_changed();
3105    }
3106
3107    pub(crate) fn need_emit_timeline_marker(&self, timeline_type: TimelineMarkerType) -> bool {
3108        let markers = self.devtools_markers.borrow();
3109        markers.contains(&timeline_type)
3110    }
3111
3112    pub(crate) fn emit_timeline_marker(&self, marker: TimelineMarker) {
3113        let sender = self.devtools_marker_sender.borrow();
3114        let sender = sender.as_ref().expect("There is no marker sender");
3115        sender.send(Some(marker)).unwrap();
3116    }
3117
3118    pub(crate) fn set_devtools_timeline_markers(
3119        &self,
3120        markers: Vec<TimelineMarkerType>,
3121        reply: IpcSender<Option<TimelineMarker>>,
3122    ) {
3123        *self.devtools_marker_sender.borrow_mut() = Some(reply);
3124        self.devtools_markers.borrow_mut().extend(markers);
3125    }
3126
3127    pub(crate) fn drop_devtools_timeline_markers(&self, markers: Vec<TimelineMarkerType>) {
3128        let mut devtools_markers = self.devtools_markers.borrow_mut();
3129        for marker in markers {
3130            devtools_markers.remove(&marker);
3131        }
3132        if devtools_markers.is_empty() {
3133            *self.devtools_marker_sender.borrow_mut() = None;
3134        }
3135    }
3136
3137    pub(crate) fn set_webdriver_script_chan(&self, chan: Option<IpcSender<WebDriverJSResult>>) {
3138        *self.webdriver_script_chan.borrow_mut() = chan;
3139    }
3140
3141    pub(crate) fn set_webdriver_load_status_sender(
3142        &self,
3143        sender: Option<GenericSender<WebDriverLoadStatus>>,
3144    ) {
3145        *self.webdriver_load_status_sender.borrow_mut() = sender;
3146    }
3147
3148    pub(crate) fn is_alive(&self) -> bool {
3149        self.current_state.get() == WindowState::Alive
3150    }
3151
3152    // https://html.spec.whatwg.org/multipage/#top-level-browsing-context
3153    pub(crate) fn is_top_level(&self) -> bool {
3154        self.parent_info.is_none()
3155    }
3156
3157    /// An implementation of:
3158    /// <https://drafts.csswg.org/cssom-view/#document-run-the-resize-steps>
3159    ///
3160    /// Returns true if there were any pending resize events.
3161    pub(crate) fn run_the_resize_steps(&self, can_gc: CanGc) -> bool {
3162        let Some((new_size, size_type)) = self.take_unhandled_resize_event() else {
3163            return false;
3164        };
3165
3166        if self.viewport_details() == new_size {
3167            return false;
3168        }
3169
3170        let _realm = enter_realm(self);
3171        debug!(
3172            "Resizing Window for pipeline {:?} from {:?} to {new_size:?}",
3173            self.pipeline_id(),
3174            self.viewport_details(),
3175        );
3176        self.set_viewport_details(new_size);
3177
3178        // The document needs to be repainted, because the initial containing
3179        // block is now a different size. This should be triggered before the
3180        // event is fired below so that any script queries trigger a restyle.
3181        self.Document()
3182            .add_restyle_reason(RestyleReason::ViewportChanged);
3183
3184        // If viewport units were used, all nodes need to be restyled, because
3185        // we currently do not track which ones rely on viewport units.
3186        if self.layout().device().used_viewport_units() {
3187            self.Document().dirty_all_nodes();
3188        }
3189
3190        // http://dev.w3.org/csswg/cssom-view/#resizing-viewports
3191        if size_type == WindowSizeType::Resize {
3192            let uievent = UIEvent::new(
3193                self,
3194                DOMString::from("resize"),
3195                EventBubbles::DoesNotBubble,
3196                EventCancelable::NotCancelable,
3197                Some(self),
3198                0i32,
3199                0u32,
3200                can_gc,
3201            );
3202            uievent.upcast::<Event>().fire(self.upcast(), can_gc);
3203        }
3204
3205        true
3206    }
3207
3208    /// Evaluate media query lists and report changes
3209    /// <https://drafts.csswg.org/cssom-view/#evaluate-media-queries-and-report-changes>
3210    pub(crate) fn evaluate_media_queries_and_report_changes(&self, can_gc: CanGc) {
3211        let _realm = enter_realm(self);
3212
3213        rooted_vec!(let mut mql_list);
3214        self.media_query_lists.for_each(|mql| {
3215            if let MediaQueryListMatchState::Changed = mql.evaluate_changes() {
3216                // Recording list of changed Media Queries
3217                mql_list.push(Dom::from_ref(&*mql));
3218            }
3219        });
3220        // Sending change events for all changed Media Queries
3221        for mql in mql_list.iter() {
3222            let event = MediaQueryListEvent::new(
3223                &mql.global(),
3224                atom!("change"),
3225                false,
3226                false,
3227                mql.Media(),
3228                mql.Matches(),
3229                can_gc,
3230            );
3231            event
3232                .upcast::<Event>()
3233                .fire(mql.upcast::<EventTarget>(), can_gc);
3234        }
3235    }
3236
3237    /// Set whether to use less resources by running timers at a heavily limited rate.
3238    pub(crate) fn set_throttled(&self, throttled: bool) {
3239        self.throttled.set(throttled);
3240        if throttled {
3241            self.as_global_scope().slow_down_timers();
3242        } else {
3243            self.as_global_scope().speed_up_timers();
3244        }
3245    }
3246
3247    pub(crate) fn throttled(&self) -> bool {
3248        self.throttled.get()
3249    }
3250
3251    pub(crate) fn unminified_css_dir(&self) -> Option<String> {
3252        self.unminified_css_dir.borrow().clone()
3253    }
3254
3255    pub(crate) fn local_script_source(&self) -> &Option<String> {
3256        &self.local_script_source
3257    }
3258
3259    pub(crate) fn set_navigation_start(&self) {
3260        self.navigation_start.set(CrossProcessInstant::now());
3261    }
3262
3263    pub(crate) fn send_to_embedder(&self, msg: EmbedderMsg) {
3264        self.as_global_scope()
3265            .script_to_embedder_chan()
3266            .send(msg)
3267            .unwrap();
3268    }
3269
3270    pub(crate) fn send_to_constellation(&self, msg: ScriptToConstellationMessage) {
3271        self.as_global_scope()
3272            .script_to_constellation_chan()
3273            .send(msg)
3274            .unwrap();
3275    }
3276
3277    #[cfg(feature = "webxr")]
3278    pub(crate) fn in_immersive_xr_session(&self) -> bool {
3279        self.navigator
3280            .get()
3281            .as_ref()
3282            .and_then(|nav| nav.xr())
3283            .is_some_and(|xr| xr.pending_or_active_session())
3284    }
3285
3286    #[cfg(not(feature = "webxr"))]
3287    pub(crate) fn in_immersive_xr_session(&self) -> bool {
3288        false
3289    }
3290
3291    #[expect(unsafe_code)]
3292    fn handle_pending_images_post_reflow(
3293        &self,
3294        pending_images: Vec<PendingImage>,
3295        pending_rasterization_images: Vec<PendingRasterizationImage>,
3296        pending_svg_element_for_serialization: Vec<UntrustedNodeAddress>,
3297    ) {
3298        let pipeline_id = self.pipeline_id();
3299        for image in pending_images {
3300            let id = image.id;
3301            let node = unsafe { from_untrusted_node_address(image.node) };
3302
3303            if let PendingImageState::Unrequested(ref url) = image.state {
3304                fetch_image_for_layout(url.clone(), &node, id, self.image_cache.clone());
3305            }
3306
3307            let mut images = self.pending_layout_images.borrow_mut();
3308            if !images.contains_key(&id) {
3309                let trusted_node = Trusted::new(&*node);
3310                let sender = self.register_image_cache_listener(id, move |response| {
3311                    trusted_node
3312                        .root()
3313                        .owner_window()
3314                        .pending_layout_image_notification(response);
3315                });
3316
3317                self.image_cache
3318                    .add_listener(ImageLoadListener::new(sender, pipeline_id, id));
3319            }
3320
3321            let nodes = images.entry(id).or_default();
3322            if !nodes.iter().any(|n| std::ptr::eq(&*(n.node), &*node)) {
3323                nodes.push(PendingLayoutImageAncillaryData {
3324                    node: Dom::from_ref(&*node),
3325                    destination: image.destination,
3326                });
3327            }
3328        }
3329
3330        for image in pending_rasterization_images {
3331            let node = unsafe { from_untrusted_node_address(image.node) };
3332
3333            let mut images = self.pending_images_for_rasterization.borrow_mut();
3334            if !images.contains_key(&(image.id, image.size)) {
3335                let image_cache_sender = self.image_cache_sender.clone();
3336                self.image_cache.add_rasterization_complete_listener(
3337                    pipeline_id,
3338                    image.id,
3339                    image.size,
3340                    Box::new(move |response| {
3341                        let _ = image_cache_sender.send(response);
3342                    }),
3343                );
3344            }
3345
3346            let nodes = images.entry((image.id, image.size)).or_default();
3347            if !nodes.iter().any(|n| std::ptr::eq(&**n, &*node)) {
3348                nodes.push(Dom::from_ref(&*node));
3349            }
3350        }
3351
3352        for node in pending_svg_element_for_serialization.into_iter() {
3353            let node = unsafe { from_untrusted_node_address(node) };
3354            let svg = node.downcast::<SVGSVGElement>().unwrap();
3355            svg.serialize_and_cache_subtree();
3356            node.dirty(NodeDamage::Other);
3357        }
3358    }
3359
3360    #[allow(clippy::too_many_arguments)]
3361    pub(crate) fn new(
3362        webview_id: WebViewId,
3363        runtime: Rc<Runtime>,
3364        script_chan: Sender<MainThreadScriptMsg>,
3365        layout: Box<dyn Layout>,
3366        font_context: Arc<FontContext>,
3367        image_cache_sender: Sender<ImageCacheResponseMessage>,
3368        image_cache: Arc<dyn ImageCache>,
3369        resource_threads: ResourceThreads,
3370        storage_threads: StorageThreads,
3371        #[cfg(feature = "bluetooth")] bluetooth_thread: IpcSender<BluetoothRequest>,
3372        mem_profiler_chan: MemProfilerChan,
3373        time_profiler_chan: TimeProfilerChan,
3374        devtools_chan: Option<IpcSender<ScriptToDevtoolsControlMsg>>,
3375        constellation_chan: ScriptToConstellationChan,
3376        embedder_chan: ScriptToEmbedderChan,
3377        control_chan: GenericSender<ScriptThreadMessage>,
3378        pipeline_id: PipelineId,
3379        parent_info: Option<PipelineId>,
3380        viewport_details: ViewportDetails,
3381        origin: MutableOrigin,
3382        creation_url: ServoUrl,
3383        top_level_creation_url: ServoUrl,
3384        navigation_start: CrossProcessInstant,
3385        webgl_chan: Option<WebGLChan>,
3386        #[cfg(feature = "webxr")] webxr_registry: Option<webxr_api::Registry>,
3387        compositor_api: CrossProcessCompositorApi,
3388        unminify_js: bool,
3389        unminify_css: bool,
3390        local_script_source: Option<String>,
3391        user_content_manager: UserContentManager,
3392        player_context: WindowGLContext,
3393        #[cfg(feature = "webgpu")] gpu_id_hub: Arc<IdentityHub>,
3394        inherited_secure_context: Option<bool>,
3395        theme: Theme,
3396    ) -> DomRoot<Self> {
3397        let error_reporter = CSSErrorReporter {
3398            pipelineid: pipeline_id,
3399            script_chan: control_chan,
3400        };
3401
3402        let win = Box::new(Self {
3403            webview_id,
3404            globalscope: GlobalScope::new_inherited(
3405                pipeline_id,
3406                devtools_chan,
3407                mem_profiler_chan,
3408                time_profiler_chan,
3409                constellation_chan,
3410                embedder_chan,
3411                resource_threads,
3412                storage_threads,
3413                origin,
3414                creation_url,
3415                Some(top_level_creation_url),
3416                #[cfg(feature = "webgpu")]
3417                gpu_id_hub,
3418                inherited_secure_context,
3419                unminify_js,
3420                Some(font_context.clone()),
3421            ),
3422            ongoing_navigation: Default::default(),
3423            script_chan,
3424            layout: RefCell::new(layout),
3425            image_cache_sender,
3426            image_cache,
3427            navigator: Default::default(),
3428            location: Default::default(),
3429            history: Default::default(),
3430            indexeddb: Default::default(),
3431            custom_element_registry: Default::default(),
3432            window_proxy: Default::default(),
3433            document: Default::default(),
3434            performance: Default::default(),
3435            navigation_start: Cell::new(navigation_start),
3436            screen: Default::default(),
3437            session_storage: Default::default(),
3438            local_storage: Default::default(),
3439            status: DomRefCell::new(DOMString::new()),
3440            parent_info,
3441            dom_static: GlobalStaticData::new(),
3442            js_runtime: DomRefCell::new(Some(runtime.clone())),
3443            #[cfg(feature = "bluetooth")]
3444            bluetooth_thread,
3445            #[cfg(feature = "bluetooth")]
3446            bluetooth_extra_permission_data: BluetoothExtraPermissionData::new(),
3447            unhandled_resize_event: Default::default(),
3448            viewport_details: Cell::new(viewport_details),
3449            layout_blocker: Cell::new(LayoutBlocker::WaitingForParse),
3450            current_state: Cell::new(WindowState::Alive),
3451            devtools_marker_sender: Default::default(),
3452            devtools_markers: Default::default(),
3453            webdriver_script_chan: Default::default(),
3454            webdriver_load_status_sender: Default::default(),
3455            error_reporter,
3456            media_query_lists: DOMTracker::new(),
3457            #[cfg(feature = "bluetooth")]
3458            test_runner: Default::default(),
3459            webgl_chan,
3460            #[cfg(feature = "webxr")]
3461            webxr_registry,
3462            pending_image_callbacks: Default::default(),
3463            pending_layout_images: Default::default(),
3464            pending_images_for_rasterization: Default::default(),
3465            unminified_css_dir: Default::default(),
3466            local_script_source,
3467            test_worklet: Default::default(),
3468            paint_worklet: Default::default(),
3469            exists_mut_observer: Cell::new(false),
3470            compositor_api,
3471            has_sent_idle_message: Cell::new(false),
3472            unminify_css,
3473            user_content_manager,
3474            player_context,
3475            throttled: Cell::new(false),
3476            layout_marker: DomRefCell::new(Rc::new(Cell::new(true))),
3477            current_event: DomRefCell::new(None),
3478            theme: Cell::new(theme),
3479            trusted_types: Default::default(),
3480            reporting_observer_list: Default::default(),
3481            report_list: Default::default(),
3482            endpoints_list: Default::default(),
3483            script_window_proxies: ScriptThread::window_proxies(),
3484            has_pending_screenshot_readiness_request: Default::default(),
3485        });
3486
3487        WindowBinding::Wrap::<crate::DomTypeHolder>(GlobalScope::get_cx(), win)
3488    }
3489
3490    pub(crate) fn pipeline_id(&self) -> PipelineId {
3491        self.as_global_scope().pipeline_id()
3492    }
3493
3494    /// Create a new cached instance of the given value.
3495    pub(crate) fn cache_layout_value<T>(&self, value: T) -> LayoutValue<T>
3496    where
3497        T: Copy + MallocSizeOf,
3498    {
3499        LayoutValue::new(self.layout_marker.borrow().clone(), value)
3500    }
3501}
3502
3503/// An instance of a value associated with a particular snapshot of layout. This stored
3504/// value can only be read as long as the associated layout marker that is considered
3505/// valid. It will automatically become unavailable when the next layout operation is
3506/// performed.
3507#[derive(MallocSizeOf)]
3508pub(crate) struct LayoutValue<T: MallocSizeOf> {
3509    #[conditional_malloc_size_of]
3510    is_valid: Rc<Cell<bool>>,
3511    value: T,
3512}
3513
3514#[expect(unsafe_code)]
3515unsafe impl<T: JSTraceable + MallocSizeOf> JSTraceable for LayoutValue<T> {
3516    unsafe fn trace(&self, trc: *mut js::jsapi::JSTracer) {
3517        unsafe { self.value.trace(trc) };
3518    }
3519}
3520
3521impl<T: Copy + MallocSizeOf> LayoutValue<T> {
3522    fn new(marker: Rc<Cell<bool>>, value: T) -> Self {
3523        LayoutValue {
3524            is_valid: marker,
3525            value,
3526        }
3527    }
3528
3529    /// Retrieve the stored value if it is still valid.
3530    pub(crate) fn get(&self) -> Result<T, ()> {
3531        if self.is_valid.get() {
3532            return Ok(self.value);
3533        }
3534        Err(())
3535    }
3536}
3537
3538fn should_move_clip_rect(clip_rect: UntypedRect<Au>, new_viewport: UntypedRect<f32>) -> bool {
3539    let clip_rect = UntypedRect::new(
3540        Point2D::new(
3541            clip_rect.origin.x.to_f32_px(),
3542            clip_rect.origin.y.to_f32_px(),
3543        ),
3544        Size2D::new(
3545            clip_rect.size.width.to_f32_px(),
3546            clip_rect.size.height.to_f32_px(),
3547        ),
3548    );
3549
3550    // We only need to move the clip rect if the viewport is getting near the edge of
3551    // our preexisting clip rect. We use half of the size of the viewport as a heuristic
3552    // for "close."
3553    static VIEWPORT_SCROLL_MARGIN_SIZE: f32 = 0.5;
3554    let viewport_scroll_margin = new_viewport.size * VIEWPORT_SCROLL_MARGIN_SIZE;
3555
3556    (clip_rect.origin.x - new_viewport.origin.x).abs() <= viewport_scroll_margin.width ||
3557        (clip_rect.max_x() - new_viewport.max_x()).abs() <= viewport_scroll_margin.width ||
3558        (clip_rect.origin.y - new_viewport.origin.y).abs() <= viewport_scroll_margin.height ||
3559        (clip_rect.max_y() - new_viewport.max_y()).abs() <= viewport_scroll_margin.height
3560}
3561
3562impl Window {
3563    // https://html.spec.whatwg.org/multipage/#dom-window-postmessage step 7.
3564    pub(crate) fn post_message(
3565        &self,
3566        target_origin: Option<ImmutableOrigin>,
3567        source_origin: ImmutableOrigin,
3568        source: &WindowProxy,
3569        data: StructuredSerializedData,
3570    ) {
3571        let this = Trusted::new(self);
3572        let source = Trusted::new(source);
3573        let task = task!(post_serialised_message: move || {
3574            let this = this.root();
3575            let source = source.root();
3576            let document = this.Document();
3577
3578            // Step 7.1.
3579            if let Some(ref target_origin) = target_origin {
3580                if !target_origin.same_origin(document.origin()) {
3581                    return;
3582                }
3583            }
3584
3585            // Steps 7.2.-7.5.
3586            let cx = this.get_cx();
3587            let obj = this.reflector().get_jsobject();
3588            let _ac = JSAutoRealm::new(*cx, obj.get());
3589            rooted!(in(*cx) let mut message_clone = UndefinedValue());
3590            if let Ok(ports) = structuredclone::read(this.upcast(), data, message_clone.handle_mut(), CanGc::note()) {
3591                // Step 7.6, 7.7
3592                MessageEvent::dispatch_jsval(
3593                    this.upcast(),
3594                    this.upcast(),
3595                    message_clone.handle(),
3596                    Some(&source_origin.ascii_serialization()),
3597                    Some(&*source),
3598                    ports,
3599                    CanGc::note()
3600                );
3601            } else {
3602                // Step 4, fire messageerror.
3603                MessageEvent::dispatch_error(
3604                    this.upcast(),
3605                    this.upcast(),
3606                    CanGc::note()
3607                );
3608            }
3609        });
3610        // TODO(#12718): Use the "posted message task source".
3611        self.as_global_scope()
3612            .task_manager()
3613            .dom_manipulation_task_source()
3614            .queue(task);
3615    }
3616}
3617
3618#[derive(MallocSizeOf)]
3619pub(crate) struct CSSErrorReporter {
3620    pub(crate) pipelineid: PipelineId,
3621    pub(crate) script_chan: GenericSender<ScriptThreadMessage>,
3622}
3623unsafe_no_jsmanaged_fields!(CSSErrorReporter);
3624
3625impl ParseErrorReporter for CSSErrorReporter {
3626    fn report_error(
3627        &self,
3628        url: &UrlExtraData,
3629        location: SourceLocation,
3630        error: ContextualParseError,
3631    ) {
3632        if log_enabled!(log::Level::Info) {
3633            info!(
3634                "Url:\t{}\n{}:{} {}",
3635                url.0.as_str(),
3636                location.line,
3637                location.column,
3638                error
3639            )
3640        }
3641
3642        // TODO: report a real filename
3643        let _ = self.script_chan.send(ScriptThreadMessage::ReportCSSError(
3644            self.pipelineid,
3645            url.0.to_string(),
3646            location.line,
3647            location.column,
3648            error.to_string(),
3649        ));
3650    }
3651}
3652
3653fn is_named_element_with_name_attribute(elem: &Element) -> bool {
3654    let type_ = match elem.upcast::<Node>().type_id() {
3655        NodeTypeId::Element(ElementTypeId::HTMLElement(type_)) => type_,
3656        _ => return false,
3657    };
3658    matches!(
3659        type_,
3660        HTMLElementTypeId::HTMLEmbedElement |
3661            HTMLElementTypeId::HTMLFormElement |
3662            HTMLElementTypeId::HTMLImageElement |
3663            HTMLElementTypeId::HTMLObjectElement
3664    )
3665}
3666
3667fn is_named_element_with_id_attribute(elem: &Element) -> bool {
3668    elem.is_html_element()
3669}
3670
3671#[expect(unsafe_code)]
3672#[unsafe(no_mangle)]
3673/// Helper for interactive debugging sessions in lldb/gdb.
3674unsafe extern "C" fn dump_js_stack(cx: *mut RawJSContext) {
3675    unsafe {
3676        DumpJSStack(cx, true, false, false);
3677    }
3678}
3679
3680impl WindowHelpers for Window {
3681    fn create_named_properties_object(
3682        cx: JSContext,
3683        proto: HandleObject,
3684        object: MutableHandleObject,
3685    ) {
3686        Self::create_named_properties_object(cx, proto, object)
3687    }
3688}