1use std::borrow::ToOwned;
6use std::cell::{Cell, RefCell, RefMut};
7use std::collections::HashSet;
8use std::collections::hash_map::Entry;
9use std::default::Default;
10use std::ffi::c_void;
11use std::io::{Write, stderr, stdout};
12use std::ptr::NonNull;
13use std::rc::{Rc, Weak};
14use std::sync::Arc;
15use std::time::{Duration, Instant};
16
17use app_units::Au;
18use base64::Engine;
19use content_security_policy::Violation;
20use content_security_policy::sandboxing_directive::SandboxingFlagSet;
21use crossbeam_channel::{Sender, unbounded};
22use cssparser::SourceLocation;
23use devtools_traits::{ScriptToDevtoolsControlMsg, TimelineMarker, TimelineMarkerType};
24use dom_struct::dom_struct;
25use embedder_traits::user_contents::UserScript;
26use embedder_traits::{
27 AlertResponse, ConfirmResponse, EmbedderMsg, PromptResponse, ScriptToEmbedderChan,
28 SimpleDialogRequest, Theme, UntrustedNodeAddress, ViewportDetails, WebDriverLoadStatus,
29};
30use euclid::{Point2D, Rect, Scale, Size2D, Vector2D};
31use fonts::{
32 CspViolationHandler, FontContext, NetworkTimingHandler, WebFontDocumentContext,
33 WebFontSetDifference,
34};
35use js::context::{JSContext, NoGC};
36use js::conversions::ToJSValConvertible;
37use js::glue::DumpJSStack;
38use js::jsapi::{
39 GCReason, GetObjectRealmOrNull, Heap, JSContext as RawJSContext, JSObject, JSPROP_ENUMERATE,
40 SetRealmPrincipals,
41};
42use js::jsval::{NullValue, UndefinedValue};
43use js::realm::{AutoRealm, CurrentRealm};
44use js::rust::wrappers2::{JS_DefineProperty, JS_GC};
45use js::rust::{
46 CustomAutoRooter, CustomAutoRooterGuard, HandleObject, HandleValue, MutableHandleObject,
47 MutableHandleValue,
48};
49use layout_api::{
50 AxesOverflow, BoxAreaType, CSSPixelRectVec, FragmentType, HitTestFlags, Layout,
51 LayoutImageDestination, PendingImage, PendingImageState, PendingRasterizationImage,
52 PhysicalSides, QueryMsg, ReflowGoal, ReflowPhasesRun, ReflowRequest, ReflowRequestRestyle,
53 ReflowStatistics, RestyleReason, ScrollContainerQueryFlags, ScrollContainerResponse,
54 TrustedNodeAddress, combine_id_with_fragment_type,
55};
56use malloc_size_of::MallocSizeOf;
57use media::WindowGLContext;
58use net_traits::image_cache::{
59 ImageCache, ImageCacheResponseCallback, ImageCacheResponseMessage, ImageLoadListener,
60 ImageResponse, PendingImageId, PendingImageResponse, RasterizationCompleteResponse,
61};
62use net_traits::request::{Origin, Referrer, RequestClient};
63use net_traits::{ResourceFetchTiming, ResourceThreads};
64use num_traits::ToPrimitive;
65use paint_api::largest_contentful_paint_candidate::LCPCandidate;
66use paint_api::{CrossProcessPaintApi, PinchZoomInfos};
67use profile_traits::generic_channel as ProfiledGenericChannel;
68use profile_traits::mem::ProfilerChan as MemProfilerChan;
69use profile_traits::time::ProfilerChan as TimeProfilerChan;
70use rustc_hash::{FxBuildHasher, FxHashMap};
71use script_bindings::cell::{DomRefCell, Ref};
72use script_bindings::codegen::GenericBindings::WindowBinding::ScrollToOptions;
73use script_bindings::dom::UnrootedDom;
74use script_bindings::interfaces::{HasOrigin, WindowHelpers};
75use script_bindings::like::Setlike;
76use script_bindings::principals::ServoJSPrincipals;
77use script_bindings::reflector::DomObject;
78use script_bindings::root::Root;
79use script_traits::{ConstellationInputEvent, ScriptThreadMessage};
80use selectors::attr::CaseSensitivity;
81use servo_arc::Arc as ServoArc;
82use servo_base::cross_process_instant::CrossProcessInstant;
83use servo_base::generic_channel::{self, GenericCallback, GenericSender};
84use servo_base::id::{BrowsingContextId, PipelineId, WebViewId};
85use servo_base::text::Utf32CodeUnits;
86#[cfg(feature = "bluetooth")]
87use servo_bluetooth_traits::BluetoothRequest;
88#[cfg(feature = "webgl")]
89use servo_canvas_traits::webgl::WebGLChan;
90use servo_config::pref;
91use servo_constellation_traits::{
92 LoadData, LoadOrigin, ScreenshotReadinessResponse, ScriptToConstellationMessage,
93 ScriptToConstellationSender, StructuredSerializedData, WindowSizeType,
94};
95use servo_geometry::DeviceIndependentIntRect;
96use servo_url::{ImmutableOrigin, MutableOrigin, ServoUrl};
97use storage_traits::StorageThreads;
98use storage_traits::webstorage_thread::WebStorageType;
99use style::dom::OpaqueNode;
100use style::error_reporting::{ContextualParseError, ParseErrorReporter};
101use style::properties::PropertyId;
102use style::properties::style_structs::Font;
103use style::selector_parser::PseudoElement;
104use style::str::HTML_SPACE_CHARACTERS;
105use style::stylesheets::UrlExtraData;
106use style_traits::CSSPixel;
107use stylo_atoms::Atom;
108use time::Duration as TimeDuration;
109use webrender_api::ExternalScrollId;
110use webrender_api::units::{DeviceIntSize, DevicePixel, LayoutPixel, LayoutPoint};
111
112use crate::dom::StatelessWorkletThreadPool;
113use crate::dom::bindings::codegen::Bindings::AnimationFrameProviderBinding::FrameRequestCallback;
114use crate::dom::bindings::codegen::Bindings::DocumentBinding::{
115 DocumentMethods, DocumentReadyState, NamedPropertyValue,
116};
117use crate::dom::bindings::codegen::Bindings::HTMLIFrameElementBinding::HTMLIFrameElementMethods;
118use crate::dom::bindings::codegen::Bindings::HistoryBinding::History_Binding::HistoryMethods;
119use crate::dom::bindings::codegen::Bindings::ImageBitmapBinding::{
120 ImageBitmapOptions, ImageBitmapSource,
121};
122use crate::dom::bindings::codegen::Bindings::MediaQueryListBinding::MediaQueryList_Binding::MediaQueryListMethods;
123use crate::dom::bindings::codegen::Bindings::MessagePortBinding::StructuredSerializeOptions;
124use crate::dom::bindings::codegen::Bindings::ReportingObserverBinding::Report;
125use crate::dom::bindings::codegen::Bindings::RequestBinding::{RequestInfo, RequestInit};
126use crate::dom::bindings::codegen::Bindings::VoidFunctionBinding::VoidFunction;
127use crate::dom::bindings::codegen::Bindings::WindowBinding::{
128 self, DeferredRequestInit, ScrollBehavior, WindowMethods, WindowPostMessageOptions,
129};
130use crate::dom::bindings::codegen::UnionTypes::{
131 RequestOrUSVString, TrustedScriptOrString, TrustedScriptOrStringOrFunction,
132};
133use crate::dom::bindings::error::{Error, ErrorResult, Fallible};
134use crate::dom::bindings::inheritance::{Castable, ElementTypeId, HTMLElementTypeId, NodeTypeId};
135use crate::dom::bindings::num::Finite;
136use crate::dom::bindings::refcounted::Trusted;
137use crate::dom::bindings::reflector::DomGlobal;
138use crate::dom::bindings::root::{Dom, DomRoot, MutNullableDom};
139use crate::dom::bindings::str::{DOMString, USVString};
140use crate::dom::bindings::structuredclone;
141use crate::dom::bindings::trace::{
142 CustomTraceable, HashMapTracedValues, JSTraceable, RootedTraceableBox,
143};
144use crate::dom::bindings::utils::GlobalStaticData;
145use crate::dom::bindings::weakref::DOMTracker;
146#[cfg(feature = "bluetooth")]
147use crate::dom::bluetooth::BluetoothExtraPermissionData;
148use crate::dom::cookiestore::cookiestore::CookieStore;
149use crate::dom::csp::GlobalCspReporting;
150use crate::dom::css::cssstyledeclaration::{
151 CSSModificationAccess, CSSStyleDeclaration, CSSStyleOwner,
152};
153use crate::dom::customelementregistry::CustomElementRegistry;
154use crate::dom::document::focus::FocusableArea;
155use crate::dom::document::{
156 AnimationFrameCallback, Document, SameOriginDescendantNavigablesIterator,
157};
158use crate::dom::element::Element;
159use crate::dom::event::{Event, EventBubbles, EventCancelable};
160use crate::dom::eventtarget::EventTarget;
161use crate::dom::fetchlaterresult::FetchLaterResult;
162use crate::dom::globalscope::GlobalScope;
163use crate::dom::history::History;
164use crate::dom::html::htmlcollection::{CollectionFilter, HTMLCollection};
165use crate::dom::html::htmliframeelement::HTMLIFrameElement;
166use crate::dom::idbfactory::IDBFactory;
167use crate::dom::inputevent::HitTestResult;
168use crate::dom::location::Location;
169use crate::dom::medialist::MediaList;
170use crate::dom::mediaquerylist::{MediaQueryList, MediaQueryListMatchState};
171use crate::dom::mediaquerylistevent::MediaQueryListEvent;
172use crate::dom::messageevent::MessageEvent;
173use crate::dom::navigator::Navigator;
174use crate::dom::node::{Node, NodeDamage, NodeTraits, from_untrusted_node_address};
175use crate::dom::performance::performance::Performance;
176use crate::dom::performanceresourcetiming::InitiatorType;
177use crate::dom::promise::Promise;
178use crate::dom::reporting::reportingendpoint::{ReportingEndpoint, SendReportsToEndpoints};
179use crate::dom::reporting::reportingobserver::ReportingObserver;
180use crate::dom::selection::Selection;
181use crate::dom::serviceworker::cachestorage::CacheStorage;
182use crate::dom::shadowroot::ShadowRoot;
183use crate::dom::storage::Storage;
184#[cfg(feature = "bluetooth")]
185use crate::dom::testrunner::TestRunner;
186use crate::dom::trustedtypes::trustedtypepolicyfactory::TrustedTypePolicyFactory;
187use crate::dom::types::{FontFace, ImageBitmap, SVGSVGElement, UIEvent};
188use crate::dom::visualviewport::{VisualViewport, VisualViewportChanges};
189#[cfg(feature = "webgpu")]
190use crate::dom::webgpu::identityhub::IdentityHub;
191use crate::dom::window::layout_image::fetch_image_for_layout;
192use crate::dom::window::screen::Screen;
193use crate::dom::window::scrolling_box::{ScrollingBox, ScrollingBoxSource};
194use crate::dom::window::useractivation::UserActivationTimestamp;
195use crate::dom::windowproxy::{WindowProxy, WindowProxyHandler};
196use crate::dom::worklet::Worklet;
197use crate::dom::workletglobalscope::WorkletGlobalScopeType;
198use crate::event_loop::script_thread::ScriptThread;
199use crate::event_loop::script_window_proxies::ScriptWindowProxies;
200use crate::event_loop::timers::{IsInterval, OneshotTimers, TimerCallback};
201use crate::event_loop::webdriver_handlers::find_node_by_unique_id_in_document;
202use crate::fetch::fetch;
203use crate::fetch::network_listener::{ResourceTimingListener, submit_timing};
204use crate::messaging::{MainThreadScriptMsg, ScriptEventLoopReceiver, ScriptEventLoopSender};
205use crate::realms::enter_auto_realm;
206use crate::runtime::microtask::UserMicrotask;
207use crate::runtime::script_runtime::Runtime;
208use crate::tasks::task_manager::TaskManager;
209use crate::tasks::task_source::SendableTaskSource;
210use crate::unminify::unminified_path;
211use crate::window_named_properties;
212
213#[derive(MallocSizeOf)]
218pub struct PendingImageCallback(
219 #[ignore_malloc_size_of = "dyn Fn is currently impossible to measure"]
220 #[expect(clippy::type_complexity)]
221 Box<dyn Fn(PendingImageResponse, &mut JSContext) + 'static>,
222);
223
224#[derive(Clone, Copy, Debug, JSTraceable, MallocSizeOf, PartialEq)]
226enum WindowState {
227 Alive,
228 Zombie, }
230
231const INITIAL_REFLOW_DELAY: Duration = Duration::from_millis(200);
234
235#[derive(Clone, Copy, MallocSizeOf)]
246enum LayoutBlocker {
247 WaitingForParse,
249 Parsing(Instant),
251 FiredLoadEventOrParsingTimerExpired,
255}
256
257impl LayoutBlocker {
258 fn layout_blocked(&self) -> bool {
259 !matches!(self, Self::FiredLoadEventOrParsingTimerExpired)
260 }
261}
262
263#[derive(Clone, Copy, Debug, Default, JSTraceable, MallocSizeOf, PartialEq)]
266pub(crate) struct OngoingNavigation(u32);
267
268type PendingImageRasterizationKey = (PendingImageId, DeviceIntSize);
269
270#[cfg_attr(crown, crown::unrooted_must_root_lint::must_root)]
274#[derive(JSTraceable, MallocSizeOf)]
275struct PendingLayoutImageAncillaryData {
276 node: Dom<Node>,
277 #[no_trace]
278 destination: LayoutImageDestination,
279}
280
281#[dom_struct]
282pub(crate) struct Window {
283 globalscope: GlobalScope,
284
285 #[ignore_malloc_size_of = "Weak does not need to be accounted"]
289 #[no_trace]
290 weak_script_thread: Weak<ScriptThread>,
291
292 #[no_trace]
296 webview_id: WebViewId,
297 script_chan: Sender<MainThreadScriptMsg>,
298 #[no_trace]
299 #[ignore_malloc_size_of = "TODO: Add MallocSizeOf support to layout"]
300 layout: RefCell<Box<dyn Layout>>,
301 navigator: MutNullableDom<Navigator>,
302 #[cfg(feature = "webcrypto")]
303 crypto: MutNullableDom<crate::dom::crypto::Crypto>,
304 #[no_trace]
305 image_cache_sender: Sender<ImageCacheResponseMessage>,
306 window_proxy: MutNullableDom<WindowProxy>,
307 document: MutNullableDom<Document>,
308 location: MutNullableDom<Location>,
309 performance: MutNullableDom<Performance>,
310 #[no_trace]
311 navigation_start: Cell<CrossProcessInstant>,
312 screen: MutNullableDom<Screen>,
313 session_storage: MutNullableDom<Storage>,
314 local_storage: MutNullableDom<Storage>,
315 cookie_store: MutNullableDom<CookieStore>,
317 status: DomRefCell<DOMString>,
318 trusted_types: MutNullableDom<TrustedTypePolicyFactory>,
319
320 ongoing_navigation: Cell<OngoingNavigation>,
323
324 caches: MutNullableDom<CacheStorage>,
326
327 #[no_trace]
330 devtools_markers: DomRefCell<HashSet<TimelineMarkerType>>,
331 #[no_trace]
332 devtools_marker_sender: DomRefCell<Option<GenericSender<Option<TimelineMarker>>>>,
333
334 #[no_trace]
336 unhandled_resize_event: DomRefCell<Option<(ViewportDetails, WindowSizeType)>>,
337
338 #[no_trace]
342 viewport_details_at_last_resize_steps: Cell<ViewportDetails>,
343
344 #[no_trace]
346 embedder_theme: Cell<Theme>,
347
348 #[no_trace]
350 parent_info: Option<PipelineId>,
351
352 dom_static: GlobalStaticData,
354
355 #[conditional_malloc_size_of]
357 js_runtime: DomRefCell<Option<Rc<Runtime>>>,
358
359 #[no_trace]
361 viewport_details: Cell<ViewportDetails>,
362
363 #[no_trace]
365 #[cfg(feature = "bluetooth")]
366 bluetooth_thread: GenericSender<BluetoothRequest>,
367
368 #[cfg(feature = "bluetooth")]
369 bluetooth_extra_permission_data: BluetoothExtraPermissionData,
370
371 #[no_trace]
375 layout_blocker: Cell<LayoutBlocker>,
376
377 #[no_trace]
379 webdriver_load_status_sender: RefCell<Option<GenericSender<WebDriverLoadStatus>>>,
380
381 current_state: Cell<WindowState>,
383
384 error_reporter: CSSErrorReporter,
385
386 media_query_lists: DOMTracker<MediaQueryList>,
388
389 #[cfg(feature = "bluetooth")]
390 test_runner: MutNullableDom<TestRunner>,
391
392 #[no_trace]
394 #[cfg(feature = "webgl")]
395 webgl_chan: Option<WebGLChan>,
396
397 #[ignore_malloc_size_of = "defined in webxr"]
398 #[no_trace]
399 #[cfg(feature = "webxr")]
400 webxr_registry: Option<webxr_api::Registry>,
401
402 #[no_trace]
406 pending_image_callbacks: DomRefCell<FxHashMap<PendingImageId, Vec<PendingImageCallback>>>,
407
408 pending_layout_images: DomRefCell<
413 HashMapTracedValues<PendingImageId, Vec<PendingLayoutImageAncillaryData>, FxBuildHasher>,
414 >,
415
416 pending_images_for_rasterization: DomRefCell<
420 HashMapTracedValues<PendingImageRasterizationKey, Vec<Dom<Node>>, FxBuildHasher>,
421 >,
422
423 unminified_css_dir: DomRefCell<Option<String>>,
426
427 local_script_source: Option<String>,
429
430 test_worklet: MutNullableDom<Worklet>,
432 paint_worklet: MutNullableDom<Worklet>,
434
435 exists_mut_observer: Cell<bool>,
437
438 #[no_trace]
440 paint_api: CrossProcessPaintApi,
441
442 #[no_trace]
445 #[conditional_malloc_size_of]
446 user_scripts: Rc<Vec<UserScript>>,
447
448 #[no_trace]
450 player_context: WindowGLContext,
451
452 throttled: Cell<bool>,
453
454 #[conditional_malloc_size_of]
458 layout_marker: DomRefCell<Rc<Cell<bool>>>,
459
460 current_event: DomRefCell<Option<Dom<Event>>>,
462
463 reporting_observer_list: DomRefCell<Vec<Dom<ReportingObserver>>>,
465
466 report_list: DomRefCell<Vec<Report>>,
468
469 #[no_trace]
471 endpoints_list: DomRefCell<Vec<ReportingEndpoint>>,
472
473 #[conditional_malloc_size_of]
475 script_window_proxies: Rc<ScriptWindowProxies>,
476
477 has_pending_screenshot_readiness_request: Cell<bool>,
479
480 visual_viewport: MutNullableDom<VisualViewport>,
483
484 has_changed_visual_viewport_dimension: Cell<bool>,
486
487 pending_media_query_evaluation: Cell<bool>,
492
493 #[no_trace]
495 last_activation_timestamp: Cell<UserActivationTimestamp>,
496
497 devtools_wants_updates: Cell<bool>,
500
501 has_dispatched_scroll_event: Cell<bool>,
503
504 has_dispatched_input_event: Cell<bool>,
506}
507
508impl Window {
509 pub(crate) fn script_thread(&self) -> Rc<ScriptThread> {
510 Weak::upgrade(&self.weak_script_thread)
511 .expect("Weak reference should always be upgradable when a ScriptThread is running")
512 }
513
514 pub(crate) fn webview_id(&self) -> WebViewId {
515 self.webview_id
516 }
517
518 pub(crate) fn as_global_scope(&self) -> &GlobalScope {
519 self.upcast::<GlobalScope>()
520 }
521
522 pub(crate) fn mark_has_dispatched_scroll_event(&self) {
524 self.has_dispatched_scroll_event.set(true);
525 }
526
527 pub(crate) fn mark_has_dispatched_input_event(&self) {
529 self.has_dispatched_input_event.set(true);
530 }
531
532 pub(crate) fn layout(&self) -> Ref<'_, Box<dyn Layout>> {
533 self.layout.borrow()
534 }
535
536 pub(crate) fn layout_mut(&self) -> RefMut<'_, Box<dyn Layout>> {
537 self.layout.borrow_mut()
538 }
539
540 pub(crate) fn get_exists_mut_observer(&self) -> bool {
541 self.exists_mut_observer.get()
542 }
543
544 pub(crate) fn set_exists_mut_observer(&self) {
545 self.exists_mut_observer.set(true);
546 }
547
548 #[expect(unsafe_code)]
549 pub(crate) fn clear_js_runtime_for_script_deallocation(&self) {
550 self.as_global_scope()
551 .remove_web_messaging_and_dedicated_workers_infra();
552 unsafe {
553 *self.js_runtime.borrow_for_script_deallocation() = None;
554 self.window_proxy.set(None);
555 self.current_state.set(WindowState::Zombie);
556 self.as_global_scope()
557 .task_manager()
558 .cancel_all_tasks_and_ignore_future_tasks();
559 }
560 }
561
562 pub(crate) fn discard_browsing_context(&self) {
565 let proxy = self
566 .window_proxy
567 .get()
568 .expect("Discarding a BC from a window that has none");
569 proxy.discard_browsing_context();
570
571 self.as_global_scope()
575 .task_manager()
576 .cancel_all_tasks_and_ignore_future_tasks();
577 }
578
579 pub(crate) fn time_profiler_chan(&self) -> &TimeProfilerChan {
581 self.globalscope.time_profiler_chan()
582 }
583
584 pub(crate) fn origin(&self) -> MutableOrigin {
586 self.Document().origin().clone()
588 }
589
590 pub(crate) fn main_thread_script_chan(&self) -> &Sender<MainThreadScriptMsg> {
591 &self.script_chan
592 }
593
594 pub(crate) fn parent_info(&self) -> Option<PipelineId> {
595 self.parent_info
596 }
597
598 pub(crate) fn new_script_pair(&self) -> (ScriptEventLoopSender, ScriptEventLoopReceiver) {
599 let (sender, receiver) = unbounded();
600 (
601 ScriptEventLoopSender::MainThread(sender),
602 ScriptEventLoopReceiver::MainThread(receiver),
603 )
604 }
605
606 pub(crate) fn event_loop_sender(&self) -> ScriptEventLoopSender {
607 ScriptEventLoopSender::MainThread(self.script_chan.clone())
608 }
609
610 pub(crate) fn image_cache(&self) -> Arc<dyn ImageCache> {
611 self.Document().image_cache()
612 }
613
614 pub(crate) fn window_proxy(&self) -> DomRoot<WindowProxy> {
616 self.window_proxy.get().unwrap()
617 }
618
619 pub(crate) fn append_reporting_observer(&self, reporting_observer: &ReportingObserver) {
620 self.reporting_observer_list
621 .borrow_mut()
622 .push(Dom::from_ref(reporting_observer));
623 }
624
625 pub(crate) fn remove_reporting_observer(&self, reporting_observer: &ReportingObserver) {
626 let index = {
627 let list = self.reporting_observer_list.borrow();
628 list.iter()
629 .position(|observer| &**observer == reporting_observer)
630 };
631
632 if let Some(index) = index {
633 self.reporting_observer_list.borrow_mut().remove(index);
634 }
635 }
636
637 pub(crate) fn registered_reporting_observers(&self) -> Vec<DomRoot<ReportingObserver>> {
638 self.reporting_observer_list
639 .borrow()
640 .iter()
641 .map(|observer| DomRoot::from_ref(&**observer))
642 .collect()
643 }
644
645 pub(crate) fn append_report(&self, report: Report) {
646 self.report_list.borrow_mut().push(report);
647 let trusted_window = Trusted::new(self);
648 self.upcast::<GlobalScope>()
649 .task_manager()
650 .dom_manipulation_task_source()
651 .queue(task!(send_to_reporting_endpoints: move || {
652 let window = trusted_window.root();
653 let reports = std::mem::take(&mut *window.report_list.borrow_mut());
654 window.upcast::<GlobalScope>().send_reports_to_endpoints(
655 reports,
656 window.endpoints_list.borrow().clone(),
657 );
658 }));
659 }
660
661 pub(crate) fn buffered_reports(&self) -> Vec<Report> {
662 self.report_list.borrow().clone()
663 }
664
665 pub(crate) fn set_endpoints_list(&self, endpoints: Vec<ReportingEndpoint>) {
666 *self.endpoints_list.borrow_mut() = endpoints;
667 }
668
669 pub(crate) fn undiscarded_window_proxy(&self) -> Option<DomRoot<WindowProxy>> {
672 self.window_proxy
673 .get()
674 .filter(|window_proxy| !window_proxy.is_browsing_context_discarded())
675 }
676
677 pub(crate) fn top_level_document_if_local(&self) -> Option<DomRoot<Document>> {
682 if self.is_top_level() {
683 return Some(self.Document());
684 }
685
686 let window_proxy = self.undiscarded_window_proxy()?;
687 self.script_window_proxies
688 .find_window_proxy(window_proxy.webview_id().into())?
689 .document()
690 }
691
692 #[cfg(feature = "bluetooth")]
693 pub(crate) fn bluetooth_thread(&self) -> GenericSender<BluetoothRequest> {
694 self.bluetooth_thread.clone()
695 }
696
697 #[cfg(feature = "bluetooth")]
698 pub(crate) fn bluetooth_extra_permission_data(&self) -> &BluetoothExtraPermissionData {
699 &self.bluetooth_extra_permission_data
700 }
701
702 pub(crate) fn css_error_reporter(&self) -> &CSSErrorReporter {
703 &self.error_reporter
704 }
705
706 #[cfg(feature = "webgl")]
707 pub(crate) fn webgl_chan(&self) -> Option<WebGLChan> {
708 self.webgl_chan.clone()
709 }
710
711 #[cfg(feature = "webgl")]
713 pub(crate) fn webgl_chan_value(&self) -> Option<WebGLChan> {
714 self.webgl_chan.clone()
715 }
716
717 #[cfg(feature = "webxr")]
718 pub(crate) fn webxr_registry(&self) -> Option<webxr_api::Registry> {
719 self.webxr_registry.clone()
720 }
721
722 fn new_paint_worklet(&self, cx: &mut JSContext) -> DomRoot<Worklet> {
723 debug!("Creating new paint worklet.");
724
725 let worklet_global_scope_init = self.into();
726 Worklet::new(
727 cx,
728 self,
729 WorkletGlobalScopeType::Paint,
730 Box::new(|| Rc::new(StatelessWorkletThreadPool::spawn(worklet_global_scope_init))),
731 )
732 }
733
734 pub(crate) fn register_image_cache_listener(
735 &self,
736 id: PendingImageId,
737 callback: impl Fn(PendingImageResponse, &mut JSContext) + 'static,
738 ) -> ImageCacheResponseCallback {
739 self.pending_image_callbacks
740 .borrow_mut()
741 .entry(id)
742 .or_default()
743 .push(PendingImageCallback(Box::new(callback)));
744
745 let image_cache_sender = self.image_cache_sender.clone();
746 Box::new(move |message| {
747 let _ = image_cache_sender.send(message);
748 })
749 }
750
751 fn pending_layout_image_notification(&self, no_gc: &NoGC, response: PendingImageResponse) {
752 let mut images = self.pending_layout_images.borrow_mut();
753 let nodes = images.entry(response.id);
754 let nodes = match nodes {
755 Entry::Occupied(nodes) => nodes,
756 Entry::Vacant(_) => return,
757 };
758 if matches!(
759 response.response,
760 ImageResponse::Loaded(_, _) | ImageResponse::FailedToLoadOrDecode
761 ) {
762 for ancillary_data in nodes.get() {
763 match ancillary_data.destination {
764 LayoutImageDestination::BoxTreeConstruction => {
765 ancillary_data.node.dirty(no_gc, NodeDamage::Other);
766 },
767 LayoutImageDestination::DisplayListBuilding => {
768 self.layout().set_needs_new_display_list();
769 },
770 }
771 }
772 }
773
774 match response.response {
775 ImageResponse::MetadataLoaded(_) => {},
776 ImageResponse::Loaded(_, _) | ImageResponse::FailedToLoadOrDecode => {
777 nodes.remove();
778 },
779 }
780 }
781
782 pub(crate) fn handle_image_rasterization_complete_notification(
783 &self,
784 no_gc: &NoGC,
785 response: RasterizationCompleteResponse,
786 ) {
787 let mut images = self.pending_images_for_rasterization.borrow_mut();
788 let nodes = images.entry((response.image_id, response.requested_size));
789 let nodes = match nodes {
790 Entry::Occupied(nodes) => nodes,
791 Entry::Vacant(_) => return,
792 };
793 for node in nodes.get() {
794 node.dirty(no_gc, NodeDamage::Other);
795 }
796 nodes.remove();
797 }
798
799 pub(crate) fn pending_image_notification(
800 &self,
801 response: PendingImageResponse,
802 cx: &mut JSContext,
803 ) {
804 let mut images = std::mem::take(&mut *self.pending_image_callbacks.borrow_mut());
809 let Entry::Occupied(callbacks) = images.entry(response.id) else {
810 let _ = std::mem::replace(&mut *self.pending_image_callbacks.borrow_mut(), images);
811 return;
812 };
813
814 for callback in callbacks.get() {
815 callback.0(response.clone(), cx);
816 }
817
818 match response.response {
819 ImageResponse::MetadataLoaded(_) => {},
820 ImageResponse::Loaded(_, _) | ImageResponse::FailedToLoadOrDecode => {
821 callbacks.remove();
822 },
823 }
824
825 let _ = std::mem::replace(&mut *self.pending_image_callbacks.borrow_mut(), images);
826 }
827
828 pub(crate) fn paint_api(&self) -> &CrossProcessPaintApi {
829 &self.paint_api
830 }
831
832 pub(crate) fn userscripts(&self) -> &[UserScript] {
833 &self.user_scripts
834 }
835
836 pub(crate) fn get_player_context(&self) -> WindowGLContext {
837 self.player_context.clone()
838 }
839
840 pub(crate) fn dispatch_event_with_target_override(&self, cx: &mut JSContext, event: &Event) {
842 event.dispatch(cx, self.upcast(), true);
843 }
844
845 pub(crate) fn font_context(&self) -> Arc<FontContext> {
846 self.layout().font_context().clone()
847 }
848
849 pub(crate) fn ongoing_navigation(&self) -> OngoingNavigation {
850 self.ongoing_navigation.get()
851 }
852
853 pub(crate) fn set_ongoing_navigation(&self) -> OngoingNavigation {
855 let new_value = self.ongoing_navigation.get().0.wrapping_add(1);
859
860 self.ongoing_navigation.set(OngoingNavigation(new_value));
867
868 OngoingNavigation(new_value)
870 }
871
872 fn stop_loading(&self, cx: &mut JSContext) {
874 let doc = self.Document();
876
877 self.set_ongoing_navigation();
887
888 doc.abort_a_document_and_its_descendants(cx);
890 }
891
892 fn destroy_top_level_traversable(&self, cx: &mut JSContext) {
894 let document = self.Document();
900 document.destroy_document_and_its_descendants(cx);
902 self.send_to_constellation(ScriptToConstellationMessage::DiscardTopLevelBrowsingContext);
904 }
905
906 fn definitely_close(&self, cx: &mut JSContext) {
908 let document = self.Document();
909 if !document.check_if_unloading_is_cancelled(cx, false) {
914 return;
915 }
916 document.unload(cx, false);
920 self.destroy_top_level_traversable(cx);
922 }
923
924 fn cannot_show_simple_dialogs(&self) -> bool {
926 if self
929 .Document()
930 .has_active_sandboxing_flag(SandboxingFlagSet::SANDBOXED_MODALS_FLAG)
931 {
932 return true;
933 }
934
935 false
954 }
955
956 pub(crate) fn perform_a_microtask_checkpoint(&self, cx: &mut JSContext) {
957 self.script_thread().perform_a_microtask_checkpoint(cx);
958 }
959
960 pub(crate) fn web_font_context(&self, no_gc: &NoGC) -> WebFontDocumentContext {
961 let global = self.as_global_scope();
962 let task_source = global
963 .task_manager()
964 .dom_manipulation_task_source()
965 .to_sendable();
966 let target_global = Trusted::new(global);
967 let document = self.document_unrooted(no_gc);
968 WebFontDocumentContext {
969 policy_container: document.policy_container().clone(),
970 request_client: self.request_client(Some(no_gc)),
971 document_url: document.base_url(),
972 csp_handler: Box::new(FontCspHandler {
973 global: target_global.clone(),
974 task_source: task_source.clone(),
975 }),
976 network_timing_handler: Box::new(FontNetworkTimingHandler {
977 global: target_global,
978 task_source,
979 }),
980 }
981 }
982
983 pub(crate) fn request_client(&self, no_gc: Option<&NoGC>) -> RequestClient {
985 let (
988 preloaded_resources,
989 insecure_requests_policy,
990 has_trustworthy_ancestor_origin,
991 policy_container,
992 origin,
993 ) = if let Some(no_gc) = no_gc {
994 let document = self.document_unrooted(no_gc);
995 (
996 document.preloaded_resources().clone(),
997 document.insecure_requests_policy(),
998 document.has_trustworthy_ancestor_or_current_origin(),
999 document.policy_container().clone(),
1000 document.origin().clone(),
1001 )
1002 } else {
1003 let document = self.Document();
1004 (
1005 document.preloaded_resources().clone(),
1006 document.insecure_requests_policy(),
1007 document.has_trustworthy_ancestor_or_current_origin(),
1008 document.policy_container().clone(),
1009 document.origin().clone(),
1010 )
1011 };
1012 RequestClient {
1013 preloaded_resources,
1014 policy_container,
1015 origin: Origin::Origin(origin.immutable().clone()),
1016 is_nested_browsing_context: !self.is_top_level(),
1017 insecure_requests_policy,
1018 has_trustworthy_ancestor_origin,
1019 }
1020 }
1021
1022 #[expect(unsafe_code)]
1023 pub(crate) fn gc(&self, cx: &mut JSContext) {
1024 unsafe { JS_GC(cx, GCReason::API) };
1025 }
1026
1027 pub(crate) fn with_timers<T>(&self, f: impl FnOnce(&OneshotTimers) -> T) -> T {
1028 let document = self.Document();
1029 f(document.timers())
1030 }
1031}
1032
1033#[derive(Debug, MallocSizeOf)]
1034struct FontCspHandler {
1035 global: Trusted<GlobalScope>,
1036 task_source: SendableTaskSource,
1037}
1038
1039impl CspViolationHandler for FontCspHandler {
1040 fn process_violations(&self, violations: Vec<Violation>) {
1041 let global = self.global.clone();
1042 self.task_source.queue(task!(csp_violation: move |cx| {
1043 global.root().report_csp_violations(cx, violations, None, None);
1044 }));
1045 }
1046
1047 fn clone(&self) -> Box<dyn CspViolationHandler> {
1048 Box::new(Self {
1049 global: self.global.clone(),
1050 task_source: self.task_source.clone(),
1051 })
1052 }
1053}
1054
1055#[derive(Debug, MallocSizeOf)]
1056struct FontNetworkTimingHandler {
1057 global: Trusted<GlobalScope>,
1058 task_source: SendableTaskSource,
1059}
1060
1061impl NetworkTimingHandler for FontNetworkTimingHandler {
1062 fn submit_timing(&self, url: ServoUrl, response: ResourceFetchTiming) {
1063 let global = self.global.clone();
1064 self.task_source.queue(task!(network_timing: move |cx| {
1065 submit_timing(
1066 cx,
1067 &FontFetchListener {
1068 url,
1069 global
1070 },
1071 &Ok(()),
1072 &response,
1073 );
1074 }));
1075 }
1076
1077 fn clone(&self) -> Box<dyn NetworkTimingHandler> {
1078 Box::new(Self {
1079 global: self.global.clone(),
1080 task_source: self.task_source.clone(),
1081 })
1082 }
1083}
1084
1085#[derive(Debug)]
1086struct FontFetchListener {
1087 global: Trusted<GlobalScope>,
1088 url: ServoUrl,
1089}
1090
1091impl ResourceTimingListener for FontFetchListener {
1092 fn resource_timing_information(&self) -> (InitiatorType, ServoUrl) {
1093 (InitiatorType::Css, self.url.clone())
1094 }
1095
1096 fn resource_timing_global(&self) -> DomRoot<GlobalScope> {
1097 self.global.root()
1098 }
1099}
1100
1101pub(crate) fn base64_btoa(input: DOMString) -> Fallible<DOMString> {
1103 if input.str().chars().any(|c: char| c > '\u{FF}') {
1107 Err(Error::InvalidCharacter(None))
1108 } else {
1109 let octets = input
1114 .str()
1115 .chars()
1116 .map(|c: char| c as u8)
1117 .collect::<Vec<u8>>();
1118
1119 let config =
1122 base64::engine::general_purpose::GeneralPurposeConfig::new().with_encode_padding(true);
1123 let engine = base64::engine::GeneralPurpose::new(&base64::alphabet::STANDARD, config);
1124 Ok(DOMString::from(engine.encode(octets)))
1125 }
1126}
1127
1128pub(crate) fn base64_atob(input: DOMString) -> Fallible<DOMString> {
1130 fn is_html_space(c: char) -> bool {
1132 HTML_SPACE_CHARACTERS.contains(&c)
1133 }
1134 let without_spaces = input
1135 .str()
1136 .chars()
1137 .filter(|&c| !is_html_space(c))
1138 .collect::<String>();
1139 let mut input = &*without_spaces;
1140
1141 if input.len() % 4 == 0 {
1145 if input.ends_with("==") {
1146 input = &input[..input.len() - 2]
1147 } else if input.ends_with('=') {
1148 input = &input[..input.len() - 1]
1149 }
1150 }
1151
1152 if input.len() % 4 == 1 {
1155 return Err(Error::InvalidCharacter(None));
1156 }
1157
1158 if input
1166 .chars()
1167 .any(|c| c != '+' && c != '/' && !c.is_alphanumeric())
1168 {
1169 return Err(Error::InvalidCharacter(None));
1170 }
1171
1172 let config = base64::engine::general_purpose::GeneralPurposeConfig::new()
1173 .with_decode_padding_mode(base64::engine::DecodePaddingMode::RequireNone)
1174 .with_decode_allow_trailing_bits(true);
1175 let engine = base64::engine::GeneralPurpose::new(&base64::alphabet::STANDARD, config);
1176
1177 let data = engine
1178 .decode(input)
1179 .map_err(|_| Error::InvalidCharacter(None))?;
1180 Ok(data.iter().map(|&b| b as char).collect::<String>().into())
1181}
1182
1183impl WindowMethods<crate::DomTypeHolder> for Window {
1184 fn Alert_(&self) {
1186 self.Alert(DOMString::new());
1189 }
1190
1191 fn Alert(&self, mut message: DOMString) {
1193 if self.cannot_show_simple_dialogs() {
1195 return;
1196 }
1197
1198 message.normalize_newlines();
1202
1203 {
1214 let stderr = stderr();
1218 let mut stderr = stderr.lock();
1219 let stdout = stdout();
1220 let mut stdout = stdout.lock();
1221 writeln!(&mut stdout, "\nALERT: {message}").unwrap();
1222 stdout.flush().unwrap();
1223 stderr.flush().unwrap();
1224 }
1225
1226 let (sender, receiver) =
1227 ProfiledGenericChannel::channel(self.global().time_profiler_chan().clone()).unwrap();
1228 let dialog = SimpleDialogRequest::Alert {
1229 id: self.Document().embedder_controls().next_control_id(),
1230 message: String::from(message),
1231 response_sender: sender,
1232 };
1233 self.send_to_embedder(EmbedderMsg::ShowSimpleDialog(self.webview_id(), dialog));
1234 receiver.recv().unwrap_or_else(|_| {
1235 debug!("Alert dialog was cancelled or failed to show.");
1237 AlertResponse::Ok
1238 });
1239
1240 }
1243
1244 fn Caches(&self, cx: &mut JSContext) -> DomRoot<CacheStorage> {
1246 self.caches
1247 .or_init(|| CacheStorage::new(cx, self.as_global_scope()))
1248 }
1249
1250 fn Confirm(&self, mut message: DOMString) -> bool {
1252 if self.cannot_show_simple_dialogs() {
1254 return false;
1255 }
1256
1257 message.normalize_newlines();
1259
1260 let (sender, receiver) =
1266 ProfiledGenericChannel::channel(self.global().time_profiler_chan().clone()).unwrap();
1267 let dialog = SimpleDialogRequest::Confirm {
1268 id: self.Document().embedder_controls().next_control_id(),
1269 message: String::from(message),
1270 response_sender: sender,
1271 };
1272 self.send_to_embedder(EmbedderMsg::ShowSimpleDialog(self.webview_id(), dialog));
1273
1274 match receiver.recv() {
1290 Ok(ConfirmResponse::Ok) => true,
1291 Ok(ConfirmResponse::Cancel) => false,
1292 Err(_) => {
1293 warn!("Confirm dialog was cancelled or failed to show.");
1294 false
1295 },
1296 }
1297 }
1298
1299 fn Prompt(&self, mut message: DOMString, default: DOMString) -> Option<DOMString> {
1301 if self.cannot_show_simple_dialogs() {
1303 return None;
1304 }
1305
1306 message.normalize_newlines();
1308
1309 let (sender, receiver) =
1317 ProfiledGenericChannel::channel(self.global().time_profiler_chan().clone()).unwrap();
1318 let dialog = SimpleDialogRequest::Prompt {
1319 id: self.Document().embedder_controls().next_control_id(),
1320 message: String::from(message),
1321 default: String::from(default),
1322 response_sender: sender,
1323 };
1324 self.send_to_embedder(EmbedderMsg::ShowSimpleDialog(self.webview_id(), dialog));
1325
1326 match receiver.recv() {
1345 Ok(PromptResponse::Ok(input)) => Some(input.into()),
1346 Ok(PromptResponse::Cancel) => None,
1347 Err(_) => {
1348 warn!("Prompt dialog was cancelled or failed to show.");
1349 None
1350 },
1351 }
1352 }
1353
1354 fn Stop(&self, cx: &mut JSContext) {
1356 self.stop_loading(cx);
1361 }
1362
1363 fn Focus(&self, cx: &mut JSContext) {
1365 let document = self.Document();
1373 if !document.is_active() {
1374 return;
1375 }
1376
1377 document.focus_handler().focus(cx, &FocusableArea::Viewport);
1382
1383 }
1388
1389 fn Blur(&self) {
1391 }
1394
1395 fn Open(
1397 &self,
1398 cx: &mut JSContext,
1399 url: USVString,
1400 target: DOMString,
1401 features: DOMString,
1402 ) -> Fallible<Option<DomRoot<WindowProxy>>> {
1403 self.window_proxy().open(cx, url, target, features)
1404 }
1405
1406 fn GetOpener(&self, cx: &mut CurrentRealm, mut retval: MutableHandleValue) -> Fallible<()> {
1408 let current = match self.window_proxy.get() {
1410 Some(proxy) => proxy,
1411 None => {
1413 retval.set(NullValue());
1414 return Ok(());
1415 },
1416 };
1417 if current.is_browsing_context_discarded() {
1422 retval.set(NullValue());
1423 return Ok(());
1424 }
1425 current.opener(cx, retval);
1427 Ok(())
1428 }
1429
1430 #[expect(unsafe_code)]
1431 fn SetOpener(&self, cx: &mut JSContext, value: HandleValue) -> ErrorResult {
1433 if value.is_null() {
1435 if let Some(proxy) = self.window_proxy.get() {
1436 proxy.disown();
1437 }
1438 return Ok(());
1439 }
1440
1441 let obj = self.reflector().get_jsobject();
1443 let result = unsafe {
1444 JS_DefineProperty(cx, obj, c"opener".as_ptr(), value, JSPROP_ENUMERATE as u32)
1445 };
1446
1447 if result { Ok(()) } else { Err(Error::JSFailed) }
1448 }
1449
1450 fn Closed(&self) -> bool {
1452 self.window_proxy
1453 .get()
1454 .map(|ref proxy| proxy.is_browsing_context_discarded() || proxy.is_closing())
1455 .unwrap_or(true)
1456 }
1457
1458 fn Close(&self, cx: &mut JSContext) {
1460 let window_proxy = match self.window_proxy.get() {
1462 Some(proxy) => proxy,
1463 None => return,
1465 };
1466 if window_proxy.is_closing() {
1468 return;
1469 }
1470 if let Ok(history_length) = self.History(cx).GetLength() {
1473 let is_auxiliary = window_proxy.is_auxiliary();
1474
1475 let is_script_closable = (self.is_top_level() && history_length == 1) ||
1477 is_auxiliary ||
1478 pref!(dom_allow_scripts_to_close_windows);
1479
1480 if is_script_closable {
1484 window_proxy.close();
1486
1487 let this = Trusted::new(self);
1489 let task = task!(window_close_browsing_context: move |cx| {
1490 let window = this.root();
1491 window.definitely_close(cx);
1492 });
1493 self.as_global_scope()
1494 .task_manager()
1495 .dom_manipulation_task_source()
1496 .queue(task);
1497 }
1498 }
1499 }
1500
1501 fn Document(&self) -> DomRoot<Document> {
1503 self.document
1504 .get()
1505 .expect("Document accessed before initialization.")
1506 }
1507
1508 fn History(&self, cx: &mut JSContext) -> DomRoot<History> {
1510 self.Document().history(cx)
1511 }
1512
1513 fn IndexedDB(&self, cx: &mut JSContext) -> DomRoot<IDBFactory> {
1515 self.upcast::<GlobalScope>().ensure_indexeddb_factory(cx)
1516 }
1517
1518 fn CustomElements(&self, cx: &mut JSContext) -> DomRoot<CustomElementRegistry> {
1520 let document = self.Document();
1523 if let Some(registry) = document.custom_element_registry() {
1524 return registry;
1525 }
1526 let registry = CustomElementRegistry::new(cx, self);
1529 document.set_custom_element_registry(®istry);
1530 registry
1532 }
1533
1534 fn Location(&self, cx: &mut JSContext) -> DomRoot<Location> {
1536 self.location.or_init(|| Location::new(cx, self))
1537 }
1538
1539 fn GetSessionStorage(&self, cx: &mut JSContext) -> Fallible<DomRoot<Storage>> {
1541 if let Some(storage) = self.session_storage.get() {
1544 return Ok(storage);
1545 }
1546
1547 if !self.origin().is_tuple() {
1551 return Err(Error::Security(Some(
1552 "Cannot access sessionStorage from opaque origin.".to_string(),
1553 )));
1554 }
1555
1556 let storage = Storage::new(cx, self, WebStorageType::Session);
1558
1559 self.session_storage.set(Some(&storage));
1561
1562 Ok(storage)
1564 }
1565
1566 fn GetLocalStorage(&self, cx: &mut JSContext) -> Fallible<DomRoot<Storage>> {
1568 if let Some(storage) = self.local_storage.get() {
1571 return Ok(storage);
1572 }
1573
1574 if !self.origin().is_tuple() {
1578 return Err(Error::Security(Some(
1579 "Cannot access localStorage from opaque origin.".to_string(),
1580 )));
1581 }
1582
1583 let storage = Storage::new(cx, self, WebStorageType::Local);
1585
1586 self.local_storage.set(Some(&storage));
1588
1589 Ok(storage)
1591 }
1592
1593 fn CookieStore(&self, cx: &mut JSContext) -> DomRoot<CookieStore> {
1595 self.cookie_store
1596 .or_init(|| CookieStore::new(cx, self.upcast::<GlobalScope>()))
1597 }
1598
1599 #[cfg(feature = "webcrypto")]
1601 fn Crypto(&self, cx: &mut JSContext) -> DomRoot<crate::dom::crypto::Crypto> {
1602 self.crypto
1603 .or_init(|| crate::dom::crypto::Crypto::new(cx, self.as_global_scope()))
1604 }
1605
1606 fn GetFrameElement(&self) -> Option<DomRoot<Element>> {
1608 let window_proxy = self.window_proxy.get()?;
1610
1611 let container = window_proxy.frame_element()?;
1613
1614 let container_doc = container.owner_document();
1616 let current_doc = GlobalScope::current()
1617 .expect("No current global object")
1618 .as_window()
1619 .Document();
1620 if !current_doc
1621 .origin()
1622 .same_origin_domain(&container_doc.origin())
1623 {
1624 return None;
1625 }
1626 Some(DomRoot::from_ref(container))
1628 }
1629
1630 fn ReportError(&self, cx: &mut JSContext, error: HandleValue) {
1632 self.as_global_scope().report_an_exception(cx, error);
1633 }
1634
1635 fn Navigator(&self, cx: &mut JSContext) -> DomRoot<Navigator> {
1637 self.navigator.or_init(|| Navigator::new(cx, self))
1638 }
1639
1640 fn ClientInformation(&self, cx: &mut JSContext) -> DomRoot<Navigator> {
1642 self.Navigator(cx)
1643 }
1644
1645 fn SetTimeout(
1647 &self,
1648 cx: &mut JSContext,
1649 callback: TrustedScriptOrStringOrFunction,
1650 timeout: i32,
1651 args: Vec<HandleValue>,
1652 ) -> Fallible<i32> {
1653 let callback = match callback {
1654 TrustedScriptOrStringOrFunction::String(i) => {
1655 TimerCallback::StringTimerCallback(TrustedScriptOrString::String(i))
1656 },
1657 TrustedScriptOrStringOrFunction::TrustedScript(i) => {
1658 TimerCallback::StringTimerCallback(TrustedScriptOrString::TrustedScript(i))
1659 },
1660 TrustedScriptOrStringOrFunction::Function(i) => TimerCallback::FunctionTimerCallback(i),
1661 };
1662 self.as_global_scope().set_timeout_or_interval(
1663 cx,
1664 callback,
1665 args,
1666 Duration::from_millis(timeout.max(0) as u64),
1667 IsInterval::NonInterval,
1668 )
1669 }
1670
1671 fn ClearTimeout(&self, handle: i32) {
1673 self.as_global_scope().clear_timeout_or_interval(handle);
1674 }
1675
1676 fn SetInterval(
1678 &self,
1679 cx: &mut JSContext,
1680 callback: TrustedScriptOrStringOrFunction,
1681 timeout: i32,
1682 args: Vec<HandleValue>,
1683 ) -> Fallible<i32> {
1684 let callback = match callback {
1685 TrustedScriptOrStringOrFunction::String(i) => {
1686 TimerCallback::StringTimerCallback(TrustedScriptOrString::String(i))
1687 },
1688 TrustedScriptOrStringOrFunction::TrustedScript(i) => {
1689 TimerCallback::StringTimerCallback(TrustedScriptOrString::TrustedScript(i))
1690 },
1691 TrustedScriptOrStringOrFunction::Function(i) => TimerCallback::FunctionTimerCallback(i),
1692 };
1693 self.as_global_scope().set_timeout_or_interval(
1694 cx,
1695 callback,
1696 args,
1697 Duration::from_millis(timeout.max(0) as u64),
1698 IsInterval::Interval,
1699 )
1700 }
1701
1702 fn ClearInterval(&self, handle: i32) {
1704 self.ClearTimeout(handle);
1705 }
1706
1707 fn QueueMicrotask(&self, cx: &JSContext, callback: Rc<VoidFunction>) {
1709 ScriptThread::enqueue_microtask(
1710 cx,
1711 Box::new(UserMicrotask {
1712 callback,
1713 global: Dom::from_ref(&self.globalscope),
1714 }),
1715 );
1716 }
1717
1718 fn CreateImageBitmap(
1720 &self,
1721 realm: &mut CurrentRealm,
1722 image: ImageBitmapSource,
1723 options: &ImageBitmapOptions,
1724 ) -> Rc<Promise> {
1725 ImageBitmap::create_image_bitmap(
1726 self.as_global_scope(),
1727 image,
1728 0,
1729 0,
1730 None,
1731 None,
1732 options,
1733 realm,
1734 )
1735 }
1736
1737 fn CreateImageBitmap_(
1739 &self,
1740 realm: &mut CurrentRealm,
1741 image: ImageBitmapSource,
1742 sx: i32,
1743 sy: i32,
1744 sw: i32,
1745 sh: i32,
1746 options: &ImageBitmapOptions,
1747 ) -> Rc<Promise> {
1748 ImageBitmap::create_image_bitmap(
1749 self.as_global_scope(),
1750 image,
1751 sx,
1752 sy,
1753 Some(sw),
1754 Some(sh),
1755 options,
1756 realm,
1757 )
1758 }
1759
1760 fn Window(&self) -> DomRoot<WindowProxy> {
1762 self.window_proxy()
1763 }
1764
1765 fn Self_(&self) -> DomRoot<WindowProxy> {
1767 self.window_proxy()
1768 }
1769
1770 fn Frames(&self) -> DomRoot<WindowProxy> {
1772 self.window_proxy()
1773 }
1774
1775 fn Length(&self) -> u32 {
1777 self.Document().iframes().iter().count() as u32
1778 }
1779
1780 fn GetParent(&self) -> Option<DomRoot<WindowProxy>> {
1782 let window_proxy = self.undiscarded_window_proxy()?;
1784
1785 if let Some(parent) = window_proxy.parent() {
1787 return Some(DomRoot::from_ref(parent));
1788 }
1789 Some(window_proxy)
1791 }
1792
1793 fn GetTop(&self) -> Option<DomRoot<WindowProxy>> {
1795 let window_proxy = self.undiscarded_window_proxy()?;
1797
1798 Some(DomRoot::from_ref(window_proxy.top()))
1800 }
1801
1802 fn Performance(&self, cx: &mut JSContext) -> DomRoot<Performance> {
1805 self.performance
1806 .or_init(|| Performance::new(cx, self.as_global_scope(), self.navigation_start.get()))
1807 }
1808
1809 global_event_handlers!();
1811
1812 window_event_handlers!();
1814
1815 fn Screen(&self, cx: &mut JSContext) -> DomRoot<Screen> {
1817 self.screen.or_init(|| Screen::new(cx, self))
1818 }
1819
1820 fn GetVisualViewport(&self, cx: &mut JSContext) -> Option<DomRoot<VisualViewport>> {
1822 if !self.Document().is_fully_active() {
1826 return None;
1827 }
1828
1829 Some(self.get_or_init_visual_viewport(cx))
1830 }
1831
1832 fn Btoa(&self, btoa: DOMString) -> Fallible<DOMString> {
1834 base64_btoa(btoa)
1835 }
1836
1837 fn Atob(&self, atob: DOMString) -> Fallible<DOMString> {
1839 base64_atob(atob)
1840 }
1841
1842 fn RequestAnimationFrame(&self, callback: Rc<FrameRequestCallback>) -> Fallible<u32> {
1844 Ok(self
1845 .Document()
1846 .request_animation_frame(AnimationFrameCallback::FrameRequestCallback { callback }))
1847 }
1848
1849 fn CancelAnimationFrame(&self, ident: u32) -> ErrorResult {
1851 let doc = self.Document();
1852 doc.cancel_animation_frame(ident);
1853 Ok(())
1854 }
1855
1856 fn PostMessage(
1858 &self,
1859 cx: &mut JSContext,
1860 message: HandleValue,
1861 target_origin: USVString,
1862 transfer: CustomAutoRooterGuard<Vec<*mut JSObject>>,
1863 ) -> ErrorResult {
1864 let incumbent = GlobalScope::incumbent().expect("no incumbent global?");
1865 let source = incumbent.as_window();
1866 let source_origin = source.Document().origin().immutable().clone();
1867
1868 self.post_message_impl(&target_origin, source_origin, source, cx, message, transfer)
1869 }
1870
1871 fn PostMessage_(
1873 &self,
1874 cx: &mut JSContext,
1875 message: HandleValue,
1876 options: RootedTraceableBox<WindowPostMessageOptions>,
1877 ) -> ErrorResult {
1878 let mut rooted = CustomAutoRooter::new(
1879 options
1880 .parent
1881 .transfer
1882 .iter()
1883 .map(|js: &RootedTraceableBox<Heap<*mut JSObject>>| js.get())
1884 .collect(),
1885 );
1886 #[expect(unsafe_code)]
1887 let transfer = unsafe { CustomAutoRooterGuard::new(cx.raw_cx(), &mut rooted) };
1888
1889 let incumbent = GlobalScope::incumbent().expect("no incumbent global?");
1890 let source = incumbent.as_window();
1891
1892 let source_origin = source.Document().origin().immutable().clone();
1893
1894 self.post_message_impl(
1895 &options.targetOrigin,
1896 source_origin,
1897 source,
1898 cx,
1899 message,
1900 transfer,
1901 )
1902 }
1903
1904 fn CaptureEvents(&self) {
1906 }
1908
1909 fn ReleaseEvents(&self) {
1911 }
1913
1914 fn WebdriverElement(&self, id: DOMString) -> Option<DomRoot<Element>> {
1915 find_node_by_unique_id_in_document(&self.Document(), id.into()).and_then(Root::downcast)
1916 }
1917
1918 fn WebdriverFrame(&self, browsing_context_id: DOMString) -> Option<DomRoot<WindowProxy>> {
1919 self.Document()
1920 .iframes()
1921 .iter()
1922 .find(|iframe| {
1923 iframe
1924 .browsing_context_id()
1925 .as_ref()
1926 .map(BrowsingContextId::to_string) ==
1927 Some(browsing_context_id.to_string())
1928 })
1929 .and_then(|iframe| iframe.GetContentWindow())
1930 }
1931
1932 fn WebdriverWindow(&self, webview_id: DOMString) -> DomRoot<WindowProxy> {
1933 let window_proxy = &self
1934 .window_proxy
1935 .get()
1936 .expect("Should always have a WindowProxy when calling WebdriverWindow");
1937 assert!(
1938 self.is_top_level(),
1939 "Window must be top level browsing context."
1940 );
1941 assert!(self.webview_id().to_string() == webview_id);
1942 DomRoot::from_ref(window_proxy)
1943 }
1944
1945 fn WebdriverShadowRoot(&self, id: DOMString) -> Option<DomRoot<ShadowRoot>> {
1946 find_node_by_unique_id_in_document(&self.Document(), id.into()).and_then(Root::downcast)
1947 }
1948
1949 fn GetComputedStyle(
1951 &self,
1952 cx: &mut JSContext,
1953 element: &Element,
1954 pseudo: Option<DOMString>,
1955 ) -> DomRoot<CSSStyleDeclaration> {
1956 let mut is_null = false;
1960
1961 let pseudo = pseudo.map(|mut s| {
1967 s.make_ascii_lowercase();
1968 s
1969 });
1970 let pseudo = match pseudo {
1971 Some(ref pseudo) if pseudo == ":before" || pseudo == "::before" => {
1972 Some(PseudoElement::Before)
1973 },
1974 Some(ref pseudo) if pseudo == ":after" || pseudo == "::after" => {
1975 Some(PseudoElement::After)
1976 },
1977 Some(ref pseudo) if pseudo == "::selection" => Some(PseudoElement::Selection),
1978 Some(ref pseudo) if pseudo == "::marker" => Some(PseudoElement::Marker),
1979 Some(ref pseudo) if pseudo == "::placeholder" => Some(PseudoElement::Placeholder),
1980 Some(ref pseudo) if pseudo.starts_with(':') => {
1981 is_null = true;
1984 None
1985 },
1986 _ => None,
1987 };
1988
1989 CSSStyleDeclaration::new(
2005 cx,
2006 self,
2007 if is_null {
2008 CSSStyleOwner::Null
2009 } else {
2010 CSSStyleOwner::Element(Dom::from_ref(element))
2011 },
2012 pseudo,
2013 CSSModificationAccess::Readonly,
2014 )
2015 }
2016
2017 fn InnerHeight(&self) -> i32 {
2020 self.viewport_details
2021 .get()
2022 .size
2023 .height
2024 .to_i32()
2025 .unwrap_or(0)
2026 }
2027
2028 fn InnerWidth(&self) -> i32 {
2031 self.viewport_details.get().size.width.to_i32().unwrap_or(0)
2032 }
2033
2034 fn ScrollX(&self) -> i32 {
2036 self.scroll_offset().x as i32
2037 }
2038
2039 fn PageXOffset(&self) -> i32 {
2041 self.ScrollX()
2042 }
2043
2044 fn ScrollY(&self) -> i32 {
2046 self.scroll_offset().y as i32
2047 }
2048
2049 fn PageYOffset(&self) -> i32 {
2051 self.ScrollY()
2052 }
2053
2054 fn Scroll(&self, cx: &mut JSContext, options: &ScrollToOptions) {
2056 let x = options.left.unwrap_or(0.0) as f32;
2061
2062 let y = options.top.unwrap_or(0.0) as f32;
2065
2066 self.scroll(cx, x, y, options.parent.behavior);
2068 }
2069
2070 fn Scroll_(&self, cx: &mut JSContext, x: f64, y: f64) {
2072 self.scroll(cx, x as f32, y as f32, ScrollBehavior::Auto);
2076 }
2077
2078 fn ScrollTo(&self, cx: &mut JSContext, options: &ScrollToOptions) {
2083 self.Scroll(cx, options);
2084 }
2085
2086 fn ScrollTo_(&self, cx: &mut JSContext, x: f64, y: f64) {
2091 self.Scroll_(cx, x, y)
2092 }
2093
2094 fn ScrollBy(&self, cx: &mut JSContext, options: &ScrollToOptions) {
2096 let mut options = options.clone();
2102 let x = options.left.unwrap_or(0.0);
2103 let x = if x.is_finite() { x } else { 0.0 };
2104 let y = options.top.unwrap_or(0.0);
2105 let y = if y.is_finite() { y } else { 0.0 };
2106
2107 options.left.replace(x + self.ScrollX() as f64);
2109
2110 options.top.replace(y + self.ScrollY() as f64);
2112
2113 self.Scroll(cx, &options)
2115 }
2116
2117 fn ScrollBy_(&self, cx: &mut JSContext, x: f64, y: f64) {
2119 let mut options = ScrollToOptions::empty();
2123
2124 options.left.replace(x);
2127
2128 options.top.replace(y);
2130
2131 self.ScrollBy(cx, &options);
2133 }
2134
2135 fn ResizeTo(&self, width: i32, height: i32) {
2137 let window_proxy = match self.window_proxy.get() {
2139 Some(proxy) => proxy,
2140 None => return,
2141 };
2142
2143 if !window_proxy.is_auxiliary() {
2146 return;
2147 }
2148
2149 let dpr = self.device_pixel_ratio();
2150 let size = Size2D::new(width, height).to_f32() * dpr;
2151 self.send_to_embedder(EmbedderMsg::ResizeTo(self.webview_id(), size.to_i32()));
2152 }
2153
2154 fn ResizeBy(&self, x: i32, y: i32) {
2156 let size = self.client_window().size();
2157 self.ResizeTo(x + size.width, y + size.height)
2159 }
2160
2161 fn MoveTo(&self, x: i32, y: i32) {
2163 let dpr = self.device_pixel_ratio();
2166 let point = Point2D::new(x, y).to_f32() * dpr;
2167 let msg = EmbedderMsg::MoveTo(self.webview_id(), point.to_i32());
2168 self.send_to_embedder(msg);
2169 }
2170
2171 fn MoveBy(&self, x: i32, y: i32) {
2173 let origin = self.client_window().min;
2174 self.MoveTo(x + origin.x, y + origin.y)
2176 }
2177
2178 fn ScreenX(&self) -> i32 {
2180 self.client_window().min.x
2181 }
2182
2183 fn ScreenLeft(&self) -> i32 {
2185 self.client_window().min.x
2186 }
2187
2188 fn ScreenY(&self) -> i32 {
2190 self.client_window().min.y
2191 }
2192
2193 fn ScreenTop(&self) -> i32 {
2195 self.client_window().min.y
2196 }
2197
2198 fn OuterHeight(&self) -> i32 {
2200 self.client_window().height()
2201 }
2202
2203 fn OuterWidth(&self) -> i32 {
2205 self.client_window().width()
2206 }
2207
2208 fn DevicePixelRatio(&self) -> Finite<f64> {
2210 Finite::wrap(self.device_pixel_ratio().get() as f64)
2211 }
2212
2213 fn Status(&self) -> DOMString {
2215 self.status.borrow().clone()
2216 }
2217
2218 fn SetStatus(&self, status: DOMString) {
2220 *self.status.borrow_mut() = status
2221 }
2222
2223 fn MatchMedia(&self, cx: &mut JSContext, query: DOMString) -> DomRoot<MediaQueryList> {
2225 let media_query_list = MediaList::parse_media_list(&query.str(), self);
2226 let document = self.Document();
2227 let mql = MediaQueryList::new(cx, &document, media_query_list);
2228 self.media_query_lists.track(&*mql);
2229 mql
2230 }
2231
2232 fn Fetch(
2234 &self,
2235 realm: &mut CurrentRealm,
2236 input: RequestOrUSVString,
2237 init: RootedTraceableBox<RequestInit>,
2238 ) -> Rc<Promise> {
2239 fetch::Fetch(self.upcast(), input, init, realm)
2240 }
2241
2242 fn FetchLater(
2244 &self,
2245 cx: &mut JSContext,
2246 input: RequestInfo,
2247 init: RootedTraceableBox<DeferredRequestInit>,
2248 ) -> Fallible<DomRoot<FetchLaterResult>> {
2249 fetch::FetchLater(cx, self, input, init)
2250 }
2251
2252 #[cfg(feature = "bluetooth")]
2253 fn TestRunner(&self, cx: &mut JSContext) -> DomRoot<TestRunner> {
2254 self.test_runner
2255 .or_init(|| TestRunner::new(cx, self.upcast()))
2256 }
2257
2258 fn RunningAnimationCount(&self) -> u32 {
2259 self.document
2260 .get()
2261 .map_or(0, |d| d.animations().running_animation_count() as u32)
2262 }
2263
2264 fn SetName(&self, name: DOMString) {
2266 if let Some(proxy) = self.undiscarded_window_proxy() {
2267 proxy.set_name(name);
2268 }
2269 }
2270
2271 fn Name(&self) -> DOMString {
2273 match self.undiscarded_window_proxy() {
2274 Some(proxy) => proxy.get_name(),
2275 None => "".into(),
2276 }
2277 }
2278
2279 fn Origin(&self) -> USVString {
2281 USVString(self.origin().immutable().ascii_serialization().into_owned())
2282 }
2283
2284 fn GetSelection(&self, cx: &mut JSContext) -> Option<DomRoot<Selection>> {
2286 self.document.get().and_then(|d| d.GetSelection(cx))
2287 }
2288
2289 fn Event(&self, cx: &mut JSContext, rval: MutableHandleValue) {
2291 if let Some(ref event) = *self.current_event.borrow() {
2292 event.reflector().get_jsobject().to_jsval(cx, rval);
2293 }
2294 }
2295
2296 fn IsSecureContext(&self) -> bool {
2297 self.as_global_scope().is_secure_context()
2298 }
2299
2300 fn NamedGetter(&self, cx: &mut JSContext, name: DOMString) -> Option<NamedPropertyValue> {
2302 if name.is_empty() {
2303 return None;
2304 }
2305 let document = self.Document();
2306
2307 let iframes: Vec<_> = document
2309 .iframes()
2310 .iter()
2311 .filter(|iframe| {
2312 if let Some(window) = iframe.GetContentWindow() {
2313 return window.get_name() == name;
2314 }
2315 false
2316 })
2317 .collect();
2318
2319 let iframe_iter = iframes.iter().map(|iframe| iframe.upcast::<Element>());
2320
2321 let name = Atom::from(name);
2322
2323 let elements_with_name = document.get_elements_with_name(cx, &name);
2325 let name_iter = elements_with_name
2326 .iter()
2327 .map(|element| &**element)
2328 .filter(|elem| is_named_element_with_name_attribute(elem));
2329
2330 let elements_with_id = document.get_elements_with_id(cx, &name);
2331 let id_iter = elements_with_id
2332 .iter()
2333 .map(|element| &**element)
2334 .filter(|elem| is_named_element_with_id_attribute(elem));
2335
2336 for elem in iframe_iter.clone() {
2338 if let Some(nested_window_proxy) = elem
2339 .downcast::<HTMLIFrameElement>()
2340 .and_then(|iframe| iframe.GetContentWindow())
2341 {
2342 return Some(NamedPropertyValue::WindowProxy(nested_window_proxy));
2343 }
2344 }
2345
2346 let mut elements = iframe_iter.chain(name_iter).chain(id_iter);
2347
2348 let first = elements.next()?;
2349
2350 if elements.next().is_none() {
2351 return Some(NamedPropertyValue::Element(DomRoot::from_ref(first)));
2353 }
2354
2355 #[derive(JSTraceable, MallocSizeOf)]
2357 struct WindowNamedGetter {
2358 #[no_trace]
2359 name: Atom,
2360 }
2361 impl CollectionFilter for WindowNamedGetter {
2362 fn filter(&self, elem: &Element, _root: &Node) -> bool {
2363 let type_ = match elem.upcast::<Node>().type_id() {
2364 NodeTypeId::Element(ElementTypeId::HTMLElement(type_)) => type_,
2365 _ => return false,
2366 };
2367 if elem.get_id().as_ref() == Some(&self.name) {
2368 return true;
2369 }
2370 match type_ {
2371 HTMLElementTypeId::HTMLEmbedElement |
2372 HTMLElementTypeId::HTMLFormElement |
2373 HTMLElementTypeId::HTMLImageElement |
2374 HTMLElementTypeId::HTMLObjectElement => {
2375 elem.get_name().as_ref() == Some(&self.name)
2376 },
2377 _ => false,
2378 }
2379 }
2380 }
2381 let collection = HTMLCollection::create(
2382 cx,
2383 self,
2384 document.upcast(),
2385 Box::new(WindowNamedGetter { name }),
2386 );
2387 Some(NamedPropertyValue::HTMLCollection(collection))
2388 }
2389
2390 fn SupportedPropertyNames(&self, no_gc: &NoGC) -> Vec<DOMString> {
2392 self.Document().SupportedPropertyNames(no_gc)
2393 }
2394
2395 fn StructuredClone(
2397 &self,
2398 cx: &mut JSContext,
2399 value: HandleValue,
2400 options: RootedTraceableBox<StructuredSerializeOptions>,
2401 retval: MutableHandleValue,
2402 ) -> Fallible<()> {
2403 self.as_global_scope()
2404 .structured_clone(cx, value, options, retval)
2405 }
2406
2407 fn TrustedTypes(&self, cx: &mut JSContext) -> DomRoot<TrustedTypePolicyFactory> {
2408 self.trusted_types
2409 .or_init(|| TrustedTypePolicyFactory::new(cx, self.as_global_scope()))
2410 }
2411}
2412
2413impl Window {
2414 pub(crate) fn scroll_offset(&self) -> Vector2D<f32, LayoutPixel> {
2415 self.scroll_offset_query_with_external_scroll_id(self.pipeline_id().root_scroll_id())
2416 }
2417
2418 pub(crate) fn create_named_properties_object(
2421 cx: &mut JSContext,
2422 proto: HandleObject,
2423 object: MutableHandleObject,
2424 ) {
2425 window_named_properties::create(cx, proto, object)
2426 }
2427
2428 pub(crate) fn current_event(&self) -> Option<DomRoot<Event>> {
2429 self.current_event
2430 .borrow()
2431 .as_ref()
2432 .map(|e| DomRoot::from_ref(&**e))
2433 }
2434
2435 pub(crate) fn set_current_event(&self, event: Option<&Event>) -> Option<DomRoot<Event>> {
2436 let current = self.current_event();
2437 *self.current_event.borrow_mut() = event.map(Dom::from_ref);
2438 current
2439 }
2440
2441 fn post_message_impl(
2443 &self,
2444 target_origin: &USVString,
2445 source_origin: ImmutableOrigin,
2446 source: &Window,
2447 cx: &mut JSContext,
2448 message: HandleValue,
2449 transfer: CustomAutoRooterGuard<Vec<*mut JSObject>>,
2450 ) -> ErrorResult {
2451 let data = structuredclone::write(cx, message, Some(transfer))?;
2453
2454 let target_origin = match target_origin.0[..].as_ref() {
2456 "*" => None,
2457 "/" => Some(source_origin.clone()),
2458 url => match ServoUrl::parse(url) {
2459 Ok(url) => Some(url.origin()),
2460 Err(_) => return Err(Error::Syntax(None)),
2461 },
2462 };
2463
2464 self.post_message(target_origin, source_origin, &source.window_proxy(), data);
2466 Ok(())
2467 }
2468
2469 pub(crate) fn paint_worklet(&self, cx: &mut JSContext) -> DomRoot<Worklet> {
2471 self.paint_worklet.or_init(|| self.new_paint_worklet(cx))
2472 }
2473
2474 pub(crate) fn clear_js_runtime(&self) {
2475 self.as_global_scope()
2476 .remove_web_messaging_and_dedicated_workers_infra();
2477
2478 self.Document().teardown_custom_element_registry();
2481
2482 self.current_state.set(WindowState::Zombie);
2483 *self.js_runtime.borrow_mut() = None;
2484
2485 if let Some(performance) = self.performance.get() {
2486 performance.clear_and_disable_performance_entry_buffer();
2487 }
2488
2489 self.as_global_scope()
2490 .task_manager()
2491 .cancel_all_tasks_and_ignore_future_tasks();
2492
2493 if let Some(factory) = self.upcast::<GlobalScope>().indexeddb_factory() {
2498 factory.abort_pending_upgrades_and_close_databases();
2499 }
2500
2501 self.pending_image_callbacks.borrow_mut().clear();
2504 }
2505
2506 pub(crate) fn scroll(&self, cx: &mut JSContext, x: f32, y: f32, behavior: ScrollBehavior) {
2508 let xfinite = if x.is_finite() { x } else { 0.0 };
2510 let yfinite = if y.is_finite() { y } else { 0.0 };
2511
2512 let viewport = self.viewport_details.get().size;
2522
2523 let scrolling_area = self.scrolling_area_query(None).to_f32();
2542 let x = xfinite.clamp(0.0, 0.0f32.max(scrolling_area.width() - viewport.width));
2543 let y = yfinite.clamp(0.0, 0.0f32.max(scrolling_area.height() - viewport.height));
2544
2545 let scroll_offset = self.scroll_offset();
2548 if x == scroll_offset.x && y == scroll_offset.y {
2549 return;
2550 }
2551
2552 self.perform_a_scroll(
2557 cx,
2558 x,
2559 y,
2560 self.pipeline_id().root_scroll_id(),
2561 behavior,
2562 None,
2563 );
2564 }
2565
2566 pub(crate) fn perform_a_scroll(
2568 &self,
2569 cx: &mut JSContext,
2570 x: f32,
2571 y: f32,
2572 scroll_id: ExternalScrollId,
2573 _behavior: ScrollBehavior,
2574 element: Option<&Element>,
2575 ) {
2576 let (reflow_phases_run, _) = self.reflow(
2580 cx,
2581 ReflowGoal::UpdateScrollNode(scroll_id, Vector2D::new(x, y)),
2582 );
2583 if reflow_phases_run.needs_frame() {
2584 self.paint_api()
2585 .generate_frame(vec![self.webview_id().into()]);
2586 }
2587
2588 if reflow_phases_run.contains(ReflowPhasesRun::UpdatedScrollNodeOffset) {
2593 match element {
2594 Some(element) if !scroll_id.is_root() => element.handle_scroll_event(),
2595 _ => self.Document().handle_viewport_scroll_event(),
2596 };
2597 }
2598 }
2599
2600 pub(crate) fn device_pixel_ratio(&self) -> Scale<f32, CSSPixel, DevicePixel> {
2601 self.viewport_details.get().hidpi_scale_factor
2602 }
2603
2604 fn client_window(&self) -> DeviceIndependentIntRect {
2605 let (sender, receiver) = generic_channel::channel().expect("Failed to create IPC channel!");
2606
2607 self.send_to_embedder(EmbedderMsg::GetWindowRect(self.webview_id(), sender));
2608
2609 receiver.recv().unwrap_or_default()
2610 }
2611
2612 pub(crate) fn advance_animation_clock(&self, no_gc: &NoGC, delta: TimeDuration) {
2615 self.Document()
2616 .advance_animation_timeline_for_testing(delta);
2617 ScriptThread::handle_tick_all_animations_for_testing(no_gc, self.pipeline_id());
2618 }
2619
2620 pub(crate) fn reflow(
2628 &self,
2629 cx: &mut JSContext,
2630 reflow_goal: ReflowGoal,
2631 ) -> (ReflowPhasesRun, ReflowStatistics) {
2632 let document = self.Document();
2633
2634 if !document.is_fully_active() {
2636 return Default::default();
2637 }
2638
2639 self.document_unrooted(cx.no_gc())
2640 .ensure_safe_to_run_script_or_layout();
2641
2642 match reflow_goal {
2646 ReflowGoal::LayoutQuery(_) | ReflowGoal::UpdateScrollNode(..) => {
2647 self.flush_ancestor_layouts_if_necessary(cx);
2648 },
2649 ReflowGoal::UpdateTheRendering => { },
2650 }
2651
2652 let pipeline_id = self.pipeline_id();
2656 if reflow_goal == ReflowGoal::UpdateTheRendering &&
2657 self.layout_blocker.get().layout_blocked()
2658 {
2659 debug!("Suppressing pre-load-event reflow pipeline {pipeline_id}");
2660 return Default::default();
2661 }
2662
2663 debug!("script: performing reflow for goal {reflow_goal:?}");
2664 let marker = if self.need_emit_timeline_marker(TimelineMarkerType::Reflow) {
2665 Some(TimelineMarker::start("Reflow".to_owned()))
2666 } else {
2667 None
2668 };
2669
2670 if let Some(selection) = document.selection() {
2671 selection.update_overlaps_document_selection_flags(cx.no_gc());
2672 }
2673
2674 let restyle_reason = document.restyle_reason(cx.no_gc());
2675 document.clear_restyle_reasons();
2676 let restyle = if restyle_reason.needs_restyle() {
2677 debug!("Invalidating layout cache due to reflow condition {restyle_reason:?}",);
2678 self.layout_marker.borrow().set(false);
2680 *self.layout_marker.borrow_mut() = Rc::new(Cell::new(true));
2682
2683 if restyle_reason.contains(RestyleReason::ViewportChanged) &&
2687 self.layout().device().used_viewport_size()
2688 {
2689 document.dirty_all_nodes(cx.no_gc());
2690 }
2691
2692 let stylesheets_changed = document.flush_stylesheets_for_reflow();
2693 let pending_restyles = document.drain_pending_restyles(cx.no_gc());
2694 let dirty_root = document
2695 .take_dirty_root()
2696 .filter(|_| !stylesheets_changed)
2697 .or_else(|| document.GetDocumentElement())
2698 .map(|root| root.upcast::<Node>().to_trusted_node_address());
2699
2700 Some(ReflowRequestRestyle {
2701 reason: restyle_reason,
2702 dirty_root,
2703 stylesheets_changed,
2704 pending_restyles,
2705 })
2706 } else {
2707 None
2708 };
2709
2710 document.id_map().resolve_all(cx.no_gc(), document.upcast());
2713
2714 let document_context = self.web_font_context(cx.no_gc());
2715
2716 let mut rooted_nodes_for_accessibility_integrity_check = None;
2717 let mut accessibility_damage = None;
2718 if reflow_goal == ReflowGoal::UpdateTheRendering && self.layout().accessibility_active() {
2719 rooted_nodes_for_accessibility_integrity_check =
2720 document.rooted_nodes_for_accessibility_integrity_check();
2721 let mut accessibility_data = document.accessibility_data_mut();
2722 accessibility_damage = Some(accessibility_data.drain_pending_accessibility_damage());
2723 }
2724
2725 let reflow = ReflowRequest {
2727 document: document.upcast::<Node>().to_trusted_node_address(),
2728 epoch: document.current_rendering_epoch(),
2729 restyle,
2730 viewport_details: self.viewport_details.get(),
2731 origin: self.origin().immutable().clone(),
2732 reflow_goal,
2733 animation_timeline_value: document.current_animation_timeline_value(),
2734 animations: document.animations().sets.clone(),
2735 animating_images: document.image_animation_manager().animating_images(),
2736 highlighted_dom_node: document.highlighted_dom_node().map(|node| node.to_opaque()),
2737 halt_lcp: self.has_dispatched_scroll_event.get() ||
2738 self.has_dispatched_input_event.get(),
2739 document_context,
2740 accessibility_damage,
2741 rooted_nodes_for_accessibility_integrity_check,
2742 };
2743
2744 let Some(reflow_result) = self.layout.borrow_mut().reflow(reflow) else {
2745 return Default::default();
2746 };
2747
2748 debug!("script: layout complete");
2749 if let Some(marker) = marker {
2750 self.emit_timeline_marker(marker.end());
2751 }
2752
2753 self.handle_new_or_removed_web_fonts_post_reflow(cx, reflow_result.changed_web_fonts);
2754
2755 self.handle_pending_images_post_reflow(
2756 cx,
2757 reflow_result.pending_images,
2758 reflow_result.pending_rasterization_images,
2759 reflow_result.pending_svg_elements_for_serialization,
2760 );
2761
2762 if let Some(candidate) = &reflow_result.lcp_candidate &&
2763 let Some(node_address) = reflow_result.lcp_node_address
2764 {
2765 self.process_lcp_candidate_post_reflow(candidate, node_address, &document);
2766 }
2767
2768 if let Some(iframe_sizes) = reflow_result.iframe_sizes {
2769 document
2770 .iframes_mut()
2771 .handle_new_iframe_sizes_after_layout(cx, self, iframe_sizes);
2772 }
2773
2774 document.update_animations_post_reflow();
2775
2776 (
2777 reflow_result.reflow_phases_run,
2778 reflow_result.reflow_statistics,
2779 )
2780 }
2781
2782 pub(crate) fn request_screenshot_readiness(&self, cx: &mut JSContext) {
2783 self.has_pending_screenshot_readiness_request.set(true);
2784 self.maybe_resolve_pending_screenshot_readiness_requests(cx);
2785 }
2786
2787 pub(crate) fn maybe_resolve_pending_screenshot_readiness_requests(&self, cx: &mut JSContext) {
2788 let pending_request = self.has_pending_screenshot_readiness_request.get();
2789 if !pending_request {
2790 return;
2791 }
2792
2793 let document = self.Document();
2794 if document.ReadyState() != DocumentReadyState::Complete {
2795 return;
2796 }
2797
2798 if document.render_blocking_element_count() > 0 {
2799 return;
2800 }
2801
2802 if document.GetDocumentElement().is_some_and(|elem| {
2806 elem.has_class(&atom!("reftest-wait"), CaseSensitivity::CaseSensitive) ||
2807 elem.has_class(&Atom::from("test-wait"), CaseSensitivity::CaseSensitive)
2808 }) {
2809 return;
2810 }
2811
2812 if self.font_context().web_fonts_still_loading() != 0 {
2813 return;
2814 }
2815
2816 if self.Document().Fonts(cx).waiting_to_fullfill_promise() {
2817 return;
2818 }
2819
2820 if !self.pending_layout_images.borrow().is_empty() ||
2821 !self.pending_images_for_rasterization.borrow().is_empty()
2822 {
2823 return;
2824 }
2825
2826 let document = self.Document();
2827 if document.needs_rendering_update(cx.no_gc()) {
2828 return;
2829 }
2830
2831 let epoch = document.current_rendering_epoch();
2834 let pipeline_id = self.pipeline_id();
2835 debug!("Ready to take screenshot of {pipeline_id:?} at epoch={epoch:?}");
2836
2837 self.send_to_constellation(
2838 ScriptToConstellationMessage::RespondToScreenshotReadinessRequest(
2839 ScreenshotReadinessResponse::Ready(epoch),
2840 ),
2841 );
2842 self.has_pending_screenshot_readiness_request.set(false);
2843 }
2844
2845 pub(crate) fn reflow_if_reflow_timer_expired(&self, cx: &mut JSContext) {
2848 if !matches!(
2851 self.layout_blocker.get(),
2852 LayoutBlocker::Parsing(instant) if instant + INITIAL_REFLOW_DELAY < Instant::now()
2853 ) {
2854 return;
2855 }
2856 self.allow_layout_if_necessary(cx);
2857 }
2858
2859 pub(crate) fn prevent_layout_until_load_event(&self) {
2863 if !matches!(self.layout_blocker.get(), LayoutBlocker::WaitingForParse) {
2866 return;
2867 }
2868
2869 self.layout_blocker
2870 .set(LayoutBlocker::Parsing(Instant::now()));
2871 }
2872
2873 pub(crate) fn allow_layout_if_necessary(&self, cx: &mut JSContext) {
2876 if matches!(
2877 self.layout_blocker.get(),
2878 LayoutBlocker::FiredLoadEventOrParsingTimerExpired
2879 ) {
2880 return;
2881 }
2882
2883 self.layout_blocker
2884 .set(LayoutBlocker::FiredLoadEventOrParsingTimerExpired);
2885
2886 let document = self.Document();
2898 if !document.is_render_blocked() && document.update_the_rendering(cx).0.needs_frame() {
2899 self.paint_api()
2900 .generate_frame(vec![self.webview_id().into()]);
2901 }
2902 }
2903
2904 pub(crate) fn layout_blocked(&self) -> bool {
2905 self.layout_blocker.get().layout_blocked()
2906 }
2907
2908 fn flush_ancestor_layouts_if_necessary(&self, cx: &mut JSContext) {
2909 let Some(parent_pipeline_id) = self.parent_info else {
2910 return;
2911 };
2912 let Some(parent_window) = ScriptThread::find_window(parent_pipeline_id) else {
2913 return;
2914 };
2915 if !parent_window.Document().is_safe_to_run_script_or_layout() {
2918 return;
2919 }
2920 if parent_window.Document().is_render_blocked() {
2923 return;
2924 }
2925 parent_window.flush_ancestor_layouts_if_necessary(cx);
2926 if parent_window
2927 .document_unrooted(cx.no_gc())
2928 .restyle_reason(cx.no_gc())
2929 .needs_restyle()
2930 {
2931 parent_window.reflow(
2932 cx,
2933 ReflowGoal::LayoutQuery(QueryMsg::FlushForUpdateTheRenderingQuery),
2934 );
2935 }
2936 }
2937
2938 #[expect(unsafe_code)]
2940 pub(crate) fn layout_reflow(&self, query_msg: QueryMsg) {
2941 let mut cx = unsafe { script_bindings::script_runtime::temp_cx() };
2943
2944 self.reflow(&mut cx, ReflowGoal::LayoutQuery(query_msg));
2945 }
2946
2947 pub(crate) fn reflow_for_non_flushing_update_the_rendering_queries(&self, cx: &mut JSContext) {
2949 self.reflow(
2950 cx,
2951 ReflowGoal::LayoutQuery(QueryMsg::FlushForUpdateTheRenderingQuery),
2952 );
2953 }
2954
2955 pub(crate) fn resolved_font_style_query(
2956 &self,
2957 node: &Node,
2958 value: String,
2959 ) -> Option<ServoArc<Font>> {
2960 self.layout_reflow(QueryMsg::ResolvedFontStyleQuery);
2961
2962 let document = self.Document();
2963 let animations = document.animations().sets.clone();
2964 self.layout.borrow().query_resolved_font_style(
2965 node.to_trusted_node_address(),
2966 &value,
2967 animations,
2968 document.current_animation_timeline_value(),
2969 )
2970 }
2971
2972 #[expect(unsafe_code)]
2975 pub(crate) fn containing_block_node_query_without_reflow(
2976 &self,
2977 node: &Node,
2978 ) -> Option<DomRoot<Node>> {
2979 self.layout
2980 .borrow()
2981 .query_containing_block(node.to_trusted_node_address())
2982 .map(|address| unsafe { from_untrusted_node_address(address) })
2983 }
2984
2985 pub(crate) fn is_containing_block_descendant_query_without_reflow(
2988 &self,
2989 possible_ancestor: &Node,
2990 possible_descendant: &Node,
2991 ) -> bool {
2992 self.layout.borrow().query_containing_block_is_descendant(
2993 possible_ancestor.to_trusted_node_address(),
2994 possible_descendant.to_trusted_node_address(),
2995 )
2996 }
2997
2998 pub(crate) fn padding_query_without_reflow(&self, node: &Node) -> Option<PhysicalSides> {
3003 let layout = self.layout.borrow();
3004 layout.query_padding(node.to_trusted_node_address())
3005 }
3006
3007 pub(crate) fn box_area_query_without_reflow(
3012 &self,
3013 node: &Node,
3014 area: BoxAreaType,
3015 exclude_transform_and_inline: bool,
3016 ) -> Option<Rect<Au, CSSPixel>> {
3017 let layout = self.layout.borrow();
3018 layout.ensure_stacking_context_tree(self.viewport_details.get());
3019 layout.query_box_area(
3020 node.to_trusted_node_address(),
3021 area,
3022 exclude_transform_and_inline,
3023 )
3024 }
3025
3026 pub(crate) fn box_area_query(
3027 &self,
3028 node: &Node,
3029 area: BoxAreaType,
3030 exclude_transform_and_inline: bool,
3031 ) -> Option<Rect<Au, CSSPixel>> {
3032 self.layout_reflow(QueryMsg::BoxArea);
3033 self.box_area_query_without_reflow(node, area, exclude_transform_and_inline)
3034 }
3035
3036 pub(crate) fn box_areas_query(&self, node: &Node, area: BoxAreaType) -> CSSPixelRectVec {
3037 self.layout_reflow(QueryMsg::BoxAreas);
3038 self.layout
3039 .borrow()
3040 .query_box_areas(node.to_trusted_node_address(), area)
3041 }
3042
3043 pub(crate) fn client_rect_query(&self, node: &Node) -> Rect<i32, CSSPixel> {
3044 self.layout_reflow(QueryMsg::ClientRectQuery);
3045 self.layout
3046 .borrow()
3047 .query_client_rect(node.to_trusted_node_address())
3048 }
3049
3050 pub(crate) fn current_css_zoom_query(&self, node: &Node) -> f32 {
3051 self.layout_reflow(QueryMsg::CurrentCSSZoomQuery);
3052 self.layout
3053 .borrow()
3054 .query_current_css_zoom(node.to_trusted_node_address())
3055 }
3056
3057 pub(crate) fn document_unrooted<'a>(&self, no_gc: &'a NoGC) -> UnrootedDom<'a, Document> {
3059 self.document
3060 .get_unrooted(no_gc)
3061 .expect("Document accessed before initialization.")
3062 }
3063
3064 pub(crate) fn scrolling_area_query(&self, node: Option<&Node>) -> Rect<i32, CSSPixel> {
3067 self.layout_reflow(QueryMsg::ScrollingAreaOrOffsetQuery);
3068 self.layout
3069 .borrow()
3070 .query_scrolling_area(node.map(Node::to_trusted_node_address))
3071 }
3072
3073 pub(crate) fn scroll_offset_query(&self, node: &Node) -> Vector2D<f32, LayoutPixel> {
3074 let external_scroll_id = ExternalScrollId(
3075 combine_id_with_fragment_type(node.to_opaque().id(), FragmentType::FragmentBody),
3076 self.pipeline_id().into(),
3077 );
3078 self.scroll_offset_query_with_external_scroll_id(external_scroll_id)
3079 }
3080
3081 fn scroll_offset_query_with_external_scroll_id(
3082 &self,
3083 external_scroll_id: ExternalScrollId,
3084 ) -> Vector2D<f32, LayoutPixel> {
3085 self.layout_reflow(QueryMsg::ScrollingAreaOrOffsetQuery);
3086 self.scroll_offset_query_with_external_scroll_id_no_reflow(external_scroll_id)
3087 }
3088
3089 fn scroll_offset_query_with_external_scroll_id_no_reflow(
3090 &self,
3091 external_scroll_id: ExternalScrollId,
3092 ) -> Vector2D<f32, LayoutPixel> {
3093 self.layout
3094 .borrow()
3095 .scroll_offset(external_scroll_id)
3096 .unwrap_or_default()
3097 }
3098
3099 pub(crate) fn scroll_an_element(
3102 &self,
3103 cx: &mut JSContext,
3104 element: &Element,
3105 x: f32,
3106 y: f32,
3107 behavior: ScrollBehavior,
3108 ) {
3109 let scroll_id = ExternalScrollId(
3110 combine_id_with_fragment_type(
3111 element.upcast::<Node>().to_opaque().id(),
3112 FragmentType::FragmentBody,
3113 ),
3114 self.pipeline_id().into(),
3115 );
3116
3117 self.perform_a_scroll(cx, x, y, scroll_id, behavior, Some(element));
3121 }
3122
3123 pub(crate) fn resolved_style_query(
3124 &self,
3125 element: TrustedNodeAddress,
3126 pseudo: Option<PseudoElement>,
3127 property: PropertyId,
3128 ) -> DOMString {
3129 self.layout_reflow(QueryMsg::ResolvedStyleQuery(property.clone()));
3130
3131 let document = self.Document();
3132 let animations = document.animations().sets.clone();
3133 DOMString::from(self.layout.borrow().query_resolved_style(
3134 element,
3135 pseudo,
3136 property,
3137 animations,
3138 document.current_animation_timeline_value(),
3139 ))
3140 }
3141
3142 pub(crate) fn get_iframe_viewport_details_if_known(
3146 &self,
3147 browsing_context_id: BrowsingContextId,
3148 ) -> Option<ViewportDetails> {
3149 self.layout_reflow(QueryMsg::InnerWindowDimensionsQuery);
3151 self.Document()
3152 .iframes()
3153 .get(browsing_context_id)
3154 .and_then(|iframe| iframe.size)
3155 }
3156
3157 #[expect(unsafe_code)]
3158 pub(crate) fn offset_parent_query(
3159 &self,
3160 node: &Node,
3161 ) -> (Option<DomRoot<Element>>, Rect<Au, CSSPixel>) {
3162 self.layout_reflow(QueryMsg::OffsetParentQuery);
3163 let response = self
3164 .layout
3165 .borrow()
3166 .query_offset_parent(node.to_trusted_node_address());
3167 let element = response.node_address.and_then(|parent_node_address| {
3168 let node = unsafe { from_untrusted_node_address(parent_node_address) };
3169 DomRoot::downcast(node)
3170 });
3171 (element, response.rect)
3172 }
3173
3174 pub(crate) fn scroll_container_query(
3175 &self,
3176 node: Option<&Node>,
3177 flags: ScrollContainerQueryFlags,
3178 ) -> Option<ScrollContainerResponse> {
3179 self.layout_reflow(QueryMsg::ScrollParentQuery);
3180 self.layout
3181 .borrow()
3182 .query_scroll_container(node.map(Node::to_trusted_node_address), flags)
3183 }
3184
3185 #[expect(unsafe_code)]
3186 pub(crate) fn scrolling_box_query(
3187 &self,
3188 node: Option<&Node>,
3189 flags: ScrollContainerQueryFlags,
3190 ) -> Option<ScrollingBox> {
3191 self.scroll_container_query(node, flags)
3192 .and_then(|response| {
3193 Some(match response {
3194 ScrollContainerResponse::Viewport(overflow) => {
3195 (ScrollingBoxSource::Viewport(self.Document()), overflow)
3196 },
3197 ScrollContainerResponse::Element(parent_node_address, overflow) => {
3198 let node = unsafe { from_untrusted_node_address(parent_node_address) };
3199 (
3200 ScrollingBoxSource::Element(DomRoot::downcast(node)?),
3201 overflow,
3202 )
3203 },
3204 })
3205 })
3206 .map(|(source, overflow)| ScrollingBox::new(source, overflow))
3207 }
3208
3209 #[expect(unsafe_code)]
3210 pub(crate) fn text_index_query_on_node_for_event(
3211 &self,
3212 node: &Node,
3213 point_in_viewport: Point2D<Au, CSSPixel>,
3214 ) -> Option<(DomRoot<Node>, Utf32CodeUnits)> {
3215 self.layout_reflow(QueryMsg::TextIndexQuery);
3216 let result = self
3217 .layout
3218 .borrow()
3219 .query_text_index(node.to_trusted_node_address(), point_in_viewport)?;
3220 let node = unsafe { from_untrusted_node_address(result.0.into()) };
3221 Some((node, result.1))
3222 }
3223
3224 pub(crate) fn elements_from_point_query(
3225 &self,
3226 flags: HitTestFlags,
3227 point: LayoutPoint,
3228 ) -> layout_api::HitTestResult {
3229 self.layout_reflow(QueryMsg::ElementsFromPoint);
3230 self.layout().hit_test(flags, point)
3231 }
3232
3233 pub(crate) fn query_effective_overflow(&self, node: &Node) -> Option<AxesOverflow> {
3234 self.layout_reflow(QueryMsg::EffectiveOverflow);
3235 self.query_effective_overflow_without_reflow(node)
3236 }
3237
3238 pub(crate) fn query_effective_overflow_without_reflow(
3239 &self,
3240 node: &Node,
3241 ) -> Option<AxesOverflow> {
3242 self.layout
3243 .borrow()
3244 .query_effective_overflow(node.to_trusted_node_address())
3245 }
3246
3247 pub(crate) fn hit_test_from_input_event(
3248 &self,
3249 flags: HitTestFlags,
3250 input_event: &ConstellationInputEvent,
3251 ) -> Option<HitTestResult> {
3252 self.hit_test_from_point_in_viewport(
3253 flags,
3254 input_event.hit_test_result.as_ref()?.point_in_viewport,
3255 )
3256 }
3257
3258 #[expect(unsafe_code)]
3259 pub(crate) fn hit_test_from_point_in_viewport(
3260 &self,
3261 flags: HitTestFlags,
3262 point_in_frame: Point2D<f32, CSSPixel>,
3263 ) -> Option<HitTestResult> {
3264 let result = self.elements_from_point_query(flags, point_in_frame.cast_unit());
3265 let item = result.items.into_iter().next()?;
3266
3267 let point_relative_to_initial_containing_block =
3268 point_in_frame + self.scroll_offset().cast_unit();
3269
3270 let from_opaque_node = |node: OpaqueNode| {
3273 let address = UntrustedNodeAddress(node.0 as *const c_void);
3274 unsafe { from_untrusted_node_address(address) }
3275 };
3276 Some(HitTestResult {
3277 node: from_opaque_node(item.node),
3278 dom_position_for_selection: result
3279 .dom_position_for_selection
3280 .map(|(node, offset)| (from_opaque_node(node), offset)),
3281 cursor: item.cursor,
3282 point_in_node: item.point_in_target,
3283 point_in_frame,
3284 point_relative_to_initial_containing_block,
3285 })
3286 }
3287
3288 pub(crate) fn init_window_proxy(&self, window_proxy: &WindowProxy) {
3289 assert!(
3290 self.window_proxy
3291 .get()
3292 .is_none_or(|current_proxy| &*current_proxy as *const WindowProxy == window_proxy)
3293 );
3294 self.window_proxy.set(Some(window_proxy));
3295 }
3296
3297 pub(crate) fn init_document(&self, document: &Document) {
3298 assert!(
3299 self.document
3300 .get()
3301 .is_none_or(|document| document.is_initial_about_blank())
3302 );
3303 assert!(document.window() == self);
3304 self.document.set(Some(document));
3305 self.update_jsprincipals_from_document(document);
3306 }
3307
3308 #[expect(unsafe_code)]
3315 pub(crate) fn update_jsprincipals_from_document(&self, document: &Document) {
3316 let realm = unsafe { GetObjectRealmOrNull(self.reflector().get_jsobject().get()) };
3317 let new_principals = ServoJSPrincipals::new::<crate::DomTypeHolder>(&document.origin());
3318 unsafe { SetRealmPrincipals(realm, new_principals.as_raw()) };
3319 }
3320
3321 pub(crate) fn load_data_for_document(
3322 &self,
3323 url: ServoUrl,
3324 pipeline_id: PipelineId,
3325 ) -> LoadData {
3326 let source_document = self.Document();
3327 let secure_context = if self.is_top_level() {
3328 None
3329 } else {
3330 Some(self.IsSecureContext())
3331 };
3332 LoadData::new(
3333 LoadOrigin::Script(self.origin().snapshot()),
3334 url,
3335 source_document.about_base_url(),
3336 Some(pipeline_id),
3337 Referrer::ReferrerUrl(source_document.url()),
3338 source_document.get_referrer_policy(),
3339 secure_context,
3340 Some(source_document.insecure_requests_policy()),
3341 source_document.has_trustworthy_ancestor_origin(),
3342 source_document.creation_sandboxing_flag_set_considering_parent_iframe(),
3343 )
3344 }
3345
3346 pub(crate) fn set_viewport_details(&self, viewport_details: ViewportDetails) {
3349 self.viewport_details.set(viewport_details);
3350 if !self.layout_mut().set_viewport_details(viewport_details) {
3351 return;
3352 }
3353 self.Document()
3354 .add_restyle_reason(RestyleReason::ViewportChanged);
3355 }
3356
3357 pub(crate) fn viewport_details(&self) -> ViewportDetails {
3358 self.viewport_details.get()
3359 }
3360
3361 pub(crate) fn get_or_init_visual_viewport(
3362 &self,
3363 cx: &mut JSContext,
3364 ) -> DomRoot<VisualViewport> {
3365 self.visual_viewport.or_init(|| {
3366 VisualViewport::new_from_layout_viewport(cx, self, self.viewport_details().size)
3367 })
3368 }
3369
3370 pub(crate) fn maybe_update_visual_viewport(
3372 &self,
3373 cx: &mut JSContext,
3374 pinch_zoom_infos: PinchZoomInfos,
3375 ) {
3376 if pinch_zoom_infos.rect == Rect::from_size(self.viewport_details().size) &&
3379 self.visual_viewport.get().is_none()
3380 {
3381 return;
3382 }
3383
3384 let visual_viewport = self.get_or_init_visual_viewport(cx);
3385 let changes = visual_viewport.update_from_pinch_zoom_infos(pinch_zoom_infos);
3386
3387 if changes.intersects(VisualViewportChanges::DimensionChanged) {
3388 self.has_changed_visual_viewport_dimension.set(true);
3389 }
3390 if changes.intersects(VisualViewportChanges::OffsetChanged) {
3391 visual_viewport.handle_scroll_event();
3392 }
3393 }
3394
3395 pub(crate) fn embedder_theme(&self) -> Theme {
3397 self.embedder_theme.get()
3398 }
3399
3400 pub(crate) fn set_embedder_theme(&self, new_theme: Theme) {
3402 self.embedder_theme.set(new_theme);
3403 self.refresh_theme();
3404 }
3405
3406 pub(crate) fn refresh_theme(&self) {
3407 let document = self.Document();
3408 let new_theme = document.theme().unwrap_or(self.embedder_theme.get());
3410 if !self.layout_mut().set_theme(new_theme) {
3411 return;
3412 }
3413 document.add_restyle_reason(RestyleReason::ThemeChanged);
3414 self.pending_media_query_evaluation.set(true);
3417 }
3418
3419 pub(crate) fn take_pending_media_query_evaluation(&self) -> bool {
3422 self.pending_media_query_evaluation.replace(false)
3423 }
3424
3425 pub(crate) fn has_pending_media_query_evaluation(&self) -> bool {
3426 self.pending_media_query_evaluation.get()
3427 }
3428
3429 pub(crate) fn get_url(&self) -> ServoUrl {
3430 self.Document().url()
3431 }
3432
3433 pub(crate) fn windowproxy_handler(&self) -> &'static WindowProxyHandler {
3434 self.dom_static.windowproxy_handler
3435 }
3436
3437 pub(crate) fn add_resize_event(&self, event: ViewportDetails, event_type: WindowSizeType) {
3438 if self.viewport_details() == event {
3439 return;
3440 }
3441
3442 self.set_viewport_details(event);
3444
3445 *self.unhandled_resize_event.borrow_mut() = Some((event, event_type))
3448 }
3449
3450 pub(crate) fn take_unhandled_resize_event(&self) -> Option<(ViewportDetails, WindowSizeType)> {
3451 self.unhandled_resize_event.borrow_mut().take()
3452 }
3453
3454 pub(crate) fn has_unhandled_resize_event(&self) -> bool {
3456 self.unhandled_resize_event.borrow().is_some()
3457 }
3458
3459 pub(crate) fn suspend(&self, cx: &mut JSContext) {
3460 self.as_global_scope().suspend();
3462
3463 if self.window_proxy().currently_active() == Some(self.global().pipeline_id()) {
3465 self.window_proxy().unset_currently_active(cx);
3466 }
3467
3468 self.gc(cx);
3473 }
3474
3475 pub(crate) fn resume(&self, cx: &mut JSContext) {
3476 self.as_global_scope().resume();
3478
3479 self.window_proxy().set_currently_active(cx, self);
3481
3482 self.Document().title_changed();
3485 }
3486
3487 pub(crate) fn need_emit_timeline_marker(&self, timeline_type: TimelineMarkerType) -> bool {
3488 let markers = self.devtools_markers.borrow();
3489 markers.contains(&timeline_type)
3490 }
3491
3492 pub(crate) fn emit_timeline_marker(&self, marker: TimelineMarker) {
3493 let sender = self.devtools_marker_sender.borrow();
3494 let sender = sender.as_ref().expect("There is no marker sender");
3495 sender.send(Some(marker)).unwrap();
3496 }
3497
3498 pub(crate) fn set_devtools_timeline_markers(
3499 &self,
3500 markers: Vec<TimelineMarkerType>,
3501 reply: GenericSender<Option<TimelineMarker>>,
3502 ) {
3503 *self.devtools_marker_sender.borrow_mut() = Some(reply);
3504 self.devtools_markers.borrow_mut().extend(markers);
3505 }
3506
3507 pub(crate) fn drop_devtools_timeline_markers(&self, markers: Vec<TimelineMarkerType>) {
3508 let mut devtools_markers = self.devtools_markers.borrow_mut();
3509 for marker in markers {
3510 devtools_markers.remove(&marker);
3511 }
3512 if devtools_markers.is_empty() {
3513 *self.devtools_marker_sender.borrow_mut() = None;
3514 }
3515 }
3516
3517 pub(crate) fn set_webdriver_load_status_sender(
3518 &self,
3519 sender: Option<GenericSender<WebDriverLoadStatus>>,
3520 ) {
3521 *self.webdriver_load_status_sender.borrow_mut() = sender;
3522 }
3523
3524 pub(crate) fn webdriver_load_status_sender(
3525 &self,
3526 ) -> Option<GenericSender<WebDriverLoadStatus>> {
3527 self.webdriver_load_status_sender.borrow().clone()
3528 }
3529
3530 pub(crate) fn is_alive(&self) -> bool {
3531 self.current_state.get() == WindowState::Alive
3532 }
3533
3534 pub(crate) fn is_top_level(&self) -> bool {
3536 self.parent_info.is_none()
3537 }
3538
3539 fn run_resize_steps_for_layout_viewport(&self, cx: &mut JSContext) -> bool {
3544 let Some((new_size, size_type)) = self.take_unhandled_resize_event() else {
3545 return false;
3546 };
3547
3548 let current_viewport = self.viewport_details();
3551 if current_viewport == self.viewport_details_at_last_resize_steps.get() {
3552 return false;
3553 }
3554 self.viewport_details_at_last_resize_steps
3555 .set(current_viewport);
3556
3557 debug!(
3558 "Running resize steps for pipeline {:?} with viewport {new_size:?}",
3559 self.pipeline_id(),
3560 );
3561
3562 if size_type == WindowSizeType::Resize {
3564 let mut realm = enter_auto_realm(cx, self);
3565 let cx = &mut realm.current_realm();
3566 let uievent = UIEvent::new(
3567 cx,
3568 self,
3569 atom!("resize"),
3570 EventBubbles::DoesNotBubble,
3571 EventCancelable::NotCancelable,
3572 Some(self),
3573 0i32,
3574 0u32,
3575 );
3576 uievent.upcast::<Event>().fire(cx, self.upcast());
3577 }
3578
3579 true
3580 }
3581
3582 pub(crate) fn run_the_resize_steps(&self, cx: &mut JSContext) -> bool {
3587 let layout_viewport_resized = self.run_resize_steps_for_layout_viewport(cx);
3588
3589 if self.has_changed_visual_viewport_dimension.get() {
3590 let visual_viewport = self.get_or_init_visual_viewport(cx);
3591
3592 let uievent = UIEvent::new(
3593 cx,
3594 self,
3595 atom!("resize"),
3596 EventBubbles::DoesNotBubble,
3597 EventCancelable::NotCancelable,
3598 Some(self),
3599 0i32,
3600 0u32,
3601 );
3602 uievent.upcast::<Event>().fire(cx, visual_viewport.upcast());
3603
3604 self.has_changed_visual_viewport_dimension.set(false);
3605 }
3606
3607 layout_viewport_resized
3608 }
3609
3610 pub(crate) fn evaluate_media_queries_and_report_changes(&self, cx: &mut JSContext) {
3613 let mut realm = enter_auto_realm(cx, self);
3614 let cx = &mut realm.current_realm();
3615 rooted_vec!(let mut mql_list);
3616
3617 self.media_query_lists.for_each(|mql| {
3618 if let MediaQueryListMatchState::Changed = mql.evaluate_changes() {
3619 mql_list.push(Dom::from_ref(&*mql));
3621 }
3622 });
3623 for mql in mql_list.iter() {
3625 let event = MediaQueryListEvent::new(
3626 cx,
3627 &mql.global(),
3628 atom!("change"),
3629 false,
3630 false,
3631 mql.Media(),
3632 mql.Matches(),
3633 );
3634 event
3635 .upcast::<Event>()
3636 .fire(cx, mql.upcast::<EventTarget>());
3637 }
3638 }
3639
3640 pub(crate) fn set_throttled(&self, throttled: bool) {
3642 self.throttled.set(throttled);
3643 if throttled {
3644 self.as_global_scope().slow_down_timers();
3645 } else {
3646 self.as_global_scope().speed_up_timers();
3647 }
3648 }
3649
3650 pub(crate) fn throttled(&self) -> bool {
3651 self.throttled.get()
3652 }
3653
3654 pub(crate) fn unminified_css_dir(&self) -> Option<String> {
3655 self.unminified_css_dir.borrow().clone()
3656 }
3657
3658 pub(crate) fn local_script_source(&self) -> &Option<String> {
3659 &self.local_script_source
3660 }
3661
3662 pub(crate) fn set_navigation_start(&self) {
3663 self.navigation_start.set(CrossProcessInstant::now());
3664 }
3665
3666 pub(crate) fn navigation_start(&self) -> CrossProcessInstant {
3667 self.navigation_start.get()
3668 }
3669
3670 pub(crate) fn set_last_activation_timestamp(&self, time: UserActivationTimestamp) {
3671 self.last_activation_timestamp.set(time);
3672 }
3673
3674 pub(crate) fn send_to_embedder(&self, msg: EmbedderMsg) {
3675 self.as_global_scope()
3676 .script_to_embedder_chan()
3677 .send(msg)
3678 .unwrap();
3679 }
3680
3681 pub(crate) fn send_to_constellation(&self, msg: ScriptToConstellationMessage) {
3682 self.as_global_scope()
3683 .script_to_constellation_chan()
3684 .send(msg)
3685 .unwrap();
3686 }
3687
3688 #[cfg(feature = "webxr")]
3689 pub(crate) fn in_immersive_xr_session(&self) -> bool {
3690 self.navigator
3691 .get()
3692 .as_ref()
3693 .and_then(|nav| nav.xr())
3694 .is_some_and(|xr| xr.pending_or_active_session())
3695 }
3696
3697 #[cfg(all(feature = "webgl", not(feature = "webxr")))]
3698 pub(crate) fn in_immersive_xr_session(&self) -> bool {
3699 false
3700 }
3701
3702 fn handle_new_or_removed_web_fonts_post_reflow(
3704 &self,
3705 cx: &mut JSContext,
3706 changed_web_fonts: WebFontSetDifference,
3707 ) {
3708 if changed_web_fonts.is_empty() {
3709 return;
3710 }
3711
3712 let document = self.Document();
3713 let fonts = document.Fonts(cx);
3714 if !changed_web_fonts.removed_font_faces.is_empty() {
3715 fonts.notify_font_face_rules_removed(&changed_web_fonts.removed_font_faces);
3716 }
3717
3718 if !changed_web_fonts.removed_font_faces.is_empty() ||
3719 changed_web_fonts.cascade_index_of_any_rule_changed
3720 {
3721 document.dirty_all_nodes(cx.no_gc());
3724 }
3725
3726 if !changed_web_fonts.added_font_faces.is_empty() {
3727 fonts.switch_to_loading(cx);
3728
3729 for new_web_font in changed_web_fonts.added_font_faces {
3730 if let Some(font_face) = FontFace::new_for_web_font(cx, self.upcast(), new_web_font)
3731 {
3732 fonts.add(cx, font_face);
3733 }
3734 }
3735 }
3736 }
3737
3738 #[expect(unsafe_code)]
3740 fn process_lcp_candidate_post_reflow(
3741 &self,
3742 candidate: &LCPCandidate,
3743 node_address: UntrustedNodeAddress,
3744 document: &Document,
3745 ) {
3746 let node = unsafe { from_untrusted_node_address(node_address) };
3747 if let Some(element) = DomRoot::downcast::<Element>(node) {
3748 document.store_lcp_candidate(candidate.id, &element);
3749 }
3750 }
3751
3752 #[expect(unsafe_code)]
3753 fn handle_pending_images_post_reflow(
3754 &self,
3755 cx: &mut JSContext,
3756 pending_images: Vec<PendingImage>,
3757 pending_rasterization_images: Vec<PendingRasterizationImage>,
3758 pending_svg_element_for_serialization: Vec<UntrustedNodeAddress>,
3759 ) {
3760 let pipeline_id = self.pipeline_id();
3761 let image_cache = self.image_cache();
3762 for image in pending_images {
3763 let id = image.id;
3764 let node = unsafe { from_untrusted_node_address(image.node) };
3765
3766 if let PendingImageState::Unrequested(ref url) = image.state {
3767 fetch_image_for_layout(
3768 url.clone(),
3769 &node,
3770 id,
3771 image.is_internal_request,
3772 image_cache.clone(),
3773 );
3774 }
3775
3776 let mut images = self.pending_layout_images.borrow_mut();
3777 if !images.contains_key(&id) {
3778 let trusted_node = Trusted::new(&*node);
3779 let sender = self.register_image_cache_listener(id, move |response, cx| {
3780 trusted_node
3781 .root()
3782 .owner_window()
3783 .pending_layout_image_notification(cx.no_gc(), response);
3784 });
3785
3786 image_cache.add_listener(ImageLoadListener::new(sender, pipeline_id, id));
3787 }
3788
3789 let nodes = images.entry(id).or_default();
3790 if !nodes.iter().any(|n| *n.node == *node) {
3791 nodes.push(PendingLayoutImageAncillaryData {
3792 node: Dom::from_ref(&*node),
3793 destination: image.destination,
3794 });
3795 }
3796 }
3797
3798 for image in pending_rasterization_images {
3799 let node = unsafe { from_untrusted_node_address(image.node) };
3800
3801 let mut images = self.pending_images_for_rasterization.borrow_mut();
3802 if !images.contains_key(&(image.id, image.size)) {
3803 let image_cache_sender = self.image_cache_sender.clone();
3804 image_cache.add_rasterization_complete_listener(
3805 pipeline_id,
3806 image.id,
3807 image.size,
3808 Box::new(move |response| {
3809 let _ = image_cache_sender.send(response);
3810 }),
3811 );
3812 }
3813
3814 let nodes = images.entry((image.id, image.size)).or_default();
3815 if !nodes.iter().any(|n| **n == *node) {
3816 nodes.push(Dom::from_ref(&*node));
3817 }
3818 }
3819
3820 for node in pending_svg_element_for_serialization.into_iter() {
3821 let node = unsafe { from_untrusted_node_address(node) };
3822 let svg = node.downcast::<SVGSVGElement>().unwrap();
3823 svg.serialize_and_cache_subtree(cx);
3824 node.dirty(cx.no_gc(), NodeDamage::Other);
3825 }
3826 }
3827
3828 pub(crate) fn has_sticky_activation(&self) -> bool {
3830 UserActivationTimestamp::TimeStamp(CrossProcessInstant::now()) >=
3832 self.last_activation_timestamp.get()
3833 }
3834
3835 pub(crate) fn has_transient_activation(&self) -> bool {
3837 let current_time = CrossProcessInstant::now();
3840 UserActivationTimestamp::TimeStamp(current_time) >= self.last_activation_timestamp.get() &&
3841 UserActivationTimestamp::TimeStamp(current_time) <
3842 self.last_activation_timestamp.get() +
3843 pref!(dom_transient_activation_duration_ms)
3844 }
3845
3846 pub(crate) fn consume_last_activation_timestamp(&self) {
3847 if self.last_activation_timestamp.get() != UserActivationTimestamp::PositiveInfinity {
3848 self.set_last_activation_timestamp(UserActivationTimestamp::NegativeInfinity);
3849 }
3850 }
3851
3852 pub(crate) fn consume_user_activation(&self) {
3854 if self.undiscarded_window_proxy().is_none() {
3857 return;
3858 }
3859
3860 let Some(top_level_document) = self.top_level_document_if_local() else {
3864 return;
3865 };
3866
3867 top_level_document
3875 .window()
3876 .consume_last_activation_timestamp();
3877 for document in SameOriginDescendantNavigablesIterator::new(&top_level_document) {
3878 document.window().consume_last_activation_timestamp();
3879 }
3880 }
3881
3882 #[allow(clippy::too_many_arguments)]
3883 pub(crate) fn new(
3884 cx: &mut JSContext,
3885 webview_id: WebViewId,
3886 runtime: Rc<Runtime>,
3887 script_chan: Sender<MainThreadScriptMsg>,
3888 layout: Box<dyn Layout>,
3889 image_cache_sender: Sender<ImageCacheResponseMessage>,
3890 resource_threads: ResourceThreads,
3891 storage_threads: StorageThreads,
3892 #[cfg(feature = "bluetooth")] bluetooth_thread: GenericSender<BluetoothRequest>,
3893 mem_profiler_chan: MemProfilerChan,
3894 time_profiler_chan: TimeProfilerChan,
3895 devtools_chan: Option<GenericCallback<ScriptToDevtoolsControlMsg>>,
3896 script_to_constellation_sender: ScriptToConstellationSender,
3897 embedder_chan: ScriptToEmbedderChan,
3898 control_chan: GenericSender<ScriptThreadMessage>,
3899 pipeline_id: PipelineId,
3900 parent_info: Option<PipelineId>,
3901 viewport_details: ViewportDetails,
3902 origin: MutableOrigin,
3903 creation_url: ServoUrl,
3904 top_level_creation_url: ServoUrl,
3905 navigation_start: CrossProcessInstant,
3906 #[cfg(feature = "webgl")] webgl_chan: Option<WebGLChan>,
3907 #[cfg(feature = "webxr")] webxr_registry: Option<webxr_api::Registry>,
3908 paint_api: CrossProcessPaintApi,
3909 unminify_js: bool,
3910 unminify_css: bool,
3911 local_script_source: Option<String>,
3912 user_scripts: Rc<Vec<UserScript>>,
3913 player_context: WindowGLContext,
3914 #[cfg(feature = "webgpu")] gpu_id_hub: Arc<IdentityHub>,
3915 inherited_secure_context: Option<bool>,
3916 embedder_theme: Theme,
3917 weak_script_thread: Weak<ScriptThread>,
3918 ) -> DomRoot<Self> {
3919 let error_reporter = CSSErrorReporter {
3920 pipelineid: pipeline_id,
3921 script_chan: control_chan,
3922 };
3923
3924 let win = Box::new(Self {
3925 webview_id,
3926 globalscope: GlobalScope::new_inherited(
3927 devtools_chan,
3928 mem_profiler_chan,
3929 time_profiler_chan,
3930 script_to_constellation_sender,
3931 embedder_chan,
3932 resource_threads,
3933 storage_threads,
3934 creation_url,
3935 Some(top_level_creation_url),
3936 #[cfg(feature = "webgpu")]
3937 gpu_id_hub,
3938 inherited_secure_context,
3939 unminify_js,
3940 ),
3941 caches: Default::default(),
3942 ongoing_navigation: Default::default(),
3943 script_chan,
3944 layout: RefCell::new(layout),
3945 image_cache_sender,
3946 navigator: Default::default(),
3947 #[cfg(feature = "webcrypto")]
3948 crypto: Default::default(),
3949 location: Default::default(),
3950 window_proxy: Default::default(),
3951 document: Default::default(),
3952 performance: Default::default(),
3953 navigation_start: Cell::new(navigation_start),
3954 screen: Default::default(),
3955 session_storage: Default::default(),
3956 local_storage: Default::default(),
3957 cookie_store: Default::default(),
3958 status: DomRefCell::new(DOMString::new()),
3959 parent_info,
3960 dom_static: GlobalStaticData::new(),
3961 js_runtime: DomRefCell::new(Some(runtime)),
3962 #[cfg(feature = "bluetooth")]
3963 bluetooth_thread,
3964 #[cfg(feature = "bluetooth")]
3965 bluetooth_extra_permission_data: BluetoothExtraPermissionData::new(),
3966 unhandled_resize_event: Default::default(),
3967 viewport_details_at_last_resize_steps: Cell::new(viewport_details),
3968 viewport_details: Cell::new(viewport_details),
3969 layout_blocker: Cell::new(LayoutBlocker::WaitingForParse),
3970 current_state: Cell::new(WindowState::Alive),
3971 devtools_marker_sender: Default::default(),
3972 devtools_markers: Default::default(),
3973 webdriver_load_status_sender: Default::default(),
3974 error_reporter,
3975 media_query_lists: DOMTracker::new(),
3976 #[cfg(feature = "bluetooth")]
3977 test_runner: Default::default(),
3978 #[cfg(feature = "webgl")]
3979 webgl_chan,
3980 #[cfg(feature = "webxr")]
3981 webxr_registry,
3982 pending_image_callbacks: Default::default(),
3983 pending_layout_images: Default::default(),
3984 pending_images_for_rasterization: Default::default(),
3985 unminified_css_dir: DomRefCell::new(if unminify_css {
3986 Some(unminified_path("unminified-css"))
3987 } else {
3988 None
3989 }),
3990 local_script_source,
3991 test_worklet: Default::default(),
3992 paint_worklet: Default::default(),
3993 exists_mut_observer: Cell::new(false),
3994 paint_api,
3995 user_scripts,
3996 player_context,
3997 throttled: Cell::new(false),
3998 layout_marker: DomRefCell::new(Rc::new(Cell::new(true))),
3999 current_event: DomRefCell::new(None),
4000 embedder_theme: Cell::new(embedder_theme),
4001 trusted_types: Default::default(),
4002 reporting_observer_list: Default::default(),
4003 report_list: Default::default(),
4004 endpoints_list: Default::default(),
4005 script_window_proxies: ScriptThread::window_proxies(),
4006 has_pending_screenshot_readiness_request: Default::default(),
4007 visual_viewport: Default::default(),
4008 weak_script_thread,
4009 has_changed_visual_viewport_dimension: Default::default(),
4010 pending_media_query_evaluation: Default::default(),
4011 last_activation_timestamp: Cell::new(UserActivationTimestamp::PositiveInfinity),
4012 devtools_wants_updates: Default::default(),
4013 has_dispatched_scroll_event: Cell::new(false),
4014 has_dispatched_input_event: Cell::new(false),
4015 });
4016
4017 WindowBinding::Wrap::<crate::DomTypeHolder>(cx, &origin, win)
4018 }
4019
4020 pub(crate) fn task_manager(&self) -> Rc<TaskManager> {
4021 self.Document().task_manager()
4022 }
4023
4024 pub(crate) fn pipeline_id(&self) -> PipelineId {
4025 self.Document().pipeline_id()
4026 }
4027
4028 pub(crate) fn live_devtools_updates(&self) -> bool {
4029 self.devtools_wants_updates.get()
4030 }
4031
4032 pub(crate) fn set_devtools_wants_updates(&self, value: bool) {
4033 self.devtools_wants_updates.set(value);
4034 }
4035
4036 pub(crate) fn cache_layout_value<T>(&self, value: T) -> LayoutValue<T>
4038 where
4039 T: Copy + MallocSizeOf,
4040 {
4041 LayoutValue::new(self.layout_marker.borrow().clone(), value)
4042 }
4043
4044 pub(crate) fn set_up_a_window_environment_settings_object(
4053 &self,
4054 layout: Box<dyn Layout>,
4055 creation_url: ServoUrl,
4056 top_level_creation_url: ServoUrl,
4057 navigation_start: CrossProcessInstant,
4058 viewport_details: ViewportDetails,
4059 ) {
4060 *self.layout.borrow_mut() = layout;
4061 self.set_viewport_details(viewport_details);
4062 self.navigation_start.set(navigation_start);
4063
4064 let global = self.upcast::<GlobalScope>();
4067 global.set_creation_url(creation_url);
4068 global.set_top_level_creation_url(top_level_creation_url);
4069
4070 self.Document().detach_window();
4071 }
4072}
4073
4074#[derive(MallocSizeOf)]
4079pub(crate) struct LayoutValue<T: MallocSizeOf> {
4080 #[conditional_malloc_size_of]
4081 is_valid: Rc<Cell<bool>>,
4082 value: T,
4083}
4084
4085#[expect(unsafe_code)]
4086unsafe impl<T: JSTraceable + MallocSizeOf> JSTraceable for LayoutValue<T> {
4087 unsafe fn trace(&self, trc: *mut js::jsapi::JSTracer) {
4088 unsafe { self.value.trace(trc) };
4089 }
4090}
4091
4092impl<T: Copy + MallocSizeOf> LayoutValue<T> {
4093 fn new(marker: Rc<Cell<bool>>, value: T) -> Self {
4094 LayoutValue {
4095 is_valid: marker,
4096 value,
4097 }
4098 }
4099
4100 pub(crate) fn get(&self) -> Result<T, ()> {
4102 if self.is_valid.get() {
4103 return Ok(self.value);
4104 }
4105 Err(())
4106 }
4107}
4108
4109impl Window {
4110 pub(crate) fn post_message(
4112 &self,
4113 target_origin: Option<ImmutableOrigin>,
4114 source_origin: ImmutableOrigin,
4115 source: &WindowProxy,
4116 data: StructuredSerializedData,
4117 ) {
4118 let this = Trusted::new(self);
4119 let source = Trusted::new(source);
4120 let task = task!(post_serialised_message: move |cx| {
4121 let this = this.root();
4122 let source = source.root();
4123 let document = this.Document();
4124
4125 if let Some(ref target_origin) = target_origin
4127 && !target_origin.same_origin(&*document.origin()) {
4128 return;
4129 }
4130
4131 let obj = this.reflector().get_jsobject();
4133 let mut realm = AutoRealm::new(cx, NonNull::new(obj.get()).unwrap());
4134 let cx = &mut *realm;
4135 rooted!(&in(cx) let mut message_clone = UndefinedValue());
4136 if let Ok(ports) = structuredclone::read(cx, this.upcast(), data, message_clone.handle_mut()) {
4137 MessageEvent::dispatch_jsval(
4139 cx,
4140 this.upcast(),
4141 this.upcast(),
4142 message_clone.handle(),
4143 Some(source_origin.ascii_serialization().as_ref()),
4144 Some(&*source),
4145 ports,
4146 );
4147 } else {
4148 MessageEvent::dispatch_error(
4150 cx,
4151 this.upcast(),
4152 this.upcast(),
4153 );
4154 }
4155 });
4156 self.as_global_scope()
4158 .task_manager()
4159 .dom_manipulation_task_source()
4160 .queue(task);
4161 }
4162}
4163
4164#[derive(Clone, MallocSizeOf)]
4165pub(crate) struct CSSErrorReporter {
4166 pub(crate) pipelineid: PipelineId,
4167 pub(crate) script_chan: GenericSender<ScriptThreadMessage>,
4168}
4169unsafe_no_jsmanaged_fields!(CSSErrorReporter);
4170
4171impl ParseErrorReporter for CSSErrorReporter {
4172 fn report_error(
4173 &self,
4174 url: &UrlExtraData,
4175 location: SourceLocation,
4176 error: ContextualParseError,
4177 ) {
4178 if log_enabled!(log::Level::Info) {
4179 info!(
4180 "Url:\t{}\n{}:{} {}",
4181 url.0.as_str(),
4182 location.line,
4183 location.column,
4184 error
4185 )
4186 }
4187
4188 let _ = self.script_chan.send(ScriptThreadMessage::ReportCSSError(
4190 self.pipelineid,
4191 url.0.to_string(),
4192 location.line,
4193 location.column,
4194 error.to_string(),
4195 ));
4196 }
4197}
4198
4199fn is_named_element_with_name_attribute(elem: &Element) -> bool {
4200 let type_ = match elem.upcast::<Node>().type_id() {
4201 NodeTypeId::Element(ElementTypeId::HTMLElement(type_)) => type_,
4202 _ => return false,
4203 };
4204 matches!(
4205 type_,
4206 HTMLElementTypeId::HTMLEmbedElement |
4207 HTMLElementTypeId::HTMLFormElement |
4208 HTMLElementTypeId::HTMLImageElement |
4209 HTMLElementTypeId::HTMLObjectElement
4210 )
4211}
4212
4213fn is_named_element_with_id_attribute(elem: &Element) -> bool {
4214 elem.is_html_element() || elem.is_svg_element()
4215}
4216
4217#[expect(unsafe_code)]
4218#[unsafe(no_mangle)]
4219unsafe extern "C" fn dump_js_stack(cx: *mut RawJSContext) {
4221 unsafe {
4222 DumpJSStack(cx, true, false, false);
4223 }
4224}
4225
4226impl WindowHelpers for Window {
4227 fn create_named_properties_object(
4228 cx: &mut JSContext,
4229 proto: HandleObject,
4230 object: MutableHandleObject,
4231 ) {
4232 Self::create_named_properties_object(cx, proto, object)
4233 }
4234}
4235
4236impl HasOrigin for Window {
4237 fn origin(&self) -> MutableOrigin {
4238 Window::origin(self)
4239 }
4240}