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, JavaScriptEvaluationError, PromptResponse,
28 ScriptToEmbedderChan, SimpleDialogRequest, Theme, UntrustedNodeAddress, ViewportDetails,
29 WebDriverJSResult, WebDriverLoadStatus,
30};
31use euclid::{Point2D, Rect, Scale, Size2D, Vector2D};
32use fonts::{
33 CspViolationHandler, FontContext, NetworkTimingHandler, WebFontDocumentContext,
34 WebFontSetDifference,
35};
36use js::context::{JSContext, NoGC};
37use js::conversions::ToJSValConvertible;
38use js::glue::DumpJSStack;
39use js::jsapi::{GCReason, Heap, JSContext as RawJSContext, JSObject, JSPROP_ENUMERATE};
40use js::jsval::{NullValue, UndefinedValue};
41use js::realm::{AutoRealm, CurrentRealm};
42use js::rust::wrappers2::{JS_DefineProperty, JS_GC};
43use js::rust::{
44 CustomAutoRooter, CustomAutoRooterGuard, HandleObject, HandleValue, MutableHandleObject,
45 MutableHandleValue,
46};
47use layout_api::{
48 AxesOverflow, BoxAreaType, CSSPixelRectVec, FragmentType, HitTestFlags, Layout,
49 LayoutImageDestination, PendingImage, PendingImageState, PendingRasterizationImage,
50 PhysicalSides, QueryMsg, ReflowGoal, ReflowPhasesRun, ReflowRequest, ReflowRequestRestyle,
51 ReflowStatistics, RestyleReason, ScrollContainerQueryFlags, ScrollContainerResponse,
52 TrustedNodeAddress, combine_id_with_fragment_type,
53};
54use malloc_size_of::MallocSizeOf;
55use media::WindowGLContext;
56use net_traits::image_cache::{
57 ImageCache, ImageCacheResponseCallback, ImageCacheResponseMessage, ImageLoadListener,
58 ImageResponse, PendingImageId, PendingImageResponse, RasterizationCompleteResponse,
59};
60use net_traits::request::{Origin, Referrer, RequestClient};
61use net_traits::{ResourceFetchTiming, ResourceThreads};
62use num_traits::ToPrimitive;
63use paint_api::largest_contentful_paint_candidate::LCPCandidate;
64use paint_api::{CrossProcessPaintApi, PinchZoomInfos};
65use profile_traits::generic_channel as ProfiledGenericChannel;
66use profile_traits::mem::ProfilerChan as MemProfilerChan;
67use profile_traits::time::ProfilerChan as TimeProfilerChan;
68use rustc_hash::{FxBuildHasher, FxHashMap};
69use script_bindings::cell::{DomRefCell, Ref};
70use script_bindings::codegen::GenericBindings::WindowBinding::ScrollToOptions;
71use script_bindings::dom::UnrootedDom;
72use script_bindings::interfaces::{HasOrigin, WindowHelpers};
73use script_bindings::like::Setlike;
74use script_bindings::reflector::DomObject;
75use script_bindings::root::Root;
76use script_traits::{ConstellationInputEvent, ScriptThreadMessage};
77use selectors::attr::CaseSensitivity;
78use servo_arc::Arc as ServoArc;
79use servo_base::cross_process_instant::CrossProcessInstant;
80use servo_base::generic_channel::{self, GenericCallback, GenericSender};
81use servo_base::id::{BrowsingContextId, PipelineId, WebViewId};
82#[cfg(feature = "bluetooth")]
83use servo_bluetooth_traits::BluetoothRequest;
84#[cfg(feature = "webgl")]
85use servo_canvas_traits::webgl::WebGLChan;
86use servo_config::pref;
87use servo_constellation_traits::{
88 LoadData, LoadOrigin, ScreenshotReadinessResponse, ScriptToConstellationMessage,
89 ScriptToConstellationSender, StructuredSerializedData, WindowSizeType,
90};
91use servo_geometry::DeviceIndependentIntRect;
92use servo_url::{ImmutableOrigin, MutableOrigin, ServoUrl};
93use storage_traits::StorageThreads;
94use storage_traits::webstorage_thread::WebStorageType;
95use style::dom::OpaqueNode;
96use style::error_reporting::{ContextualParseError, ParseErrorReporter};
97use style::properties::PropertyId;
98use style::properties::style_structs::Font;
99use style::selector_parser::PseudoElement;
100use style::shared_lock::StylesheetGuards;
101use style::str::HTML_SPACE_CHARACTERS;
102use style::stylesheets::UrlExtraData;
103use style_traits::CSSPixel;
104use stylo_atoms::Atom;
105use time::Duration as TimeDuration;
106use webrender_api::ExternalScrollId;
107use webrender_api::units::{DeviceIntSize, DevicePixel, LayoutPixel, LayoutPoint};
108
109use crate::dom::WorkletThreadPool;
110use crate::dom::bindings::codegen::Bindings::AnimationFrameProviderBinding::FrameRequestCallback;
111use crate::dom::bindings::codegen::Bindings::DocumentBinding::{
112 DocumentMethods, DocumentReadyState, NamedPropertyValue,
113};
114use crate::dom::bindings::codegen::Bindings::HTMLIFrameElementBinding::HTMLIFrameElementMethods;
115use crate::dom::bindings::codegen::Bindings::HistoryBinding::History_Binding::HistoryMethods;
116use crate::dom::bindings::codegen::Bindings::ImageBitmapBinding::{
117 ImageBitmapOptions, ImageBitmapSource,
118};
119use crate::dom::bindings::codegen::Bindings::MediaQueryListBinding::MediaQueryList_Binding::MediaQueryListMethods;
120use crate::dom::bindings::codegen::Bindings::MessagePortBinding::StructuredSerializeOptions;
121use crate::dom::bindings::codegen::Bindings::ReportingObserverBinding::Report;
122use crate::dom::bindings::codegen::Bindings::RequestBinding::{RequestInfo, RequestInit};
123use crate::dom::bindings::codegen::Bindings::VoidFunctionBinding::VoidFunction;
124use crate::dom::bindings::codegen::Bindings::WindowBinding::{
125 self, DeferredRequestInit, ScrollBehavior, WindowMethods, WindowPostMessageOptions,
126};
127use crate::dom::bindings::codegen::UnionTypes::{
128 RequestOrUSVString, TrustedScriptOrString, TrustedScriptOrStringOrFunction,
129};
130use crate::dom::bindings::error::{
131 Error, ErrorInfo, ErrorResult, Fallible, javascript_error_info_from_error_info,
132};
133use crate::dom::bindings::inheritance::{Castable, ElementTypeId, HTMLElementTypeId, NodeTypeId};
134use crate::dom::bindings::num::Finite;
135use crate::dom::bindings::refcounted::Trusted;
136use crate::dom::bindings::reflector::DomGlobal;
137use crate::dom::bindings::root::{Dom, DomRoot, MutNullableDom};
138use crate::dom::bindings::str::{DOMString, USVString};
139use crate::dom::bindings::structuredclone;
140use crate::dom::bindings::trace::{
141 CustomTraceable, HashMapTracedValues, JSTraceable, RootedTraceableBox,
142};
143use crate::dom::bindings::utils::GlobalStaticData;
144use crate::dom::bindings::weakref::DOMTracker;
145#[cfg(feature = "bluetooth")]
146use crate::dom::bluetooth::BluetoothExtraPermissionData;
147use crate::dom::cookiestore::CookieStore;
148use crate::dom::crypto::Crypto;
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::screen::Screen;
192use crate::dom::window::scrolling_box::{ScrollingBox, ScrollingBoxSource};
193use crate::dom::window::useractivation::UserActivationTimestamp;
194use crate::dom::windowproxy::{WindowProxy, WindowProxyHandler};
195use crate::dom::worklet::Worklet;
196use crate::dom::workletglobalscope::WorkletGlobalScopeType;
197use crate::event_loop::script_thread::ScriptThread;
198use crate::event_loop::script_window_proxies::ScriptWindowProxies;
199use crate::layout_image::fetch_image_for_layout;
200use crate::messaging::{MainThreadScriptMsg, ScriptEventLoopReceiver, ScriptEventLoopSender};
201use crate::microtask::UserMicrotask;
202use crate::network_listener::{ResourceTimingListener, submit_timing};
203use crate::realms::enter_auto_realm;
204use crate::script_runtime::Runtime;
205use crate::tasks::task_manager::TaskManager;
206use crate::tasks::task_source::SendableTaskSource;
207use crate::timers::{IsInterval, OneshotTimers, TimerCallback};
208use crate::unminify::unminified_path;
209use crate::webdriver_handlers::{find_node_by_unique_id_in_document, jsval_to_webdriver};
210use crate::{fetch, window_named_properties};
211
212#[derive(MallocSizeOf)]
217pub struct PendingImageCallback(
218 #[ignore_malloc_size_of = "dyn Fn is currently impossible to measure"]
219 #[expect(clippy::type_complexity)]
220 Box<dyn Fn(PendingImageResponse, &mut JSContext) + 'static>,
221);
222
223#[derive(Clone, Copy, Debug, JSTraceable, MallocSizeOf, PartialEq)]
225enum WindowState {
226 Alive,
227 Zombie, }
229
230const INITIAL_REFLOW_DELAY: Duration = Duration::from_millis(200);
233
234#[derive(Clone, Copy, MallocSizeOf)]
245enum LayoutBlocker {
246 WaitingForParse,
248 Parsing(Instant),
250 FiredLoadEventOrParsingTimerExpired,
254}
255
256impl LayoutBlocker {
257 fn layout_blocked(&self) -> bool {
258 !matches!(self, Self::FiredLoadEventOrParsingTimerExpired)
259 }
260}
261
262#[derive(Clone, Copy, Debug, Default, JSTraceable, MallocSizeOf, PartialEq)]
265pub(crate) struct OngoingNavigation(u32);
266
267type PendingImageRasterizationKey = (PendingImageId, DeviceIntSize);
268
269#[cfg_attr(crown, crown::unrooted_must_root_lint::must_root)]
273#[derive(JSTraceable, MallocSizeOf)]
274struct PendingLayoutImageAncillaryData {
275 node: Dom<Node>,
276 #[no_trace]
277 destination: LayoutImageDestination,
278}
279
280#[dom_struct]
281pub(crate) struct Window {
282 globalscope: GlobalScope,
283
284 #[ignore_malloc_size_of = "Weak does not need to be accounted"]
288 #[no_trace]
289 weak_script_thread: Weak<ScriptThread>,
290
291 #[no_trace]
295 webview_id: WebViewId,
296 script_chan: Sender<MainThreadScriptMsg>,
297 #[no_trace]
298 #[ignore_malloc_size_of = "TODO: Add MallocSizeOf support to layout"]
299 layout: RefCell<Box<dyn Layout>>,
300 navigator: MutNullableDom<Navigator>,
301 crypto: MutNullableDom<Crypto>,
302 #[no_trace]
303 image_cache_sender: Sender<ImageCacheResponseMessage>,
304 window_proxy: MutNullableDom<WindowProxy>,
305 document: MutNullableDom<Document>,
306 location: MutNullableDom<Location>,
307 performance: MutNullableDom<Performance>,
308 #[no_trace]
309 navigation_start: Cell<CrossProcessInstant>,
310 screen: MutNullableDom<Screen>,
311 session_storage: MutNullableDom<Storage>,
312 local_storage: MutNullableDom<Storage>,
313 cookie_store: MutNullableDom<CookieStore>,
315 status: DomRefCell<DOMString>,
316 trusted_types: MutNullableDom<TrustedTypePolicyFactory>,
317
318 ongoing_navigation: Cell<OngoingNavigation>,
321
322 caches: MutNullableDom<CacheStorage>,
324
325 #[no_trace]
328 devtools_markers: DomRefCell<HashSet<TimelineMarkerType>>,
329 #[no_trace]
330 devtools_marker_sender: DomRefCell<Option<GenericSender<Option<TimelineMarker>>>>,
331
332 #[no_trace]
334 unhandled_resize_event: DomRefCell<Option<(ViewportDetails, WindowSizeType)>>,
335
336 #[no_trace]
340 viewport_details_at_last_resize_steps: Cell<ViewportDetails>,
341
342 #[no_trace]
344 embedder_theme: Cell<Theme>,
345
346 #[no_trace]
348 parent_info: Option<PipelineId>,
349
350 dom_static: GlobalStaticData,
352
353 #[conditional_malloc_size_of]
355 js_runtime: DomRefCell<Option<Rc<Runtime>>>,
356
357 #[no_trace]
359 viewport_details: Cell<ViewportDetails>,
360
361 #[no_trace]
363 #[cfg(feature = "bluetooth")]
364 bluetooth_thread: GenericSender<BluetoothRequest>,
365
366 #[cfg(feature = "bluetooth")]
367 bluetooth_extra_permission_data: BluetoothExtraPermissionData,
368
369 #[no_trace]
373 layout_blocker: Cell<LayoutBlocker>,
374
375 #[no_trace]
377 webdriver_script_chan: DomRefCell<Option<GenericSender<WebDriverJSResult>>>,
378
379 #[no_trace]
381 webdriver_load_status_sender: RefCell<Option<GenericSender<WebDriverLoadStatus>>>,
382
383 current_state: Cell<WindowState>,
385
386 error_reporter: CSSErrorReporter,
387
388 media_query_lists: DOMTracker<MediaQueryList>,
390
391 #[cfg(feature = "bluetooth")]
392 test_runner: MutNullableDom<TestRunner>,
393
394 #[no_trace]
396 #[cfg(feature = "webgl")]
397 webgl_chan: Option<WebGLChan>,
398
399 #[ignore_malloc_size_of = "defined in webxr"]
400 #[no_trace]
401 #[cfg(feature = "webxr")]
402 webxr_registry: Option<webxr_api::Registry>,
403
404 #[no_trace]
408 pending_image_callbacks: DomRefCell<FxHashMap<PendingImageId, Vec<PendingImageCallback>>>,
409
410 pending_layout_images: DomRefCell<
415 HashMapTracedValues<PendingImageId, Vec<PendingLayoutImageAncillaryData>, FxBuildHasher>,
416 >,
417
418 pending_images_for_rasterization: DomRefCell<
422 HashMapTracedValues<PendingImageRasterizationKey, Vec<Dom<Node>>, FxBuildHasher>,
423 >,
424
425 unminified_css_dir: DomRefCell<Option<String>>,
428
429 local_script_source: Option<String>,
431
432 test_worklet: MutNullableDom<Worklet>,
434 paint_worklet: MutNullableDom<Worklet>,
436
437 exists_mut_observer: Cell<bool>,
439
440 #[no_trace]
442 paint_api: CrossProcessPaintApi,
443
444 #[no_trace]
447 #[conditional_malloc_size_of]
448 user_scripts: Rc<Vec<UserScript>>,
449
450 #[ignore_malloc_size_of = "defined in script_thread"]
452 #[no_trace]
453 player_context: WindowGLContext,
454
455 throttled: Cell<bool>,
456
457 #[conditional_malloc_size_of]
461 layout_marker: DomRefCell<Rc<Cell<bool>>>,
462
463 current_event: DomRefCell<Option<Dom<Event>>>,
465
466 reporting_observer_list: DomRefCell<Vec<Dom<ReportingObserver>>>,
468
469 report_list: DomRefCell<Vec<Report>>,
471
472 #[no_trace]
474 endpoints_list: DomRefCell<Vec<ReportingEndpoint>>,
475
476 #[conditional_malloc_size_of]
478 script_window_proxies: Rc<ScriptWindowProxies>,
479
480 has_pending_screenshot_readiness_request: Cell<bool>,
482
483 visual_viewport: MutNullableDom<VisualViewport>,
486
487 has_changed_visual_viewport_dimension: Cell<bool>,
489
490 pending_media_query_evaluation: Cell<bool>,
495
496 #[no_trace]
498 last_activation_timestamp: Cell<UserActivationTimestamp>,
499
500 devtools_wants_updates: Cell<bool>,
503}
504
505impl Window {
506 pub(crate) fn script_thread(&self) -> Rc<ScriptThread> {
507 Weak::upgrade(&self.weak_script_thread)
508 .expect("Weak reference should always be upgradable when a ScriptThread is running")
509 }
510
511 pub(crate) fn webview_id(&self) -> WebViewId {
512 self.webview_id
513 }
514
515 pub(crate) fn as_global_scope(&self) -> &GlobalScope {
516 self.upcast::<GlobalScope>()
517 }
518
519 pub(crate) fn layout(&self) -> Ref<'_, Box<dyn Layout>> {
520 self.layout.borrow()
521 }
522
523 pub(crate) fn layout_mut(&self) -> RefMut<'_, Box<dyn Layout>> {
524 self.layout.borrow_mut()
525 }
526
527 pub(crate) fn get_exists_mut_observer(&self) -> bool {
528 self.exists_mut_observer.get()
529 }
530
531 pub(crate) fn set_exists_mut_observer(&self) {
532 self.exists_mut_observer.set(true);
533 }
534
535 #[expect(unsafe_code)]
536 pub(crate) fn clear_js_runtime_for_script_deallocation(&self) {
537 self.as_global_scope()
538 .remove_web_messaging_and_dedicated_workers_infra();
539 unsafe {
540 *self.js_runtime.borrow_for_script_deallocation() = None;
541 self.window_proxy.set(None);
542 self.current_state.set(WindowState::Zombie);
543 self.as_global_scope()
544 .task_manager()
545 .cancel_all_tasks_and_ignore_future_tasks();
546 }
547 }
548
549 pub(crate) fn discard_browsing_context(&self) {
552 let proxy = match self.window_proxy.get() {
553 Some(proxy) => proxy,
554 None => panic!("Discarding a BC from a window that has none"),
555 };
556 proxy.discard_browsing_context();
557 self.as_global_scope()
561 .task_manager()
562 .cancel_all_tasks_and_ignore_future_tasks();
563 }
564
565 pub(crate) fn time_profiler_chan(&self) -> &TimeProfilerChan {
567 self.globalscope.time_profiler_chan()
568 }
569
570 pub(crate) fn origin(&self) -> MutableOrigin {
572 self.Document().origin().clone()
574 }
575
576 pub(crate) fn main_thread_script_chan(&self) -> &Sender<MainThreadScriptMsg> {
577 &self.script_chan
578 }
579
580 pub(crate) fn parent_info(&self) -> Option<PipelineId> {
581 self.parent_info
582 }
583
584 pub(crate) fn new_script_pair(&self) -> (ScriptEventLoopSender, ScriptEventLoopReceiver) {
585 let (sender, receiver) = unbounded();
586 (
587 ScriptEventLoopSender::MainThread(sender),
588 ScriptEventLoopReceiver::MainThread(receiver),
589 )
590 }
591
592 pub(crate) fn event_loop_sender(&self) -> ScriptEventLoopSender {
593 ScriptEventLoopSender::MainThread(self.script_chan.clone())
594 }
595
596 pub(crate) fn image_cache(&self) -> Arc<dyn ImageCache> {
597 self.Document().image_cache()
598 }
599
600 pub(crate) fn window_proxy(&self) -> DomRoot<WindowProxy> {
602 self.window_proxy.get().unwrap()
603 }
604
605 pub(crate) fn append_reporting_observer(&self, reporting_observer: &ReportingObserver) {
606 self.reporting_observer_list
607 .borrow_mut()
608 .push(Dom::from_ref(reporting_observer));
609 }
610
611 pub(crate) fn remove_reporting_observer(&self, reporting_observer: &ReportingObserver) {
612 let index = {
613 let list = self.reporting_observer_list.borrow();
614 list.iter()
615 .position(|observer| &**observer == reporting_observer)
616 };
617
618 if let Some(index) = index {
619 self.reporting_observer_list.borrow_mut().remove(index);
620 }
621 }
622
623 pub(crate) fn registered_reporting_observers(&self) -> Vec<DomRoot<ReportingObserver>> {
624 self.reporting_observer_list
625 .borrow()
626 .iter()
627 .map(|observer| DomRoot::from_ref(&**observer))
628 .collect()
629 }
630
631 pub(crate) fn append_report(&self, report: Report) {
632 self.report_list.borrow_mut().push(report);
633 let trusted_window = Trusted::new(self);
634 self.upcast::<GlobalScope>()
635 .task_manager()
636 .dom_manipulation_task_source()
637 .queue(task!(send_to_reporting_endpoints: move || {
638 let window = trusted_window.root();
639 let reports = std::mem::take(&mut *window.report_list.borrow_mut());
640 window.upcast::<GlobalScope>().send_reports_to_endpoints(
641 reports,
642 window.endpoints_list.borrow().clone(),
643 );
644 }));
645 }
646
647 pub(crate) fn buffered_reports(&self) -> Vec<Report> {
648 self.report_list.borrow().clone()
649 }
650
651 pub(crate) fn set_endpoints_list(&self, endpoints: Vec<ReportingEndpoint>) {
652 *self.endpoints_list.borrow_mut() = endpoints;
653 }
654
655 pub(crate) fn undiscarded_window_proxy(&self) -> Option<DomRoot<WindowProxy>> {
658 self.window_proxy
659 .get()
660 .filter(|window_proxy| !window_proxy.is_browsing_context_discarded())
661 }
662
663 pub(crate) fn top_level_document_if_local(&self) -> Option<DomRoot<Document>> {
668 if self.is_top_level() {
669 return Some(self.Document());
670 }
671
672 let window_proxy = self.undiscarded_window_proxy()?;
673 self.script_window_proxies
674 .find_window_proxy(window_proxy.webview_id().into())?
675 .document()
676 }
677
678 #[cfg(feature = "bluetooth")]
679 pub(crate) fn bluetooth_thread(&self) -> GenericSender<BluetoothRequest> {
680 self.bluetooth_thread.clone()
681 }
682
683 #[cfg(feature = "bluetooth")]
684 pub(crate) fn bluetooth_extra_permission_data(&self) -> &BluetoothExtraPermissionData {
685 &self.bluetooth_extra_permission_data
686 }
687
688 pub(crate) fn css_error_reporter(&self) -> &CSSErrorReporter {
689 &self.error_reporter
690 }
691
692 #[cfg(feature = "webgl")]
693 pub(crate) fn webgl_chan(&self) -> Option<WebGLChan> {
694 self.webgl_chan.clone()
695 }
696
697 #[cfg(feature = "webgl")]
699 pub(crate) fn webgl_chan_value(&self) -> Option<WebGLChan> {
700 self.webgl_chan.clone()
701 }
702
703 #[cfg(feature = "webxr")]
704 pub(crate) fn webxr_registry(&self) -> Option<webxr_api::Registry> {
705 self.webxr_registry.clone()
706 }
707
708 fn new_paint_worklet(&self, cx: &mut JSContext) -> DomRoot<Worklet> {
709 debug!("Creating new paint worklet.");
710
711 let worklet_global_scope_init = self.into();
712 Worklet::new(
713 cx,
714 self,
715 WorkletGlobalScopeType::Paint,
716 Box::new(|| Rc::new(WorkletThreadPool::spawn(worklet_global_scope_init))),
717 )
718 }
719
720 pub(crate) fn register_image_cache_listener(
721 &self,
722 id: PendingImageId,
723 callback: impl Fn(PendingImageResponse, &mut JSContext) + 'static,
724 ) -> ImageCacheResponseCallback {
725 self.pending_image_callbacks
726 .borrow_mut()
727 .entry(id)
728 .or_default()
729 .push(PendingImageCallback(Box::new(callback)));
730
731 let image_cache_sender = self.image_cache_sender.clone();
732 Box::new(move |message| {
733 let _ = image_cache_sender.send(message);
734 })
735 }
736
737 fn pending_layout_image_notification(&self, no_gc: &NoGC, response: PendingImageResponse) {
738 let mut images = self.pending_layout_images.borrow_mut();
739 let nodes = images.entry(response.id);
740 let nodes = match nodes {
741 Entry::Occupied(nodes) => nodes,
742 Entry::Vacant(_) => return,
743 };
744 if matches!(
745 response.response,
746 ImageResponse::Loaded(_, _) | ImageResponse::FailedToLoadOrDecode
747 ) {
748 for ancillary_data in nodes.get() {
749 match ancillary_data.destination {
750 LayoutImageDestination::BoxTreeConstruction => {
751 ancillary_data.node.dirty(no_gc, NodeDamage::Other);
752 },
753 LayoutImageDestination::DisplayListBuilding => {
754 self.layout().set_needs_new_display_list();
755 },
756 }
757 }
758 }
759
760 match response.response {
761 ImageResponse::MetadataLoaded(_) => {},
762 ImageResponse::Loaded(_, _) | ImageResponse::FailedToLoadOrDecode => {
763 nodes.remove();
764 },
765 }
766 }
767
768 pub(crate) fn handle_image_rasterization_complete_notification(
769 &self,
770 no_gc: &NoGC,
771 response: RasterizationCompleteResponse,
772 ) {
773 let mut images = self.pending_images_for_rasterization.borrow_mut();
774 let nodes = images.entry((response.image_id, response.requested_size));
775 let nodes = match nodes {
776 Entry::Occupied(nodes) => nodes,
777 Entry::Vacant(_) => return,
778 };
779 for node in nodes.get() {
780 node.dirty(no_gc, NodeDamage::Other);
781 }
782 nodes.remove();
783 }
784
785 pub(crate) fn pending_image_notification(
786 &self,
787 response: PendingImageResponse,
788 cx: &mut JSContext,
789 ) {
790 let mut images = std::mem::take(&mut *self.pending_image_callbacks.borrow_mut());
795 let Entry::Occupied(callbacks) = images.entry(response.id) else {
796 let _ = std::mem::replace(&mut *self.pending_image_callbacks.borrow_mut(), images);
797 return;
798 };
799
800 for callback in callbacks.get() {
801 callback.0(response.clone(), cx);
802 }
803
804 match response.response {
805 ImageResponse::MetadataLoaded(_) => {},
806 ImageResponse::Loaded(_, _) | ImageResponse::FailedToLoadOrDecode => {
807 callbacks.remove();
808 },
809 }
810
811 let _ = std::mem::replace(&mut *self.pending_image_callbacks.borrow_mut(), images);
812 }
813
814 pub(crate) fn paint_api(&self) -> &CrossProcessPaintApi {
815 &self.paint_api
816 }
817
818 pub(crate) fn userscripts(&self) -> &[UserScript] {
819 &self.user_scripts
820 }
821
822 pub(crate) fn get_player_context(&self) -> WindowGLContext {
823 self.player_context.clone()
824 }
825
826 pub(crate) fn dispatch_event_with_target_override(&self, cx: &mut JSContext, event: &Event) {
828 event.dispatch(cx, self.upcast(), true);
829 }
830
831 pub(crate) fn font_context(&self) -> Arc<FontContext> {
832 self.layout().font_context().clone()
833 }
834
835 pub(crate) fn ongoing_navigation(&self) -> OngoingNavigation {
836 self.ongoing_navigation.get()
837 }
838
839 pub(crate) fn set_ongoing_navigation(&self) -> OngoingNavigation {
841 let new_value = self.ongoing_navigation.get().0.wrapping_add(1);
845
846 self.ongoing_navigation.set(OngoingNavigation(new_value));
853
854 OngoingNavigation(new_value)
856 }
857
858 fn stop_loading(&self, cx: &mut JSContext) {
860 let doc = self.Document();
862
863 self.set_ongoing_navigation();
873
874 doc.abort_a_document_and_its_descendants(cx);
876 }
877
878 fn destroy_top_level_traversable(&self, cx: &mut JSContext) {
880 let document = self.Document();
886 document.destroy_document_and_its_descendants(cx);
888 self.send_to_constellation(ScriptToConstellationMessage::DiscardTopLevelBrowsingContext);
890 }
891
892 fn definitely_close(&self, cx: &mut JSContext) {
894 let document = self.Document();
895 if !document.check_if_unloading_is_cancelled(cx, false) {
900 return;
901 }
902 document.unload(cx, false);
906 self.destroy_top_level_traversable(cx);
908 }
909
910 fn cannot_show_simple_dialogs(&self) -> bool {
912 if self
915 .Document()
916 .has_active_sandboxing_flag(SandboxingFlagSet::SANDBOXED_MODALS_FLAG)
917 {
918 return true;
919 }
920
921 false
940 }
941
942 pub(crate) fn perform_a_microtask_checkpoint(&self, cx: &mut JSContext) {
943 self.script_thread().perform_a_microtask_checkpoint(cx);
944 }
945
946 pub(crate) fn web_font_context(&self, no_gc: &NoGC) -> WebFontDocumentContext {
947 let global = self.as_global_scope();
948 let task_source = global
949 .task_manager()
950 .dom_manipulation_task_source()
951 .to_sendable();
952 let target_global = Trusted::new(global);
953 let document = self.document_unrooted(no_gc);
954 WebFontDocumentContext {
955 policy_container: document.policy_container().clone(),
956 request_client: self.request_client(Some(no_gc)),
957 document_url: document.base_url(),
958 csp_handler: Box::new(FontCspHandler {
959 global: target_global.clone(),
960 task_source: task_source.clone(),
961 }),
962 network_timing_handler: Box::new(FontNetworkTimingHandler {
963 global: target_global,
964 task_source,
965 }),
966 }
967 }
968
969 pub(crate) fn request_client(&self, no_gc: Option<&NoGC>) -> RequestClient {
971 let (
974 preloaded_resources,
975 insecure_requests_policy,
976 has_trustworthy_ancestor_origin,
977 policy_container,
978 origin,
979 ) = if let Some(no_gc) = no_gc {
980 let document = self.document_unrooted(no_gc);
981 (
982 document.preloaded_resources().clone(),
983 document.insecure_requests_policy(),
984 document.has_trustworthy_ancestor_or_current_origin(),
985 document.policy_container().clone(),
986 document.origin().clone(),
987 )
988 } else {
989 let document = self.Document();
990 (
991 document.preloaded_resources().clone(),
992 document.insecure_requests_policy(),
993 document.has_trustworthy_ancestor_or_current_origin(),
994 document.policy_container().clone(),
995 document.origin().clone(),
996 )
997 };
998 RequestClient {
999 preloaded_resources,
1000 policy_container,
1001 origin: Origin::Origin(origin.immutable().clone()),
1002 is_nested_browsing_context: !self.is_top_level(),
1003 insecure_requests_policy,
1004 has_trustworthy_ancestor_origin,
1005 }
1006 }
1007
1008 #[expect(unsafe_code)]
1009 pub(crate) fn gc(&self, cx: &mut JSContext) {
1010 unsafe { JS_GC(cx, GCReason::API) };
1011 }
1012
1013 pub(crate) fn with_timers<T>(&self, f: impl FnOnce(&OneshotTimers) -> T) -> T {
1014 let document = self.Document();
1015 f(document.timers())
1016 }
1017}
1018
1019#[derive(Debug, MallocSizeOf)]
1020struct FontCspHandler {
1021 global: Trusted<GlobalScope>,
1022 task_source: SendableTaskSource,
1023}
1024
1025impl CspViolationHandler for FontCspHandler {
1026 fn process_violations(&self, violations: Vec<Violation>) {
1027 let global = self.global.clone();
1028 self.task_source.queue(task!(csp_violation: move |cx| {
1029 global.root().report_csp_violations(cx, violations, None, None);
1030 }));
1031 }
1032
1033 fn clone(&self) -> Box<dyn CspViolationHandler> {
1034 Box::new(Self {
1035 global: self.global.clone(),
1036 task_source: self.task_source.clone(),
1037 })
1038 }
1039}
1040
1041#[derive(Debug, MallocSizeOf)]
1042struct FontNetworkTimingHandler {
1043 global: Trusted<GlobalScope>,
1044 task_source: SendableTaskSource,
1045}
1046
1047impl NetworkTimingHandler for FontNetworkTimingHandler {
1048 fn submit_timing(&self, url: ServoUrl, response: ResourceFetchTiming) {
1049 let global = self.global.clone();
1050 self.task_source.queue(task!(network_timing: move |cx| {
1051 submit_timing(
1052 cx,
1053 &FontFetchListener {
1054 url,
1055 global
1056 },
1057 &Ok(()),
1058 &response,
1059 );
1060 }));
1061 }
1062
1063 fn clone(&self) -> Box<dyn NetworkTimingHandler> {
1064 Box::new(Self {
1065 global: self.global.clone(),
1066 task_source: self.task_source.clone(),
1067 })
1068 }
1069}
1070
1071#[derive(Debug)]
1072struct FontFetchListener {
1073 global: Trusted<GlobalScope>,
1074 url: ServoUrl,
1075}
1076
1077impl ResourceTimingListener for FontFetchListener {
1078 fn resource_timing_information(&self) -> (InitiatorType, ServoUrl) {
1079 (InitiatorType::Css, self.url.clone())
1080 }
1081
1082 fn resource_timing_global(&self) -> DomRoot<GlobalScope> {
1083 self.global.root()
1084 }
1085}
1086
1087pub(crate) fn base64_btoa(input: DOMString) -> Fallible<DOMString> {
1089 if input.str().chars().any(|c: char| c > '\u{FF}') {
1093 Err(Error::InvalidCharacter(None))
1094 } else {
1095 let octets = input
1100 .str()
1101 .chars()
1102 .map(|c: char| c as u8)
1103 .collect::<Vec<u8>>();
1104
1105 let config =
1108 base64::engine::general_purpose::GeneralPurposeConfig::new().with_encode_padding(true);
1109 let engine = base64::engine::GeneralPurpose::new(&base64::alphabet::STANDARD, config);
1110 Ok(DOMString::from(engine.encode(octets)))
1111 }
1112}
1113
1114pub(crate) fn base64_atob(input: DOMString) -> Fallible<DOMString> {
1116 fn is_html_space(c: char) -> bool {
1118 HTML_SPACE_CHARACTERS.contains(&c)
1119 }
1120 let without_spaces = input
1121 .str()
1122 .chars()
1123 .filter(|&c| !is_html_space(c))
1124 .collect::<String>();
1125 let mut input = &*without_spaces;
1126
1127 if input.len() % 4 == 0 {
1131 if input.ends_with("==") {
1132 input = &input[..input.len() - 2]
1133 } else if input.ends_with('=') {
1134 input = &input[..input.len() - 1]
1135 }
1136 }
1137
1138 if input.len() % 4 == 1 {
1141 return Err(Error::InvalidCharacter(None));
1142 }
1143
1144 if input
1152 .chars()
1153 .any(|c| c != '+' && c != '/' && !c.is_alphanumeric())
1154 {
1155 return Err(Error::InvalidCharacter(None));
1156 }
1157
1158 let config = base64::engine::general_purpose::GeneralPurposeConfig::new()
1159 .with_decode_padding_mode(base64::engine::DecodePaddingMode::RequireNone)
1160 .with_decode_allow_trailing_bits(true);
1161 let engine = base64::engine::GeneralPurpose::new(&base64::alphabet::STANDARD, config);
1162
1163 let data = engine
1164 .decode(input)
1165 .map_err(|_| Error::InvalidCharacter(None))?;
1166 Ok(data.iter().map(|&b| b as char).collect::<String>().into())
1167}
1168
1169impl WindowMethods<crate::DomTypeHolder> for Window {
1170 fn Alert_(&self) {
1172 self.Alert(DOMString::new());
1175 }
1176
1177 fn Alert(&self, mut message: DOMString) {
1179 if self.cannot_show_simple_dialogs() {
1181 return;
1182 }
1183
1184 message.normalize_newlines();
1188
1189 {
1200 let stderr = stderr();
1204 let mut stderr = stderr.lock();
1205 let stdout = stdout();
1206 let mut stdout = stdout.lock();
1207 writeln!(&mut stdout, "\nALERT: {message}").unwrap();
1208 stdout.flush().unwrap();
1209 stderr.flush().unwrap();
1210 }
1211
1212 let (sender, receiver) =
1213 ProfiledGenericChannel::channel(self.global().time_profiler_chan().clone()).unwrap();
1214 let dialog = SimpleDialogRequest::Alert {
1215 id: self.Document().embedder_controls().next_control_id(),
1216 message: String::from(message),
1217 response_sender: sender,
1218 };
1219 self.send_to_embedder(EmbedderMsg::ShowSimpleDialog(self.webview_id(), dialog));
1220 receiver.recv().unwrap_or_else(|_| {
1221 debug!("Alert dialog was cancelled or failed to show.");
1223 AlertResponse::Ok
1224 });
1225
1226 }
1229
1230 fn Caches(&self, cx: &mut JSContext) -> DomRoot<CacheStorage> {
1232 self.caches
1233 .or_init(|| CacheStorage::new(cx, self.as_global_scope()))
1234 }
1235
1236 fn Confirm(&self, mut message: DOMString) -> bool {
1238 if self.cannot_show_simple_dialogs() {
1240 return false;
1241 }
1242
1243 message.normalize_newlines();
1245
1246 let (sender, receiver) =
1252 ProfiledGenericChannel::channel(self.global().time_profiler_chan().clone()).unwrap();
1253 let dialog = SimpleDialogRequest::Confirm {
1254 id: self.Document().embedder_controls().next_control_id(),
1255 message: String::from(message),
1256 response_sender: sender,
1257 };
1258 self.send_to_embedder(EmbedderMsg::ShowSimpleDialog(self.webview_id(), dialog));
1259
1260 match receiver.recv() {
1276 Ok(ConfirmResponse::Ok) => true,
1277 Ok(ConfirmResponse::Cancel) => false,
1278 Err(_) => {
1279 warn!("Confirm dialog was cancelled or failed to show.");
1280 false
1281 },
1282 }
1283 }
1284
1285 fn Prompt(&self, mut message: DOMString, default: DOMString) -> Option<DOMString> {
1287 if self.cannot_show_simple_dialogs() {
1289 return None;
1290 }
1291
1292 message.normalize_newlines();
1294
1295 let (sender, receiver) =
1303 ProfiledGenericChannel::channel(self.global().time_profiler_chan().clone()).unwrap();
1304 let dialog = SimpleDialogRequest::Prompt {
1305 id: self.Document().embedder_controls().next_control_id(),
1306 message: String::from(message),
1307 default: String::from(default),
1308 response_sender: sender,
1309 };
1310 self.send_to_embedder(EmbedderMsg::ShowSimpleDialog(self.webview_id(), dialog));
1311
1312 match receiver.recv() {
1331 Ok(PromptResponse::Ok(input)) => Some(input.into()),
1332 Ok(PromptResponse::Cancel) => None,
1333 Err(_) => {
1334 warn!("Prompt dialog was cancelled or failed to show.");
1335 None
1336 },
1337 }
1338 }
1339
1340 fn Stop(&self, cx: &mut JSContext) {
1342 self.stop_loading(cx);
1347 }
1348
1349 fn Focus(&self, cx: &mut JSContext) {
1351 let document = self.Document();
1360 if !document.is_active() || self.undiscarded_window_proxy().is_none() {
1361 return;
1362 }
1363
1364 document.focus_handler().focus(cx, &FocusableArea::Viewport);
1369
1370 }
1375
1376 fn Blur(&self) {
1378 }
1381
1382 fn Open(
1384 &self,
1385 cx: &mut JSContext,
1386 url: USVString,
1387 target: DOMString,
1388 features: DOMString,
1389 ) -> Fallible<Option<DomRoot<WindowProxy>>> {
1390 self.window_proxy().open(cx, url, target, features)
1391 }
1392
1393 fn GetOpener(&self, cx: &mut CurrentRealm, mut retval: MutableHandleValue) -> Fallible<()> {
1395 let current = match self.window_proxy.get() {
1397 Some(proxy) => proxy,
1398 None => {
1400 retval.set(NullValue());
1401 return Ok(());
1402 },
1403 };
1404 if current.is_browsing_context_discarded() {
1409 retval.set(NullValue());
1410 return Ok(());
1411 }
1412 current.opener(cx, retval);
1414 Ok(())
1415 }
1416
1417 #[expect(unsafe_code)]
1418 fn SetOpener(&self, cx: &mut JSContext, value: HandleValue) -> ErrorResult {
1420 if value.is_null() {
1422 if let Some(proxy) = self.window_proxy.get() {
1423 proxy.disown();
1424 }
1425 return Ok(());
1426 }
1427
1428 let obj = self.reflector().get_jsobject();
1430 let result = unsafe {
1431 JS_DefineProperty(cx, obj, c"opener".as_ptr(), value, JSPROP_ENUMERATE as u32)
1432 };
1433
1434 if result { Ok(()) } else { Err(Error::JSFailed) }
1435 }
1436
1437 fn Closed(&self) -> bool {
1439 self.window_proxy
1440 .get()
1441 .map(|ref proxy| proxy.is_browsing_context_discarded() || proxy.is_closing())
1442 .unwrap_or(true)
1443 }
1444
1445 fn Close(&self, cx: &mut JSContext) {
1447 let window_proxy = match self.window_proxy.get() {
1449 Some(proxy) => proxy,
1450 None => return,
1452 };
1453 if window_proxy.is_closing() {
1455 return;
1456 }
1457 if let Ok(history_length) = self.History(cx).GetLength() {
1460 let is_auxiliary = window_proxy.is_auxiliary();
1461
1462 let is_script_closable = (self.is_top_level() && history_length == 1) ||
1464 is_auxiliary ||
1465 pref!(dom_allow_scripts_to_close_windows);
1466
1467 if is_script_closable {
1471 window_proxy.close();
1473
1474 let this = Trusted::new(self);
1476 let task = task!(window_close_browsing_context: move |cx| {
1477 let window = this.root();
1478 window.definitely_close(cx);
1479 });
1480 self.as_global_scope()
1481 .task_manager()
1482 .dom_manipulation_task_source()
1483 .queue(task);
1484 }
1485 }
1486 }
1487
1488 fn Document(&self) -> DomRoot<Document> {
1490 self.document
1491 .get()
1492 .expect("Document accessed before initialization.")
1493 }
1494
1495 fn History(&self, cx: &mut JSContext) -> DomRoot<History> {
1497 self.Document().history(cx)
1498 }
1499
1500 fn IndexedDB(&self, cx: &mut JSContext) -> DomRoot<IDBFactory> {
1502 self.upcast::<GlobalScope>().ensure_indexeddb_factory(cx)
1503 }
1504
1505 fn CustomElements(&self, cx: &mut JSContext) -> DomRoot<CustomElementRegistry> {
1507 let document = self.Document();
1510 if let Some(registry) = document.custom_element_registry() {
1511 return registry;
1512 }
1513 let registry = CustomElementRegistry::new(cx, self);
1516 document.set_custom_element_registry(®istry);
1517 registry
1519 }
1520
1521 fn Location(&self, cx: &mut JSContext) -> DomRoot<Location> {
1523 self.location.or_init(|| Location::new(cx, self))
1524 }
1525
1526 fn GetSessionStorage(&self, cx: &mut JSContext) -> Fallible<DomRoot<Storage>> {
1528 if let Some(storage) = self.session_storage.get() {
1531 return Ok(storage);
1532 }
1533
1534 if !self.origin().is_tuple() {
1538 return Err(Error::Security(Some(
1539 "Cannot access sessionStorage from opaque origin.".to_string(),
1540 )));
1541 }
1542
1543 let storage = Storage::new(cx, self, WebStorageType::Session);
1545
1546 self.session_storage.set(Some(&storage));
1548
1549 Ok(storage)
1551 }
1552
1553 fn GetLocalStorage(&self, cx: &mut JSContext) -> Fallible<DomRoot<Storage>> {
1555 if let Some(storage) = self.local_storage.get() {
1558 return Ok(storage);
1559 }
1560
1561 if !self.origin().is_tuple() {
1565 return Err(Error::Security(Some(
1566 "Cannot access localStorage from opaque origin.".to_string(),
1567 )));
1568 }
1569
1570 let storage = Storage::new(cx, self, WebStorageType::Local);
1572
1573 self.local_storage.set(Some(&storage));
1575
1576 Ok(storage)
1578 }
1579
1580 fn CookieStore(&self, cx: &mut JSContext) -> DomRoot<CookieStore> {
1582 self.cookie_store
1583 .or_init(|| CookieStore::new(cx, self.upcast::<GlobalScope>()))
1584 }
1585
1586 fn Crypto(&self, cx: &mut JSContext) -> DomRoot<Crypto> {
1588 self.crypto
1589 .or_init(|| Crypto::new(cx, self.as_global_scope()))
1590 }
1591
1592 fn GetFrameElement(&self) -> Option<DomRoot<Element>> {
1594 let window_proxy = self.window_proxy.get()?;
1596
1597 let container = window_proxy.frame_element()?;
1599
1600 let container_doc = container.owner_document();
1602 let current_doc = GlobalScope::current()
1603 .expect("No current global object")
1604 .as_window()
1605 .Document();
1606 if !current_doc
1607 .origin()
1608 .same_origin_domain(&container_doc.origin())
1609 {
1610 return None;
1611 }
1612 Some(DomRoot::from_ref(container))
1614 }
1615
1616 fn ReportError(&self, cx: &mut JSContext, error: HandleValue) {
1618 self.as_global_scope().report_an_exception(cx, error);
1619 }
1620
1621 fn Navigator(&self, cx: &mut JSContext) -> DomRoot<Navigator> {
1623 self.navigator.or_init(|| Navigator::new(cx, self))
1624 }
1625
1626 fn ClientInformation(&self, cx: &mut JSContext) -> DomRoot<Navigator> {
1628 self.Navigator(cx)
1629 }
1630
1631 fn SetTimeout(
1633 &self,
1634 cx: &mut JSContext,
1635 callback: TrustedScriptOrStringOrFunction,
1636 timeout: i32,
1637 args: Vec<HandleValue>,
1638 ) -> Fallible<i32> {
1639 let callback = match callback {
1640 TrustedScriptOrStringOrFunction::String(i) => {
1641 TimerCallback::StringTimerCallback(TrustedScriptOrString::String(i))
1642 },
1643 TrustedScriptOrStringOrFunction::TrustedScript(i) => {
1644 TimerCallback::StringTimerCallback(TrustedScriptOrString::TrustedScript(i))
1645 },
1646 TrustedScriptOrStringOrFunction::Function(i) => TimerCallback::FunctionTimerCallback(i),
1647 };
1648 self.as_global_scope().set_timeout_or_interval(
1649 cx,
1650 callback,
1651 args,
1652 Duration::from_millis(timeout.max(0) as u64),
1653 IsInterval::NonInterval,
1654 )
1655 }
1656
1657 fn ClearTimeout(&self, handle: i32) {
1659 self.as_global_scope().clear_timeout_or_interval(handle);
1660 }
1661
1662 fn SetInterval(
1664 &self,
1665 cx: &mut JSContext,
1666 callback: TrustedScriptOrStringOrFunction,
1667 timeout: i32,
1668 args: Vec<HandleValue>,
1669 ) -> Fallible<i32> {
1670 let callback = match callback {
1671 TrustedScriptOrStringOrFunction::String(i) => {
1672 TimerCallback::StringTimerCallback(TrustedScriptOrString::String(i))
1673 },
1674 TrustedScriptOrStringOrFunction::TrustedScript(i) => {
1675 TimerCallback::StringTimerCallback(TrustedScriptOrString::TrustedScript(i))
1676 },
1677 TrustedScriptOrStringOrFunction::Function(i) => TimerCallback::FunctionTimerCallback(i),
1678 };
1679 self.as_global_scope().set_timeout_or_interval(
1680 cx,
1681 callback,
1682 args,
1683 Duration::from_millis(timeout.max(0) as u64),
1684 IsInterval::Interval,
1685 )
1686 }
1687
1688 fn ClearInterval(&self, handle: i32) {
1690 self.ClearTimeout(handle);
1691 }
1692
1693 fn QueueMicrotask(&self, cx: &JSContext, callback: Rc<VoidFunction>) {
1695 ScriptThread::enqueue_microtask(
1696 cx,
1697 Box::new(UserMicrotask {
1698 callback,
1699 global: Dom::from_ref(&self.globalscope),
1700 }),
1701 );
1702 }
1703
1704 fn CreateImageBitmap(
1706 &self,
1707 realm: &mut CurrentRealm,
1708 image: ImageBitmapSource,
1709 options: &ImageBitmapOptions,
1710 ) -> Rc<Promise> {
1711 ImageBitmap::create_image_bitmap(
1712 self.as_global_scope(),
1713 image,
1714 0,
1715 0,
1716 None,
1717 None,
1718 options,
1719 realm,
1720 )
1721 }
1722
1723 fn CreateImageBitmap_(
1725 &self,
1726 realm: &mut CurrentRealm,
1727 image: ImageBitmapSource,
1728 sx: i32,
1729 sy: i32,
1730 sw: i32,
1731 sh: i32,
1732 options: &ImageBitmapOptions,
1733 ) -> Rc<Promise> {
1734 ImageBitmap::create_image_bitmap(
1735 self.as_global_scope(),
1736 image,
1737 sx,
1738 sy,
1739 Some(sw),
1740 Some(sh),
1741 options,
1742 realm,
1743 )
1744 }
1745
1746 fn Window(&self) -> DomRoot<WindowProxy> {
1748 self.window_proxy()
1749 }
1750
1751 fn Self_(&self) -> DomRoot<WindowProxy> {
1753 self.window_proxy()
1754 }
1755
1756 fn Frames(&self) -> DomRoot<WindowProxy> {
1758 self.window_proxy()
1759 }
1760
1761 fn Length(&self) -> u32 {
1763 self.Document().iframes().iter().count() as u32
1764 }
1765
1766 fn GetParent(&self) -> Option<DomRoot<WindowProxy>> {
1768 let window_proxy = self.undiscarded_window_proxy()?;
1770
1771 if let Some(parent) = window_proxy.parent() {
1773 return Some(DomRoot::from_ref(parent));
1774 }
1775 Some(window_proxy)
1777 }
1778
1779 fn GetTop(&self) -> Option<DomRoot<WindowProxy>> {
1781 let window_proxy = self.undiscarded_window_proxy()?;
1783
1784 Some(DomRoot::from_ref(window_proxy.top()))
1786 }
1787
1788 fn Performance(&self, cx: &mut JSContext) -> DomRoot<Performance> {
1791 self.performance.or_init(|| {
1792 Performance::new(
1793 cx,
1794 self.as_global_scope(),
1795 self.navigation_start.get(),
1796 self.Document().navigation_timing(),
1797 )
1798 })
1799 }
1800
1801 global_event_handlers!();
1803
1804 window_event_handlers!();
1806
1807 fn Screen(&self, cx: &mut JSContext) -> DomRoot<Screen> {
1809 self.screen.or_init(|| Screen::new(cx, self))
1810 }
1811
1812 fn GetVisualViewport(&self, cx: &mut JSContext) -> Option<DomRoot<VisualViewport>> {
1814 if !self.Document().is_fully_active() {
1818 return None;
1819 }
1820
1821 Some(self.get_or_init_visual_viewport(cx))
1822 }
1823
1824 fn Btoa(&self, btoa: DOMString) -> Fallible<DOMString> {
1826 base64_btoa(btoa)
1827 }
1828
1829 fn Atob(&self, atob: DOMString) -> Fallible<DOMString> {
1831 base64_atob(atob)
1832 }
1833
1834 fn RequestAnimationFrame(&self, callback: Rc<FrameRequestCallback>) -> Fallible<u32> {
1836 Ok(self
1837 .Document()
1838 .request_animation_frame(AnimationFrameCallback::FrameRequestCallback { callback }))
1839 }
1840
1841 fn CancelAnimationFrame(&self, ident: u32) -> ErrorResult {
1843 let doc = self.Document();
1844 doc.cancel_animation_frame(ident);
1845 Ok(())
1846 }
1847
1848 fn PostMessage(
1850 &self,
1851 cx: &mut JSContext,
1852 message: HandleValue,
1853 target_origin: USVString,
1854 transfer: CustomAutoRooterGuard<Vec<*mut JSObject>>,
1855 ) -> ErrorResult {
1856 let incumbent = GlobalScope::incumbent().expect("no incumbent global?");
1857 let source = incumbent.as_window();
1858 let source_origin = source.Document().origin().immutable().clone();
1859
1860 self.post_message_impl(&target_origin, source_origin, source, cx, message, transfer)
1861 }
1862
1863 fn PostMessage_(
1865 &self,
1866 cx: &mut JSContext,
1867 message: HandleValue,
1868 options: RootedTraceableBox<WindowPostMessageOptions>,
1869 ) -> ErrorResult {
1870 let mut rooted = CustomAutoRooter::new(
1871 options
1872 .parent
1873 .transfer
1874 .iter()
1875 .map(|js: &RootedTraceableBox<Heap<*mut JSObject>>| js.get())
1876 .collect(),
1877 );
1878 #[expect(unsafe_code)]
1879 let transfer = unsafe { CustomAutoRooterGuard::new(cx.raw_cx(), &mut rooted) };
1880
1881 let incumbent = GlobalScope::incumbent().expect("no incumbent global?");
1882 let source = incumbent.as_window();
1883
1884 let source_origin = source.Document().origin().immutable().clone();
1885
1886 self.post_message_impl(
1887 &options.targetOrigin,
1888 source_origin,
1889 source,
1890 cx,
1891 message,
1892 transfer,
1893 )
1894 }
1895
1896 fn CaptureEvents(&self) {
1898 }
1900
1901 fn ReleaseEvents(&self) {
1903 }
1905
1906 fn WebdriverCallback(&self, realm: &mut CurrentRealm, value: HandleValue) {
1908 let webdriver_script_sender = self.webdriver_script_chan.borrow_mut().take();
1909 if let Some(webdriver_script_sender) = webdriver_script_sender {
1910 let result = jsval_to_webdriver(realm, &self.globalscope, value);
1911 let _ = webdriver_script_sender.send(result);
1912 }
1913 }
1914
1915 fn WebdriverException(&self, cx: &mut JSContext, value: HandleValue) {
1916 let webdriver_script_sender = self.webdriver_script_chan.borrow_mut().take();
1917 if let Some(webdriver_script_sender) = webdriver_script_sender {
1918 let error_info = ErrorInfo::from_value(cx, value);
1919 let _ = webdriver_script_sender.send(Err(
1920 JavaScriptEvaluationError::EvaluationFailure(Some(
1921 javascript_error_info_from_error_info(cx, &error_info, value),
1922 )),
1923 ));
1924 }
1925 }
1926
1927 fn WebdriverElement(&self, id: DOMString) -> Option<DomRoot<Element>> {
1928 find_node_by_unique_id_in_document(&self.Document(), id.into()).and_then(Root::downcast)
1929 }
1930
1931 fn WebdriverFrame(&self, browsing_context_id: DOMString) -> Option<DomRoot<WindowProxy>> {
1932 self.Document()
1933 .iframes()
1934 .iter()
1935 .find(|iframe| {
1936 iframe
1937 .browsing_context_id()
1938 .as_ref()
1939 .map(BrowsingContextId::to_string) ==
1940 Some(browsing_context_id.to_string())
1941 })
1942 .and_then(|iframe| iframe.GetContentWindow())
1943 }
1944
1945 fn WebdriverWindow(&self, webview_id: DOMString) -> DomRoot<WindowProxy> {
1946 let window_proxy = &self
1947 .window_proxy
1948 .get()
1949 .expect("Should always have a WindowProxy when calling WebdriverWindow");
1950 assert!(
1951 self.is_top_level(),
1952 "Window must be top level browsing context."
1953 );
1954 assert!(self.webview_id().to_string() == webview_id);
1955 DomRoot::from_ref(window_proxy)
1956 }
1957
1958 fn WebdriverShadowRoot(&self, id: DOMString) -> Option<DomRoot<ShadowRoot>> {
1959 find_node_by_unique_id_in_document(&self.Document(), id.into()).and_then(Root::downcast)
1960 }
1961
1962 fn GetComputedStyle(
1964 &self,
1965 cx: &mut JSContext,
1966 element: &Element,
1967 pseudo: Option<DOMString>,
1968 ) -> DomRoot<CSSStyleDeclaration> {
1969 let mut is_null = false;
1973
1974 let pseudo = pseudo.map(|mut s| {
1980 s.make_ascii_lowercase();
1981 s
1982 });
1983 let pseudo = match pseudo {
1984 Some(ref pseudo) if pseudo == ":before" || pseudo == "::before" => {
1985 Some(PseudoElement::Before)
1986 },
1987 Some(ref pseudo) if pseudo == ":after" || pseudo == "::after" => {
1988 Some(PseudoElement::After)
1989 },
1990 Some(ref pseudo) if pseudo == "::selection" => Some(PseudoElement::Selection),
1991 Some(ref pseudo) if pseudo == "::marker" => Some(PseudoElement::Marker),
1992 Some(ref pseudo) if pseudo == "::placeholder" => Some(PseudoElement::Placeholder),
1993 Some(ref pseudo) if pseudo.starts_with(':') => {
1994 is_null = true;
1997 None
1998 },
1999 _ => None,
2000 };
2001
2002 CSSStyleDeclaration::new(
2018 cx,
2019 self,
2020 if is_null {
2021 CSSStyleOwner::Null
2022 } else {
2023 CSSStyleOwner::Element(Dom::from_ref(element))
2024 },
2025 pseudo,
2026 CSSModificationAccess::Readonly,
2027 )
2028 }
2029
2030 fn InnerHeight(&self) -> i32 {
2033 self.viewport_details
2034 .get()
2035 .size
2036 .height
2037 .to_i32()
2038 .unwrap_or(0)
2039 }
2040
2041 fn InnerWidth(&self) -> i32 {
2044 self.viewport_details.get().size.width.to_i32().unwrap_or(0)
2045 }
2046
2047 fn ScrollX(&self) -> i32 {
2049 self.scroll_offset().x as i32
2050 }
2051
2052 fn PageXOffset(&self) -> i32 {
2054 self.ScrollX()
2055 }
2056
2057 fn ScrollY(&self) -> i32 {
2059 self.scroll_offset().y as i32
2060 }
2061
2062 fn PageYOffset(&self) -> i32 {
2064 self.ScrollY()
2065 }
2066
2067 fn Scroll(&self, cx: &mut JSContext, options: &ScrollToOptions) {
2069 let x = options.left.unwrap_or(0.0) as f32;
2074
2075 let y = options.top.unwrap_or(0.0) as f32;
2078
2079 self.scroll(cx, x, y, options.parent.behavior);
2081 }
2082
2083 fn Scroll_(&self, cx: &mut JSContext, x: f64, y: f64) {
2085 self.scroll(cx, x as f32, y as f32, ScrollBehavior::Auto);
2089 }
2090
2091 fn ScrollTo(&self, cx: &mut JSContext, options: &ScrollToOptions) {
2096 self.Scroll(cx, options);
2097 }
2098
2099 fn ScrollTo_(&self, cx: &mut JSContext, x: f64, y: f64) {
2104 self.Scroll_(cx, x, y)
2105 }
2106
2107 fn ScrollBy(&self, cx: &mut JSContext, options: &ScrollToOptions) {
2109 let mut options = options.clone();
2115 let x = options.left.unwrap_or(0.0);
2116 let x = if x.is_finite() { x } else { 0.0 };
2117 let y = options.top.unwrap_or(0.0);
2118 let y = if y.is_finite() { y } else { 0.0 };
2119
2120 options.left.replace(x + self.ScrollX() as f64);
2122
2123 options.top.replace(y + self.ScrollY() as f64);
2125
2126 self.Scroll(cx, &options)
2128 }
2129
2130 fn ScrollBy_(&self, cx: &mut JSContext, x: f64, y: f64) {
2132 let mut options = ScrollToOptions::empty();
2136
2137 options.left.replace(x);
2140
2141 options.top.replace(y);
2143
2144 self.ScrollBy(cx, &options);
2146 }
2147
2148 fn ResizeTo(&self, width: i32, height: i32) {
2150 let window_proxy = match self.window_proxy.get() {
2152 Some(proxy) => proxy,
2153 None => return,
2154 };
2155
2156 if !window_proxy.is_auxiliary() {
2159 return;
2160 }
2161
2162 let dpr = self.device_pixel_ratio();
2163 let size = Size2D::new(width, height).to_f32() * dpr;
2164 self.send_to_embedder(EmbedderMsg::ResizeTo(self.webview_id(), size.to_i32()));
2165 }
2166
2167 fn ResizeBy(&self, x: i32, y: i32) {
2169 let size = self.client_window().size();
2170 self.ResizeTo(x + size.width, y + size.height)
2172 }
2173
2174 fn MoveTo(&self, x: i32, y: i32) {
2176 let dpr = self.device_pixel_ratio();
2179 let point = Point2D::new(x, y).to_f32() * dpr;
2180 let msg = EmbedderMsg::MoveTo(self.webview_id(), point.to_i32());
2181 self.send_to_embedder(msg);
2182 }
2183
2184 fn MoveBy(&self, x: i32, y: i32) {
2186 let origin = self.client_window().min;
2187 self.MoveTo(x + origin.x, y + origin.y)
2189 }
2190
2191 fn ScreenX(&self) -> i32 {
2193 self.client_window().min.x
2194 }
2195
2196 fn ScreenLeft(&self) -> i32 {
2198 self.client_window().min.x
2199 }
2200
2201 fn ScreenY(&self) -> i32 {
2203 self.client_window().min.y
2204 }
2205
2206 fn ScreenTop(&self) -> i32 {
2208 self.client_window().min.y
2209 }
2210
2211 fn OuterHeight(&self) -> i32 {
2213 self.client_window().height()
2214 }
2215
2216 fn OuterWidth(&self) -> i32 {
2218 self.client_window().width()
2219 }
2220
2221 fn DevicePixelRatio(&self) -> Finite<f64> {
2223 Finite::wrap(self.device_pixel_ratio().get() as f64)
2224 }
2225
2226 fn Status(&self) -> DOMString {
2228 self.status.borrow().clone()
2229 }
2230
2231 fn SetStatus(&self, status: DOMString) {
2233 *self.status.borrow_mut() = status
2234 }
2235
2236 fn MatchMedia(&self, cx: &mut JSContext, query: DOMString) -> DomRoot<MediaQueryList> {
2238 let media_query_list = MediaList::parse_media_list(&query.str(), self);
2239 let document = self.Document();
2240 let mql = MediaQueryList::new(cx, &document, media_query_list);
2241 self.media_query_lists.track(&*mql);
2242 mql
2243 }
2244
2245 fn Fetch(
2247 &self,
2248 realm: &mut CurrentRealm,
2249 input: RequestOrUSVString,
2250 init: RootedTraceableBox<RequestInit>,
2251 ) -> Rc<Promise> {
2252 fetch::Fetch(self.upcast(), input, init, realm)
2253 }
2254
2255 fn FetchLater(
2257 &self,
2258 cx: &mut JSContext,
2259 input: RequestInfo,
2260 init: RootedTraceableBox<DeferredRequestInit>,
2261 ) -> Fallible<DomRoot<FetchLaterResult>> {
2262 fetch::FetchLater(cx, self, input, init)
2263 }
2264
2265 #[cfg(feature = "bluetooth")]
2266 fn TestRunner(&self, cx: &mut JSContext) -> DomRoot<TestRunner> {
2267 self.test_runner
2268 .or_init(|| TestRunner::new(cx, self.upcast()))
2269 }
2270
2271 fn RunningAnimationCount(&self) -> u32 {
2272 self.document
2273 .get()
2274 .map_or(0, |d| d.animations().running_animation_count() as u32)
2275 }
2276
2277 fn SetName(&self, name: DOMString) {
2279 if let Some(proxy) = self.undiscarded_window_proxy() {
2280 proxy.set_name(name);
2281 }
2282 }
2283
2284 fn Name(&self) -> DOMString {
2286 match self.undiscarded_window_proxy() {
2287 Some(proxy) => proxy.get_name(),
2288 None => "".into(),
2289 }
2290 }
2291
2292 fn Origin(&self) -> USVString {
2294 USVString(self.origin().immutable().ascii_serialization())
2295 }
2296
2297 fn GetSelection(&self, cx: &mut JSContext) -> Option<DomRoot<Selection>> {
2299 self.document.get().and_then(|d| d.GetSelection(cx))
2300 }
2301
2302 fn Event(&self, cx: &mut JSContext, rval: MutableHandleValue) {
2304 if let Some(ref event) = *self.current_event.borrow() {
2305 event.reflector().get_jsobject().safe_to_jsval(cx, rval);
2306 }
2307 }
2308
2309 fn IsSecureContext(&self) -> bool {
2310 self.as_global_scope().is_secure_context()
2311 }
2312
2313 fn NamedGetter(&self, cx: &mut JSContext, name: DOMString) -> Option<NamedPropertyValue> {
2315 if name.is_empty() {
2316 return None;
2317 }
2318 let document = self.Document();
2319
2320 let iframes: Vec<_> = document
2322 .iframes()
2323 .iter()
2324 .filter(|iframe| {
2325 if let Some(window) = iframe.GetContentWindow() {
2326 return window.get_name() == name;
2327 }
2328 false
2329 })
2330 .collect();
2331
2332 let iframe_iter = iframes.iter().map(|iframe| iframe.upcast::<Element>());
2333
2334 let name = Atom::from(name);
2335
2336 let elements_with_name = document.get_elements_with_name(cx, &name);
2338 let name_iter = elements_with_name
2339 .iter()
2340 .map(|element| &**element)
2341 .filter(|elem| is_named_element_with_name_attribute(elem));
2342
2343 let elements_with_id = document.get_elements_with_id(cx, &name);
2344 let id_iter = elements_with_id
2345 .iter()
2346 .map(|element| &**element)
2347 .filter(|elem| is_named_element_with_id_attribute(elem));
2348
2349 for elem in iframe_iter.clone() {
2351 if let Some(nested_window_proxy) = elem
2352 .downcast::<HTMLIFrameElement>()
2353 .and_then(|iframe| iframe.GetContentWindow())
2354 {
2355 return Some(NamedPropertyValue::WindowProxy(nested_window_proxy));
2356 }
2357 }
2358
2359 let mut elements = iframe_iter.chain(name_iter).chain(id_iter);
2360
2361 let first = elements.next()?;
2362
2363 if elements.next().is_none() {
2364 return Some(NamedPropertyValue::Element(DomRoot::from_ref(first)));
2366 }
2367
2368 #[derive(JSTraceable, MallocSizeOf)]
2370 struct WindowNamedGetter {
2371 #[no_trace]
2372 name: Atom,
2373 }
2374 impl CollectionFilter for WindowNamedGetter {
2375 fn filter(&self, elem: &Element, _root: &Node) -> bool {
2376 let type_ = match elem.upcast::<Node>().type_id() {
2377 NodeTypeId::Element(ElementTypeId::HTMLElement(type_)) => type_,
2378 _ => return false,
2379 };
2380 if elem.get_id().as_ref() == Some(&self.name) {
2381 return true;
2382 }
2383 match type_ {
2384 HTMLElementTypeId::HTMLEmbedElement |
2385 HTMLElementTypeId::HTMLFormElement |
2386 HTMLElementTypeId::HTMLImageElement |
2387 HTMLElementTypeId::HTMLObjectElement => {
2388 elem.get_name().as_ref() == Some(&self.name)
2389 },
2390 _ => false,
2391 }
2392 }
2393 }
2394 let collection = HTMLCollection::create(
2395 cx,
2396 self,
2397 document.upcast(),
2398 Box::new(WindowNamedGetter { name }),
2399 );
2400 Some(NamedPropertyValue::HTMLCollection(collection))
2401 }
2402
2403 fn SupportedPropertyNames(&self, no_gc: &NoGC) -> Vec<DOMString> {
2405 self.Document().SupportedPropertyNames(no_gc)
2406 }
2407
2408 fn StructuredClone(
2410 &self,
2411 cx: &mut JSContext,
2412 value: HandleValue,
2413 options: RootedTraceableBox<StructuredSerializeOptions>,
2414 retval: MutableHandleValue,
2415 ) -> Fallible<()> {
2416 self.as_global_scope()
2417 .structured_clone(cx, value, options, retval)
2418 }
2419
2420 fn TrustedTypes(&self, cx: &mut JSContext) -> DomRoot<TrustedTypePolicyFactory> {
2421 self.trusted_types
2422 .or_init(|| TrustedTypePolicyFactory::new(cx, self.as_global_scope()))
2423 }
2424}
2425
2426impl Window {
2427 pub(crate) fn scroll_offset(&self) -> Vector2D<f32, LayoutPixel> {
2428 self.scroll_offset_query_with_external_scroll_id(self.pipeline_id().root_scroll_id())
2429 }
2430
2431 pub(crate) fn create_named_properties_object(
2434 cx: &mut JSContext,
2435 proto: HandleObject,
2436 object: MutableHandleObject,
2437 ) {
2438 window_named_properties::create(cx, proto, object)
2439 }
2440
2441 pub(crate) fn current_event(&self) -> Option<DomRoot<Event>> {
2442 self.current_event
2443 .borrow()
2444 .as_ref()
2445 .map(|e| DomRoot::from_ref(&**e))
2446 }
2447
2448 pub(crate) fn set_current_event(&self, event: Option<&Event>) -> Option<DomRoot<Event>> {
2449 let current = self.current_event();
2450 *self.current_event.borrow_mut() = event.map(Dom::from_ref);
2451 current
2452 }
2453
2454 fn post_message_impl(
2456 &self,
2457 target_origin: &USVString,
2458 source_origin: ImmutableOrigin,
2459 source: &Window,
2460 cx: &mut JSContext,
2461 message: HandleValue,
2462 transfer: CustomAutoRooterGuard<Vec<*mut JSObject>>,
2463 ) -> ErrorResult {
2464 let data = structuredclone::write(cx, message, Some(transfer))?;
2466
2467 let target_origin = match target_origin.0[..].as_ref() {
2469 "*" => None,
2470 "/" => Some(source_origin.clone()),
2471 url => match ServoUrl::parse(url) {
2472 Ok(url) => Some(url.origin()),
2473 Err(_) => return Err(Error::Syntax(None)),
2474 },
2475 };
2476
2477 self.post_message(target_origin, source_origin, &source.window_proxy(), data);
2479 Ok(())
2480 }
2481
2482 pub(crate) fn paint_worklet(&self, cx: &mut JSContext) -> DomRoot<Worklet> {
2484 self.paint_worklet.or_init(|| self.new_paint_worklet(cx))
2485 }
2486
2487 pub(crate) fn clear_js_runtime(&self) {
2488 self.as_global_scope()
2489 .remove_web_messaging_and_dedicated_workers_infra();
2490
2491 self.Document().teardown_custom_element_registry();
2494
2495 self.current_state.set(WindowState::Zombie);
2496 *self.js_runtime.borrow_mut() = None;
2497
2498 if let Some(performance) = self.performance.get() {
2499 performance.clear_and_disable_performance_entry_buffer();
2500 }
2501
2502 self.as_global_scope()
2503 .task_manager()
2504 .cancel_all_tasks_and_ignore_future_tasks();
2505
2506 if let Some(factory) = self.upcast::<GlobalScope>().indexeddb_factory() {
2511 factory.abort_pending_upgrades_and_close_databases();
2512 }
2513
2514 self.pending_image_callbacks.borrow_mut().clear();
2517 }
2518
2519 pub(crate) fn scroll(&self, cx: &mut JSContext, x: f32, y: f32, behavior: ScrollBehavior) {
2521 let xfinite = if x.is_finite() { x } else { 0.0 };
2523 let yfinite = if y.is_finite() { y } else { 0.0 };
2524
2525 let viewport = self.viewport_details.get().size;
2535
2536 let scrolling_area = self.scrolling_area_query(None).to_f32();
2555 let x = xfinite.clamp(0.0, 0.0f32.max(scrolling_area.width() - viewport.width));
2556 let y = yfinite.clamp(0.0, 0.0f32.max(scrolling_area.height() - viewport.height));
2557
2558 let scroll_offset = self.scroll_offset();
2561 if x == scroll_offset.x && y == scroll_offset.y {
2562 return;
2563 }
2564
2565 self.perform_a_scroll(
2570 cx,
2571 x,
2572 y,
2573 self.pipeline_id().root_scroll_id(),
2574 behavior,
2575 None,
2576 );
2577 }
2578
2579 pub(crate) fn perform_a_scroll(
2581 &self,
2582 cx: &mut JSContext,
2583 x: f32,
2584 y: f32,
2585 scroll_id: ExternalScrollId,
2586 _behavior: ScrollBehavior,
2587 element: Option<&Element>,
2588 ) {
2589 let (reflow_phases_run, _) = self.reflow(
2593 cx,
2594 ReflowGoal::UpdateScrollNode(scroll_id, Vector2D::new(x, y)),
2595 );
2596 if reflow_phases_run.needs_frame() {
2597 self.paint_api()
2598 .generate_frame(vec![self.webview_id().into()]);
2599 }
2600
2601 if reflow_phases_run.contains(ReflowPhasesRun::UpdatedScrollNodeOffset) {
2606 match element {
2607 Some(element) if !scroll_id.is_root() => element.handle_scroll_event(),
2608 _ => self.Document().handle_viewport_scroll_event(),
2609 };
2610 }
2611 }
2612
2613 pub(crate) fn device_pixel_ratio(&self) -> Scale<f32, CSSPixel, DevicePixel> {
2614 self.viewport_details.get().hidpi_scale_factor
2615 }
2616
2617 fn client_window(&self) -> DeviceIndependentIntRect {
2618 let (sender, receiver) = generic_channel::channel().expect("Failed to create IPC channel!");
2619
2620 self.send_to_embedder(EmbedderMsg::GetWindowRect(self.webview_id(), sender));
2621
2622 receiver.recv().unwrap_or_default()
2623 }
2624
2625 pub(crate) fn advance_animation_clock(&self, no_gc: &NoGC, delta: TimeDuration) {
2628 self.Document()
2629 .advance_animation_timeline_for_testing(delta);
2630 ScriptThread::handle_tick_all_animations_for_testing(no_gc, self.pipeline_id());
2631 }
2632
2633 pub(crate) fn reflow(
2641 &self,
2642 cx: &mut JSContext,
2643 reflow_goal: ReflowGoal,
2644 ) -> (ReflowPhasesRun, ReflowStatistics) {
2645 let document = self.Document();
2646
2647 if !document.is_fully_active() {
2649 return Default::default();
2650 }
2651
2652 self.document_unrooted(cx.no_gc())
2653 .ensure_safe_to_run_script_or_layout();
2654
2655 match reflow_goal {
2659 ReflowGoal::LayoutQuery(_) | ReflowGoal::UpdateScrollNode(..) => {
2660 self.flush_ancestor_layouts_if_necessary(cx);
2661 },
2662 ReflowGoal::UpdateTheRendering => { },
2663 }
2664
2665 let pipeline_id = self.pipeline_id();
2669 if reflow_goal == ReflowGoal::UpdateTheRendering &&
2670 self.layout_blocker.get().layout_blocked()
2671 {
2672 debug!("Suppressing pre-load-event reflow pipeline {pipeline_id}");
2673 return Default::default();
2674 }
2675
2676 debug!("script: performing reflow for goal {reflow_goal:?}");
2677 let marker = if self.need_emit_timeline_marker(TimelineMarkerType::Reflow) {
2678 Some(TimelineMarker::start("Reflow".to_owned()))
2679 } else {
2680 None
2681 };
2682
2683 if let Some(selection) = document.selection() {
2684 selection.set_flags_for_visible_selection(cx.no_gc());
2685 }
2686
2687 let restyle_reason = document.restyle_reason(cx.no_gc());
2688 document.clear_restyle_reasons();
2689 let restyle = if restyle_reason.needs_restyle() {
2690 debug!("Invalidating layout cache due to reflow condition {restyle_reason:?}",);
2691 self.layout_marker.borrow().set(false);
2693 *self.layout_marker.borrow_mut() = Rc::new(Cell::new(true));
2695
2696 if restyle_reason.contains(RestyleReason::ViewportChanged) &&
2700 self.layout().device().used_viewport_size()
2701 {
2702 document.dirty_all_nodes(cx.no_gc());
2703 }
2704
2705 let stylesheets_changed = document.flush_stylesheets_for_reflow();
2706 let pending_restyles = document.drain_pending_restyles(cx.no_gc());
2707 let dirty_root = document
2708 .take_dirty_root()
2709 .filter(|_| !stylesheets_changed)
2710 .or_else(|| document.GetDocumentElement())
2711 .map(|root| root.upcast::<Node>().to_trusted_node_address());
2712
2713 Some(ReflowRequestRestyle {
2714 reason: restyle_reason,
2715 dirty_root,
2716 stylesheets_changed,
2717 pending_restyles,
2718 })
2719 } else {
2720 None
2721 };
2722
2723 document.id_map().resolve_all(cx.no_gc(), document.upcast());
2726
2727 let document_context = self.web_font_context(cx.no_gc());
2728
2729 let mut rooted_nodes_for_accessibility_integrity_check = None;
2730 let mut accessibility_damage = None;
2731 if reflow_goal == ReflowGoal::UpdateTheRendering && self.layout().accessibility_active() {
2732 rooted_nodes_for_accessibility_integrity_check =
2733 document.rooted_nodes_for_accessibility_integrity_check();
2734 let mut accessibility_data = document.accessibility_data_mut();
2735 accessibility_damage = Some(accessibility_data.drain_pending_accessibility_damage());
2736 }
2737
2738 let reflow = ReflowRequest {
2740 document: document.upcast::<Node>().to_trusted_node_address(),
2741 epoch: document.current_rendering_epoch(),
2742 restyle,
2743 viewport_details: self.viewport_details.get(),
2744 origin: self.origin().immutable().clone(),
2745 reflow_goal,
2746 animation_timeline_value: document.current_animation_timeline_value(),
2747 animations: document.animations().sets.clone(),
2748 animating_images: document.image_animation_manager().animating_images(),
2749 highlighted_dom_node: document.highlighted_dom_node().map(|node| node.to_opaque()),
2750 document_context,
2751 accessibility_damage,
2752 rooted_nodes_for_accessibility_integrity_check,
2753 };
2754
2755 let Some(reflow_result) = self.layout.borrow_mut().reflow(reflow) else {
2756 return Default::default();
2757 };
2758
2759 debug!("script: layout complete");
2760 if let Some(marker) = marker {
2761 self.emit_timeline_marker(marker.end());
2762 }
2763
2764 self.handle_new_or_removed_web_fonts_post_reflow(cx, reflow_result.changed_web_fonts);
2765
2766 self.handle_pending_images_post_reflow(
2767 cx,
2768 reflow_result.pending_images,
2769 reflow_result.pending_rasterization_images,
2770 reflow_result.pending_svg_elements_for_serialization,
2771 );
2772
2773 if let Some(candidate) = &reflow_result.lcp_candidate &&
2774 let Some(node_address) = reflow_result.lcp_node_address
2775 {
2776 self.process_lcp_candidate_post_reflow(candidate, node_address, &document);
2777 }
2778
2779 if let Some(iframe_sizes) = reflow_result.iframe_sizes {
2780 document
2781 .iframes_mut()
2782 .handle_new_iframe_sizes_after_layout(cx, self, iframe_sizes);
2783 }
2784
2785 document.update_animations_post_reflow();
2786
2787 (
2788 reflow_result.reflow_phases_run,
2789 reflow_result.reflow_statistics,
2790 )
2791 }
2792
2793 pub(crate) fn request_screenshot_readiness(&self, cx: &mut JSContext) {
2794 self.has_pending_screenshot_readiness_request.set(true);
2795 self.maybe_resolve_pending_screenshot_readiness_requests(cx);
2796 }
2797
2798 pub(crate) fn maybe_resolve_pending_screenshot_readiness_requests(&self, cx: &mut JSContext) {
2799 let pending_request = self.has_pending_screenshot_readiness_request.get();
2800 if !pending_request {
2801 return;
2802 }
2803
2804 let document = self.Document();
2805 if document.ReadyState() != DocumentReadyState::Complete {
2806 return;
2807 }
2808
2809 if document.render_blocking_element_count() > 0 {
2810 return;
2811 }
2812
2813 if document.GetDocumentElement().is_some_and(|elem| {
2817 elem.has_class(&atom!("reftest-wait"), CaseSensitivity::CaseSensitive) ||
2818 elem.has_class(&Atom::from("test-wait"), CaseSensitivity::CaseSensitive)
2819 }) {
2820 return;
2821 }
2822
2823 if self.font_context().web_fonts_still_loading() != 0 {
2824 return;
2825 }
2826
2827 if self.Document().Fonts(cx).waiting_to_fullfill_promise() {
2828 return;
2829 }
2830
2831 if !self.pending_layout_images.borrow().is_empty() ||
2832 !self.pending_images_for_rasterization.borrow().is_empty()
2833 {
2834 return;
2835 }
2836
2837 let document = self.Document();
2838 if document.needs_rendering_update(cx.no_gc()) {
2839 return;
2840 }
2841
2842 let epoch = document.current_rendering_epoch();
2845 let pipeline_id = self.pipeline_id();
2846 debug!("Ready to take screenshot of {pipeline_id:?} at epoch={epoch:?}");
2847
2848 self.send_to_constellation(
2849 ScriptToConstellationMessage::RespondToScreenshotReadinessRequest(
2850 ScreenshotReadinessResponse::Ready(epoch),
2851 ),
2852 );
2853 self.has_pending_screenshot_readiness_request.set(false);
2854 }
2855
2856 pub(crate) fn reflow_if_reflow_timer_expired(&self, cx: &mut JSContext) {
2859 if !matches!(
2862 self.layout_blocker.get(),
2863 LayoutBlocker::Parsing(instant) if instant + INITIAL_REFLOW_DELAY < Instant::now()
2864 ) {
2865 return;
2866 }
2867 self.allow_layout_if_necessary(cx);
2868 }
2869
2870 pub(crate) fn prevent_layout_until_load_event(&self) {
2874 if !matches!(self.layout_blocker.get(), LayoutBlocker::WaitingForParse) {
2877 return;
2878 }
2879
2880 self.layout_blocker
2881 .set(LayoutBlocker::Parsing(Instant::now()));
2882 }
2883
2884 pub(crate) fn allow_layout_if_necessary(&self, cx: &mut JSContext) {
2887 if matches!(
2888 self.layout_blocker.get(),
2889 LayoutBlocker::FiredLoadEventOrParsingTimerExpired
2890 ) {
2891 return;
2892 }
2893
2894 self.layout_blocker
2895 .set(LayoutBlocker::FiredLoadEventOrParsingTimerExpired);
2896
2897 let document = self.Document();
2909 if !document.is_render_blocked() && document.update_the_rendering(cx).0.needs_frame() {
2910 self.paint_api()
2911 .generate_frame(vec![self.webview_id().into()]);
2912 }
2913 }
2914
2915 pub(crate) fn layout_blocked(&self) -> bool {
2916 self.layout_blocker.get().layout_blocked()
2917 }
2918
2919 fn flush_ancestor_layouts_if_necessary(&self, cx: &mut JSContext) {
2920 let Some(parent_pipeline_id) = self.parent_info else {
2921 return;
2922 };
2923 let Some(parent_window) = ScriptThread::find_window(parent_pipeline_id) else {
2924 return;
2925 };
2926 if !parent_window.Document().is_safe_to_run_script_or_layout() {
2929 return;
2930 }
2931 if parent_window.Document().is_render_blocked() {
2934 return;
2935 }
2936 parent_window.flush_ancestor_layouts_if_necessary(cx);
2937 if parent_window
2938 .document_unrooted(cx.no_gc())
2939 .restyle_reason(cx.no_gc())
2940 .needs_restyle()
2941 {
2942 parent_window.reflow(
2943 cx,
2944 ReflowGoal::LayoutQuery(QueryMsg::FlushForUpdateTheRenderingQuery),
2945 );
2946 }
2947 }
2948
2949 #[expect(unsafe_code)]
2951 pub(crate) fn layout_reflow(&self, query_msg: QueryMsg) {
2952 let mut cx = unsafe { script_bindings::script_runtime::temp_cx() };
2954
2955 self.reflow(&mut cx, ReflowGoal::LayoutQuery(query_msg));
2956 }
2957
2958 pub(crate) fn reflow_for_non_flushing_update_the_rendering_queries(&self, cx: &mut JSContext) {
2960 self.reflow(
2961 cx,
2962 ReflowGoal::LayoutQuery(QueryMsg::FlushForUpdateTheRenderingQuery),
2963 );
2964 }
2965
2966 pub(crate) fn resolved_font_style_query(
2967 &self,
2968 node: &Node,
2969 value: String,
2970 ) -> Option<ServoArc<Font>> {
2971 self.layout_reflow(QueryMsg::ResolvedFontStyleQuery);
2972
2973 let document = self.Document();
2974 let animations = document.animations().sets.clone();
2975 self.layout.borrow().query_resolved_font_style(
2976 node.to_trusted_node_address(),
2977 &value,
2978 animations,
2979 document.current_animation_timeline_value(),
2980 )
2981 }
2982
2983 #[expect(unsafe_code)]
2986 pub(crate) fn containing_block_node_query_without_reflow(
2987 &self,
2988 node: &Node,
2989 ) -> Option<DomRoot<Node>> {
2990 self.layout
2991 .borrow()
2992 .query_containing_block(node.to_trusted_node_address())
2993 .map(|address| unsafe { from_untrusted_node_address(address) })
2994 }
2995
2996 pub(crate) fn is_containing_block_descendant_query_without_reflow(
2999 &self,
3000 possible_ancestor: &Node,
3001 possible_descendant: &Node,
3002 ) -> bool {
3003 self.layout.borrow().query_containing_block_is_descendant(
3004 possible_ancestor.to_trusted_node_address(),
3005 possible_descendant.to_trusted_node_address(),
3006 )
3007 }
3008
3009 pub(crate) fn padding_query_without_reflow(&self, node: &Node) -> Option<PhysicalSides> {
3014 let layout = self.layout.borrow();
3015 layout.query_padding(node.to_trusted_node_address())
3016 }
3017
3018 pub(crate) fn box_area_query_without_reflow(
3023 &self,
3024 node: &Node,
3025 area: BoxAreaType,
3026 exclude_transform_and_inline: bool,
3027 ) -> Option<Rect<Au, CSSPixel>> {
3028 let layout = self.layout.borrow();
3029 layout.ensure_stacking_context_tree(self.viewport_details.get());
3030 layout.query_box_area(
3031 node.to_trusted_node_address(),
3032 area,
3033 exclude_transform_and_inline,
3034 )
3035 }
3036
3037 pub(crate) fn box_area_query(
3038 &self,
3039 node: &Node,
3040 area: BoxAreaType,
3041 exclude_transform_and_inline: bool,
3042 ) -> Option<Rect<Au, CSSPixel>> {
3043 self.layout_reflow(QueryMsg::BoxArea);
3044 self.box_area_query_without_reflow(node, area, exclude_transform_and_inline)
3045 }
3046
3047 pub(crate) fn box_areas_query(&self, node: &Node, area: BoxAreaType) -> CSSPixelRectVec {
3048 self.layout_reflow(QueryMsg::BoxAreas);
3049 self.layout
3050 .borrow()
3051 .query_box_areas(node.to_trusted_node_address(), area)
3052 }
3053
3054 pub(crate) fn client_rect_query(&self, node: &Node) -> Rect<i32, CSSPixel> {
3055 self.layout_reflow(QueryMsg::ClientRectQuery);
3056 self.layout
3057 .borrow()
3058 .query_client_rect(node.to_trusted_node_address())
3059 }
3060
3061 pub(crate) fn current_css_zoom_query(&self, node: &Node) -> f32 {
3062 self.layout_reflow(QueryMsg::CurrentCSSZoomQuery);
3063 self.layout
3064 .borrow()
3065 .query_current_css_zoom(node.to_trusted_node_address())
3066 }
3067
3068 pub(crate) fn document_unrooted<'a>(&self, no_gc: &'a NoGC) -> UnrootedDom<'a, Document> {
3070 self.document
3071 .get_unrooted(no_gc)
3072 .expect("Document accessed before initialization.")
3073 }
3074
3075 pub(crate) fn scrolling_area_query(&self, node: Option<&Node>) -> Rect<i32, CSSPixel> {
3078 self.layout_reflow(QueryMsg::ScrollingAreaOrOffsetQuery);
3079 self.layout
3080 .borrow()
3081 .query_scrolling_area(node.map(Node::to_trusted_node_address))
3082 }
3083
3084 pub(crate) fn scroll_offset_query(&self, node: &Node) -> Vector2D<f32, LayoutPixel> {
3085 let external_scroll_id = ExternalScrollId(
3086 combine_id_with_fragment_type(node.to_opaque().id(), FragmentType::FragmentBody),
3087 self.pipeline_id().into(),
3088 );
3089 self.scroll_offset_query_with_external_scroll_id(external_scroll_id)
3090 }
3091
3092 fn scroll_offset_query_with_external_scroll_id(
3093 &self,
3094 external_scroll_id: ExternalScrollId,
3095 ) -> Vector2D<f32, LayoutPixel> {
3096 self.layout_reflow(QueryMsg::ScrollingAreaOrOffsetQuery);
3097 self.scroll_offset_query_with_external_scroll_id_no_reflow(external_scroll_id)
3098 }
3099
3100 fn scroll_offset_query_with_external_scroll_id_no_reflow(
3101 &self,
3102 external_scroll_id: ExternalScrollId,
3103 ) -> Vector2D<f32, LayoutPixel> {
3104 self.layout
3105 .borrow()
3106 .scroll_offset(external_scroll_id)
3107 .unwrap_or_default()
3108 }
3109
3110 pub(crate) fn scroll_an_element(
3113 &self,
3114 cx: &mut JSContext,
3115 element: &Element,
3116 x: f32,
3117 y: f32,
3118 behavior: ScrollBehavior,
3119 ) {
3120 let scroll_id = ExternalScrollId(
3121 combine_id_with_fragment_type(
3122 element.upcast::<Node>().to_opaque().id(),
3123 FragmentType::FragmentBody,
3124 ),
3125 self.pipeline_id().into(),
3126 );
3127
3128 self.perform_a_scroll(cx, x, y, scroll_id, behavior, Some(element));
3132 }
3133
3134 pub(crate) fn resolved_style_query(
3135 &self,
3136 element: TrustedNodeAddress,
3137 pseudo: Option<PseudoElement>,
3138 property: PropertyId,
3139 ) -> DOMString {
3140 self.layout_reflow(QueryMsg::ResolvedStyleQuery(property.clone()));
3141
3142 let document = self.Document();
3143 let animations = document.animations().sets.clone();
3144 DOMString::from(self.layout.borrow().query_resolved_style(
3145 element,
3146 pseudo,
3147 property,
3148 animations,
3149 document.current_animation_timeline_value(),
3150 ))
3151 }
3152
3153 pub(crate) fn get_iframe_viewport_details_if_known(
3157 &self,
3158 browsing_context_id: BrowsingContextId,
3159 ) -> Option<ViewportDetails> {
3160 self.layout_reflow(QueryMsg::InnerWindowDimensionsQuery);
3162 self.Document()
3163 .iframes()
3164 .get(browsing_context_id)
3165 .and_then(|iframe| iframe.size)
3166 }
3167
3168 #[expect(unsafe_code)]
3169 pub(crate) fn offset_parent_query(
3170 &self,
3171 node: &Node,
3172 ) -> (Option<DomRoot<Element>>, Rect<Au, CSSPixel>) {
3173 self.layout_reflow(QueryMsg::OffsetParentQuery);
3174 let response = self
3175 .layout
3176 .borrow()
3177 .query_offset_parent(node.to_trusted_node_address());
3178 let element = response.node_address.and_then(|parent_node_address| {
3179 let node = unsafe { from_untrusted_node_address(parent_node_address) };
3180 DomRoot::downcast(node)
3181 });
3182 (element, response.rect)
3183 }
3184
3185 pub(crate) fn scroll_container_query(
3186 &self,
3187 node: Option<&Node>,
3188 flags: ScrollContainerQueryFlags,
3189 ) -> Option<ScrollContainerResponse> {
3190 self.layout_reflow(QueryMsg::ScrollParentQuery);
3191 self.layout
3192 .borrow()
3193 .query_scroll_container(node.map(Node::to_trusted_node_address), flags)
3194 }
3195
3196 #[expect(unsafe_code)]
3197 pub(crate) fn scrolling_box_query(
3198 &self,
3199 node: Option<&Node>,
3200 flags: ScrollContainerQueryFlags,
3201 ) -> Option<ScrollingBox> {
3202 self.scroll_container_query(node, flags)
3203 .and_then(|response| {
3204 Some(match response {
3205 ScrollContainerResponse::Viewport(overflow) => {
3206 (ScrollingBoxSource::Viewport(self.Document()), overflow)
3207 },
3208 ScrollContainerResponse::Element(parent_node_address, overflow) => {
3209 let node = unsafe { from_untrusted_node_address(parent_node_address) };
3210 (
3211 ScrollingBoxSource::Element(DomRoot::downcast(node)?),
3212 overflow,
3213 )
3214 },
3215 })
3216 })
3217 .map(|(source, overflow)| ScrollingBox::new(source, overflow))
3218 }
3219
3220 pub(crate) fn elements_from_point_query(
3221 &self,
3222 flags: HitTestFlags,
3223 point: LayoutPoint,
3224 ) -> layout_api::HitTestResult {
3225 self.layout_reflow(QueryMsg::ElementsFromPoint);
3226 self.layout().hit_test(flags, point)
3227 }
3228
3229 pub(crate) fn query_effective_overflow(&self, node: &Node) -> Option<AxesOverflow> {
3230 self.layout_reflow(QueryMsg::EffectiveOverflow);
3231 self.query_effective_overflow_without_reflow(node)
3232 }
3233
3234 pub(crate) fn query_effective_overflow_without_reflow(
3235 &self,
3236 node: &Node,
3237 ) -> Option<AxesOverflow> {
3238 self.layout
3239 .borrow()
3240 .query_effective_overflow(node.to_trusted_node_address())
3241 }
3242
3243 pub(crate) fn hit_test_from_input_event(
3244 &self,
3245 flags: HitTestFlags,
3246 input_event: &ConstellationInputEvent,
3247 ) -> Option<HitTestResult> {
3248 self.hit_test_from_point_in_viewport(
3249 flags,
3250 input_event.hit_test_result.as_ref()?.point_in_viewport,
3251 )
3252 }
3253
3254 #[expect(unsafe_code)]
3255 pub(crate) fn hit_test_from_point_in_viewport(
3256 &self,
3257 flags: HitTestFlags,
3258 point_in_frame: Point2D<f32, CSSPixel>,
3259 ) -> Option<HitTestResult> {
3260 let result = self.elements_from_point_query(flags, point_in_frame.cast_unit());
3261 let item = result.items.into_iter().next()?;
3262
3263 let point_relative_to_initial_containing_block =
3264 point_in_frame + self.scroll_offset().cast_unit();
3265
3266 let from_opaque_node = |node: OpaqueNode| {
3269 let address = UntrustedNodeAddress(node.0 as *const c_void);
3270 unsafe { from_untrusted_node_address(address) }
3271 };
3272 Some(HitTestResult {
3273 node: from_opaque_node(item.node),
3274 dom_position_for_selection: result
3275 .dom_position_for_selection
3276 .map(|(node, offset)| (from_opaque_node(node), offset)),
3277 cursor: item.cursor,
3278 point_in_node: item.point_in_target,
3279 point_in_frame,
3280 point_relative_to_initial_containing_block,
3281 })
3282 }
3283
3284 pub(crate) fn init_window_proxy(&self, window_proxy: &WindowProxy) {
3285 assert!(self.window_proxy.get().is_none());
3286 self.window_proxy.set(Some(window_proxy));
3287 }
3288
3289 pub(crate) fn init_document(&self, document: &Document) {
3290 assert!(self.document.get().is_none());
3291 assert!(document.window() == self);
3292 self.document.set(Some(document));
3293 }
3294
3295 pub(crate) fn load_data_for_document(
3296 &self,
3297 url: ServoUrl,
3298 pipeline_id: PipelineId,
3299 ) -> LoadData {
3300 let source_document = self.Document();
3301 let secure_context = if self.is_top_level() {
3302 None
3303 } else {
3304 Some(self.IsSecureContext())
3305 };
3306 LoadData::new(
3307 LoadOrigin::Script(self.origin().snapshot()),
3308 url,
3309 source_document.about_base_url(),
3310 Some(pipeline_id),
3311 Referrer::ReferrerUrl(source_document.url()),
3312 source_document.get_referrer_policy(),
3313 secure_context,
3314 Some(source_document.insecure_requests_policy()),
3315 source_document.has_trustworthy_ancestor_origin(),
3316 source_document.creation_sandboxing_flag_set_considering_parent_iframe(),
3317 )
3318 }
3319
3320 pub(crate) fn set_viewport_details(&self, viewport_details: ViewportDetails) {
3323 self.viewport_details.set(viewport_details);
3324 if !self.layout_mut().set_viewport_details(viewport_details) {
3325 return;
3326 }
3327 self.Document()
3328 .add_restyle_reason(RestyleReason::ViewportChanged);
3329 }
3330
3331 pub(crate) fn viewport_details(&self) -> ViewportDetails {
3332 self.viewport_details.get()
3333 }
3334
3335 pub(crate) fn get_or_init_visual_viewport(
3336 &self,
3337 cx: &mut JSContext,
3338 ) -> DomRoot<VisualViewport> {
3339 self.visual_viewport.or_init(|| {
3340 VisualViewport::new_from_layout_viewport(cx, self, self.viewport_details().size)
3341 })
3342 }
3343
3344 pub(crate) fn maybe_update_visual_viewport(
3346 &self,
3347 cx: &mut JSContext,
3348 pinch_zoom_infos: PinchZoomInfos,
3349 ) {
3350 if pinch_zoom_infos.rect == Rect::from_size(self.viewport_details().size) &&
3353 self.visual_viewport.get().is_none()
3354 {
3355 return;
3356 }
3357
3358 let visual_viewport = self.get_or_init_visual_viewport(cx);
3359 let changes = visual_viewport.update_from_pinch_zoom_infos(pinch_zoom_infos);
3360
3361 if changes.intersects(VisualViewportChanges::DimensionChanged) {
3362 self.has_changed_visual_viewport_dimension.set(true);
3363 }
3364 if changes.intersects(VisualViewportChanges::OffsetChanged) {
3365 visual_viewport.handle_scroll_event();
3366 }
3367 }
3368
3369 pub(crate) fn embedder_theme(&self) -> Theme {
3371 self.embedder_theme.get()
3372 }
3373
3374 pub(crate) fn set_embedder_theme(&self, new_theme: Theme) {
3376 self.embedder_theme.set(new_theme);
3377 self.refresh_theme();
3378 }
3379
3380 pub(crate) fn refresh_theme(&self) {
3381 let document = self.Document();
3382 let new_theme = document.theme().unwrap_or(self.embedder_theme.get());
3384 if !self.layout_mut().set_theme(new_theme) {
3385 return;
3386 }
3387 document.add_restyle_reason(RestyleReason::ThemeChanged);
3388 self.pending_media_query_evaluation.set(true);
3391 }
3392
3393 pub(crate) fn take_pending_media_query_evaluation(&self) -> bool {
3396 self.pending_media_query_evaluation.replace(false)
3397 }
3398
3399 pub(crate) fn has_pending_media_query_evaluation(&self) -> bool {
3400 self.pending_media_query_evaluation.get()
3401 }
3402
3403 pub(crate) fn get_url(&self) -> ServoUrl {
3404 self.Document().url()
3405 }
3406
3407 pub(crate) fn windowproxy_handler(&self) -> &'static WindowProxyHandler {
3408 self.dom_static.windowproxy_handler
3409 }
3410
3411 pub(crate) fn add_resize_event(&self, event: ViewportDetails, event_type: WindowSizeType) {
3412 if self.viewport_details() == event {
3413 return;
3414 }
3415
3416 self.set_viewport_details(event);
3418
3419 *self.unhandled_resize_event.borrow_mut() = Some((event, event_type))
3422 }
3423
3424 pub(crate) fn take_unhandled_resize_event(&self) -> Option<(ViewportDetails, WindowSizeType)> {
3425 self.unhandled_resize_event.borrow_mut().take()
3426 }
3427
3428 pub(crate) fn has_unhandled_resize_event(&self) -> bool {
3430 self.unhandled_resize_event.borrow().is_some()
3431 }
3432
3433 pub(crate) fn suspend(&self, cx: &mut JSContext) {
3434 self.as_global_scope().suspend();
3436
3437 if self.window_proxy().currently_active() == Some(self.global().pipeline_id()) {
3439 self.window_proxy().unset_currently_active(cx);
3440 }
3441
3442 self.gc(cx);
3447 }
3448
3449 pub(crate) fn resume(&self, cx: &mut JSContext) {
3450 self.as_global_scope().resume();
3452
3453 self.window_proxy().set_currently_active(cx, self);
3455
3456 self.Document().title_changed();
3459 }
3460
3461 pub(crate) fn need_emit_timeline_marker(&self, timeline_type: TimelineMarkerType) -> bool {
3462 let markers = self.devtools_markers.borrow();
3463 markers.contains(&timeline_type)
3464 }
3465
3466 pub(crate) fn emit_timeline_marker(&self, marker: TimelineMarker) {
3467 let sender = self.devtools_marker_sender.borrow();
3468 let sender = sender.as_ref().expect("There is no marker sender");
3469 sender.send(Some(marker)).unwrap();
3470 }
3471
3472 pub(crate) fn set_devtools_timeline_markers(
3473 &self,
3474 markers: Vec<TimelineMarkerType>,
3475 reply: GenericSender<Option<TimelineMarker>>,
3476 ) {
3477 *self.devtools_marker_sender.borrow_mut() = Some(reply);
3478 self.devtools_markers.borrow_mut().extend(markers);
3479 }
3480
3481 pub(crate) fn drop_devtools_timeline_markers(&self, markers: Vec<TimelineMarkerType>) {
3482 let mut devtools_markers = self.devtools_markers.borrow_mut();
3483 for marker in markers {
3484 devtools_markers.remove(&marker);
3485 }
3486 if devtools_markers.is_empty() {
3487 *self.devtools_marker_sender.borrow_mut() = None;
3488 }
3489 }
3490
3491 pub(crate) fn set_webdriver_script_chan(&self, chan: Option<GenericSender<WebDriverJSResult>>) {
3492 *self.webdriver_script_chan.borrow_mut() = chan;
3493 }
3494
3495 pub(crate) fn set_webdriver_load_status_sender(
3496 &self,
3497 sender: Option<GenericSender<WebDriverLoadStatus>>,
3498 ) {
3499 *self.webdriver_load_status_sender.borrow_mut() = sender;
3500 }
3501
3502 pub(crate) fn webdriver_load_status_sender(
3503 &self,
3504 ) -> Option<GenericSender<WebDriverLoadStatus>> {
3505 self.webdriver_load_status_sender.borrow().clone()
3506 }
3507
3508 pub(crate) fn is_alive(&self) -> bool {
3509 self.current_state.get() == WindowState::Alive
3510 }
3511
3512 pub(crate) fn is_top_level(&self) -> bool {
3514 self.parent_info.is_none()
3515 }
3516
3517 fn run_resize_steps_for_layout_viewport(&self, cx: &mut JSContext) -> bool {
3522 let Some((new_size, size_type)) = self.take_unhandled_resize_event() else {
3523 return false;
3524 };
3525
3526 let current_viewport = self.viewport_details();
3529 if current_viewport == self.viewport_details_at_last_resize_steps.get() {
3530 return false;
3531 }
3532 self.viewport_details_at_last_resize_steps
3533 .set(current_viewport);
3534
3535 debug!(
3536 "Running resize steps for pipeline {:?} with viewport {new_size:?}",
3537 self.pipeline_id(),
3538 );
3539
3540 if size_type == WindowSizeType::Resize {
3542 let mut realm = enter_auto_realm(cx, self);
3543 let cx = &mut realm.current_realm();
3544 let uievent = UIEvent::new(
3545 cx,
3546 self,
3547 atom!("resize"),
3548 EventBubbles::DoesNotBubble,
3549 EventCancelable::NotCancelable,
3550 Some(self),
3551 0i32,
3552 0u32,
3553 );
3554 uievent.upcast::<Event>().fire(cx, self.upcast());
3555 }
3556
3557 true
3558 }
3559
3560 pub(crate) fn run_the_resize_steps(&self, cx: &mut JSContext) -> bool {
3565 let layout_viewport_resized = self.run_resize_steps_for_layout_viewport(cx);
3566
3567 if self.has_changed_visual_viewport_dimension.get() {
3568 let visual_viewport = self.get_or_init_visual_viewport(cx);
3569
3570 let uievent = UIEvent::new(
3571 cx,
3572 self,
3573 atom!("resize"),
3574 EventBubbles::DoesNotBubble,
3575 EventCancelable::NotCancelable,
3576 Some(self),
3577 0i32,
3578 0u32,
3579 );
3580 uievent.upcast::<Event>().fire(cx, visual_viewport.upcast());
3581
3582 self.has_changed_visual_viewport_dimension.set(false);
3583 }
3584
3585 layout_viewport_resized
3586 }
3587
3588 pub(crate) fn evaluate_media_queries_and_report_changes(&self, cx: &mut JSContext) {
3591 let mut realm = enter_auto_realm(cx, self);
3592 let cx = &mut realm.current_realm();
3593 rooted_vec!(let mut mql_list);
3594
3595 self.media_query_lists.for_each(|mql| {
3596 if let MediaQueryListMatchState::Changed = mql.evaluate_changes() {
3597 mql_list.push(Dom::from_ref(&*mql));
3599 }
3600 });
3601 for mql in mql_list.iter() {
3603 let event = MediaQueryListEvent::new(
3604 cx,
3605 &mql.global(),
3606 atom!("change"),
3607 false,
3608 false,
3609 mql.Media(),
3610 mql.Matches(),
3611 );
3612 event
3613 .upcast::<Event>()
3614 .fire(cx, mql.upcast::<EventTarget>());
3615 }
3616 }
3617
3618 pub(crate) fn set_throttled(&self, throttled: bool) {
3620 self.throttled.set(throttled);
3621 if throttled {
3622 self.as_global_scope().slow_down_timers();
3623 } else {
3624 self.as_global_scope().speed_up_timers();
3625 }
3626 }
3627
3628 pub(crate) fn throttled(&self) -> bool {
3629 self.throttled.get()
3630 }
3631
3632 pub(crate) fn unminified_css_dir(&self) -> Option<String> {
3633 self.unminified_css_dir.borrow().clone()
3634 }
3635
3636 pub(crate) fn local_script_source(&self) -> &Option<String> {
3637 &self.local_script_source
3638 }
3639
3640 pub(crate) fn set_navigation_start(&self) {
3641 self.navigation_start.set(CrossProcessInstant::now());
3642 }
3643
3644 pub(crate) fn navigation_start(&self) -> CrossProcessInstant {
3645 self.navigation_start.get()
3646 }
3647
3648 pub(crate) fn set_last_activation_timestamp(&self, time: UserActivationTimestamp) {
3649 self.last_activation_timestamp.set(time);
3650 }
3651
3652 pub(crate) fn send_to_embedder(&self, msg: EmbedderMsg) {
3653 self.as_global_scope()
3654 .script_to_embedder_chan()
3655 .send(msg)
3656 .unwrap();
3657 }
3658
3659 pub(crate) fn send_to_constellation(&self, msg: ScriptToConstellationMessage) {
3660 self.as_global_scope()
3661 .script_to_constellation_chan()
3662 .send(msg)
3663 .unwrap();
3664 }
3665
3666 #[cfg(feature = "webxr")]
3667 pub(crate) fn in_immersive_xr_session(&self) -> bool {
3668 self.navigator
3669 .get()
3670 .as_ref()
3671 .and_then(|nav| nav.xr())
3672 .is_some_and(|xr| xr.pending_or_active_session())
3673 }
3674
3675 #[cfg(all(feature = "webgl", not(feature = "webxr")))]
3676 pub(crate) fn in_immersive_xr_session(&self) -> bool {
3677 false
3678 }
3679
3680 fn handle_new_or_removed_web_fonts_post_reflow(
3682 &self,
3683 cx: &mut JSContext,
3684 changed_web_fonts: WebFontSetDifference,
3685 ) {
3686 if changed_web_fonts.is_empty() {
3687 return;
3688 }
3689
3690 let document = self.Document();
3691 let fonts = document.Fonts(cx);
3692 if !changed_web_fonts.removed_font_faces.is_empty() {
3693 fonts.notify_font_face_rules_removed(&changed_web_fonts.removed_font_faces);
3694
3695 document.dirty_all_nodes(cx.no_gc());
3698 }
3699
3700 if !changed_web_fonts.added_font_faces.is_empty() {
3701 fonts.switch_to_loading(cx);
3702
3703 let shared_locks = document.shared_style_locks();
3704 let guards = StylesheetGuards {
3705 author: &shared_locks.author.read(),
3706 ua_or_user: &shared_locks.ua_or_user.read(),
3707 };
3708 for new_web_font in changed_web_fonts.added_font_faces {
3709 if let Some(font_face) =
3710 FontFace::new_for_web_font(cx, self.upcast(), new_web_font, &guards)
3711 {
3712 fonts.add(cx, font_face);
3713 }
3714 }
3715 }
3716 }
3717
3718 #[expect(unsafe_code)]
3720 fn process_lcp_candidate_post_reflow(
3721 &self,
3722 candidate: &LCPCandidate,
3723 node_address: UntrustedNodeAddress,
3724 document: &Document,
3725 ) {
3726 let node = unsafe { from_untrusted_node_address(node_address) };
3727 if let Some(element) = DomRoot::downcast::<Element>(node) {
3728 document.store_lcp_candidate(candidate.id, &element);
3729 }
3730 }
3731
3732 #[expect(unsafe_code)]
3733 fn handle_pending_images_post_reflow(
3734 &self,
3735 cx: &mut JSContext,
3736 pending_images: Vec<PendingImage>,
3737 pending_rasterization_images: Vec<PendingRasterizationImage>,
3738 pending_svg_element_for_serialization: Vec<UntrustedNodeAddress>,
3739 ) {
3740 let pipeline_id = self.pipeline_id();
3741 let image_cache = self.image_cache();
3742 for image in pending_images {
3743 let id = image.id;
3744 let node = unsafe { from_untrusted_node_address(image.node) };
3745
3746 if let PendingImageState::Unrequested(ref url) = image.state {
3747 fetch_image_for_layout(
3748 url.clone(),
3749 &node,
3750 id,
3751 image.is_internal_request,
3752 image_cache.clone(),
3753 );
3754 }
3755
3756 let mut images = self.pending_layout_images.borrow_mut();
3757 if !images.contains_key(&id) {
3758 let trusted_node = Trusted::new(&*node);
3759 let sender = self.register_image_cache_listener(id, move |response, cx| {
3760 trusted_node
3761 .root()
3762 .owner_window()
3763 .pending_layout_image_notification(cx.no_gc(), response);
3764 });
3765
3766 image_cache.add_listener(ImageLoadListener::new(sender, pipeline_id, id));
3767 }
3768
3769 let nodes = images.entry(id).or_default();
3770 if !nodes.iter().any(|n| *n.node == *node) {
3771 nodes.push(PendingLayoutImageAncillaryData {
3772 node: Dom::from_ref(&*node),
3773 destination: image.destination,
3774 });
3775 }
3776 }
3777
3778 for image in pending_rasterization_images {
3779 let node = unsafe { from_untrusted_node_address(image.node) };
3780
3781 let mut images = self.pending_images_for_rasterization.borrow_mut();
3782 if !images.contains_key(&(image.id, image.size)) {
3783 let image_cache_sender = self.image_cache_sender.clone();
3784 image_cache.add_rasterization_complete_listener(
3785 pipeline_id,
3786 image.id,
3787 image.size,
3788 Box::new(move |response| {
3789 let _ = image_cache_sender.send(response);
3790 }),
3791 );
3792 }
3793
3794 let nodes = images.entry((image.id, image.size)).or_default();
3795 if !nodes.iter().any(|n| **n == *node) {
3796 nodes.push(Dom::from_ref(&*node));
3797 }
3798 }
3799
3800 for node in pending_svg_element_for_serialization.into_iter() {
3801 let node = unsafe { from_untrusted_node_address(node) };
3802 let svg = node.downcast::<SVGSVGElement>().unwrap();
3803 svg.serialize_and_cache_subtree(cx);
3804 node.dirty(cx.no_gc(), NodeDamage::Other);
3805 }
3806 }
3807
3808 pub(crate) fn has_sticky_activation(&self) -> bool {
3810 UserActivationTimestamp::TimeStamp(CrossProcessInstant::now()) >=
3812 self.last_activation_timestamp.get()
3813 }
3814
3815 pub(crate) fn has_transient_activation(&self) -> bool {
3817 let current_time = CrossProcessInstant::now();
3820 UserActivationTimestamp::TimeStamp(current_time) >= self.last_activation_timestamp.get() &&
3821 UserActivationTimestamp::TimeStamp(current_time) <
3822 self.last_activation_timestamp.get() +
3823 pref!(dom_transient_activation_duration_ms)
3824 }
3825
3826 pub(crate) fn consume_last_activation_timestamp(&self) {
3827 if self.last_activation_timestamp.get() != UserActivationTimestamp::PositiveInfinity {
3828 self.set_last_activation_timestamp(UserActivationTimestamp::NegativeInfinity);
3829 }
3830 }
3831
3832 pub(crate) fn consume_user_activation(&self) {
3834 if self.undiscarded_window_proxy().is_none() {
3837 return;
3838 }
3839
3840 let Some(top_level_document) = self.top_level_document_if_local() else {
3844 return;
3845 };
3846
3847 top_level_document
3855 .window()
3856 .consume_last_activation_timestamp();
3857 for document in SameOriginDescendantNavigablesIterator::new(&top_level_document) {
3858 document.window().consume_last_activation_timestamp();
3859 }
3860 }
3861
3862 #[allow(clippy::too_many_arguments)]
3863 pub(crate) fn new(
3864 cx: &mut JSContext,
3865 webview_id: WebViewId,
3866 runtime: Rc<Runtime>,
3867 script_chan: Sender<MainThreadScriptMsg>,
3868 layout: Box<dyn Layout>,
3869 image_cache_sender: Sender<ImageCacheResponseMessage>,
3870 resource_threads: ResourceThreads,
3871 storage_threads: StorageThreads,
3872 #[cfg(feature = "bluetooth")] bluetooth_thread: GenericSender<BluetoothRequest>,
3873 mem_profiler_chan: MemProfilerChan,
3874 time_profiler_chan: TimeProfilerChan,
3875 devtools_chan: Option<GenericCallback<ScriptToDevtoolsControlMsg>>,
3876 script_to_constellation_sender: ScriptToConstellationSender,
3877 embedder_chan: ScriptToEmbedderChan,
3878 control_chan: GenericSender<ScriptThreadMessage>,
3879 pipeline_id: PipelineId,
3880 parent_info: Option<PipelineId>,
3881 viewport_details: ViewportDetails,
3882 origin: MutableOrigin,
3883 creation_url: ServoUrl,
3884 top_level_creation_url: ServoUrl,
3885 navigation_start: CrossProcessInstant,
3886 #[cfg(feature = "webgl")] webgl_chan: Option<WebGLChan>,
3887 #[cfg(feature = "webxr")] webxr_registry: Option<webxr_api::Registry>,
3888 paint_api: CrossProcessPaintApi,
3889 unminify_js: bool,
3890 unminify_css: bool,
3891 local_script_source: Option<String>,
3892 user_scripts: Rc<Vec<UserScript>>,
3893 player_context: WindowGLContext,
3894 #[cfg(feature = "webgpu")] gpu_id_hub: Arc<IdentityHub>,
3895 inherited_secure_context: Option<bool>,
3896 embedder_theme: Theme,
3897 weak_script_thread: Weak<ScriptThread>,
3898 ) -> DomRoot<Self> {
3899 let error_reporter = CSSErrorReporter {
3900 pipelineid: pipeline_id,
3901 script_chan: control_chan,
3902 };
3903
3904 let win = Box::new(Self {
3905 webview_id,
3906 globalscope: GlobalScope::new_inherited(
3907 devtools_chan,
3908 mem_profiler_chan,
3909 time_profiler_chan,
3910 script_to_constellation_sender,
3911 embedder_chan,
3912 resource_threads,
3913 storage_threads,
3914 creation_url,
3915 Some(top_level_creation_url),
3916 #[cfg(feature = "webgpu")]
3917 gpu_id_hub,
3918 inherited_secure_context,
3919 unminify_js,
3920 ),
3921 caches: Default::default(),
3922 ongoing_navigation: Default::default(),
3923 script_chan,
3924 layout: RefCell::new(layout),
3925 image_cache_sender,
3926 navigator: Default::default(),
3927 crypto: Default::default(),
3928 location: Default::default(),
3929 window_proxy: Default::default(),
3930 document: Default::default(),
3931 performance: Default::default(),
3932 navigation_start: Cell::new(navigation_start),
3933 screen: Default::default(),
3934 session_storage: Default::default(),
3935 local_storage: Default::default(),
3936 cookie_store: Default::default(),
3937 status: DomRefCell::new(DOMString::new()),
3938 parent_info,
3939 dom_static: GlobalStaticData::new(),
3940 js_runtime: DomRefCell::new(Some(runtime)),
3941 #[cfg(feature = "bluetooth")]
3942 bluetooth_thread,
3943 #[cfg(feature = "bluetooth")]
3944 bluetooth_extra_permission_data: BluetoothExtraPermissionData::new(),
3945 unhandled_resize_event: Default::default(),
3946 viewport_details_at_last_resize_steps: Cell::new(viewport_details),
3947 viewport_details: Cell::new(viewport_details),
3948 layout_blocker: Cell::new(LayoutBlocker::WaitingForParse),
3949 current_state: Cell::new(WindowState::Alive),
3950 devtools_marker_sender: Default::default(),
3951 devtools_markers: Default::default(),
3952 webdriver_script_chan: Default::default(),
3953 webdriver_load_status_sender: Default::default(),
3954 error_reporter,
3955 media_query_lists: DOMTracker::new(),
3956 #[cfg(feature = "bluetooth")]
3957 test_runner: Default::default(),
3958 #[cfg(feature = "webgl")]
3959 webgl_chan,
3960 #[cfg(feature = "webxr")]
3961 webxr_registry,
3962 pending_image_callbacks: Default::default(),
3963 pending_layout_images: Default::default(),
3964 pending_images_for_rasterization: Default::default(),
3965 unminified_css_dir: DomRefCell::new(if unminify_css {
3966 Some(unminified_path("unminified-css"))
3967 } else {
3968 None
3969 }),
3970 local_script_source,
3971 test_worklet: Default::default(),
3972 paint_worklet: Default::default(),
3973 exists_mut_observer: Cell::new(false),
3974 paint_api,
3975 user_scripts,
3976 player_context,
3977 throttled: Cell::new(false),
3978 layout_marker: DomRefCell::new(Rc::new(Cell::new(true))),
3979 current_event: DomRefCell::new(None),
3980 embedder_theme: Cell::new(embedder_theme),
3981 trusted_types: Default::default(),
3982 reporting_observer_list: Default::default(),
3983 report_list: Default::default(),
3984 endpoints_list: Default::default(),
3985 script_window_proxies: ScriptThread::window_proxies(),
3986 has_pending_screenshot_readiness_request: Default::default(),
3987 visual_viewport: Default::default(),
3988 weak_script_thread,
3989 has_changed_visual_viewport_dimension: Default::default(),
3990 pending_media_query_evaluation: Default::default(),
3991 last_activation_timestamp: Cell::new(UserActivationTimestamp::PositiveInfinity),
3992 devtools_wants_updates: Default::default(),
3993 });
3994
3995 WindowBinding::Wrap::<crate::DomTypeHolder>(cx, &origin, win)
3996 }
3997
3998 pub(crate) fn task_manager(&self) -> Rc<TaskManager> {
3999 self.Document().task_manager()
4000 }
4001
4002 pub(crate) fn pipeline_id(&self) -> PipelineId {
4003 self.Document().pipeline_id()
4004 }
4005
4006 pub(crate) fn live_devtools_updates(&self) -> bool {
4007 self.devtools_wants_updates.get()
4008 }
4009
4010 pub(crate) fn set_devtools_wants_updates(&self, value: bool) {
4011 self.devtools_wants_updates.set(value);
4012 }
4013
4014 pub(crate) fn cache_layout_value<T>(&self, value: T) -> LayoutValue<T>
4016 where
4017 T: Copy + MallocSizeOf,
4018 {
4019 LayoutValue::new(self.layout_marker.borrow().clone(), value)
4020 }
4021}
4022
4023#[derive(MallocSizeOf)]
4028pub(crate) struct LayoutValue<T: MallocSizeOf> {
4029 #[conditional_malloc_size_of]
4030 is_valid: Rc<Cell<bool>>,
4031 value: T,
4032}
4033
4034#[expect(unsafe_code)]
4035unsafe impl<T: JSTraceable + MallocSizeOf> JSTraceable for LayoutValue<T> {
4036 unsafe fn trace(&self, trc: *mut js::jsapi::JSTracer) {
4037 unsafe { self.value.trace(trc) };
4038 }
4039}
4040
4041impl<T: Copy + MallocSizeOf> LayoutValue<T> {
4042 fn new(marker: Rc<Cell<bool>>, value: T) -> Self {
4043 LayoutValue {
4044 is_valid: marker,
4045 value,
4046 }
4047 }
4048
4049 pub(crate) fn get(&self) -> Result<T, ()> {
4051 if self.is_valid.get() {
4052 return Ok(self.value);
4053 }
4054 Err(())
4055 }
4056}
4057
4058impl Window {
4059 pub(crate) fn post_message(
4061 &self,
4062 target_origin: Option<ImmutableOrigin>,
4063 source_origin: ImmutableOrigin,
4064 source: &WindowProxy,
4065 data: StructuredSerializedData,
4066 ) {
4067 let this = Trusted::new(self);
4068 let source = Trusted::new(source);
4069 let task = task!(post_serialised_message: move |cx| {
4070 let this = this.root();
4071 let source = source.root();
4072 let document = this.Document();
4073
4074 if let Some(ref target_origin) = target_origin
4076 && !target_origin.same_origin(&*document.origin()) {
4077 return;
4078 }
4079
4080 let obj = this.reflector().get_jsobject();
4082 let mut realm = AutoRealm::new(cx, NonNull::new(obj.get()).unwrap());
4083 let cx = &mut *realm;
4084 rooted!(&in(cx) let mut message_clone = UndefinedValue());
4085 if let Ok(ports) = structuredclone::read(cx, this.upcast(), data, message_clone.handle_mut()) {
4086 MessageEvent::dispatch_jsval(
4088 cx,
4089 this.upcast(),
4090 this.upcast(),
4091 message_clone.handle(),
4092 Some(&source_origin.ascii_serialization()),
4093 Some(&*source),
4094 ports,
4095 );
4096 } else {
4097 MessageEvent::dispatch_error(
4099 cx,
4100 this.upcast(),
4101 this.upcast(),
4102 );
4103 }
4104 });
4105 self.as_global_scope()
4107 .task_manager()
4108 .dom_manipulation_task_source()
4109 .queue(task);
4110 }
4111}
4112
4113#[derive(Clone, MallocSizeOf)]
4114pub(crate) struct CSSErrorReporter {
4115 pub(crate) pipelineid: PipelineId,
4116 pub(crate) script_chan: GenericSender<ScriptThreadMessage>,
4117}
4118unsafe_no_jsmanaged_fields!(CSSErrorReporter);
4119
4120impl ParseErrorReporter for CSSErrorReporter {
4121 fn report_error(
4122 &self,
4123 url: &UrlExtraData,
4124 location: SourceLocation,
4125 error: ContextualParseError,
4126 ) {
4127 if log_enabled!(log::Level::Info) {
4128 info!(
4129 "Url:\t{}\n{}:{} {}",
4130 url.0.as_str(),
4131 location.line,
4132 location.column,
4133 error
4134 )
4135 }
4136
4137 let _ = self.script_chan.send(ScriptThreadMessage::ReportCSSError(
4139 self.pipelineid,
4140 url.0.to_string(),
4141 location.line,
4142 location.column,
4143 error.to_string(),
4144 ));
4145 }
4146}
4147
4148fn is_named_element_with_name_attribute(elem: &Element) -> bool {
4149 let type_ = match elem.upcast::<Node>().type_id() {
4150 NodeTypeId::Element(ElementTypeId::HTMLElement(type_)) => type_,
4151 _ => return false,
4152 };
4153 matches!(
4154 type_,
4155 HTMLElementTypeId::HTMLEmbedElement |
4156 HTMLElementTypeId::HTMLFormElement |
4157 HTMLElementTypeId::HTMLImageElement |
4158 HTMLElementTypeId::HTMLObjectElement
4159 )
4160}
4161
4162fn is_named_element_with_id_attribute(elem: &Element) -> bool {
4163 elem.is_html_element() || elem.is_svg_element()
4164}
4165
4166#[expect(unsafe_code)]
4167#[unsafe(no_mangle)]
4168unsafe extern "C" fn dump_js_stack(cx: *mut RawJSContext) {
4170 unsafe {
4171 DumpJSStack(cx, true, false, false);
4172 }
4173}
4174
4175impl WindowHelpers for Window {
4176 fn create_named_properties_object(
4177 cx: &mut JSContext,
4178 proto: HandleObject,
4179 object: MutableHandleObject,
4180 ) {
4181 Self::create_named_properties_object(cx, proto, object)
4182 }
4183}
4184
4185impl HasOrigin for Window {
4186 fn origin(&self) -> MutableOrigin {
4187 Window::origin(self)
4188 }
4189}