1#![cfg_attr(crown, allow(crown::jscontext_first_arg))]
6
7use std::borrow::ToOwned;
8use std::cell::{Cell, RefCell, RefMut};
9use std::collections::HashSet;
10use std::collections::hash_map::Entry;
11use std::default::Default;
12use std::ffi::c_void;
13use std::io::{Write, stderr, stdout};
14use std::ptr::NonNull;
15use std::rc::{Rc, Weak};
16use std::sync::Arc;
17use std::time::{Duration, Instant};
18
19use accesskit::Action;
20use app_units::Au;
21use base64::Engine;
22use content_security_policy::Violation;
23use content_security_policy::sandboxing_directive::SandboxingFlagSet;
24use crossbeam_channel::{Sender, unbounded};
25use cssparser::SourceLocation;
26use dom_struct::dom_struct;
27use embedder_traits::user_contents::UserScript;
28use embedder_traits::{
29 AlertResponse, ConfirmResponse, EmbedderMsg, LoadStatus, PromptResponse, ScriptToEmbedderChan,
30 SimpleDialogRequest, Theme, UntrustedNodeAddress, ViewportDetails,
31};
32use euclid::{Point2D, Rect, Scale, Size2D, Vector2D};
33use fonts::{CspViolationHandler, FontContext, NetworkTimingHandler, WebFontSetDifference};
34use html5ever::LocalName;
35use js::context::{JSContext, NoGC};
36use js::conversions::ToJSValConvertible;
37use js::glue::DumpJSStack;
38use js::jsapi::{
39 GCReason, GetObjectRealmOrNull, JSContext as RawJSContext, JSObject, SetRealmPrincipals,
40};
41use js::jsval::{NullValue, UndefinedValue};
42use js::realm::{AutoRealm, CurrentRealm};
43use js::rust::wrappers2::{JS_GC, JS_MaybeGC};
44use js::rust::{
45 CustomAutoRooterGuard, HandleObject, HandleValue, MutableHandleObject, MutableHandleValue,
46};
47use layout_api::{
48 AccessibilityActionRequest, AxesOverflow, BoxAreaType, CSSPixelRectVec, ContainerTimingRecord,
49 FragmentType, HitTestFlags, LCPCandidate, Layout, LayoutImageDestination, PendingImage,
50 PendingImageState, PendingRasterizationImage, PhysicalSides, QueryMsg, ReflowGoal,
51 ReflowPhasesRun, ReflowRequest, ReflowRequestAccessibility, ReflowRequestRestyle,
52 ReflowStatistics, RestyleReason, ScrollContainerQueryFlags, ScrollContainerResponse,
53 SegmentGranularity, TrustedNodeAddress, combine_id_with_fragment_type,
54};
55use malloc_size_of::MallocSizeOf;
56use media::WindowGLContext;
57use net_traits::image_cache::{
58 ImageCache, ImageCacheResponseCallback, ImageCacheResponseMessage, ImageLoadListener,
59 ImageResponse, PendingImageId, PendingImageResponse, RasterizationCompleteResponse,
60};
61use net_traits::request::{Origin, Referrer, RequestClient, UpgradeInsecureNavigations};
62use net_traits::{ResourceFetchTiming, ResourceThreads};
63use num_traits::ToPrimitive;
64use paint_api::{CrossProcessPaintApi, PinchZoomInfos};
65use profile_traits::generic_channel as ProfiledGenericChannel;
66use profile_traits::mem::ProfilerChan as MemProfilerChan;
67use profile_traits::time::ProfilerChan as TimeProfilerChan;
68use rustc_hash::{FxBuildHasher, FxHashMap, FxHashSet};
69use script_bindings::cell::{DomRefCell, Ref};
70use script_bindings::dom::UnrootedDom;
71use script_bindings::domstring::TracedDOMString;
72use script_bindings::interfaces::{HasOrigin, WindowHelpers};
73use script_bindings::js::{JS_DefineProperty, PropertyFlags};
74use script_bindings::like::Setlike;
75use script_bindings::principals::ServoJSPrincipals;
76use script_bindings::reflector::DomObject;
77use script_bindings::root::Root;
78use script_traits::{ConstellationInputEvent, ScriptThreadMessage, WebViewState};
79use selectors::Parser;
80use selectors::attr::CaseSensitivity;
81use selectors::parser::is_css2_pseudo_element;
82use servo_arc::Arc as ServoArc;
83use servo_base::cross_process_instant::CrossProcessInstant;
84use servo_base::generic_channel::{self, GenericCallback, GenericSender};
85use servo_base::id::{BrowsingContextId, PipelineId, WebViewId};
86use servo_base::text::{Utf32CodeUnits, Utf32CodeUnitsOrNodeOffset};
87#[cfg(feature = "bluetooth")]
88use servo_bluetooth_traits::BluetoothRequest;
89#[cfg(feature = "webgl")]
90use servo_canvas_traits::webgl::WebGLChan;
91use servo_config::pref;
92use servo_constellation_traits::{
93 LoadData, LoadOrigin, ScreenshotReadinessResponse, ScriptToConstellationMessage,
94 ScriptToConstellationSender, StructuredSerializedData, WindowSizeType,
95};
96use servo_geometry::DeviceIndependentIntRect;
97use servo_url::{ImmutableOrigin, MutableOrigin, ServoUrl};
98use storage_traits::StorageThreads;
99use storage_traits::webstorage_thread::WebStorageType;
100use style::dom::OpaqueNode;
101use style::error_reporting::{ContextualParseError, ParseErrorReporter};
102use style::properties::PropertyId;
103use style::properties::style_structs::Font;
104use style::selector_parser::{PseudoElement, SelectorParser};
105use style::str::HTML_SPACE_CHARACTERS;
106use style::stylesheets::{Origin as StyleOrigin, UrlExtraData};
107use style_traits::CSSPixel;
108use stylo_atoms::Atom;
109use time::Duration as TimeDuration;
110use webrender_api::ExternalScrollId;
111use webrender_api::units::{DeviceIntSize, DevicePixel, LayoutPixel, LayoutPoint};
112
113use crate::dom::StatelessWorkletThreadPool;
114use crate::dom::bindings::callback::RootedCallback;
115use crate::dom::bindings::codegen::Bindings::AnimationFrameProviderBinding::FrameRequestCallback;
116use crate::dom::bindings::codegen::Bindings::DocumentBinding::{
117 DocumentMethods, DocumentReadyState, NamedPropertyValue,
118};
119use crate::dom::bindings::codegen::Bindings::HTMLIFrameElementBinding::HTMLIFrameElementMethods;
120use crate::dom::bindings::codegen::Bindings::HistoryBinding::History_Binding::HistoryMethods;
121use crate::dom::bindings::codegen::Bindings::ImageBitmapBinding::{
122 ImageBitmapOptions, ImageBitmapSource,
123};
124use crate::dom::bindings::codegen::Bindings::MediaQueryListBinding::MediaQueryList_Binding::MediaQueryListMethods;
125use crate::dom::bindings::codegen::Bindings::MessagePortBinding::StructuredSerializeOptions;
126use crate::dom::bindings::codegen::Bindings::ReportingObserverBinding::Report;
127use crate::dom::bindings::codegen::Bindings::RequestBinding::{RequestInfo, RequestInit};
128use crate::dom::bindings::codegen::Bindings::VoidFunctionBinding::VoidFunction;
129use crate::dom::bindings::codegen::Bindings::WindowBinding::{
130 self, DeferredRequestInit, ScrollBehavior, ScrollToOptions, WindowMethods,
131 WindowPostMessageOptions,
132};
133use crate::dom::bindings::codegen::UnionTypes::{
134 RequestOrUSVString, TrustedScriptOrString, TrustedScriptOrStringOrFunction,
135};
136use crate::dom::bindings::error::{Error, ErrorResult, Fallible};
137use crate::dom::bindings::inheritance::{Castable, ElementTypeId, HTMLElementTypeId, NodeTypeId};
138use crate::dom::bindings::num::Finite;
139use crate::dom::bindings::refcounted::Trusted;
140use crate::dom::bindings::reflector::DomGlobal;
141use crate::dom::bindings::root::{Dom, DomRoot, MutNullableDom};
142use crate::dom::bindings::str::{DOMString, USVString};
143use crate::dom::bindings::structuredclone;
144use crate::dom::bindings::trace::{CustomTraceable, HashMapTracedValues, JSTraceable};
145use crate::dom::bindings::utils::GlobalStaticData;
146use crate::dom::bindings::weakref::DOMTracker;
147#[cfg(feature = "bluetooth")]
148use crate::dom::bluetooth::BluetoothExtraPermissionData;
149use crate::dom::closewatchermanager::CloseWatcherManager;
150use crate::dom::cookiestore::cookiestore::CookieStore;
151use crate::dom::csp::GlobalCspReporting;
152use crate::dom::css::cssstyledeclaration::{
153 CSSModificationAccess, CSSStyleDeclaration, CSSStyleOwner,
154};
155use crate::dom::customelementregistry::CustomElementRegistry;
156use crate::dom::document::focus::FocusableArea;
157use crate::dom::document::{
158 AbortReason, AnimationFrameCallback, Document, LocalDescendantNavigablesIterator,
159};
160use crate::dom::element::Element;
161use crate::dom::event::{Event, EventBubbles, EventCancelable};
162use crate::dom::eventtarget::EventTarget;
163use crate::dom::fetchlaterresult::FetchLaterResult;
164use crate::dom::geolocation::Geolocation;
165use crate::dom::globalscope::GlobalScope;
166use crate::dom::history::History;
167use crate::dom::html::htmlcollection::{CollectionFilter, HTMLCollection};
168use crate::dom::html::htmliframeelement::HTMLIFrameElement;
169use crate::dom::idbfactory::IDBFactory;
170use crate::dom::inputevent::HitTestResult;
171use crate::dom::location::Location;
172use crate::dom::medialist::MediaList;
173use crate::dom::mediaquerylist::{MediaQueryList, MediaQueryListMatchState};
174use crate::dom::mediaquerylistevent::MediaQueryListEvent;
175use crate::dom::messageevent::MessageEvent;
176use crate::dom::navigator::Navigator;
177use crate::dom::node::focus::FocusTrigger;
178use crate::dom::node::{Node, NodeDamage, NodeTraits, from_untrusted_node_address};
179use crate::dom::performance::performance::Performance;
180use crate::dom::performanceresourcetiming::InitiatorType;
181use crate::dom::promise::RootedPromise;
182use crate::dom::reporting::reportingendpoint::{ReportingEndpoint, SendReportsToEndpoints};
183use crate::dom::reporting::reportingobserver::ReportingObserver;
184use crate::dom::selection::Selection;
185use crate::dom::selection_range::RootedSelectionBoundary;
186use crate::dom::serviceworker::cachestorage::CacheStorage;
187use crate::dom::shadowroot::shadowroot::ShadowRoot;
188use crate::dom::storage::Storage;
189#[cfg(feature = "bluetooth")]
190use crate::dom::testrunner::TestRunner;
191use crate::dom::trustedtypes::trustedtypepolicyfactory::TrustedTypePolicyFactory;
192use crate::dom::types::{FontFace, ImageBitmap, SVGSVGElement, UIEvent};
193use crate::dom::visualviewport::{VisualViewport, VisualViewportChanges};
194#[cfg(feature = "webgpu")]
195use crate::dom::webgpu::identityhub::IdentityHub;
196use crate::dom::window::layout_image::fetch_image_for_layout;
197use crate::dom::window::screen::Screen;
198use crate::dom::window::scrolling_box::{ScrollingBox, ScrollingBoxSource};
199use crate::dom::window::useractivation::UserActivationTimestamp;
200use crate::dom::windowproxy::{WindowProxy, WindowProxyHandler};
201use crate::dom::worklet::Worklet;
202use crate::dom::workletglobalscope::WorkletGlobalScopeType;
203use crate::event_loop::script_thread::ScriptThread;
204use crate::event_loop::script_window_proxies::ScriptWindowProxies;
205use crate::event_loop::timers::{IsInterval, OneshotTimers, TimerCallback};
206use crate::event_loop::webdriver_handlers::find_node_by_unique_id_in_document;
207use crate::fetch::fetch;
208use crate::fetch::network_listener::{ResourceTimingListener, submit_timing};
209use crate::messaging::{MainThreadScriptMsg, ScriptEventLoopReceiver, ScriptEventLoopSender};
210use crate::realms::enter_auto_realm;
211use crate::runtime::job_queue::UserMicrotask;
212use crate::runtime::script_runtime::Runtime;
213use crate::tasks::task_manager::TaskManager;
214use crate::tasks::task_source::SendableTaskSource;
215use crate::unminify::unminified_path;
216use crate::window_named_properties;
217
218#[derive(MallocSizeOf)]
223pub struct PendingImageCallback(
224 #[ignore_malloc_size_of = "dyn Fn is currently impossible to measure"]
225 #[expect(clippy::type_complexity)]
226 Box<dyn Fn(PendingImageResponse, &mut JSContext) + 'static>,
227);
228
229#[derive(Clone, Copy, Debug, JSTraceable, MallocSizeOf, PartialEq)]
231enum WindowState {
232 Alive,
233 Zombie, }
235
236const INITIAL_REFLOW_DELAY: Duration = Duration::from_millis(200);
239
240#[derive(Clone, Copy, MallocSizeOf)]
252enum LayoutBlocker {
253 WaitingForParse,
255 Parsing(Instant),
257 NotBlocked,
267}
268
269impl LayoutBlocker {
270 fn layout_blocked(&self) -> bool {
271 !matches!(self, Self::NotBlocked)
272 }
273}
274
275#[derive(Clone, Copy, Debug, Default, JSTraceable, MallocSizeOf, PartialEq)]
278pub(crate) struct OngoingNavigation(u32);
279
280type PendingImageRasterizationKey = (PendingImageId, DeviceIntSize);
281
282#[cfg_attr(crown, crown::unrooted_must_root_lint::must_root)]
286#[derive(JSTraceable, MallocSizeOf)]
287struct PendingLayoutImageAncillaryData {
288 node: Dom<Node>,
289 #[no_trace]
290 destination: LayoutImageDestination,
291}
292
293#[dom_struct]
294pub(crate) struct Window {
295 globalscope: GlobalScope,
296 #[ignore_malloc_size_of = "Weak does not need to be accounted"]
300 #[no_trace]
301 weak_script_thread: Weak<ScriptThread>,
302 #[no_trace]
305 #[conditional_malloc_size_of]
306 webview_state: Rc<WebViewState>,
307 script_chan: Sender<MainThreadScriptMsg>,
308 #[no_trace]
309 #[ignore_malloc_size_of = "TODO: Add MallocSizeOf support to layout"]
310 layout: RefCell<Box<dyn Layout>>,
311 navigator: MutNullableDom<Navigator>,
312 crypto: MutNullableDom<crate::dom::crypto::Crypto>,
313 #[no_trace]
314 image_cache_sender: Sender<ImageCacheResponseMessage>,
315 window_proxy: MutNullableDom<WindowProxy>,
316 document: MutNullableDom<Document>,
317 location: MutNullableDom<Location>,
318 performance: MutNullableDom<Performance>,
319 #[no_trace]
320 navigation_start: Cell<CrossProcessInstant>,
321 screen: MutNullableDom<Screen>,
322 session_storage: MutNullableDom<Storage>,
323 local_storage: MutNullableDom<Storage>,
324 cookie_store: MutNullableDom<CookieStore>,
326 status: DomRefCell<TracedDOMString>,
327 trusted_types: MutNullableDom<TrustedTypePolicyFactory>,
328
329 ongoing_navigation: Cell<OngoingNavigation>,
332
333 caches: MutNullableDom<CacheStorage>,
335
336 #[no_trace]
339 #[cfg(feature = "devtools")]
340 devtools_markers: DomRefCell<FxHashSet<devtools_traits::TimelineMarkerType>>,
341 #[no_trace]
342 #[cfg(feature = "devtools")]
343 devtools_marker_sender:
344 DomRefCell<Option<GenericSender<Option<devtools_traits::TimelineMarker>>>>,
345
346 #[no_trace]
348 unhandled_resize_event: DomRefCell<Option<(ViewportDetails, WindowSizeType)>>,
349
350 #[no_trace]
354 viewport_details_at_last_resize_steps: Cell<ViewportDetails>,
355
356 #[no_trace]
358 parent_info: Option<PipelineId>,
359
360 dom_static: GlobalStaticData,
362
363 #[conditional_malloc_size_of]
365 js_runtime: DomRefCell<Option<Rc<Runtime>>>,
366
367 #[no_trace]
369 viewport_details: Cell<ViewportDetails>,
370
371 #[no_trace]
373 #[cfg(feature = "bluetooth")]
374 bluetooth_thread: GenericSender<BluetoothRequest>,
375
376 #[cfg(feature = "bluetooth")]
377 bluetooth_extra_permission_data: BluetoothExtraPermissionData,
378
379 #[no_trace]
383 layout_blocker: Cell<LayoutBlocker>,
384
385 current_state: Cell<WindowState>,
387
388 error_reporter: CSSErrorReporter,
389
390 media_query_lists: DOMTracker<MediaQueryList>,
392
393 #[cfg(feature = "bluetooth")]
394 test_runner: MutNullableDom<TestRunner>,
395
396 #[no_trace]
398 #[cfg(feature = "webgl")]
399 webgl_chan: Option<WebGLChan>,
400
401 #[no_trace]
402 #[cfg(feature = "webxr")]
403 webxr_registry: Option<webxr_api::Registry>,
404
405 #[no_trace]
409 pending_image_callbacks: DomRefCell<FxHashMap<PendingImageId, Vec<PendingImageCallback>>>,
410
411 pending_layout_images: DomRefCell<
416 HashMapTracedValues<PendingImageId, Vec<PendingLayoutImageAncillaryData>, FxBuildHasher>,
417 >,
418
419 pending_images_for_rasterization: DomRefCell<
423 HashMapTracedValues<PendingImageRasterizationKey, Vec<Dom<Node>>, FxBuildHasher>,
424 >,
425
426 unminified_css_dir: DomRefCell<Option<String>>,
429
430 local_script_source: Option<String>,
432
433 test_worklet: MutNullableDom<Worklet>,
435 paint_worklet: MutNullableDom<Worklet>,
437
438 exists_mut_observer: Cell<bool>,
440
441 #[no_trace]
443 paint_api: CrossProcessPaintApi,
444
445 #[no_trace]
448 #[conditional_malloc_size_of]
449 user_scripts: Rc<Vec<UserScript>>,
450
451 #[no_trace]
453 player_context: WindowGLContext,
454
455 throttled: Cell<bool>,
459
460 #[conditional_malloc_size_of]
464 layout_marker: DomRefCell<Rc<Cell<bool>>>,
465
466 current_event: MutNullableDom<Event>,
468
469 reporting_observer_list: DomRefCell<Vec<Dom<ReportingObserver>>>,
471
472 report_list: DomRefCell<Vec<Report>>,
474
475 #[no_trace]
477 endpoints_list: DomRefCell<Vec<ReportingEndpoint>>,
478
479 #[conditional_malloc_size_of]
481 script_window_proxies: Rc<ScriptWindowProxies>,
482
483 has_pending_screenshot_readiness_request: Cell<bool>,
485
486 visual_viewport: MutNullableDom<VisualViewport>,
489
490 has_changed_visual_viewport_dimension: Cell<bool>,
492
493 pending_media_query_evaluation: Cell<bool>,
498
499 #[no_trace]
501 last_activation_timestamp: Cell<UserActivationTimestamp>,
502
503 devtools_wants_updates: Cell<bool>,
506
507 has_dispatched_scroll_event: Cell<bool>,
509
510 has_dispatched_input_event: Cell<bool>,
512
513 #[no_trace]
515 last_history_action_activation_timestamp: Cell<UserActivationTimestamp>,
516
517 close_watcher_manager: CloseWatcherManager,
519}
520
521impl Window {
522 pub(crate) fn script_thread(&self) -> Rc<ScriptThread> {
523 Weak::upgrade(&self.weak_script_thread)
524 .expect("Weak reference should always be upgradable when a ScriptThread is running")
525 }
526
527 pub(crate) fn webview_id(&self) -> WebViewId {
528 self.webview_state.id
529 }
530
531 pub(crate) fn webview_state(&self) -> Rc<WebViewState> {
532 self.webview_state.clone()
533 }
534
535 pub(crate) fn as_global_scope(&self) -> &GlobalScope {
536 self.upcast::<GlobalScope>()
537 }
538
539 pub(crate) fn cookie_store(&self) -> Option<DomRoot<CookieStore>> {
540 self.cookie_store.get()
541 }
542
543 pub(crate) fn mark_has_dispatched_scroll_event(&self) {
545 self.has_dispatched_scroll_event.set(true);
546 }
547
548 pub(crate) fn mark_has_dispatched_input_event(&self) {
550 self.has_dispatched_input_event.set(true);
551 }
552
553 pub(crate) fn layout(&self) -> Ref<'_, Box<dyn Layout>> {
554 self.layout.borrow()
555 }
556
557 pub(crate) fn layout_mut(&self) -> RefMut<'_, Box<dyn Layout>> {
558 self.layout.borrow_mut()
559 }
560
561 pub(crate) fn get_exists_mut_observer(&self) -> bool {
562 self.exists_mut_observer.get()
563 }
564
565 pub(crate) fn set_exists_mut_observer(&self) {
566 self.exists_mut_observer.set(true);
567 }
568
569 fn clear_js_runtime_common(&self) {
570 self.stop_geolocation_watches();
571 self.as_global_scope()
572 .remove_web_messaging_and_dedicated_workers_infra();
573 self.current_state.set(WindowState::Zombie);
574 self.as_global_scope()
575 .task_manager()
576 .cancel_all_tasks_and_ignore_future_tasks();
577 }
578
579 #[expect(unsafe_code)]
580 pub(crate) fn clear_js_runtime_for_script_deallocation(&self) {
581 self.clear_js_runtime_common();
582 unsafe {
583 *self.js_runtime.borrow_for_script_deallocation() = None;
584 }
585 self.window_proxy.set(None);
586 }
587
588 fn stop_geolocation_watches(&self) {
591 if let Some(geolocation) = self.maybe_geolocation() {
592 geolocation.stop_all_watches();
593 }
594 }
595
596 pub(crate) fn maybe_geolocation(&self) -> Option<DomRoot<Geolocation>> {
598 self.navigator.get()?.maybe_geolocation()
599 }
600
601 pub(crate) fn discard_browsing_context(&self) {
604 let proxy = self
605 .window_proxy
606 .get()
607 .expect("Discarding a BC from a window that has none");
608 proxy.discard_browsing_context();
609
610 self.as_global_scope()
614 .task_manager()
615 .cancel_all_tasks_and_ignore_future_tasks();
616
617 #[cfg(feature = "webxr")]
620 if let Some(mut registry) = self.webxr_registry() {
621 registry.remove_device_change_callbacks(self.pipeline_id());
622 }
623 }
624
625 pub(crate) fn time_profiler_chan(&self) -> &TimeProfilerChan {
627 self.globalscope.time_profiler_chan()
628 }
629
630 pub(crate) fn origin(&self) -> MutableOrigin {
632 self.Document().origin().clone()
634 }
635
636 pub(crate) fn main_thread_script_chan(&self) -> &Sender<MainThreadScriptMsg> {
637 &self.script_chan
638 }
639
640 pub(crate) fn parent_info(&self) -> Option<PipelineId> {
641 self.parent_info
642 }
643
644 pub(crate) fn new_script_pair(&self) -> (ScriptEventLoopSender, ScriptEventLoopReceiver) {
645 let (sender, receiver) = unbounded();
646 (
647 ScriptEventLoopSender::MainThread(sender),
648 ScriptEventLoopReceiver::MainThread(receiver),
649 )
650 }
651
652 pub(crate) fn event_loop_sender(&self) -> ScriptEventLoopSender {
653 ScriptEventLoopSender::MainThread(self.script_chan.clone())
654 }
655
656 pub(crate) fn image_cache(&self) -> Arc<dyn ImageCache> {
657 self.Document().image_cache()
658 }
659
660 pub(crate) fn window_proxy(&self) -> DomRoot<WindowProxy> {
662 self.window_proxy.get().unwrap()
663 }
664
665 pub(crate) fn append_reporting_observer(&self, reporting_observer: &ReportingObserver) {
666 self.reporting_observer_list
667 .borrow_mut()
668 .push(Dom::from_ref(reporting_observer));
669 }
670
671 pub(crate) fn remove_reporting_observer(&self, reporting_observer: &ReportingObserver) {
672 let index = {
673 let list = self.reporting_observer_list.borrow();
674 list.iter()
675 .position(|observer| &**observer == reporting_observer)
676 };
677
678 if let Some(index) = index {
679 self.reporting_observer_list.borrow_mut().remove(index);
680 }
681 }
682
683 pub(crate) fn registered_reporting_observers(&self) -> Vec<DomRoot<ReportingObserver>> {
684 self.reporting_observer_list
685 .borrow()
686 .iter()
687 .map(|observer| DomRoot::from_ref(&**observer))
688 .collect()
689 }
690
691 pub(crate) fn append_report(&self, report: Report) {
692 self.report_list.borrow_mut().push(report);
693 let trusted_window = Trusted::new(self);
694 self.upcast::<GlobalScope>()
695 .task_manager()
696 .dom_manipulation_task_source()
697 .queue(task!(send_to_reporting_endpoints: move || {
698 let window = trusted_window.root();
699 let reports = std::mem::take(&mut *window.report_list.borrow_mut());
700 window.upcast::<GlobalScope>().send_reports_to_endpoints(
701 reports,
702 window.endpoints_list.borrow().clone(),
703 );
704 }));
705 }
706
707 pub(crate) fn buffered_reports(&self) -> Vec<Report> {
708 self.report_list.borrow().clone()
709 }
710
711 pub(crate) fn set_endpoints_list(&self, endpoints: Vec<ReportingEndpoint>) {
712 *self.endpoints_list.borrow_mut() = endpoints;
713 }
714
715 pub(crate) fn undiscarded_window_proxy(&self) -> Option<DomRoot<WindowProxy>> {
718 self.window_proxy
719 .get()
720 .filter(|window_proxy| !window_proxy.is_browsing_context_discarded())
721 }
722
723 pub(crate) fn top_level_document_if_local(&self) -> Option<DomRoot<Document>> {
728 if self.is_top_level() {
729 return Some(self.Document());
730 }
731
732 let window_proxy = self.undiscarded_window_proxy()?;
733 self.script_window_proxies
734 .find_window_proxy(window_proxy.webview_id().into())?
735 .document()
736 }
737
738 #[cfg(feature = "bluetooth")]
739 pub(crate) fn bluetooth_thread(&self) -> GenericSender<BluetoothRequest> {
740 self.bluetooth_thread.clone()
741 }
742
743 #[cfg(feature = "bluetooth")]
744 pub(crate) fn bluetooth_extra_permission_data(&self) -> &BluetoothExtraPermissionData {
745 &self.bluetooth_extra_permission_data
746 }
747
748 pub(crate) fn css_error_reporter(&self) -> &CSSErrorReporter {
749 &self.error_reporter
750 }
751
752 #[cfg(feature = "webgl")]
753 pub(crate) fn webgl_chan(&self) -> Option<WebGLChan> {
754 self.webgl_chan.clone()
755 }
756
757 #[cfg(feature = "webxr")]
758 pub(crate) fn webxr_registry(&self) -> Option<webxr_api::Registry> {
759 self.webxr_registry.clone()
760 }
761
762 fn new_paint_worklet(&self, cx: &mut JSContext) -> DomRoot<Worklet> {
763 debug!("Creating new paint worklet.");
764
765 let worklet_global_scope_init = self.into();
766 Worklet::new(
767 cx,
768 self,
769 WorkletGlobalScopeType::Paint,
770 Box::new(|| Rc::new(StatelessWorkletThreadPool::spawn(worklet_global_scope_init))),
771 )
772 }
773
774 pub(crate) fn register_image_cache_listener(
775 &self,
776 id: PendingImageId,
777 callback: impl Fn(PendingImageResponse, &mut JSContext) + 'static,
778 ) -> ImageCacheResponseCallback {
779 self.pending_image_callbacks
780 .borrow_mut()
781 .entry(id)
782 .or_default()
783 .push(PendingImageCallback(Box::new(callback)));
784
785 let image_cache_sender = self.image_cache_sender.clone();
786 Box::new(move |message| {
787 let _ = image_cache_sender.send(message);
788 })
789 }
790
791 fn pending_layout_image_notification(&self, no_gc: &NoGC, response: PendingImageResponse) {
792 let mut images = self.pending_layout_images.borrow_mut();
793 let nodes = images.entry(response.id);
794 let nodes = match nodes {
795 Entry::Occupied(nodes) => nodes,
796 Entry::Vacant(_) => return,
797 };
798 if matches!(
799 response.response,
800 ImageResponse::Loaded(_, _) | ImageResponse::FailedToLoadOrDecode
801 ) {
802 for ancillary_data in nodes.get() {
803 match ancillary_data.destination {
804 LayoutImageDestination::BoxTreeConstruction => {
805 ancillary_data.node.dirty(no_gc, NodeDamage::Other);
806 },
807 LayoutImageDestination::DisplayListBuilding => {
808 self.layout().set_needs_new_display_list();
809 },
810 }
811 }
812 }
813
814 match response.response {
815 ImageResponse::MetadataLoaded(_) => {},
816 ImageResponse::Loaded(_, _) | ImageResponse::FailedToLoadOrDecode => {
817 nodes.remove();
818 },
819 }
820 }
821
822 pub(crate) fn handle_image_rasterization_complete_notification(
823 &self,
824 no_gc: &NoGC,
825 response: RasterizationCompleteResponse,
826 ) {
827 let mut images = self.pending_images_for_rasterization.borrow_mut();
828 let nodes = images.entry((response.image_id, response.requested_size));
829 let nodes = match nodes {
830 Entry::Occupied(nodes) => nodes,
831 Entry::Vacant(_) => return,
832 };
833 for node in nodes.get() {
834 node.dirty(no_gc, NodeDamage::Other);
835 }
836 nodes.remove();
837 }
838
839 pub(crate) fn pending_image_notification(
840 &self,
841 response: PendingImageResponse,
842 cx: &mut JSContext,
843 ) {
844 let mut images = std::mem::take(&mut *self.pending_image_callbacks.borrow_mut());
849 let Entry::Occupied(callbacks) = images.entry(response.id) else {
850 let _ = std::mem::replace(&mut *self.pending_image_callbacks.borrow_mut(), images);
851 return;
852 };
853
854 for callback in callbacks.get() {
855 callback.0(response.clone(), cx);
856 }
857
858 match response.response {
859 ImageResponse::MetadataLoaded(_) => {},
860 ImageResponse::Loaded(_, _) | ImageResponse::FailedToLoadOrDecode => {
861 callbacks.remove();
862 },
863 }
864
865 let _ = std::mem::replace(&mut *self.pending_image_callbacks.borrow_mut(), images);
866 }
867
868 pub(crate) fn paint_api(&self) -> &CrossProcessPaintApi {
869 &self.paint_api
870 }
871
872 pub(crate) fn userscripts(&self) -> &[UserScript] {
873 &self.user_scripts
874 }
875
876 pub(crate) fn get_player_context(&self) -> WindowGLContext {
877 self.player_context.clone()
878 }
879
880 pub(crate) fn dispatch_event_with_target_override(&self, cx: &mut JSContext, event: &Event) {
882 event.dispatch(cx, self.upcast(), true);
883 }
884
885 pub(crate) fn font_context(&self) -> Arc<FontContext> {
886 self.layout().font_context().clone()
887 }
888
889 pub(crate) fn ongoing_navigation(&self) -> OngoingNavigation {
890 self.ongoing_navigation.get()
891 }
892
893 pub(crate) fn set_ongoing_navigation(&self) -> OngoingNavigation {
895 let new_value = self.ongoing_navigation.get().0.wrapping_add(1);
899
900 self.ongoing_navigation.set(OngoingNavigation(new_value));
907
908 OngoingNavigation(new_value)
910 }
911
912 fn stop_loading(&self, cx: &mut JSContext) {
914 let document = self.Document();
916 let was_loading = document.ReadyState() != DocumentReadyState::Complete;
917
918 self.set_ongoing_navigation();
927
928 document.abort_a_document_and_its_descendants(cx, AbortReason::StopLoading);
930
931 document.notify_constellation_that_load_finished(true );
935
936 if self.is_top_level() && was_loading {
937 self.send_to_embedder(EmbedderMsg::NotifyLoadStatusChanged(
938 self.webview_id(),
939 LoadStatus::Stopped,
940 ));
941 }
942 }
943
944 fn destroy_top_level_traversable(&self, cx: &mut JSContext) {
946 let document = self.Document();
952 document.destroy_document_and_its_descendants(cx);
954 self.send_to_constellation(ScriptToConstellationMessage::DiscardTopLevelBrowsingContext);
956 }
957
958 fn definitely_close(&self, cx: &mut JSContext) {
960 let document = self.Document();
961 if !document.check_if_unloading_is_cancelled(cx, false) {
966 return;
967 }
968 document.unload(cx, false);
972 self.destroy_top_level_traversable(cx);
974 }
975
976 fn cannot_show_simple_dialogs(&self) -> bool {
978 if self
981 .Document()
982 .has_active_sandboxing_flag(SandboxingFlagSet::SANDBOXED_MODALS_FLAG)
983 {
984 return true;
985 }
986
987 false
1006 }
1007
1008 pub(crate) fn notify_the_close_watcher_manager_about_user_activation(&self) {
1010 let manager = self.close_watcher_manager();
1012
1013 if manager.next_user_interaction_allows_a_new_group() {
1016 manager.increment_allowed_number_of_groups();
1017 }
1018
1019 manager.set_next_user_interaction_allows_a_new_group(false);
1021 }
1022
1023 pub(crate) fn close_watcher_manager(&self) -> &CloseWatcherManager {
1024 &self.close_watcher_manager
1025 }
1026
1027 pub(crate) fn perform_a_microtask_checkpoint(&self, cx: &mut JSContext) {
1028 self.script_thread().perform_a_microtask_checkpoint(cx);
1029 }
1030
1031 pub(crate) fn request_client(&self, no_gc: Option<&NoGC>) -> RequestClient {
1033 let (
1036 preloaded_resources,
1037 insecure_requests_policy,
1038 has_trustworthy_ancestor_origin,
1039 policy_container,
1040 origin,
1041 network_partition_key,
1042 ) = if let Some(no_gc) = no_gc {
1043 let document = self.document_unrooted(no_gc);
1044 (
1045 document.preloaded_resources().clone(),
1046 document.insecure_requests_policy(),
1047 document.has_trustworthy_ancestor_or_current_origin(),
1048 document.policy_container().clone(),
1049 document.origin().clone(),
1050 document.determine_the_network_partition_key(),
1051 )
1052 } else {
1053 let document = self.Document();
1054 (
1055 document.preloaded_resources().clone(),
1056 document.insecure_requests_policy(),
1057 document.has_trustworthy_ancestor_or_current_origin(),
1058 document.policy_container().clone(),
1059 document.origin().clone(),
1060 document.determine_the_network_partition_key(),
1061 )
1062 };
1063 RequestClient {
1064 preloaded_resources,
1065 policy_container,
1066 origin: Origin::Origin(origin.immutable().clone()),
1067 is_nested_browsing_context: !self.is_top_level(),
1068 insecure_requests_policy,
1069 upgrade_insecure_navigations_set: self
1070 .as_global_scope()
1071 .upgrade_insecure_navigations_set()
1072 .clone(),
1073 has_trustworthy_ancestor_origin,
1074 network_partition_key,
1075 }
1076 }
1077
1078 #[expect(unsafe_code)]
1079 pub(crate) fn gc(&self, cx: &mut JSContext) {
1080 unsafe { JS_GC(cx, GCReason::API) };
1081 }
1082
1083 #[expect(unsafe_code)]
1084 pub(crate) fn maybe_gc(&self, cx: &mut JSContext) {
1085 unsafe { JS_MaybeGC(cx) };
1086 }
1087
1088 pub(crate) fn with_timers<T>(&self, f: impl FnOnce(&OneshotTimers) -> T) -> T {
1089 let document = self.Document();
1090 f(document.timers())
1091 }
1092
1093 pub(crate) fn process_close_watchers(&self, cx: &mut JSContext) -> bool {
1095 let mut processed_a_close_watcher = false;
1097
1098 let close_watcher_manager = self.close_watcher_manager();
1103 let group = close_watcher_manager.groups().last().cloned();
1104 if let Some(group) = group {
1105 for close_watcher in group.iter().rev() {
1107 if close_watcher.get_enabled_state() {
1109 processed_a_close_watcher = true;
1110 }
1111
1112 let should_proceed = close_watcher.request_to_close(cx, true);
1114
1115 if !should_proceed {
1117 break;
1118 }
1119 }
1120 }
1121
1122 if close_watcher_manager.allowed_number_of_groups() > 1 {
1124 close_watcher_manager.decrement_allowed_number_of_groups();
1125 }
1126
1127 processed_a_close_watcher
1129 }
1130}
1131
1132#[derive(Debug, MallocSizeOf)]
1133pub(crate) struct FontCspHandler {
1134 pub(crate) task_source: SendableTaskSource,
1135}
1136
1137impl CspViolationHandler for FontCspHandler {
1138 fn process_violations(&self, violations: Vec<Violation>) {
1139 self.task_source.queue(task!(csp_violation: move |cx| {
1140 if let Some(global) = GlobalScope::current() {
1141 global.report_csp_violations(cx, violations, None, None);
1142 }
1143 }));
1144 }
1145
1146 fn clone(&self) -> Box<dyn CspViolationHandler> {
1147 Box::new(Self {
1148 task_source: self.task_source.clone(),
1149 })
1150 }
1151}
1152
1153#[derive(Debug, MallocSizeOf)]
1154pub(crate) struct FontNetworkTimingHandler {
1155 pub(crate) task_source: SendableTaskSource,
1156}
1157
1158impl NetworkTimingHandler for FontNetworkTimingHandler {
1159 fn submit_timing(&self, url: ServoUrl, response: ResourceFetchTiming) {
1160 self.task_source.queue(task!(network_timing: move |cx| {
1161 let Some(global) = GlobalScope::current() else {
1162 return
1163 };
1164
1165 submit_timing(
1166 cx,
1167 &global,
1168 &FontFetchListener {
1169 url,
1170 },
1171 &Ok(()),
1172 &response,
1173 );
1174 }));
1175 }
1176
1177 fn clone(&self) -> Box<dyn NetworkTimingHandler> {
1178 Box::new(Self {
1179 task_source: self.task_source.clone(),
1180 })
1181 }
1182}
1183
1184#[derive(Debug)]
1185struct FontFetchListener {
1186 url: ServoUrl,
1187}
1188
1189impl ResourceTimingListener for FontFetchListener {
1190 fn resource_timing_information(&self) -> (InitiatorType, ServoUrl) {
1191 (InitiatorType::Css, self.url.clone())
1192 }
1193}
1194
1195pub(crate) fn base64_btoa(input: DOMString) -> Fallible<DOMString> {
1197 if input.str().chars().any(|c: char| c > '\u{FF}') {
1201 Err(Error::InvalidCharacter(None))
1202 } else {
1203 let octets = input
1208 .str()
1209 .chars()
1210 .map(|c: char| c as u8)
1211 .collect::<Vec<u8>>();
1212
1213 let config =
1216 base64::engine::general_purpose::GeneralPurposeConfig::new().with_encode_padding(true);
1217 let engine = base64::engine::GeneralPurpose::new(&base64::alphabet::STANDARD, config);
1218 Ok(DOMString::from(engine.encode(octets)))
1219 }
1220}
1221
1222pub(crate) fn base64_atob(input: DOMString) -> Fallible<DOMString> {
1224 fn is_html_space(c: char) -> bool {
1226 HTML_SPACE_CHARACTERS.contains(&c)
1227 }
1228 let without_spaces = input
1229 .str()
1230 .chars()
1231 .filter(|&c| !is_html_space(c))
1232 .collect::<String>();
1233 let mut input = &*without_spaces;
1234
1235 if input.len() % 4 == 0 {
1239 if input.ends_with("==") {
1240 input = &input[..input.len() - 2]
1241 } else if input.ends_with('=') {
1242 input = &input[..input.len() - 1]
1243 }
1244 }
1245
1246 if input.len() % 4 == 1 {
1249 return Err(Error::InvalidCharacter(None));
1250 }
1251
1252 if input
1260 .chars()
1261 .any(|c| c != '+' && c != '/' && !c.is_alphanumeric())
1262 {
1263 return Err(Error::InvalidCharacter(None));
1264 }
1265
1266 let config = base64::engine::general_purpose::GeneralPurposeConfig::new()
1267 .with_decode_padding_mode(base64::engine::DecodePaddingMode::RequireNone)
1268 .with_decode_allow_trailing_bits(true);
1269 let engine = base64::engine::GeneralPurpose::new(&base64::alphabet::STANDARD, config);
1270
1271 let data = engine
1272 .decode(input)
1273 .map_err(|_| Error::InvalidCharacter(None))?;
1274 Ok(data.iter().map(|&b| b as char).collect::<String>().into())
1275}
1276
1277impl WindowMethods<crate::DomTypeHolder> for Window {
1278 fn Alert_(&self) {
1280 self.Alert(DOMString::new());
1283 }
1284
1285 fn Alert(&self, mut message: DOMString) {
1287 if self.cannot_show_simple_dialogs() {
1289 return;
1290 }
1291
1292 message.normalize_newlines();
1296
1297 {
1308 let stderr = stderr();
1312 let mut stderr = stderr.lock();
1313 let stdout = stdout();
1314 let mut stdout = stdout.lock();
1315 writeln!(&mut stdout, "\nALERT: {message}").unwrap();
1316 stdout.flush().unwrap();
1317 stderr.flush().unwrap();
1318 }
1319
1320 let (sender, receiver) =
1321 ProfiledGenericChannel::channel(self.global().time_profiler_chan().clone()).unwrap();
1322 let dialog = SimpleDialogRequest::Alert {
1323 id: self.Document().embedder_controls().next_control_id(),
1324 message: String::from(message),
1325 response_sender: sender,
1326 };
1327 self.send_to_embedder(EmbedderMsg::ShowSimpleDialog(self.webview_id(), dialog));
1328 receiver.recv().unwrap_or_else(|_| {
1329 debug!("Alert dialog was cancelled or failed to show.");
1331 AlertResponse::Ok
1332 });
1333
1334 }
1337
1338 fn Caches(&self, cx: &mut JSContext) -> DomRoot<CacheStorage> {
1340 self.caches
1341 .or_init(|| CacheStorage::new(cx, self.as_global_scope()))
1342 }
1343
1344 fn Confirm(&self, mut message: DOMString) -> bool {
1346 if self.cannot_show_simple_dialogs() {
1348 return false;
1349 }
1350
1351 message.normalize_newlines();
1353
1354 let (sender, receiver) =
1360 ProfiledGenericChannel::channel(self.global().time_profiler_chan().clone()).unwrap();
1361 let dialog = SimpleDialogRequest::Confirm {
1362 id: self.Document().embedder_controls().next_control_id(),
1363 message: String::from(message),
1364 response_sender: sender,
1365 };
1366 self.send_to_embedder(EmbedderMsg::ShowSimpleDialog(self.webview_id(), dialog));
1367
1368 match receiver.recv() {
1384 Ok(ConfirmResponse::Ok) => true,
1385 Ok(ConfirmResponse::Cancel) => false,
1386 Err(_) => {
1387 warn!("Confirm dialog was cancelled or failed to show.");
1388 false
1389 },
1390 }
1391 }
1392
1393 fn Prompt(&self, mut message: DOMString, default: DOMString) -> Option<DOMString> {
1395 if self.cannot_show_simple_dialogs() {
1397 return None;
1398 }
1399
1400 message.normalize_newlines();
1402
1403 let (sender, receiver) =
1411 ProfiledGenericChannel::channel(self.global().time_profiler_chan().clone()).unwrap();
1412 let dialog = SimpleDialogRequest::Prompt {
1413 id: self.Document().embedder_controls().next_control_id(),
1414 message: String::from(message),
1415 default: String::from(default),
1416 response_sender: sender,
1417 };
1418 self.send_to_embedder(EmbedderMsg::ShowSimpleDialog(self.webview_id(), dialog));
1419
1420 match receiver.recv() {
1439 Ok(PromptResponse::Ok(input)) => Some(input.into()),
1440 Ok(PromptResponse::Cancel) => None,
1441 Err(_) => {
1442 warn!("Prompt dialog was cancelled or failed to show.");
1443 None
1444 },
1445 }
1446 }
1447
1448 fn Stop(&self, cx: &mut JSContext) {
1450 self.stop_loading(cx);
1455 }
1456
1457 fn Focus(&self, cx: &mut JSContext) {
1459 let document = self.Document();
1467 if !document.is_active() {
1468 return;
1469 }
1470
1471 document
1476 .focus_handler()
1477 .focus(cx, &FocusableArea::Viewport, FocusTrigger::Script);
1478
1479 }
1484
1485 fn Blur(&self) {
1487 }
1490
1491 fn Open(
1493 &self,
1494 cx: &mut JSContext,
1495 url: USVString,
1496 target: DOMString,
1497 features: DOMString,
1498 ) -> Fallible<Option<DomRoot<WindowProxy>>> {
1499 self.window_proxy().open(cx, url, target, features)
1500 }
1501
1502 fn GetOpener(&self, cx: &mut CurrentRealm, mut retval: MutableHandleValue) -> Fallible<()> {
1504 let current = match self.window_proxy.get() {
1506 Some(proxy) => proxy,
1507 None => {
1509 retval.set(NullValue());
1510 return Ok(());
1511 },
1512 };
1513 if current.is_browsing_context_discarded() {
1518 retval.set(NullValue());
1519 return Ok(());
1520 }
1521 current.opener(cx, retval);
1523 Ok(())
1524 }
1525
1526 fn SetOpener(&self, cx: &mut JSContext, value: HandleValue) -> ErrorResult {
1528 if value.is_null() {
1530 if let Some(proxy) = self.window_proxy.get() {
1531 proxy.disown();
1532 }
1533 return Ok(());
1534 }
1535
1536 let obj = self.reflector().get_jsobject();
1538 let result = JS_DefineProperty(
1539 cx,
1540 obj,
1541 c"opener",
1542 value,
1543 PropertyFlags::ENUMERABLE | PropertyFlags::WRITABLE | PropertyFlags::CONFIGURABLE,
1544 );
1545
1546 if result { Ok(()) } else { Err(Error::JSFailed) }
1547 }
1548
1549 fn Closed(&self) -> bool {
1551 self.window_proxy
1552 .get()
1553 .map(|ref proxy| proxy.is_browsing_context_discarded() || proxy.is_closing())
1554 .unwrap_or(true)
1555 }
1556
1557 fn Close(&self, cx: &mut JSContext) {
1559 let window_proxy = match self.window_proxy.get() {
1561 Some(proxy) => proxy,
1562 None => return,
1564 };
1565 if window_proxy.is_closing() {
1567 return;
1568 }
1569 if let Ok(history_length) = self.History(cx).GetLength() {
1572 let is_auxiliary = window_proxy.is_auxiliary();
1573
1574 let is_script_closable = (self.is_top_level() && history_length == 1) ||
1576 is_auxiliary ||
1577 pref!(dom_allow_scripts_to_close_windows);
1578
1579 if is_script_closable {
1583 window_proxy.close();
1585
1586 let this = Trusted::new(self);
1588 let task = task!(window_close_browsing_context: move |cx| {
1589 let window = this.root();
1590 window.definitely_close(cx);
1591 });
1592 self.as_global_scope()
1593 .task_manager()
1594 .dom_manipulation_task_source()
1595 .queue(task);
1596 }
1597 }
1598 }
1599
1600 fn Document(&self) -> DomRoot<Document> {
1602 self.document
1603 .get()
1604 .expect("Document accessed before initialization.")
1605 }
1606
1607 fn History(&self, cx: &mut JSContext) -> DomRoot<History> {
1609 self.Document().history(cx)
1610 }
1611
1612 fn IndexedDB(&self, cx: &mut JSContext) -> DomRoot<IDBFactory> {
1614 self.upcast::<GlobalScope>().ensure_indexeddb_factory(cx)
1615 }
1616
1617 fn CustomElements(&self, cx: &mut JSContext) -> DomRoot<CustomElementRegistry> {
1619 let document = self.Document();
1622 if let Some(registry) = document.custom_element_registry() {
1623 return registry;
1624 }
1625 let registry = CustomElementRegistry::new(cx, self);
1628 document.set_custom_element_registry(®istry);
1629 registry
1631 }
1632
1633 fn Location(&self, cx: &mut JSContext) -> DomRoot<Location> {
1635 self.location.or_init(|| Location::new(cx, self))
1636 }
1637
1638 fn GetSessionStorage(&self, cx: &mut JSContext) -> Fallible<DomRoot<Storage>> {
1640 if let Some(storage) = self.session_storage.get() {
1643 return Ok(storage);
1644 }
1645
1646 if !self.origin().is_tuple() {
1650 return Err(Error::Security(Some(
1651 "Cannot access sessionStorage from opaque origin.".to_string(),
1652 )));
1653 }
1654
1655 let storage = Storage::new(cx, self, WebStorageType::Session);
1657
1658 self.session_storage.set(Some(&storage));
1660
1661 Ok(storage)
1663 }
1664
1665 fn GetLocalStorage(&self, cx: &mut JSContext) -> Fallible<DomRoot<Storage>> {
1667 if let Some(storage) = self.local_storage.get() {
1670 return Ok(storage);
1671 }
1672
1673 if !self.origin().is_tuple() {
1677 return Err(Error::Security(Some(
1678 "Cannot access localStorage from opaque origin.".to_string(),
1679 )));
1680 }
1681
1682 let storage = Storage::new(cx, self, WebStorageType::Local);
1684
1685 self.local_storage.set(Some(&storage));
1687
1688 Ok(storage)
1690 }
1691
1692 fn CookieStore(&self, cx: &mut JSContext) -> DomRoot<CookieStore> {
1694 self.cookie_store
1695 .or_init(|| CookieStore::new(cx, self.upcast::<GlobalScope>()))
1696 }
1697
1698 fn Crypto(&self, cx: &mut JSContext) -> DomRoot<crate::dom::crypto::Crypto> {
1700 self.crypto
1701 .or_init(|| crate::dom::crypto::Crypto::new(cx, self.as_global_scope()))
1702 }
1703
1704 fn GetFrameElement(&self) -> Option<DomRoot<Element>> {
1706 let window_proxy = self.window_proxy.get()?;
1708
1709 let container = window_proxy.frame_element()?;
1711
1712 let container_doc = container.owner_document();
1714 let current_doc = GlobalScope::current()
1715 .expect("No current global object")
1716 .as_window()
1717 .Document();
1718 if !current_doc
1719 .origin()
1720 .same_origin_domain(&container_doc.origin())
1721 {
1722 return None;
1723 }
1724 Some(DomRoot::from_ref(container))
1726 }
1727
1728 fn ReportError(&self, cx: &mut JSContext, error: HandleValue) {
1730 self.as_global_scope().report_an_exception(cx, error);
1731 }
1732
1733 fn Navigator(&self, cx: &mut JSContext) -> DomRoot<Navigator> {
1735 self.navigator.or_init(|| Navigator::new(cx, self))
1736 }
1737
1738 fn ClientInformation(&self, cx: &mut JSContext) -> DomRoot<Navigator> {
1740 self.Navigator(cx)
1741 }
1742
1743 fn SetTimeout(
1745 &self,
1746 cx: &mut JSContext,
1747 callback: TrustedScriptOrStringOrFunction,
1748 timeout: i32,
1749 args: Vec<HandleValue>,
1750 ) -> Fallible<i32> {
1751 let callback = match callback {
1752 TrustedScriptOrStringOrFunction::String(i) => {
1753 TimerCallback::StringTimerCallback(TrustedScriptOrString::String(i))
1754 },
1755 TrustedScriptOrStringOrFunction::TrustedScript(i) => {
1756 TimerCallback::StringTimerCallback(TrustedScriptOrString::TrustedScript(i))
1757 },
1758 TrustedScriptOrStringOrFunction::Function(i) => TimerCallback::FunctionTimerCallback(i),
1759 };
1760 self.as_global_scope().set_timeout_or_interval(
1761 cx,
1762 callback,
1763 args,
1764 Duration::from_millis(timeout.max(0) as u64),
1765 IsInterval::NonInterval,
1766 )
1767 }
1768
1769 fn ClearTimeout(&self, handle: i32) {
1771 self.as_global_scope().clear_timeout_or_interval(handle);
1772 }
1773
1774 fn SetInterval(
1776 &self,
1777 cx: &mut JSContext,
1778 callback: TrustedScriptOrStringOrFunction,
1779 timeout: i32,
1780 args: Vec<HandleValue>,
1781 ) -> Fallible<i32> {
1782 let callback = match callback {
1783 TrustedScriptOrStringOrFunction::String(i) => {
1784 TimerCallback::StringTimerCallback(TrustedScriptOrString::String(i))
1785 },
1786 TrustedScriptOrStringOrFunction::TrustedScript(i) => {
1787 TimerCallback::StringTimerCallback(TrustedScriptOrString::TrustedScript(i))
1788 },
1789 TrustedScriptOrStringOrFunction::Function(i) => TimerCallback::FunctionTimerCallback(i),
1790 };
1791 self.as_global_scope().set_timeout_or_interval(
1792 cx,
1793 callback,
1794 args,
1795 Duration::from_millis(timeout.max(0) as u64),
1796 IsInterval::Interval,
1797 )
1798 }
1799
1800 fn ClearInterval(&self, handle: i32) {
1802 self.ClearTimeout(handle);
1803 }
1804
1805 fn QueueMicrotask(&self, cx: &JSContext, callback: RootedCallback<VoidFunction>) {
1807 ScriptThread::enqueue_microtask(
1808 cx,
1809 Box::new(UserMicrotask {
1810 callback: callback.to_traced(),
1811 global: Dom::from_ref(&self.globalscope),
1812 }),
1813 );
1814 }
1815
1816 fn CreateImageBitmap(
1818 &self,
1819 realm: &mut CurrentRealm,
1820 image: ImageBitmapSource,
1821 options: &ImageBitmapOptions,
1822 ) -> RootedPromise {
1823 ImageBitmap::create_image_bitmap(
1824 self.as_global_scope(),
1825 image,
1826 0,
1827 0,
1828 None,
1829 None,
1830 options,
1831 realm,
1832 )
1833 }
1834
1835 fn CreateImageBitmap_(
1837 &self,
1838 realm: &mut CurrentRealm,
1839 image: ImageBitmapSource,
1840 sx: i32,
1841 sy: i32,
1842 sw: i32,
1843 sh: i32,
1844 options: &ImageBitmapOptions,
1845 ) -> RootedPromise {
1846 ImageBitmap::create_image_bitmap(
1847 self.as_global_scope(),
1848 image,
1849 sx,
1850 sy,
1851 Some(sw),
1852 Some(sh),
1853 options,
1854 realm,
1855 )
1856 }
1857
1858 fn Window(&self) -> DomRoot<WindowProxy> {
1860 self.window_proxy()
1861 }
1862
1863 fn Self_(&self) -> DomRoot<WindowProxy> {
1865 self.window_proxy()
1866 }
1867
1868 fn Frames(&self) -> DomRoot<WindowProxy> {
1870 self.window_proxy()
1871 }
1872
1873 fn Length(&self) -> u32 {
1875 self.Document().iframes().active_iframe_count() as u32
1876 }
1877
1878 fn GetParent(&self) -> Option<DomRoot<WindowProxy>> {
1880 let window_proxy = self.undiscarded_window_proxy()?;
1882
1883 if let Some(parent) = window_proxy.parent() {
1885 return Some(DomRoot::from_ref(parent));
1886 }
1887 Some(window_proxy)
1889 }
1890
1891 fn GetTop(&self) -> Option<DomRoot<WindowProxy>> {
1893 let window_proxy = self.undiscarded_window_proxy()?;
1895
1896 Some(DomRoot::from_ref(window_proxy.top()))
1898 }
1899
1900 fn Performance(&self, cx: &mut JSContext) -> DomRoot<Performance> {
1903 self.performance
1904 .or_init(|| Performance::new(cx, self.as_global_scope(), self.navigation_start.get()))
1905 }
1906
1907 global_event_handlers!();
1909
1910 window_event_handlers!();
1912
1913 fn Screen(&self, cx: &mut JSContext) -> DomRoot<Screen> {
1915 self.screen.or_init(|| Screen::new(cx, self))
1916 }
1917
1918 fn GetVisualViewport(&self, cx: &mut JSContext) -> Option<DomRoot<VisualViewport>> {
1920 if !self.Document().is_fully_active() {
1924 return None;
1925 }
1926
1927 Some(self.get_or_init_visual_viewport(cx))
1928 }
1929
1930 fn Btoa(&self, btoa: DOMString) -> Fallible<DOMString> {
1932 base64_btoa(btoa)
1933 }
1934
1935 fn Atob(&self, atob: DOMString) -> Fallible<DOMString> {
1937 base64_atob(atob)
1938 }
1939
1940 fn RequestAnimationFrame(
1942 &self,
1943 callback: RootedCallback<FrameRequestCallback>,
1944 ) -> Fallible<u32> {
1945 Ok(self
1946 .Document()
1947 .request_animation_frame(AnimationFrameCallback::FrameRequestCallback {
1948 callback: callback.to_traced(),
1949 }))
1950 }
1951
1952 fn CancelAnimationFrame(&self, ident: u32) -> ErrorResult {
1954 let doc = self.Document();
1955 doc.cancel_animation_frame(ident);
1956 Ok(())
1957 }
1958
1959 fn PostMessage(
1961 &self,
1962 cx: &mut JSContext,
1963 message: HandleValue,
1964 target_origin: USVString,
1965 transfer: CustomAutoRooterGuard<Vec<*mut JSObject>>,
1966 ) -> ErrorResult {
1967 let incumbent = GlobalScope::incumbent().expect("no incumbent global?");
1968 let source = incumbent.as_window();
1969 let source_origin = source.Document().origin().immutable().clone();
1970
1971 self.post_message_impl(&target_origin, source_origin, source, cx, message, transfer)
1972 }
1973
1974 fn PostMessage_(
1976 &self,
1977 cx: &mut JSContext,
1978 message: HandleValue,
1979 options: &WindowPostMessageOptions,
1980 ) -> ErrorResult {
1981 auto_root!(&in(cx) let transfer =
1982 options
1983 .parent
1984 .transfer
1985 .iter()
1986 .map(|js| js.get())
1987 .collect::<Vec<_>>());
1988
1989 let incumbent = GlobalScope::incumbent().expect("no incumbent global?");
1990 let source = incumbent.as_window();
1991
1992 let source_origin = source.Document().origin().immutable().clone();
1993
1994 self.post_message_impl(
1995 &options.targetOrigin,
1996 source_origin,
1997 source,
1998 cx,
1999 message,
2000 transfer,
2001 )
2002 }
2003
2004 fn CaptureEvents(&self) {
2006 }
2008
2009 fn ReleaseEvents(&self) {
2011 }
2013
2014 fn WebdriverElement(&self, id: DOMString) -> Option<DomRoot<Element>> {
2015 find_node_by_unique_id_in_document(&self.Document(), id.into()).and_then(Root::downcast)
2016 }
2017
2018 fn WebdriverFrame(&self, browsing_context_id: DOMString) -> Option<DomRoot<WindowProxy>> {
2019 self.Document()
2020 .iframes()
2021 .iter()
2022 .find(|iframe| {
2023 iframe
2024 .browsing_context_id()
2025 .as_ref()
2026 .map(BrowsingContextId::to_string) ==
2027 Some(browsing_context_id.to_string())
2028 })
2029 .and_then(|iframe| iframe.GetContentWindow())
2030 }
2031
2032 fn WebdriverWindow(&self, webview_id: DOMString) -> DomRoot<WindowProxy> {
2033 let window_proxy = &self
2034 .window_proxy
2035 .get()
2036 .expect("Should always have a WindowProxy when calling WebdriverWindow");
2037 assert!(
2038 self.is_top_level(),
2039 "Window must be top level browsing context."
2040 );
2041 assert!(self.webview_id().to_string() == webview_id);
2042 DomRoot::from_ref(window_proxy)
2043 }
2044
2045 fn WebdriverShadowRoot(&self, id: DOMString) -> Option<DomRoot<ShadowRoot>> {
2046 find_node_by_unique_id_in_document(&self.Document(), id.into()).and_then(Root::downcast)
2047 }
2048
2049 fn GetComputedStyle(
2051 &self,
2052 cx: &mut JSContext,
2053 element: &Element,
2054 pseudo: Option<DOMString>,
2055 ) -> DomRoot<CSSStyleDeclaration> {
2056 let mut is_null = false;
2060
2061 let pseudo = pseudo
2063 .filter(|pseudo| pseudo.starts_with(':'))
2064 .and_then(|pseudo| {
2065 let pseudo = pseudo.str();
2067 let pseudo = pseudo
2068 .strip_prefix("::")
2069 .or_else(|| {
2070 pseudo
2071 .strip_prefix(":")
2072 .filter(|pseudo_name| is_css2_pseudo_element(pseudo_name))
2073 })
2074 .and_then(|pseudo_name| {
2075 SelectorParser {
2076 stylesheet_origin: StyleOrigin::Author,
2077 namespaces: &Default::default(),
2078 url_data: &UrlExtraData(self.Document().url().get_arc()),
2079 for_supports_rule: false,
2080 }
2081 .parse_pseudo_element(pseudo_name)
2082 .ok()
2083 });
2084 is_null = pseudo.is_none();
2087 pseudo
2088 });
2089
2090 CSSStyleDeclaration::new(
2106 cx,
2107 self,
2108 if is_null {
2109 CSSStyleOwner::Null
2110 } else {
2111 CSSStyleOwner::Element(Dom::from_ref(element))
2112 },
2113 pseudo,
2114 CSSModificationAccess::Readonly,
2115 )
2116 }
2117
2118 fn InnerHeight(&self) -> i32 {
2121 self.viewport_details
2122 .get()
2123 .size
2124 .height
2125 .to_i32()
2126 .unwrap_or(0)
2127 }
2128
2129 fn InnerWidth(&self) -> i32 {
2132 self.viewport_details.get().size.width.to_i32().unwrap_or(0)
2133 }
2134
2135 fn ScrollX(&self, cx: &mut JSContext) -> i32 {
2137 self.scroll_offset(cx).x as i32
2138 }
2139
2140 fn PageXOffset(&self, cx: &mut JSContext) -> i32 {
2142 self.ScrollX(cx)
2143 }
2144
2145 fn ScrollY(&self, cx: &mut JSContext) -> i32 {
2147 self.scroll_offset(cx).y as i32
2148 }
2149
2150 fn PageYOffset(&self, cx: &mut JSContext) -> i32 {
2152 self.ScrollY(cx)
2153 }
2154
2155 fn Scroll(&self, cx: &mut JSContext, options: &ScrollToOptions) {
2157 let x = options.left.unwrap_or(0.0) as f32;
2162
2163 let y = options.top.unwrap_or(0.0) as f32;
2166
2167 self.scroll(cx, x, y, options.parent.behavior);
2169 }
2170
2171 fn Scroll_(&self, cx: &mut JSContext, x: f64, y: f64) {
2173 self.scroll(cx, x as f32, y as f32, ScrollBehavior::Auto);
2177 }
2178
2179 fn ScrollTo(&self, cx: &mut JSContext, options: &ScrollToOptions) {
2184 self.Scroll(cx, options);
2185 }
2186
2187 fn ScrollTo_(&self, cx: &mut JSContext, x: f64, y: f64) {
2192 self.Scroll_(cx, x, y)
2193 }
2194
2195 fn ScrollBy(&self, cx: &mut JSContext, options: &ScrollToOptions) {
2197 let mut options = options.clone();
2203 let x = options.left.unwrap_or(0.0);
2204 let x = if x.is_finite() { x } else { 0.0 };
2205 let y = options.top.unwrap_or(0.0);
2206 let y = if y.is_finite() { y } else { 0.0 };
2207
2208 options.left.replace(x + self.ScrollX(cx) as f64);
2210
2211 options.top.replace(y + self.ScrollY(cx) as f64);
2213
2214 self.Scroll(cx, &options)
2216 }
2217
2218 fn ScrollBy_(&self, cx: &mut JSContext, x: f64, y: f64) {
2220 let mut options = ScrollToOptions::empty();
2224
2225 options.left.replace(x);
2228
2229 options.top.replace(y);
2231
2232 self.ScrollBy(cx, &options);
2234 }
2235
2236 fn ResizeTo(&self, width: i32, height: i32) {
2238 let window_proxy = match self.window_proxy.get() {
2240 Some(proxy) => proxy,
2241 None => return,
2242 };
2243
2244 if !window_proxy.is_auxiliary() {
2247 return;
2248 }
2249
2250 let dpr = self.device_pixel_ratio();
2251 let size = Size2D::new(width, height).to_f32() * dpr;
2252 self.send_to_embedder(EmbedderMsg::ResizeTo(self.webview_id(), size.to_i32()));
2253 }
2254
2255 fn ResizeBy(&self, x: i32, y: i32) {
2257 let size = self.client_window().size();
2258 self.ResizeTo(x + size.width, y + size.height)
2260 }
2261
2262 fn MoveTo(&self, x: i32, y: i32) {
2264 let dpr = self.device_pixel_ratio();
2267 let point = Point2D::new(x, y).to_f32() * dpr;
2268 let msg = EmbedderMsg::MoveTo(self.webview_id(), point.to_i32());
2269 self.send_to_embedder(msg);
2270 }
2271
2272 fn MoveBy(&self, x: i32, y: i32) {
2274 let origin = self.client_window().min;
2275 self.MoveTo(x + origin.x, y + origin.y)
2277 }
2278
2279 fn ScreenX(&self) -> i32 {
2281 self.client_window().min.x
2282 }
2283
2284 fn ScreenLeft(&self) -> i32 {
2286 self.client_window().min.x
2287 }
2288
2289 fn ScreenY(&self) -> i32 {
2291 self.client_window().min.y
2292 }
2293
2294 fn ScreenTop(&self) -> i32 {
2296 self.client_window().min.y
2297 }
2298
2299 fn OuterHeight(&self) -> i32 {
2301 self.client_window().height()
2302 }
2303
2304 fn OuterWidth(&self) -> i32 {
2306 self.client_window().width()
2307 }
2308
2309 fn DevicePixelRatio(&self) -> Finite<f64> {
2311 Finite::wrap(self.device_pixel_ratio().get() as f64)
2312 }
2313
2314 fn Status(&self) -> DOMString {
2316 self.status.borrow().clone().root()
2317 }
2318
2319 fn SetStatus(&self, status: DOMString) {
2321 *self.status.borrow_mut() = status.traced()
2322 }
2323
2324 fn MatchMedia(&self, cx: &mut JSContext, query: DOMString) -> DomRoot<MediaQueryList> {
2326 let media_query_list = MediaList::parse_media_list(&query.str(), self);
2327 let document = self.Document();
2328 let mql = MediaQueryList::new(cx, &document, media_query_list);
2329 self.media_query_lists.track(&*mql);
2330 mql
2331 }
2332
2333 fn Fetch(
2335 &self,
2336 realm: &mut CurrentRealm,
2337 input: RequestOrUSVString,
2338 init: &RequestInit,
2339 ) -> RootedPromise {
2340 fetch::Fetch(self.upcast(), input, init, realm)
2341 }
2342
2343 fn FetchLater(
2345 &self,
2346 cx: &mut JSContext,
2347 input: RequestInfo,
2348 init: &DeferredRequestInit,
2349 ) -> Fallible<DomRoot<FetchLaterResult>> {
2350 fetch::FetchLater(cx, self, input, init)
2351 }
2352
2353 #[cfg(feature = "bluetooth")]
2354 fn TestRunner(&self, cx: &mut JSContext) -> DomRoot<TestRunner> {
2355 self.test_runner
2356 .or_init(|| TestRunner::new(cx, self.upcast()))
2357 }
2358
2359 fn RunningAnimationCount(&self) -> u32 {
2360 self.document.get().map_or(0, |document| {
2361 document.animation_manager().running_animation_count() as u32
2362 })
2363 }
2364
2365 fn SetName(&self, name: DOMString) {
2367 if let Some(proxy) = self.undiscarded_window_proxy() {
2368 proxy.set_name(name);
2369 }
2370 }
2371
2372 fn Name(&self) -> DOMString {
2374 match self.undiscarded_window_proxy() {
2375 Some(proxy) => proxy.get_name(),
2376 None => DOMString::new(),
2377 }
2378 }
2379
2380 fn Origin(&self) -> USVString {
2382 USVString(self.origin().immutable().ascii_serialization().into_owned())
2383 }
2384
2385 fn GetSelection(&self, cx: &mut JSContext) -> Option<DomRoot<Selection>> {
2387 self.document.get().and_then(|d| d.GetSelection(cx))
2388 }
2389
2390 fn Event(&self, cx: &mut JSContext, rval: MutableHandleValue) {
2392 if let Some(ref event) = self.current_event.get() {
2393 event.reflector().get_jsobject().to_jsval(cx, rval);
2394 }
2395 }
2396
2397 fn IsSecureContext(&self) -> bool {
2398 self.as_global_scope().is_secure_context()
2399 }
2400
2401 fn NamedGetter(&self, cx: &mut JSContext, name: DOMString) -> Option<NamedPropertyValue> {
2403 if name.is_empty() {
2404 return None;
2405 }
2406 let document = self.Document();
2407
2408 let iframes: Vec<_> = document
2410 .iframes()
2411 .iter()
2412 .filter(|iframe| {
2413 if let Some(window) = iframe.GetContentWindow() {
2414 return window.get_name() == name;
2415 }
2416 false
2417 })
2418 .collect();
2419
2420 let iframe_iter = iframes.iter().map(|iframe| iframe.upcast::<Element>());
2421
2422 let name = Atom::from(name);
2423
2424 let elements_with_name = document.get_elements_with_name(cx, &name);
2426 let name_iter = elements_with_name
2427 .iter()
2428 .map(|element| &**element)
2429 .filter(|elem| is_named_element_with_name_attribute(elem));
2430
2431 let elements_with_id = document.get_elements_with_id(cx, &name);
2432 let id_iter = elements_with_id
2433 .iter()
2434 .map(|element| &**element)
2435 .filter(|elem| is_named_element_with_id_attribute(elem));
2436
2437 for elem in iframe_iter.clone() {
2439 if let Some(nested_window_proxy) = elem
2440 .downcast::<HTMLIFrameElement>()
2441 .and_then(|iframe| iframe.GetContentWindow())
2442 {
2443 return Some(NamedPropertyValue::WindowProxy(nested_window_proxy));
2444 }
2445 }
2446
2447 let mut elements = iframe_iter.chain(name_iter).chain(id_iter);
2448
2449 let first = elements.next()?;
2450
2451 if elements.next().is_none() {
2452 return Some(NamedPropertyValue::Element(DomRoot::from_ref(first)));
2454 }
2455
2456 #[derive(JSTraceable, MallocSizeOf)]
2458 struct WindowNamedGetter {
2459 #[no_trace]
2460 name: Atom,
2461 }
2462 impl CollectionFilter for WindowNamedGetter {
2463 fn filter(&self, elem: &Element, _root: &Node) -> bool {
2464 let type_ = match elem.upcast::<Node>().type_id() {
2465 NodeTypeId::Element(ElementTypeId::HTMLElement(type_)) => type_,
2466 _ => return false,
2467 };
2468 if elem.get_id().as_ref() == Some(&self.name) {
2469 return true;
2470 }
2471 match type_ {
2472 HTMLElementTypeId::HTMLEmbedElement |
2473 HTMLElementTypeId::HTMLFormElement |
2474 HTMLElementTypeId::HTMLImageElement |
2475 HTMLElementTypeId::HTMLObjectElement => {
2476 elem.get_name().as_ref() == Some(&self.name)
2477 },
2478 _ => false,
2479 }
2480 }
2481 }
2482 let collection = HTMLCollection::create(
2483 cx,
2484 self,
2485 document.upcast(),
2486 Box::new(WindowNamedGetter { name }),
2487 );
2488 Some(NamedPropertyValue::HTMLCollection(collection))
2489 }
2490
2491 fn SupportedPropertyNames(&self, no_gc: &NoGC) -> Vec<DOMString> {
2493 self.Document().SupportedPropertyNames(no_gc)
2494 }
2495
2496 fn StructuredClone(
2498 &self,
2499 cx: &mut JSContext,
2500 value: HandleValue,
2501 options: &StructuredSerializeOptions,
2502 retval: MutableHandleValue,
2503 ) -> Fallible<()> {
2504 self.as_global_scope()
2505 .structured_clone(cx, value, options, retval)
2506 }
2507
2508 fn TrustedTypes(&self, cx: &mut JSContext) -> DomRoot<TrustedTypePolicyFactory> {
2509 self.trusted_types
2510 .or_init(|| TrustedTypePolicyFactory::new(cx, self.as_global_scope()))
2511 }
2512}
2513
2514impl Window {
2515 pub(crate) fn scroll_offset(&self, cx: &mut JSContext) -> Vector2D<f32, LayoutPixel> {
2516 self.scroll_offset_query_with_external_scroll_id(cx, self.pipeline_id().root_scroll_id())
2517 }
2518
2519 pub(crate) fn create_named_properties_object(
2522 cx: &mut JSContext,
2523 proto: HandleObject,
2524 object: MutableHandleObject,
2525 ) {
2526 window_named_properties::create(cx, proto, object)
2527 }
2528
2529 pub(crate) fn current_event(&self) -> Option<DomRoot<Event>> {
2530 self.current_event.get()
2531 }
2532
2533 pub(crate) fn set_current_event(&self, event: Option<&Event>) -> Option<DomRoot<Event>> {
2534 let current = self.current_event();
2535 self.current_event.set(event);
2536 current
2537 }
2538
2539 fn post_message_impl(
2541 &self,
2542 target_origin: &USVString,
2543 source_origin: ImmutableOrigin,
2544 source: &Window,
2545 cx: &mut JSContext,
2546 message: HandleValue,
2547 transfer: CustomAutoRooterGuard<Vec<*mut JSObject>>,
2548 ) -> ErrorResult {
2549 let data = structuredclone::write(cx, message, Some(transfer))?;
2551
2552 let target_origin = match target_origin.0[..].as_ref() {
2554 "*" => None,
2555 "/" => Some(source_origin.clone()),
2556 url => match ServoUrl::parse(url) {
2557 Ok(url) => Some(url.origin()),
2558 Err(_) => return Err(Error::Syntax(None)),
2559 },
2560 };
2561
2562 self.post_message(target_origin, source_origin, &source.window_proxy(), data);
2564 Ok(())
2565 }
2566
2567 pub(crate) fn paint_worklet(&self, cx: &mut JSContext) -> DomRoot<Worklet> {
2569 self.paint_worklet.or_init(|| self.new_paint_worklet(cx))
2570 }
2571
2572 pub(crate) fn clear_js_runtime(&self) {
2573 self.clear_js_runtime_common();
2574
2575 self.Document().teardown_custom_element_registry();
2578
2579 *self.js_runtime.borrow_mut() = None;
2580
2581 if let Some(performance) = self.performance.get() {
2582 performance.clear_and_disable_performance_entry_buffer();
2583 }
2584
2585 if let Some(factory) = self.upcast::<GlobalScope>().indexeddb_factory() {
2590 factory.abort_pending_upgrades_and_close_databases();
2591 }
2592
2593 self.pending_image_callbacks.borrow_mut().clear();
2596 }
2597
2598 pub(crate) fn scroll(&self, cx: &mut JSContext, x: f32, y: f32, behavior: ScrollBehavior) {
2600 let xfinite = if x.is_finite() { x } else { 0.0 };
2602 let yfinite = if y.is_finite() { y } else { 0.0 };
2603
2604 let viewport = self.viewport_details.get().size;
2614
2615 let scrolling_area = self.scrolling_area_query(cx, None).to_f32();
2634 let x = xfinite.clamp(0.0, 0.0f32.max(scrolling_area.width() - viewport.width));
2635 let y = yfinite.clamp(0.0, 0.0f32.max(scrolling_area.height() - viewport.height));
2636
2637 let scroll_offset = self.scroll_offset(cx);
2640 if x == scroll_offset.x && y == scroll_offset.y {
2641 return;
2642 }
2643
2644 self.perform_a_scroll(
2649 cx,
2650 x,
2651 y,
2652 self.pipeline_id().root_scroll_id(),
2653 behavior,
2654 None,
2655 );
2656 }
2657
2658 pub(crate) fn perform_a_scroll(
2660 &self,
2661 cx: &mut JSContext,
2662 x: f32,
2663 y: f32,
2664 scroll_id: ExternalScrollId,
2665 _behavior: ScrollBehavior,
2666 element: Option<&Element>,
2667 ) {
2668 let (reflow_phases_run, _) = self.reflow(
2692 cx,
2693 ReflowGoal::UpdateScrollNode(scroll_id, Vector2D::new(x, y)),
2694 );
2695 if reflow_phases_run.needs_frame() {
2696 self.paint_api()
2697 .generate_frame(vec![self.webview_id().into()]);
2698 }
2699
2700 if reflow_phases_run.contains(ReflowPhasesRun::UpdatedScrollNodeOffset) {
2708 match element {
2709 Some(element) if !scroll_id.is_root() => element.handle_scroll_event(),
2710 _ => self.Document().handle_viewport_scroll_event(),
2711 };
2712 }
2713
2714 }
2717
2718 pub(crate) fn device_pixel_ratio(&self) -> Scale<f32, CSSPixel, DevicePixel> {
2719 self.viewport_details.get().hidpi_scale_factor
2720 }
2721
2722 fn client_window(&self) -> DeviceIndependentIntRect {
2723 let (sender, receiver) = generic_channel::channel().expect("Failed to create IPC channel!");
2724
2725 self.send_to_embedder(EmbedderMsg::GetWindowRect(self.webview_id(), sender));
2726
2727 receiver.recv().unwrap_or_default()
2728 }
2729
2730 pub(crate) fn advance_animation_clock(&self, no_gc: &NoGC, delta: TimeDuration) {
2733 self.Document()
2734 .advance_animation_timeline_for_testing(delta);
2735 ScriptThread::handle_tick_all_animations_for_testing(no_gc, self.pipeline_id());
2736 }
2737
2738 pub(crate) fn reflow(
2746 &self,
2747 cx: &mut JSContext,
2748 reflow_goal: ReflowGoal,
2749 ) -> (ReflowPhasesRun, ReflowStatistics) {
2750 let document = self.Document();
2751
2752 if !document.is_fully_active() {
2754 return Default::default();
2755 }
2756
2757 self.document_unrooted(cx.no_gc())
2758 .ensure_safe_to_run_script_or_layout();
2759
2760 match reflow_goal {
2764 ReflowGoal::LayoutQuery(_) | ReflowGoal::UpdateScrollNode(..) => {
2765 self.flush_ancestor_layouts_if_necessary(cx);
2766 },
2767 ReflowGoal::UpdateTheRendering => { },
2768 }
2769
2770 let pipeline_id = self.pipeline_id();
2774 if reflow_goal == ReflowGoal::UpdateTheRendering &&
2775 self.layout_blocker.get().layout_blocked()
2776 {
2777 debug!("Suppressing pre-load-event reflow pipeline {pipeline_id}");
2778 return Default::default();
2779 }
2780
2781 debug!("script: performing reflow for goal {reflow_goal:?}");
2782 #[cfg(feature = "devtools")]
2783 let marker = if self.need_emit_timeline_marker(devtools_traits::TimelineMarkerType::Reflow)
2784 {
2785 Some(devtools_traits::TimelineMarker::start("Reflow".to_owned()))
2786 } else {
2787 None
2788 };
2789
2790 if let Some(selection) = document.selection() {
2791 selection.update_overlaps_document_selection_flags(cx.no_gc());
2792 }
2793
2794 let restyle_reason = document.restyle_reason(cx.no_gc());
2795 document.clear_restyle_reasons();
2796 let restyle = if restyle_reason.needs_restyle() {
2797 debug!("Invalidating layout cache due to reflow condition {restyle_reason:?}",);
2798 self.layout_marker.borrow().set(false);
2800 *self.layout_marker.borrow_mut() = Rc::new(Cell::new(true));
2802
2803 if restyle_reason.contains(RestyleReason::ViewportChanged) &&
2807 self.layout().device().used_viewport_size()
2808 {
2809 document.dirty_all_nodes(cx.no_gc());
2810 }
2811
2812 let stylesheets_changed = document.flush_stylesheets_for_reflow();
2813 let pending_restyles = document.drain_pending_restyles(cx.no_gc());
2814 let dirty_root = document
2815 .take_dirty_root()
2816 .filter(|_| !stylesheets_changed)
2817 .or_else(|| document.GetDocumentElement())
2818 .map(|root| root.upcast::<Node>().to_trusted_node_address());
2819
2820 Some(ReflowRequestRestyle {
2821 reason: restyle_reason,
2822 dirty_root,
2823 stylesheets_changed,
2824 pending_restyles,
2825 })
2826 } else {
2827 None
2828 };
2829
2830 document.id_map().resolve_all(cx.no_gc(), document.upcast());
2833
2834 let document_context = self.as_global_scope().web_font_context(cx.no_gc());
2835 let should_update_accessibility_tree = matches!(
2836 reflow_goal,
2837 ReflowGoal::UpdateTheRendering | ReflowGoal::LayoutQuery(QueryMsg::AccessKitNodeQuery)
2838 );
2839 let accessibility =
2840 if should_update_accessibility_tree && self.layout().accessibility_active() {
2841 let rooted_nodes_for_integrity_check =
2842 document.rooted_nodes_for_accessibility_integrity_check();
2843 let focused_element = document
2844 .focus_handler()
2845 .focused_area()
2846 .element()
2847 .map(|element| element.upcast::<Node>().to_opaque());
2848 let damage = document
2849 .accessibility_data_mut()
2850 .drain_pending_accessibility_damage();
2851 Some(ReflowRequestAccessibility {
2852 damage,
2853 focused_element,
2854 rooted_nodes_for_integrity_check,
2855 })
2856 } else {
2857 None
2858 };
2859
2860 let reflow = ReflowRequest {
2862 document: document.upcast::<Node>().to_trusted_node_address(),
2863 epoch: document.current_rendering_epoch(),
2864 restyle,
2865 viewport_details: self.viewport_details.get(),
2866 origin: self.origin().immutable().clone(),
2867 reflow_goal,
2868 animation_timeline_value: document.current_animation_timeline_value(),
2869 animations: document.animation_manager().sets(),
2870 animating_images: document.animation_manager().animating_images(),
2871 highlighted_dom_node: document.highlighted_dom_node().map(|node| node.to_opaque()),
2872 frame_focused: self.webview_state().has_system_focus.get() &&
2873 document.focus_handler().has_focus(),
2874 halt_lcp: self.has_dispatched_scroll_event.get() ||
2875 self.has_dispatched_input_event.get(),
2876 paint_timing_eligible: document.paint_timing_eligible(),
2877 paint_timing_info: document.paint_timing_info(),
2878 document_context,
2879 accessibility,
2880 };
2881
2882 let Some(reflow_result) = self.layout.borrow_mut().reflow(reflow) else {
2883 return Default::default();
2884 };
2885
2886 self.handle_accessibility_actions(reflow_result.pending_accessibility_actions, cx);
2887
2888 debug!("script: layout complete");
2889 #[cfg(feature = "devtools")]
2890 if let Some(marker) = marker {
2891 self.emit_timeline_marker(marker.end());
2892 }
2893
2894 self.handle_new_or_removed_web_fonts_post_reflow(cx, reflow_result.changed_web_fonts);
2895
2896 self.handle_pending_images_post_reflow(
2897 cx,
2898 reflow_result.pending_images,
2899 reflow_result.pending_rasterization_images,
2900 reflow_result.pending_svg_elements_for_serialization,
2901 );
2902
2903 if let Some(candidate) = reflow_result.lcp_candidate {
2904 self.process_lcp_candidate_post_reflow(candidate, &document);
2905 }
2906
2907 if !reflow_result.container_timing_records.is_empty() {
2908 self.process_container_timing_records_post_reflow(
2909 reflow_result.container_timing_records,
2910 &document,
2911 );
2912 }
2913
2914 if let Some(iframe_sizes) = reflow_result.iframe_sizes {
2915 document
2916 .iframes()
2917 .handle_new_iframe_sizes_after_layout(cx, self, iframe_sizes);
2918 }
2919
2920 document.update_animations_post_reflow();
2921
2922 (
2923 reflow_result.reflow_phases_run,
2924 reflow_result.reflow_statistics,
2925 )
2926 }
2927
2928 pub(crate) fn request_screenshot_readiness(&self, cx: &mut JSContext) {
2929 self.has_pending_screenshot_readiness_request.set(true);
2930 self.maybe_resolve_pending_screenshot_readiness_requests(cx);
2931 }
2932
2933 pub(crate) fn maybe_resolve_pending_screenshot_readiness_requests(&self, cx: &mut JSContext) {
2934 let pending_request = self.has_pending_screenshot_readiness_request.get();
2935 if !pending_request {
2936 return;
2937 }
2938
2939 let document = self.Document();
2940 if document.ReadyState() != DocumentReadyState::Complete {
2941 return;
2942 }
2943
2944 if document.render_blocking_element_count() > 0 {
2945 return;
2946 }
2947
2948 if document.GetDocumentElement().is_some_and(|elem| {
2952 elem.has_class(&atom!("reftest-wait"), CaseSensitivity::CaseSensitive) ||
2953 elem.has_class(&Atom::from("test-wait"), CaseSensitivity::CaseSensitive)
2954 }) {
2955 return;
2956 }
2957
2958 if self.font_context().web_fonts_still_loading() != 0 {
2959 return;
2960 }
2961
2962 if self.Document().Fonts(cx).waiting_to_fullfill_promise() {
2963 return;
2964 }
2965
2966 if !self.pending_layout_images.borrow().is_empty() ||
2967 !self.pending_images_for_rasterization.borrow().is_empty()
2968 {
2969 return;
2970 }
2971
2972 let document = self.Document();
2973 if document.needs_rendering_update(cx.no_gc()) {
2974 return;
2975 }
2976
2977 let epoch = document.current_rendering_epoch();
2980 let pipeline_id = self.pipeline_id();
2981 debug!("Ready to take screenshot of {pipeline_id:?} at epoch={epoch:?}");
2982
2983 self.send_to_constellation(
2984 ScriptToConstellationMessage::RespondToScreenshotReadinessRequest(
2985 ScreenshotReadinessResponse::Ready(epoch),
2986 ),
2987 );
2988 self.has_pending_screenshot_readiness_request.set(false);
2989 }
2990
2991 pub(crate) fn reflow_if_reflow_timer_expired(&self, cx: &mut JSContext) {
2994 if !matches!(
2997 self.layout_blocker.get(),
2998 LayoutBlocker::Parsing(instant) if instant + INITIAL_REFLOW_DELAY < Instant::now()
2999 ) {
3000 return;
3001 }
3002 self.allow_layout_if_necessary(cx);
3003 }
3004
3005 pub(crate) fn prevent_layout_until_load_event(&self) {
3009 if !matches!(self.layout_blocker.get(), LayoutBlocker::WaitingForParse) {
3012 return;
3013 }
3014
3015 self.layout_blocker
3016 .set(LayoutBlocker::Parsing(Instant::now()));
3017 }
3018
3019 pub(crate) fn allow_layout_if_necessary(&self, cx: &mut JSContext) {
3022 if matches!(self.layout_blocker.get(), LayoutBlocker::NotBlocked) {
3023 return;
3024 }
3025
3026 self.layout_blocker.set(LayoutBlocker::NotBlocked);
3027
3028 let document = self.Document();
3040 if !document.is_render_blocked() && document.update_the_rendering(cx).0.needs_frame() {
3041 self.paint_api()
3042 .generate_frame(vec![self.webview_id().into()]);
3043 }
3044 }
3045
3046 pub(crate) fn layout_blocked(&self) -> bool {
3047 self.layout_blocker.get().layout_blocked()
3048 }
3049
3050 fn flush_ancestor_layouts_if_necessary(&self, cx: &mut JSContext) {
3051 let Some(parent_pipeline_id) = self.parent_info else {
3052 return;
3053 };
3054 let Some(parent_window) = ScriptThread::find_window(parent_pipeline_id) else {
3055 return;
3056 };
3057 if !parent_window.Document().is_safe_to_run_script_or_layout() {
3060 return;
3061 }
3062 if parent_window.Document().is_render_blocked() {
3065 return;
3066 }
3067 parent_window.flush_ancestor_layouts_if_necessary(cx);
3068 if parent_window
3069 .document_unrooted(cx.no_gc())
3070 .restyle_reason(cx.no_gc())
3071 .needs_restyle()
3072 {
3073 parent_window.reflow(
3074 cx,
3075 ReflowGoal::LayoutQuery(QueryMsg::FlushForUpdateTheRenderingQuery),
3076 );
3077 }
3078 }
3079
3080 pub(crate) fn layout_reflow(&self, cx: &mut JSContext, query_msg: QueryMsg) {
3082 self.reflow(cx, ReflowGoal::LayoutQuery(query_msg));
3083 }
3084
3085 #[expect(unsafe_code)]
3087 pub(crate) fn layout_reflow_deprecated(&self, query_msg: QueryMsg) {
3088 let mut cx = unsafe { script_bindings::script_runtime::temp_cx() };
3090 self.reflow(&mut cx, ReflowGoal::LayoutQuery(query_msg));
3091 }
3092
3093 pub(crate) fn reflow_for_non_flushing_update_the_rendering_queries(&self, cx: &mut JSContext) {
3095 self.reflow(
3096 cx,
3097 ReflowGoal::LayoutQuery(QueryMsg::FlushForUpdateTheRenderingQuery),
3098 );
3099 }
3100
3101 pub(crate) fn resolved_font_style_query(
3102 &self,
3103 cx: &mut JSContext,
3104 node: &Node,
3105 value: String,
3106 ) -> Option<ServoArc<Font>> {
3107 self.layout_reflow(cx, QueryMsg::ResolvedFontStyleQuery);
3108
3109 let document = self.Document();
3110 let animations = document.animation_manager().sets();
3111 self.layout.borrow().query_resolved_font_style(
3112 node.to_trusted_node_address(),
3113 &value,
3114 animations,
3115 document.current_animation_timeline_value(),
3116 )
3117 }
3118
3119 #[expect(unsafe_code)]
3122 pub(crate) fn containing_block_node_query_without_reflow(
3123 &self,
3124 node: &Node,
3125 ) -> Option<DomRoot<Node>> {
3126 self.layout
3127 .borrow()
3128 .query_containing_block(node.to_trusted_node_address())
3129 .map(|address| unsafe { from_untrusted_node_address(address) })
3130 }
3131
3132 pub(crate) fn is_containing_block_descendant_query_without_reflow(
3135 &self,
3136 possible_ancestor: &Node,
3137 possible_descendant: &Node,
3138 ) -> bool {
3139 self.layout.borrow().query_containing_block_is_descendant(
3140 possible_ancestor.to_trusted_node_address(),
3141 possible_descendant.to_trusted_node_address(),
3142 )
3143 }
3144
3145 pub(crate) fn padding_query_without_reflow(&self, node: &Node) -> Option<PhysicalSides<Au>> {
3150 let layout = self.layout.borrow();
3151 layout.query_padding(node.to_trusted_node_address())
3152 }
3153
3154 pub(crate) fn box_area_query_without_reflow(
3159 &self,
3160 node: &Node,
3161 area: BoxAreaType,
3162 exclude_transform_and_inline: bool,
3163 ) -> Option<Rect<Au, CSSPixel>> {
3164 let layout = self.layout.borrow();
3165 layout.ensure_stacking_context_tree(self.viewport_details.get());
3166 layout.query_box_area(
3167 node.to_trusted_node_address(),
3168 area,
3169 exclude_transform_and_inline,
3170 )
3171 }
3172
3173 pub(crate) fn box_area_query(
3174 &self,
3175 cx: &mut JSContext,
3176 node: &Node,
3177 area: BoxAreaType,
3178 exclude_transform_and_inline: bool,
3179 ) -> Option<Rect<Au, CSSPixel>> {
3180 self.layout_reflow(cx, QueryMsg::BoxArea);
3181 self.box_area_query_without_reflow(node, area, exclude_transform_and_inline)
3182 }
3183
3184 pub(crate) fn box_areas_query(
3185 &self,
3186 cx: &mut JSContext,
3187 node: &Node,
3188 area: BoxAreaType,
3189 ) -> CSSPixelRectVec {
3190 self.layout_reflow(cx, QueryMsg::BoxAreas);
3191 self.layout
3192 .borrow()
3193 .query_box_areas(node.to_trusted_node_address(), area)
3194 }
3195
3196 pub(crate) fn client_rect_query(&self, cx: &mut JSContext, node: &Node) -> Rect<i32, CSSPixel> {
3197 self.layout_reflow(cx, QueryMsg::ClientRectQuery);
3198 self.layout
3199 .borrow()
3200 .query_client_rect(node.to_trusted_node_address())
3201 }
3202
3203 pub(crate) fn current_css_zoom_query(&self, cx: &mut JSContext, node: &Node) -> f32 {
3204 self.layout_reflow(cx, QueryMsg::CurrentCSSZoomQuery);
3205 self.layout
3206 .borrow()
3207 .query_current_css_zoom(node.to_trusted_node_address())
3208 }
3209
3210 pub(crate) fn document_unrooted<'a>(&self, no_gc: &'a NoGC) -> UnrootedDom<'a, Document> {
3212 self.document
3213 .get_unrooted(no_gc)
3214 .expect("Document accessed before initialization.")
3215 }
3216
3217 pub(crate) fn scrolling_area_query(
3220 &self,
3221 cx: &mut JSContext,
3222 node: Option<&Node>,
3223 ) -> Rect<i32, CSSPixel> {
3224 self.layout_reflow(cx, QueryMsg::ScrollingAreaOrOffsetQuery);
3225 self.layout
3226 .borrow()
3227 .query_scrolling_area(node.map(Node::to_trusted_node_address))
3228 }
3229
3230 pub(crate) fn scroll_offset_query(
3231 &self,
3232 cx: &mut JSContext,
3233 node: &Node,
3234 ) -> Vector2D<f32, LayoutPixel> {
3235 let external_scroll_id = ExternalScrollId(
3236 combine_id_with_fragment_type(node.to_opaque().id(), FragmentType::FragmentBody),
3237 self.pipeline_id().into(),
3238 );
3239 self.scroll_offset_query_with_external_scroll_id(cx, external_scroll_id)
3240 }
3241
3242 fn scroll_offset_query_with_external_scroll_id(
3243 &self,
3244 cx: &mut JSContext,
3245 external_scroll_id: ExternalScrollId,
3246 ) -> Vector2D<f32, LayoutPixel> {
3247 self.layout_reflow(cx, QueryMsg::ScrollingAreaOrOffsetQuery);
3248 self.scroll_offset_query_with_external_scroll_id_no_reflow(external_scroll_id)
3249 }
3250
3251 fn scroll_offset_query_with_external_scroll_id_no_reflow(
3252 &self,
3253 external_scroll_id: ExternalScrollId,
3254 ) -> Vector2D<f32, LayoutPixel> {
3255 self.layout
3256 .borrow()
3257 .scroll_offset(external_scroll_id)
3258 .unwrap_or_default()
3259 }
3260
3261 pub(crate) fn scroll_an_element(
3264 &self,
3265 cx: &mut JSContext,
3266 element: &Element,
3267 x: f32,
3268 y: f32,
3269 behavior: ScrollBehavior,
3270 ) {
3271 let scroll_id = ExternalScrollId(
3272 combine_id_with_fragment_type(
3273 element.upcast::<Node>().to_opaque().id(),
3274 FragmentType::FragmentBody,
3275 ),
3276 self.pipeline_id().into(),
3277 );
3278
3279 self.perform_a_scroll(cx, x, y, scroll_id, behavior, Some(element));
3283 }
3284
3285 pub(crate) fn resolved_style_query(
3286 &self,
3287 element: TrustedNodeAddress,
3288 pseudo: Option<PseudoElement>,
3289 property: PropertyId,
3290 ) -> DOMString {
3291 self.layout_reflow_deprecated(QueryMsg::ResolvedStyleQuery(property.clone()));
3292
3293 let document = self.Document();
3294 let animations = document.animation_manager().sets();
3295 DOMString::from(self.layout.borrow().query_resolved_style(
3296 element,
3297 pseudo,
3298 property,
3299 animations,
3300 document.current_animation_timeline_value(),
3301 ))
3302 }
3303
3304 pub(crate) fn accesskit_node_query(
3305 &self,
3306 cx: &mut JSContext,
3307 element: TrustedNodeAddress,
3308 ) -> Option<accesskit::Node> {
3309 self.layout_reflow(cx, QueryMsg::AccessKitNodeQuery);
3310 self.layout.borrow().query_accesskit_node(element)
3311 }
3312
3313 pub(crate) fn get_iframe_viewport_details_if_known(
3317 &self,
3318 cx: &mut JSContext,
3319 browsing_context_id: BrowsingContextId,
3320 ) -> Option<ViewportDetails> {
3321 self.layout_reflow(cx, QueryMsg::InnerWindowDimensionsQuery);
3323 self.Document()
3324 .iframes()
3325 .viewport_details(browsing_context_id)
3326 }
3327
3328 #[expect(unsafe_code)]
3329 pub(crate) fn offset_parent_query(
3330 &self,
3331 cx: &mut JSContext,
3332 node: &Node,
3333 ) -> (Option<DomRoot<Element>>, Rect<Au, CSSPixel>) {
3334 self.layout_reflow(cx, QueryMsg::OffsetParentQuery);
3335 let response = self
3336 .layout
3337 .borrow()
3338 .query_offset_parent(node.to_trusted_node_address());
3339 let element = response.node_address.and_then(|parent_node_address| {
3340 let node = unsafe { from_untrusted_node_address(parent_node_address) };
3341 DomRoot::downcast(node)
3342 });
3343 (element, response.rect)
3344 }
3345
3346 pub(crate) fn scroll_container_query(
3347 &self,
3348 node: Option<&Node>,
3349 flags: ScrollContainerQueryFlags,
3350 ) -> Option<ScrollContainerResponse> {
3351 self.layout_reflow_deprecated(QueryMsg::ScrollParentQuery);
3352 self.layout
3353 .borrow()
3354 .query_scroll_container(node.map(Node::to_trusted_node_address), flags)
3355 }
3356
3357 #[expect(unsafe_code)]
3358 pub(crate) fn scrolling_box_query(
3359 &self,
3360 node: Option<&Node>,
3361 flags: ScrollContainerQueryFlags,
3362 ) -> Option<ScrollingBox> {
3363 self.scroll_container_query(node, flags)
3364 .and_then(|response| {
3365 Some(match response {
3366 ScrollContainerResponse::Viewport(overflow, writing_mode) => (
3367 ScrollingBoxSource::Viewport(self.Document()),
3368 overflow,
3369 writing_mode,
3370 ),
3371 ScrollContainerResponse::Element(
3372 parent_node_address,
3373 overflow,
3374 writing_mode,
3375 ) => {
3376 let node = unsafe { from_untrusted_node_address(parent_node_address) };
3377 (
3378 ScrollingBoxSource::Element(DomRoot::downcast(node)?),
3379 overflow,
3380 writing_mode,
3381 )
3382 },
3383 })
3384 })
3385 .map(|(source, overflow, writing_mode)| {
3386 ScrollingBox::new(source, overflow, writing_mode)
3387 })
3388 }
3389
3390 #[expect(unsafe_code)]
3391 pub(crate) fn text_index_query_on_node_for_event(
3392 &self,
3393 cx: &mut JSContext,
3394 node: &Node,
3395 point_in_viewport: Point2D<Au, CSSPixel>,
3396 ) -> Option<(DomRoot<Node>, Utf32CodeUnits)> {
3397 self.layout_reflow(cx, QueryMsg::TextIndexOrSegmentQuery);
3398 let result = self
3399 .layout
3400 .borrow()
3401 .query_text_index(node.to_trusted_node_address(), point_in_viewport)?;
3402 let node = unsafe { from_untrusted_node_address(result.0.into()) };
3403 Some((node, result.1))
3404 }
3405
3406 #[expect(unsafe_code)]
3411 pub(crate) fn query_text_segment(
3412 &self,
3413 cx: &mut JSContext,
3414 node: &Node,
3415 offset: Utf32CodeUnitsOrNodeOffset,
3416 granularity: SegmentGranularity,
3417 ) -> Option<(RootedSelectionBoundary, RootedSelectionBoundary)> {
3418 self.layout_reflow(cx, QueryMsg::TextIndexOrSegmentQuery);
3419 let ((start_node, start_offset), (end_node, end_offset)) = self
3420 .layout()
3421 .query_text_segment(node.to_trusted_node_address(), offset, granularity)?;
3422 let start = RootedSelectionBoundary::new_with_utf32_offset(
3423 unsafe { from_untrusted_node_address(start_node.into()) },
3424 start_offset,
3425 );
3426 let end = RootedSelectionBoundary::new_with_utf32_offset(
3427 unsafe { from_untrusted_node_address(end_node.into()) },
3428 end_offset,
3429 );
3430 Some((start, end))
3431 }
3432
3433 pub(crate) fn elements_from_point_query(
3434 &self,
3435 cx: &mut JSContext,
3436 flags: HitTestFlags,
3437 point: LayoutPoint,
3438 ) -> layout_api::HitTestResult {
3439 self.layout_reflow(cx, QueryMsg::ElementsFromPoint);
3440 self.layout().hit_test(flags, point)
3441 }
3442
3443 pub(crate) fn query_effective_overflow(
3444 &self,
3445 cx: &mut JSContext,
3446 node: &Node,
3447 ) -> Option<AxesOverflow> {
3448 self.layout_reflow(cx, QueryMsg::EffectiveOverflow);
3449 self.query_effective_overflow_without_reflow(node)
3450 }
3451
3452 pub(crate) fn query_effective_overflow_without_reflow(
3453 &self,
3454 node: &Node,
3455 ) -> Option<AxesOverflow> {
3456 self.layout
3457 .borrow()
3458 .query_effective_overflow(node.to_trusted_node_address())
3459 }
3460
3461 pub(crate) fn hit_test_from_input_event(
3462 &self,
3463 cx: &mut JSContext,
3464 flags: HitTestFlags,
3465 input_event: &ConstellationInputEvent,
3466 ) -> Option<HitTestResult> {
3467 self.hit_test_from_point_in_viewport(
3468 cx,
3469 flags,
3470 input_event.hit_test_result.as_ref()?.point_in_viewport,
3471 )
3472 }
3473
3474 #[expect(unsafe_code)]
3475 pub(crate) fn hit_test_from_point_in_viewport(
3476 &self,
3477 cx: &mut JSContext,
3478 flags: HitTestFlags,
3479 point_in_frame: Point2D<f32, CSSPixel>,
3480 ) -> Option<HitTestResult> {
3481 let result = self.elements_from_point_query(cx, flags, point_in_frame.cast_unit());
3482 let item = result.items.into_iter().next()?;
3483
3484 let point_relative_to_initial_containing_block =
3485 point_in_frame + self.scroll_offset(cx).cast_unit();
3486
3487 let from_opaque_node = |node: OpaqueNode| {
3490 let address = UntrustedNodeAddress(node.0 as *const c_void);
3491 unsafe { from_untrusted_node_address(address) }
3492 };
3493 Some(HitTestResult {
3494 node: from_opaque_node(item.node),
3495 dom_position_for_selection: result.dom_position_for_selection.map(|(node, offset)| {
3496 RootedSelectionBoundary::new_with_utf32_offset(from_opaque_node(node), offset)
3497 }),
3498 cursor: item.cursor,
3499 point_in_node: item.point_in_target,
3500 point_in_frame,
3501 point_relative_to_initial_containing_block,
3502 })
3503 }
3504
3505 pub(crate) fn init_window_proxy(&self, window_proxy: &WindowProxy) {
3506 assert!(
3507 self.window_proxy
3508 .get()
3509 .is_none_or(|current_proxy| &*current_proxy as *const WindowProxy == window_proxy)
3510 );
3511 self.window_proxy.set(Some(window_proxy));
3512 }
3513
3514 pub(crate) fn init_document(&self, document: &Document) {
3515 assert!(
3516 self.document
3517 .get()
3518 .is_none_or(|document| document.is_initial_about_blank())
3519 );
3520 assert!(document.window() == self);
3521 self.document.set(Some(document));
3522 self.update_jsprincipals_from_document(document);
3523 self.layout_mut().set_quirks_mode(document.quirks_mode());
3524 }
3525
3526 #[expect(unsafe_code)]
3533 pub(crate) fn update_jsprincipals_from_document(&self, document: &Document) {
3534 let realm = unsafe { GetObjectRealmOrNull(self.reflector().get_jsobject().get()) };
3535 let new_principals = ServoJSPrincipals::new::<crate::DomTypeHolder>(&document.origin());
3536 unsafe { SetRealmPrincipals(realm, new_principals.as_raw()) };
3537 }
3538
3539 pub(crate) fn load_data_for_document(
3540 &self,
3541 url: ServoUrl,
3542 pipeline_id: PipelineId,
3543 ) -> LoadData {
3544 let source_document = self.Document();
3545 let secure_context = if self.is_top_level() {
3546 None
3547 } else {
3548 Some(self.IsSecureContext())
3549 };
3550
3551 let upgrade_insecure_navigations_set = self
3552 .as_global_scope()
3553 .upgrade_insecure_navigations_set()
3554 .clone();
3555
3556 LoadData::new(
3557 LoadOrigin::Script(self.origin().snapshot()),
3558 url,
3559 source_document.about_base_url(),
3560 Some(pipeline_id),
3561 Referrer::ReferrerUrl(source_document.url()),
3562 source_document.get_referrer_policy(),
3563 secure_context,
3564 Some(source_document.insecure_requests_policy()),
3565 upgrade_insecure_navigations_set,
3566 source_document.has_trustworthy_ancestor_origin(),
3567 source_document.creation_sandboxing_flag_set_considering_parent_iframe(),
3568 )
3569 }
3570
3571 pub(crate) fn set_viewport_details(&self, viewport_details: ViewportDetails) {
3574 self.viewport_details.set(viewport_details);
3575 if !self.layout_mut().set_viewport_details(viewport_details) {
3576 return;
3577 }
3578 self.Document()
3579 .add_restyle_reason(RestyleReason::ViewportChanged);
3580 }
3581
3582 pub(crate) fn viewport_details(&self) -> ViewportDetails {
3583 self.viewport_details.get()
3584 }
3585
3586 pub(crate) fn get_or_init_visual_viewport(
3587 &self,
3588 cx: &mut JSContext,
3589 ) -> DomRoot<VisualViewport> {
3590 self.visual_viewport.or_init(|| {
3591 VisualViewport::new_from_layout_viewport(cx, self, self.viewport_details().size)
3592 })
3593 }
3594
3595 pub(crate) fn maybe_update_visual_viewport(
3597 &self,
3598 cx: &mut JSContext,
3599 pinch_zoom_infos: PinchZoomInfos,
3600 ) {
3601 if pinch_zoom_infos.rect == Rect::from_size(self.viewport_details().size) &&
3604 self.visual_viewport.get().is_none()
3605 {
3606 return;
3607 }
3608
3609 let visual_viewport = self.get_or_init_visual_viewport(cx);
3610 let changes = visual_viewport.update_from_pinch_zoom_infos(pinch_zoom_infos);
3611
3612 if changes.intersects(VisualViewportChanges::DimensionChanged) {
3613 self.has_changed_visual_viewport_dimension.set(true);
3614 }
3615 if changes.intersects(VisualViewportChanges::OffsetChanged) {
3616 visual_viewport.handle_scroll_event();
3617 }
3618 }
3619
3620 pub(crate) fn webview_theme(&self) -> Theme {
3621 self.webview_state.theme.get()
3622 }
3623
3624 pub(crate) fn refresh_theme(&self) {
3625 let document = self.Document();
3630 let new_theme = document
3631 .theme_override()
3632 .or(document.theme())
3633 .unwrap_or(self.webview_theme());
3634 if !self.layout_mut().set_theme(new_theme) {
3635 return;
3636 }
3637 document.add_restyle_reason(RestyleReason::ThemeChanged);
3638 self.pending_media_query_evaluation.set(true);
3641 }
3642
3643 pub(crate) fn take_pending_media_query_evaluation(&self) -> bool {
3646 self.pending_media_query_evaluation.replace(false)
3647 }
3648
3649 pub(crate) fn has_pending_media_query_evaluation(&self) -> bool {
3650 self.pending_media_query_evaluation.get()
3651 }
3652
3653 pub(crate) fn get_url(&self) -> ServoUrl {
3654 self.Document().url()
3655 }
3656
3657 pub(crate) fn windowproxy_handler(&self) -> &'static WindowProxyHandler {
3658 self.dom_static.windowproxy_handler
3659 }
3660
3661 pub(crate) fn add_resize_event(&self, event: ViewportDetails, event_type: WindowSizeType) {
3662 if self.viewport_details() == event {
3663 return;
3664 }
3665
3666 self.set_viewport_details(event);
3668
3669 *self.unhandled_resize_event.borrow_mut() = Some((event, event_type))
3672 }
3673
3674 pub(crate) fn take_unhandled_resize_event(&self) -> Option<(ViewportDetails, WindowSizeType)> {
3675 self.unhandled_resize_event.borrow_mut().take()
3676 }
3677
3678 pub(crate) fn has_unhandled_resize_event(&self) -> bool {
3680 self.unhandled_resize_event.borrow().is_some()
3681 }
3682
3683 pub(crate) fn suspend(&self, cx: &mut JSContext) {
3684 self.as_global_scope().suspend();
3686
3687 if self.window_proxy().currently_active() == Some(self.global().pipeline_id()) {
3689 self.window_proxy().unset_currently_active(cx);
3690 }
3691
3692 self.maybe_gc(cx);
3697 }
3698
3699 pub(crate) fn resume(&self, cx: &mut JSContext) {
3700 self.as_global_scope().resume();
3702
3703 self.window_proxy().set_currently_active(cx, self);
3705
3706 self.Document().title_changed();
3709 }
3710
3711 pub(crate) fn is_alive(&self) -> bool {
3712 self.current_state.get() == WindowState::Alive
3713 }
3714
3715 pub(crate) fn is_top_level(&self) -> bool {
3717 self.parent_info.is_none()
3718 }
3719
3720 fn run_resize_steps_for_layout_viewport(&self, cx: &mut JSContext) -> bool {
3725 let Some((new_size, size_type)) = self.take_unhandled_resize_event() else {
3726 return false;
3727 };
3728
3729 let current_viewport = self.viewport_details();
3732 if current_viewport == self.viewport_details_at_last_resize_steps.get() {
3733 return false;
3734 }
3735 self.viewport_details_at_last_resize_steps
3736 .set(current_viewport);
3737
3738 debug!(
3739 "Running resize steps for pipeline {:?} with viewport {new_size:?}",
3740 self.pipeline_id(),
3741 );
3742
3743 if size_type == WindowSizeType::Resize {
3745 let mut realm = enter_auto_realm(cx, self);
3746 let cx = &mut realm.current_realm();
3747 let uievent = UIEvent::new(
3748 cx,
3749 self,
3750 atom!("resize"),
3751 EventBubbles::DoesNotBubble,
3752 EventCancelable::NotCancelable,
3753 Some(self),
3754 0i32,
3755 0u32,
3756 );
3757 uievent.upcast::<Event>().fire(cx, self.upcast());
3758 }
3759
3760 true
3761 }
3762
3763 pub(crate) fn run_the_resize_steps(&self, cx: &mut JSContext) -> bool {
3768 let layout_viewport_resized = self.run_resize_steps_for_layout_viewport(cx);
3769
3770 if self.has_changed_visual_viewport_dimension.get() {
3771 let visual_viewport = self.get_or_init_visual_viewport(cx);
3772
3773 let uievent = UIEvent::new(
3774 cx,
3775 self,
3776 atom!("resize"),
3777 EventBubbles::DoesNotBubble,
3778 EventCancelable::NotCancelable,
3779 Some(self),
3780 0i32,
3781 0u32,
3782 );
3783 uievent.upcast::<Event>().fire(cx, visual_viewport.upcast());
3784
3785 self.has_changed_visual_viewport_dimension.set(false);
3786 }
3787
3788 layout_viewport_resized
3789 }
3790
3791 pub(crate) fn evaluate_media_queries_and_report_changes(&self, cx: &mut JSContext) {
3794 let mut realm = enter_auto_realm(cx, self);
3795 let cx = &mut realm.current_realm();
3796 rooted_vec!(let mut mql_list);
3797
3798 self.media_query_lists.for_each(|mql| {
3799 if let MediaQueryListMatchState::Changed = mql.evaluate_changes() {
3800 mql_list.push(Dom::from_ref(&*mql));
3802 }
3803 });
3804 for mql in mql_list.iter() {
3806 let event = MediaQueryListEvent::new(
3807 cx,
3808 &mql.global(),
3809 atom!("change"),
3810 false,
3811 false,
3812 mql.Media(),
3813 mql.Matches(),
3814 );
3815 event
3816 .upcast::<Event>()
3817 .fire(cx, mql.upcast::<EventTarget>());
3818 }
3819 }
3820
3821 pub(crate) fn set_throttled(&self, throttled: bool) {
3823 self.throttled.set(throttled);
3824 if throttled {
3825 self.as_global_scope().slow_down_timers();
3826 } else {
3827 self.as_global_scope().speed_up_timers();
3828 }
3829 }
3830
3831 pub(crate) fn throttled(&self) -> bool {
3832 self.throttled.get()
3833 }
3834
3835 pub(crate) fn unminified_css_dir(&self) -> Option<String> {
3836 self.unminified_css_dir.borrow().clone()
3837 }
3838
3839 pub(crate) fn local_script_source(&self) -> &Option<String> {
3840 &self.local_script_source
3841 }
3842
3843 pub(crate) fn set_navigation_start(&self) {
3844 self.navigation_start.set(CrossProcessInstant::now());
3845 }
3846
3847 pub(crate) fn navigation_start(&self) -> CrossProcessInstant {
3848 self.navigation_start.get()
3849 }
3850
3851 pub(crate) fn set_last_activation_timestamp(&self, time: UserActivationTimestamp) {
3852 self.last_activation_timestamp.set(time);
3853 }
3854
3855 pub(crate) fn set_last_history_action_activation_timestamp(
3856 &self,
3857 time: UserActivationTimestamp,
3858 ) {
3859 self.last_history_action_activation_timestamp.set(time);
3860 }
3861
3862 pub(crate) fn send_to_embedder(&self, msg: EmbedderMsg) {
3863 self.as_global_scope()
3864 .script_to_embedder_chan()
3865 .send(msg)
3866 .unwrap();
3867 }
3868
3869 pub(crate) fn send_to_constellation(&self, msg: ScriptToConstellationMessage) {
3870 self.as_global_scope()
3871 .script_to_constellation_chan()
3872 .send(msg)
3873 .unwrap();
3874 }
3875
3876 #[cfg(feature = "webxr")]
3877 pub(crate) fn in_immersive_xr_session(&self) -> bool {
3878 self.navigator
3879 .get()
3880 .as_ref()
3881 .and_then(|nav| nav.xr())
3882 .is_some_and(|xr| xr.pending_or_active_session())
3883 }
3884
3885 #[cfg(all(feature = "webgl", not(feature = "webxr")))]
3886 pub(crate) fn in_immersive_xr_session(&self) -> bool {
3887 false
3888 }
3889
3890 fn handle_new_or_removed_web_fonts_post_reflow(
3892 &self,
3893 cx: &mut JSContext,
3894 changed_web_fonts: WebFontSetDifference,
3895 ) {
3896 if changed_web_fonts.is_empty() {
3897 return;
3898 }
3899
3900 let document = self.Document();
3901 let fonts = document.Fonts(cx);
3902 if !changed_web_fonts.removed_font_faces.is_empty() {
3903 fonts.notify_font_face_rules_removed(&changed_web_fonts.removed_font_faces);
3904 }
3905
3906 if !changed_web_fonts.removed_font_faces.is_empty() ||
3907 changed_web_fonts.cascade_index_of_any_rule_changed
3908 {
3909 document.dirty_all_nodes(cx.no_gc());
3912 }
3913
3914 if !changed_web_fonts.added_font_faces.is_empty() {
3915 fonts.switch_to_loading(cx);
3916
3917 for new_web_font in changed_web_fonts.added_font_faces {
3918 if let Some(font_face) = FontFace::new_for_web_font(cx, self.upcast(), new_web_font)
3919 {
3920 fonts.add(cx, font_face);
3921 }
3922 }
3923 }
3924 }
3925
3926 #[expect(unsafe_code)]
3928 fn process_lcp_candidate_post_reflow(&self, candidate: LCPCandidate, document: &Document) {
3929 let element = candidate.node.and_then(|node| {
3930 let node_address = UntrustedNodeAddress(node.id() as *const c_void);
3931 let node = unsafe { from_untrusted_node_address(node_address) };
3932 DomRoot::downcast::<Element>(node)
3933 });
3934 document.store_lcp_candidate(candidate, element.as_deref());
3935 }
3936
3937 #[expect(unsafe_code)]
3943 fn process_container_timing_records_post_reflow(
3944 &self,
3945 records: Vec<ContainerTimingRecord>,
3946 document: &Document,
3947 ) {
3948 let resolve = |node: OpaqueNode| unsafe {
3952 let node_address = UntrustedNodeAddress(node.id() as *const c_void);
3953 DomRoot::downcast::<Element>(from_untrusted_node_address(node_address))
3954 };
3955
3956 for record in records {
3957 let Some(root_element) = resolve(record.root_element) else {
3958 continue;
3959 };
3960 let Some(identifier) =
3964 root_element.get_attribute_string_value(&LocalName::from("containertiming"))
3965 else {
3966 continue;
3967 };
3968 let last_painted_element = record.last_painted_element.and_then(resolve);
3969 document.store_container_timing_record(
3970 record,
3971 identifier.into(),
3972 &root_element,
3973 last_painted_element.as_deref(),
3974 );
3975 }
3976 }
3977
3978 #[expect(unsafe_code)]
3979 fn handle_pending_images_post_reflow(
3980 &self,
3981 cx: &mut JSContext,
3982 pending_images: Vec<PendingImage>,
3983 pending_rasterization_images: Vec<PendingRasterizationImage>,
3984 pending_svg_element_for_serialization: Vec<UntrustedNodeAddress>,
3985 ) {
3986 let pipeline_id = self.pipeline_id();
3987 let image_cache = self.image_cache();
3988 for image in pending_images {
3989 let id = image.id;
3990 let node = unsafe { from_untrusted_node_address(image.node) };
3991
3992 if let PendingImageState::Unrequested(ref url) = image.state {
3993 fetch_image_for_layout(
3994 url.clone(),
3995 &node,
3996 id,
3997 image.is_internal_request,
3998 image_cache.clone(),
3999 );
4000 }
4001
4002 let mut images = self.pending_layout_images.borrow_mut();
4003 if !images.contains_key(&id) {
4004 let trusted_node = Trusted::new(&*node);
4005 let sender = self.register_image_cache_listener(id, move |response, cx| {
4006 trusted_node
4007 .root()
4008 .owner_window()
4009 .pending_layout_image_notification(cx.no_gc(), response);
4010 });
4011
4012 image_cache.add_listener(ImageLoadListener::new(sender, pipeline_id, id));
4013 }
4014
4015 let nodes = images.entry(id).or_default();
4016 if !nodes.iter().any(|n| *n.node == *node) {
4017 nodes.push(PendingLayoutImageAncillaryData {
4018 node: Dom::from_ref(&*node),
4019 destination: image.destination,
4020 });
4021 }
4022 }
4023
4024 for image in pending_rasterization_images {
4025 let node = unsafe { from_untrusted_node_address(image.node) };
4026
4027 let mut images = self.pending_images_for_rasterization.borrow_mut();
4028 if !images.contains_key(&(image.id, image.size)) {
4029 let image_cache_sender = self.image_cache_sender.clone();
4030 image_cache.add_rasterization_complete_listener(
4031 pipeline_id,
4032 image.id,
4033 image.size,
4034 Box::new(move |response| {
4035 let _ = image_cache_sender.send(response);
4036 }),
4037 );
4038 }
4039
4040 let nodes = images.entry((image.id, image.size)).or_default();
4041 if !nodes.iter().any(|n| **n == *node) {
4042 nodes.push(Dom::from_ref(&*node));
4043 }
4044 }
4045
4046 for node in pending_svg_element_for_serialization.into_iter() {
4047 let node = unsafe { from_untrusted_node_address(node) };
4048 let svg = node.downcast::<SVGSVGElement>().unwrap();
4049 svg.serialize_and_cache_subtree(cx);
4050 node.dirty(cx.no_gc(), NodeDamage::Other);
4051 }
4052 }
4053
4054 #[expect(unsafe_code)]
4055 fn handle_accessibility_actions(
4056 &self,
4057 actions: Vec<AccessibilityActionRequest>,
4058 cx: &mut JSContext,
4059 ) {
4060 for action_request in actions {
4061 let target_opaque = action_request.target;
4062 let target = unsafe { from_untrusted_node_address(target_opaque.into()) };
4063 if action_request.action == Action::Click {
4064 target.fire_synthetic_pointer_event_not_trusted(cx, atom!("click"));
4065 }
4066 }
4067 }
4068
4069 pub(crate) fn has_sticky_activation(&self) -> bool {
4071 UserActivationTimestamp::TimeStamp(CrossProcessInstant::now()) >=
4073 self.last_activation_timestamp.get()
4074 }
4075
4076 pub(crate) fn has_history_action_activation(&self) -> bool {
4078 self.last_history_action_activation_timestamp.get() != self.last_activation_timestamp.get()
4082 }
4083
4084 pub(crate) fn has_transient_activation(&self) -> bool {
4086 let current_time = CrossProcessInstant::now();
4089 UserActivationTimestamp::TimeStamp(current_time) >= self.last_activation_timestamp.get() &&
4090 UserActivationTimestamp::TimeStamp(current_time) <
4091 self.last_activation_timestamp.get() +
4092 pref!(dom_transient_activation_duration_ms)
4093 }
4094
4095 pub(crate) fn consume_last_activation_timestamp(&self) {
4096 if self.last_activation_timestamp.get() != UserActivationTimestamp::PositiveInfinity {
4097 self.set_last_activation_timestamp(UserActivationTimestamp::NegativeInfinity);
4098 }
4099 }
4100
4101 pub(crate) fn consume_user_activation(&self) {
4103 if self.undiscarded_window_proxy().is_none() {
4106 return;
4107 }
4108
4109 let Some(top_level_document) = self.top_level_document_if_local() else {
4113 return;
4114 };
4115
4116 top_level_document
4124 .window()
4125 .consume_last_activation_timestamp();
4126 for document in LocalDescendantNavigablesIterator::new(&top_level_document) {
4127 document.window().consume_last_activation_timestamp();
4128 }
4129 }
4130
4131 pub(crate) fn consume_history_action_user_activation(&self) {
4133 if self.undiscarded_window_proxy().is_none() {
4135 return;
4136 }
4137
4138 let Some(top_level_document) = self.top_level_document_if_local() else {
4141 return;
4142 };
4143
4144 top_level_document
4151 .window()
4152 .set_last_history_action_activation_timestamp(
4153 top_level_document.window().last_activation_timestamp.get(),
4154 );
4155 for document in LocalDescendantNavigablesIterator::new(&top_level_document) {
4156 document
4157 .window()
4158 .set_last_history_action_activation_timestamp(
4159 document.window().last_activation_timestamp.get(),
4160 );
4161 }
4162 }
4163
4164 #[allow(clippy::too_many_arguments)]
4165 pub(crate) fn new(
4166 cx: &mut JSContext,
4167 webview_state: Rc<WebViewState>,
4168 runtime: Rc<Runtime>,
4169 script_chan: Sender<MainThreadScriptMsg>,
4170 layout: Box<dyn Layout>,
4171 image_cache_sender: Sender<ImageCacheResponseMessage>,
4172 resource_threads: ResourceThreads,
4173 storage_threads: StorageThreads,
4174 #[cfg(feature = "bluetooth")] bluetooth_thread: GenericSender<BluetoothRequest>,
4175 mem_profiler_chan: MemProfilerChan,
4176 time_profiler_chan: TimeProfilerChan,
4177 #[cfg(feature = "devtools")] devtools_chan: Option<
4178 GenericCallback<devtools_traits::ScriptToDevtoolsControlMsg>,
4179 >,
4180 script_to_constellation_sender: ScriptToConstellationSender,
4181 embedder_chan: ScriptToEmbedderChan,
4182 control_chan: GenericSender<ScriptThreadMessage>,
4183 pipeline_id: PipelineId,
4184 parent_info: Option<PipelineId>,
4185 viewport_details: ViewportDetails,
4186 origin: MutableOrigin,
4187 creation_url: ServoUrl,
4188 top_level_creation_url: ServoUrl,
4189 navigation_start: CrossProcessInstant,
4190 #[cfg(feature = "webgl")] webgl_chan: Option<WebGLChan>,
4191 #[cfg(feature = "webxr")] webxr_registry: Option<webxr_api::Registry>,
4192 paint_api: CrossProcessPaintApi,
4193 unminify_js: bool,
4194 unminify_css: bool,
4195 local_script_source: Option<String>,
4196 user_scripts: Rc<Vec<UserScript>>,
4197 player_context: WindowGLContext,
4198 #[cfg(feature = "webgpu")] gpu_id_hub: Arc<IdentityHub>,
4199 inherited_secure_context: Option<bool>,
4200 inherited_upgrade_insecure_navigations_set: HashSet<UpgradeInsecureNavigations>,
4201 weak_script_thread: Weak<ScriptThread>,
4202 ) -> DomRoot<Self> {
4203 let error_reporter = CSSErrorReporter {
4204 pipelineid: pipeline_id,
4205 script_chan: control_chan,
4206 };
4207
4208 let win = Box::new(Self {
4209 webview_state,
4210 globalscope: GlobalScope::new_inherited(
4211 #[cfg(feature = "devtools")]
4212 devtools_chan,
4213 mem_profiler_chan,
4214 time_profiler_chan,
4215 script_to_constellation_sender,
4216 embedder_chan,
4217 resource_threads,
4218 storage_threads,
4219 creation_url,
4220 Some(top_level_creation_url),
4221 #[cfg(feature = "webgpu")]
4222 gpu_id_hub,
4223 inherited_secure_context,
4224 inherited_upgrade_insecure_navigations_set,
4225 unminify_js,
4226 ),
4227 caches: Default::default(),
4228 ongoing_navigation: Default::default(),
4229 script_chan,
4230 layout: RefCell::new(layout),
4231 image_cache_sender,
4232 navigator: Default::default(),
4233 crypto: Default::default(),
4234 location: Default::default(),
4235 window_proxy: Default::default(),
4236 document: Default::default(),
4237 performance: Default::default(),
4238 navigation_start: Cell::new(navigation_start),
4239 screen: Default::default(),
4240 session_storage: Default::default(),
4241 local_storage: Default::default(),
4242 cookie_store: Default::default(),
4243 status: DomRefCell::new(DOMString::new().traced()),
4244 parent_info,
4245 dom_static: GlobalStaticData::new(),
4246 js_runtime: DomRefCell::new(Some(runtime)),
4247 #[cfg(feature = "bluetooth")]
4248 bluetooth_thread,
4249 #[cfg(feature = "bluetooth")]
4250 bluetooth_extra_permission_data: BluetoothExtraPermissionData::new(),
4251 unhandled_resize_event: Default::default(),
4252 viewport_details_at_last_resize_steps: Cell::new(viewport_details),
4253 viewport_details: Cell::new(viewport_details),
4254 layout_blocker: Cell::new(LayoutBlocker::WaitingForParse),
4255 current_state: Cell::new(WindowState::Alive),
4256 #[cfg(feature = "devtools")]
4257 devtools_marker_sender: Default::default(),
4258 #[cfg(feature = "devtools")]
4259 devtools_markers: Default::default(),
4260 error_reporter,
4261 media_query_lists: DOMTracker::new(),
4262 #[cfg(feature = "bluetooth")]
4263 test_runner: Default::default(),
4264 #[cfg(feature = "webgl")]
4265 webgl_chan,
4266 #[cfg(feature = "webxr")]
4267 webxr_registry,
4268 pending_image_callbacks: Default::default(),
4269 pending_layout_images: Default::default(),
4270 pending_images_for_rasterization: Default::default(),
4271 unminified_css_dir: DomRefCell::new(if unminify_css {
4272 Some(unminified_path("unminified-css"))
4273 } else {
4274 None
4275 }),
4276 local_script_source,
4277 test_worklet: Default::default(),
4278 paint_worklet: Default::default(),
4279 exists_mut_observer: Cell::new(false),
4280 paint_api,
4281 user_scripts,
4282 player_context,
4283 throttled: Cell::new(false),
4284 layout_marker: DomRefCell::new(Rc::new(Cell::new(true))),
4285 current_event: MutNullableDom::new(None),
4286 trusted_types: Default::default(),
4287 reporting_observer_list: Default::default(),
4288 report_list: Default::default(),
4289 endpoints_list: Default::default(),
4290 script_window_proxies: ScriptThread::window_proxies(),
4291 has_pending_screenshot_readiness_request: Default::default(),
4292 visual_viewport: Default::default(),
4293 weak_script_thread,
4294 has_changed_visual_viewport_dimension: Default::default(),
4295 pending_media_query_evaluation: Default::default(),
4296 last_activation_timestamp: Cell::new(UserActivationTimestamp::PositiveInfinity),
4297 devtools_wants_updates: Default::default(),
4298 has_dispatched_scroll_event: Cell::new(false),
4299 has_dispatched_input_event: Cell::new(false),
4300 last_history_action_activation_timestamp: Cell::new(
4304 UserActivationTimestamp::PositiveInfinity,
4305 ),
4306 close_watcher_manager: CloseWatcherManager::new(),
4307 });
4308
4309 WindowBinding::Wrap::<crate::DomTypeHolder>(cx, &origin, win)
4310 }
4311
4312 pub(crate) fn task_manager(&self) -> Rc<TaskManager> {
4313 self.Document().task_manager()
4314 }
4315
4316 pub(crate) fn pipeline_id(&self) -> PipelineId {
4317 self.Document().pipeline_id()
4318 }
4319
4320 #[cfg(feature = "devtools")]
4321 pub(crate) fn live_devtools_updates(&self) -> bool {
4322 self.devtools_wants_updates.get()
4323 }
4324
4325 #[cfg(feature = "devtools")]
4326 pub(crate) fn set_devtools_wants_updates(&self, value: bool) {
4327 self.devtools_wants_updates.set(value);
4328 }
4329
4330 pub(crate) fn cache_layout_value<T>(&self, value: T) -> LayoutValue<T>
4332 where
4333 T: Copy + MallocSizeOf,
4334 {
4335 LayoutValue::new(self.layout_marker.borrow().clone(), value)
4336 }
4337
4338 pub(crate) fn set_up_a_window_environment_settings_object(
4347 &self,
4348 layout: Box<dyn Layout>,
4349 creation_url: ServoUrl,
4350 top_level_creation_url: ServoUrl,
4351 navigation_start: CrossProcessInstant,
4352 viewport_details: ViewportDetails,
4353 ) {
4354 *self.layout.borrow_mut() = layout;
4355 self.set_viewport_details(viewport_details);
4356 self.navigation_start.set(navigation_start);
4357
4358 let global = self.upcast::<GlobalScope>();
4361 global.set_creation_url(creation_url);
4362 global.set_top_level_creation_url(top_level_creation_url);
4363
4364 self.Document().detach_window();
4365 }
4366}
4367
4368#[cfg(feature = "devtools")]
4369impl Window {
4370 pub(crate) fn need_emit_timeline_marker(
4371 &self,
4372 timeline_type: devtools_traits::TimelineMarkerType,
4373 ) -> bool {
4374 let markers = self.devtools_markers.borrow();
4375 markers.contains(&timeline_type)
4376 }
4377
4378 pub(crate) fn emit_timeline_marker(&self, marker: devtools_traits::TimelineMarker) {
4379 let sender = self.devtools_marker_sender.borrow();
4380 let sender = sender.as_ref().expect("There is no marker sender");
4381 sender.send(Some(marker)).unwrap();
4382 }
4383
4384 pub(crate) fn set_devtools_timeline_markers(
4385 &self,
4386 markers: Vec<devtools_traits::TimelineMarkerType>,
4387 reply: GenericSender<Option<devtools_traits::TimelineMarker>>,
4388 ) {
4389 *self.devtools_marker_sender.borrow_mut() = Some(reply);
4390 self.devtools_markers.borrow_mut().extend(markers);
4391 }
4392
4393 pub(crate) fn drop_devtools_timeline_markers(
4394 &self,
4395 markers: Vec<devtools_traits::TimelineMarkerType>,
4396 ) {
4397 let mut devtools_markers = self.devtools_markers.borrow_mut();
4398 for marker in markers {
4399 devtools_markers.remove(&marker);
4400 }
4401 if devtools_markers.is_empty() {
4402 *self.devtools_marker_sender.borrow_mut() = None;
4403 }
4404 }
4405}
4406#[derive(MallocSizeOf)]
4411pub(crate) struct LayoutValue<T: MallocSizeOf> {
4412 #[conditional_malloc_size_of]
4413 is_valid: Rc<Cell<bool>>,
4414 value: T,
4415}
4416
4417#[expect(unsafe_code)]
4418unsafe impl<T: JSTraceable + MallocSizeOf> JSTraceable for LayoutValue<T> {
4419 unsafe fn trace(&self, trc: *mut js::jsapi::JSTracer) {
4420 unsafe { self.value.trace(trc) };
4421 }
4422}
4423
4424impl<T: Copy + MallocSizeOf> LayoutValue<T> {
4425 fn new(marker: Rc<Cell<bool>>, value: T) -> Self {
4426 LayoutValue {
4427 is_valid: marker,
4428 value,
4429 }
4430 }
4431
4432 pub(crate) fn get(&self) -> Result<T, ()> {
4434 if self.is_valid.get() {
4435 return Ok(self.value);
4436 }
4437 Err(())
4438 }
4439}
4440
4441impl Window {
4442 pub(crate) fn post_message(
4444 &self,
4445 target_origin: Option<ImmutableOrigin>,
4446 source_origin: ImmutableOrigin,
4447 source: &WindowProxy,
4448 data: StructuredSerializedData,
4449 ) {
4450 let this = Trusted::new(self);
4451 let source = Trusted::new(source);
4452 let task = task!(post_serialised_message: move |cx| {
4453 let this = this.root();
4454 let source = source.root();
4455 let document = this.Document();
4456
4457 if let Some(ref target_origin) = target_origin
4459 && !target_origin.same_origin(&*document.origin()) {
4460 return;
4461 }
4462
4463 let obj = this.reflector().get_jsobject();
4465 let mut realm = AutoRealm::new(cx, NonNull::new(obj.get()).unwrap());
4466 let cx = &mut *realm;
4467 rooted!(&in(cx) let mut message_clone = UndefinedValue());
4468 if let Ok(ports) = structuredclone::read(cx, this.upcast(), data, message_clone.handle_mut()) {
4469 MessageEvent::dispatch_jsval(
4471 cx,
4472 this.upcast(),
4473 this.upcast(),
4474 message_clone.handle(),
4475 Some(source_origin.ascii_serialization().as_ref()),
4476 Some(&*source),
4477 ports,
4478 );
4479 } else {
4480 MessageEvent::dispatch_error(
4482 cx,
4483 this.upcast(),
4484 this.upcast(),
4485 );
4486 }
4487 });
4488 self.as_global_scope()
4490 .task_manager()
4491 .dom_manipulation_task_source()
4492 .queue(task);
4493 }
4494}
4495
4496#[derive(Clone, MallocSizeOf)]
4497pub(crate) struct CSSErrorReporter {
4498 pub(crate) pipelineid: PipelineId,
4499 pub(crate) script_chan: GenericSender<ScriptThreadMessage>,
4500}
4501unsafe_no_jsmanaged_fields!(CSSErrorReporter);
4502
4503impl ParseErrorReporter for CSSErrorReporter {
4504 fn report_error(
4505 &self,
4506 url: &UrlExtraData,
4507 location: SourceLocation,
4508 error: ContextualParseError,
4509 ) {
4510 if log_enabled!(log::Level::Info) {
4511 info!(
4512 "Url:\t{}\n{}:{} {}",
4513 url.0.as_str(),
4514 location.line,
4515 location.column,
4516 error
4517 )
4518 }
4519
4520 #[cfg(feature = "devtools")]
4522 let _ = self.script_chan.send(ScriptThreadMessage::ReportCSSError(
4523 self.pipelineid,
4524 url.0.to_string(),
4525 location.line,
4526 location.column,
4527 error.to_string(),
4528 ));
4529 }
4530}
4531
4532fn is_named_element_with_name_attribute(elem: &Element) -> bool {
4533 let type_ = match elem.upcast::<Node>().type_id() {
4534 NodeTypeId::Element(ElementTypeId::HTMLElement(type_)) => type_,
4535 _ => return false,
4536 };
4537 matches!(
4538 type_,
4539 HTMLElementTypeId::HTMLEmbedElement |
4540 HTMLElementTypeId::HTMLFormElement |
4541 HTMLElementTypeId::HTMLImageElement |
4542 HTMLElementTypeId::HTMLObjectElement
4543 )
4544}
4545
4546fn is_named_element_with_id_attribute(elem: &Element) -> bool {
4547 elem.is_html_element() || elem.is_svg_element()
4548}
4549
4550#[expect(unsafe_code)]
4551#[unsafe(no_mangle)]
4552unsafe extern "C" fn dump_js_stack(cx: *mut RawJSContext) {
4554 unsafe {
4555 DumpJSStack(cx, true, false, false);
4556 }
4557}
4558
4559impl WindowHelpers for Window {
4560 fn create_named_properties_object(
4561 cx: &mut JSContext,
4562 proto: HandleObject,
4563 object: MutableHandleObject,
4564 ) {
4565 Self::create_named_properties_object(cx, proto, object)
4566 }
4567}
4568
4569impl HasOrigin for Window {
4570 fn origin(&self) -> MutableOrigin {
4571 Window::origin(self)
4572 }
4573}