1use std::cell::{Cell, RefCell};
21use std::collections::HashSet;
22use std::default::Default;
23use std::option::Option;
24use std::rc::{Rc, Weak};
25use std::result::Result;
26use std::sync::Arc;
27use std::sync::atomic::{AtomicBool, Ordering};
28use std::thread::{self, JoinHandle};
29use std::time::{Duration, Instant, SystemTime};
30
31use background_hang_monitor_api::{
32 BackgroundHangMonitor, BackgroundHangMonitorExitSignal, BackgroundHangMonitorRegister,
33 HangAnnotation, MonitoredComponentId, MonitoredComponentType,
34};
35use chrono::{DateTime, Local};
36use crossbeam_channel::unbounded;
37use data_url::mime::Mime;
38use devtools_traits::{
39 CSSError, DevtoolScriptControlMsg, DevtoolsPageInfo, NavigationState,
40 ScriptToDevtoolsControlMsg, WorkerId,
41};
42use embedder_traits::user_contents::{UserContentManagerId, UserContents, UserScript};
43use embedder_traits::{
44 EmbedderControlId, EmbedderControlResponse, EmbedderMsg, FocusSequenceNumber,
45 InputEventOutcome, JavaScriptEvaluationError, JavaScriptEvaluationId, MediaSessionActionType,
46 Theme, ViewportDetails, WebDriverScriptCommand,
47};
48use encoding_rs::Encoding;
49use fonts::{FontContext, SystemFontServiceProxy};
50use headers::{HeaderMapExt, LastModified, ReferrerPolicy as ReferrerPolicyHeader};
51use http::header::REFRESH;
52use hyper_serde::Serde;
53use ipc_channel::router::ROUTER;
54use js::glue::GetWindowProxyClass;
55use js::jsapi::{GCReason, JS_GC, JSContext as UnsafeJSContext};
56use js::jsval::UndefinedValue;
57use js::rust::ParentRuntime;
58use js::rust::wrappers2::{JS_AddInterruptCallback, SetWindowProxyClass};
59use layout_api::{LayoutConfig, LayoutFactory, RestyleReason, ScriptThreadFactory};
60use media::WindowGLContext;
61use metrics::MAX_TASK_NS;
62use net_traits::image_cache::{ImageCache, ImageCacheFactory, ImageCacheResponseMessage};
63use net_traits::request::{Referrer, RequestId};
64use net_traits::response::ResponseInit;
65use net_traits::{
66 FetchMetadata, FetchResponseMsg, Metadata, NetworkError, ResourceFetchTiming, ResourceThreads,
67 ResourceTimingType,
68};
69use paint_api::{CrossProcessPaintApi, PinchZoomInfos, PipelineExitSource};
70use percent_encoding::percent_decode;
71use profile_traits::mem::{ProcessReports, ReportsChan, perform_memory_report};
72use profile_traits::time::ProfilerCategory;
73use profile_traits::time_profile;
74use rustc_hash::{FxHashMap, FxHashSet};
75use script_bindings::cell::DomRefCell;
76use script_bindings::script_runtime::JSContext;
77use script_traits::{
78 ConstellationInputEvent, DiscardBrowsingContext, DocumentActivity, InitialScriptState,
79 NewPipelineInfo, Painter, ProgressiveWebMetricType, ScriptThreadMessage,
80 UpdatePipelineIdReason,
81};
82use servo_arc::Arc as ServoArc;
83use servo_base::cross_process_instant::CrossProcessInstant;
84use servo_base::generic_channel::GenericSender;
85use servo_base::id::{
86 BrowsingContextId, HistoryStateId, PipelineId, PipelineNamespace, ScriptEventLoopId,
87 TEST_WEBVIEW_ID, WebViewId,
88};
89use servo_base::{Epoch, generic_channel};
90use servo_canvas_traits::webgl::WebGLPipeline;
91use servo_config::opts::{self, DiagnosticsLoggingOption};
92use servo_config::{pref, prefs};
93use servo_constellation_traits::{
94 LoadData, LoadOrigin, NavigationHistoryBehavior, RemoteFocusOperation,
95 ScreenshotReadinessResponse, ScriptToConstellationChan, ScriptToConstellationMessage,
96 ScrollStateUpdate, StructuredSerializedData, TargetSnapshotParams, TraversalDirection,
97 WindowSizeType,
98};
99use servo_url::{ImmutableOrigin, MutableOrigin, OriginSnapshot, ServoUrl};
100use storage_traits::StorageThreads;
101use storage_traits::webstorage_thread::WebStorageType;
102use style::context::QuirksMode;
103use style::error_reporting::RustLogReporter;
104use style::media_queries::MediaList;
105use style::shared_lock::SharedRwLock;
106use style::stylesheets::{AllowImportRules, DocumentStyleSheet, Origin, Stylesheet};
107use style::thread_state::{self, ThreadState};
108use stylo_atoms::Atom;
109use timers::{TimerEventRequest, TimerId, TimerScheduler};
110use url::Position;
111#[cfg(feature = "webgpu")]
112use webgpu_traits::{WebGPUDevice, WebGPUMsg};
113
114use crate::devtools::DevtoolsState;
115use crate::document_collection::DocumentCollection;
116use crate::document_loader::DocumentLoader;
117use crate::dom::bindings::codegen::Bindings::DocumentBinding::{
118 DocumentMethods, DocumentReadyState,
119};
120use crate::dom::bindings::codegen::Bindings::NavigatorBinding::NavigatorMethods;
121use crate::dom::bindings::codegen::Bindings::WindowBinding::WindowMethods;
122use crate::dom::bindings::conversions::{
123 ConversionResult, FromJSValConvertible, StringificationBehavior,
124};
125use crate::dom::bindings::inheritance::Castable;
126use crate::dom::bindings::reflector::DomGlobal;
127use crate::dom::bindings::root::{Dom, DomRoot};
128use crate::dom::bindings::str::DOMString;
129use crate::dom::csp::{CspReporting, GlobalCspReporting, Violation};
130use crate::dom::customelementregistry::{
131 CallbackReaction, CustomElementDefinition, CustomElementReactionStack,
132};
133use crate::dom::document::focus::FocusableArea;
134use crate::dom::document::{
135 Document, DocumentSource, HasBrowsingContext, IsHTMLDocument, RenderingUpdateReason,
136};
137use crate::dom::element::Element;
138use crate::dom::globalscope::GlobalScope;
139use crate::dom::html::htmliframeelement::{HTMLIFrameElement, IframeContext, ProcessingMode};
140use crate::dom::node::{Node, NodeTraits};
141use crate::dom::servoparser::{ParserContext, ServoParser};
142use crate::dom::types::DebuggerGlobalScope;
143#[cfg(feature = "webgpu")]
144use crate::dom::webgpu::identityhub::IdentityHub;
145use crate::dom::window::Window;
146use crate::dom::windowproxy::{CreatorBrowsingContextInfo, WindowProxy};
147use crate::dom::worklet::WorkletThreadPool;
148use crate::dom::workletglobalscope::WorkletGlobalScopeInit;
149use crate::fetch::FetchCanceller;
150use crate::messaging::{
151 CommonScriptMsg, MainThreadScriptMsg, MixedMessage, ScriptEventLoopSender,
152 ScriptThreadReceivers, ScriptThreadSenders,
153};
154use crate::microtask::{Microtask, MicrotaskQueue};
155use crate::mime::{APPLICATION, CHARSET, MimeExt, TEXT, XML};
156use crate::navigation::{InProgressLoad, NavigationListener};
157use crate::network_listener::{FetchResponseListener, submit_timing};
158use crate::realms::{enter_auto_realm, enter_realm};
159use crate::script_mutation_observers::ScriptMutationObservers;
160use crate::script_runtime::{
161 CanGc, IntroductionType, Runtime, ScriptThreadEventCategory, ThreadSafeJSContext, get_reports,
162};
163use crate::script_window_proxies::ScriptWindowProxies;
164use crate::task_queue::TaskQueue;
165use crate::webdriver_handlers::jsval_to_webdriver;
166use crate::{devtools, webdriver_handlers};
167
168thread_local!(static SCRIPT_THREAD_ROOT: Cell<Option<*const ScriptThread>> = const { Cell::new(None) });
169
170fn with_optional_script_thread<R>(f: impl FnOnce(Option<&ScriptThread>) -> R) -> R {
171 SCRIPT_THREAD_ROOT.with(|root| {
172 f(root
173 .get()
174 .and_then(|script_thread| unsafe { script_thread.as_ref() }))
175 })
176}
177
178pub(crate) fn with_script_thread<R: Default>(f: impl FnOnce(&ScriptThread) -> R) -> R {
179 with_optional_script_thread(|script_thread| script_thread.map(f).unwrap_or_default())
180}
181
182pub(crate) struct IncompleteParserContexts(RefCell<Vec<(PipelineId, ParserContext)>>);
188
189unsafe_no_jsmanaged_fields!(TaskQueue<MainThreadScriptMsg>);
190
191type NodeIdSet = HashSet<String>;
192
193#[derive(Default)]
195pub(crate) struct ScriptUserInteractingGuard {
196 was_interacting: bool,
197 user_interaction_cell: Rc<Cell<bool>>,
198}
199
200impl ScriptUserInteractingGuard {
201 fn new(user_interaction_cell: Rc<Cell<bool>>) -> Self {
202 let was_interacting = user_interaction_cell.get();
203 user_interaction_cell.set(true);
204 Self {
205 was_interacting,
206 user_interaction_cell,
207 }
208 }
209}
210
211impl Drop for ScriptUserInteractingGuard {
212 fn drop(&mut self) {
213 self.user_interaction_cell.set(self.was_interacting)
214 }
215}
216
217struct ScriptThreadUserContents {
220 user_scripts: Rc<Vec<UserScript>>,
221 user_stylesheets: Rc<Vec<DocumentStyleSheet>>,
222}
223
224impl ScriptThreadUserContents {
225 fn new(user_contents: UserContents, shared_locks: &SharedRwLocks) -> Self {
226 let user_stylesheets = user_contents
227 .stylesheets
228 .iter()
229 .map(|user_stylesheet| {
230 DocumentStyleSheet(ServoArc::new(Stylesheet::from_str(
231 user_stylesheet.source(),
232 user_stylesheet.url().into(),
233 Origin::User,
234 ServoArc::new(shared_locks.ua_or_user.wrap(MediaList::empty())),
235 shared_locks.ua_or_user.clone(),
236 None,
237 Some(&RustLogReporter),
238 QuirksMode::NoQuirks,
239 AllowImportRules::Yes,
240 )))
241 })
242 .collect();
243 Self {
244 user_scripts: Rc::new(user_contents.scripts),
245 user_stylesheets: Rc::new(user_stylesheets),
246 }
247 }
248}
249
250#[derive(Clone, MallocSizeOf)]
251pub struct SharedRwLocks {
252 pub author: SharedRwLock,
253 pub ua_or_user: SharedRwLock,
254}
255
256impl Default for SharedRwLocks {
257 fn default() -> Self {
258 Self {
259 author: SharedRwLock::new(),
260 ua_or_user: SharedRwLock::new(),
261 }
262 }
263}
264
265#[derive(JSTraceable)]
266#[cfg_attr(crown, expect(crown::unrooted_must_root))]
268pub struct ScriptThread {
269 #[no_trace]
272 this: Weak<ScriptThread>,
273
274 last_render_opportunity_time: Cell<Option<Instant>>,
276
277 documents: DomRefCell<DocumentCollection>,
279 window_proxies: Rc<ScriptWindowProxies>,
281 incomplete_loads: DomRefCell<Vec<InProgressLoad>>,
283 incomplete_parser_contexts: IncompleteParserContexts,
285 #[no_trace]
288 image_cache_factory: Arc<dyn ImageCacheFactory>,
289
290 receivers: ScriptThreadReceivers,
293
294 senders: ScriptThreadSenders,
297
298 #[no_trace]
301 resource_threads: ResourceThreads,
302
303 #[no_trace]
304 storage_threads: StorageThreads,
305
306 task_queue: TaskQueue<MainThreadScriptMsg>,
308
309 #[no_trace]
311 background_hang_monitor: Box<dyn BackgroundHangMonitor>,
312 closing: Arc<AtomicBool>,
314
315 #[no_trace]
318 timer_scheduler: RefCell<TimerScheduler>,
319
320 #[no_trace]
322 system_font_service: Arc<SystemFontServiceProxy>,
323
324 js_runtime: Rc<Runtime>,
326
327 #[no_trace]
329 closed_pipelines: DomRefCell<FxHashSet<PipelineId>>,
330
331 microtask_queue: Rc<MicrotaskQueue>,
333
334 mutation_observers: Rc<ScriptMutationObservers>,
335
336 #[no_trace]
338 webgl_chan: Option<WebGLPipeline>,
339
340 #[no_trace]
342 #[cfg(feature = "webxr")]
343 webxr_registry: Option<webxr_api::Registry>,
344
345 worklet_thread_pool: DomRefCell<Option<Rc<WorkletThreadPool>>>,
347
348 docs_with_no_blocking_loads: DomRefCell<FxHashSet<Dom<Document>>>,
351
352 custom_element_reaction_stack: Rc<CustomElementReactionStack>,
354
355 #[no_trace]
357 paint_api: CrossProcessPaintApi,
358
359 profile_script_events: bool,
361
362 unminify_js: bool,
364
365 local_script_source: Option<String>,
367
368 unminify_css: bool,
370
371 #[no_trace]
373 shared_style_locks: SharedRwLocks,
374
375 #[no_trace]
379 user_contents_for_manager_id:
380 RefCell<FxHashMap<UserContentManagerId, ScriptThreadUserContents>>,
381
382 #[no_trace]
384 player_context: WindowGLContext,
385
386 #[no_trace]
388 pipeline_to_node_ids: DomRefCell<FxHashMap<PipelineId, NodeIdSet>>,
389
390 is_user_interacting: Rc<Cell<bool>>,
392
393 #[no_trace]
395 #[cfg(feature = "webgpu")]
396 gpu_id_hub: Arc<IdentityHub>,
397
398 #[no_trace]
400 layout_factory: Arc<dyn LayoutFactory>,
401
402 #[no_trace]
406 scheduled_update_the_rendering: RefCell<Option<TimerId>>,
407
408 needs_rendering_update: Arc<AtomicBool>,
415
416 debugger_global: Dom<DebuggerGlobalScope>,
417
418 debugger_paused: Cell<bool>,
419
420 #[no_trace]
422 privileged_urls: Vec<ServoUrl>,
423
424 devtools_state: DevtoolsState,
425}
426
427struct BHMExitSignal {
428 closing: Arc<AtomicBool>,
429 js_context: ThreadSafeJSContext,
430}
431
432impl BackgroundHangMonitorExitSignal for BHMExitSignal {
433 fn signal_to_exit(&self) {
434 self.closing.store(true, Ordering::SeqCst);
435 self.js_context.request_interrupt_callback();
436 }
437}
438
439#[expect(unsafe_code)]
440unsafe extern "C" fn interrupt_callback(_cx: *mut UnsafeJSContext) -> bool {
441 let res = ScriptThread::can_continue_running();
442 if !res {
443 ScriptThread::prepare_for_shutdown();
444 }
445 res
446}
447
448struct ScriptMemoryFailsafe<'a> {
453 owner: Option<&'a ScriptThread>,
454}
455
456impl<'a> ScriptMemoryFailsafe<'a> {
457 fn neuter(&mut self) {
458 self.owner = None;
459 }
460
461 fn new(owner: &'a ScriptThread) -> ScriptMemoryFailsafe<'a> {
462 ScriptMemoryFailsafe { owner: Some(owner) }
463 }
464}
465
466impl Drop for ScriptMemoryFailsafe<'_> {
467 fn drop(&mut self) {
468 if let Some(owner) = self.owner {
469 for (_, document) in owner.documents.borrow().iter() {
470 document.window().clear_js_runtime_for_script_deallocation();
471 }
472 }
473 }
474}
475
476impl ScriptThreadFactory for ScriptThread {
477 fn create(
478 state: InitialScriptState,
479 layout_factory: Arc<dyn LayoutFactory>,
480 image_cache_factory: Arc<dyn ImageCacheFactory>,
481 background_hang_monitor_register: Box<dyn BackgroundHangMonitorRegister>,
482 ) -> JoinHandle<()> {
483 PipelineNamespace::set_installer_sender(state.namespace_request_sender.clone());
486
487 let script_thread_id = state.id;
488 thread::Builder::new()
489 .name(format!("Script#{script_thread_id}"))
490 .stack_size(8 * 1024 * 1024) .spawn(move || {
492 profile_traits::debug_event!(
493 "ScriptThread::spawned",
494 script_thread_id = script_thread_id.to_string()
495 );
496 thread_state::initialize(ThreadState::SCRIPT);
497 PipelineNamespace::install(state.pipeline_namespace_id);
498 ScriptEventLoopId::install(state.id);
499 let memory_profiler_sender = state.memory_profiler_sender.clone();
500 let reporter_name = format!("script-reporter-{script_thread_id:?}");
501 let (script_thread, mut cx) = ScriptThread::new(
502 state,
503 layout_factory,
504 image_cache_factory,
505 background_hang_monitor_register,
506 );
507 SCRIPT_THREAD_ROOT.with(|root| {
508 root.set(Some(Rc::as_ptr(&script_thread)));
509 });
510 let mut failsafe = ScriptMemoryFailsafe::new(&script_thread);
511
512 memory_profiler_sender.run_with_memory_reporting(
513 || script_thread.start(&mut cx),
514 reporter_name,
515 ScriptEventLoopSender::MainThread(script_thread.senders.self_sender.clone()),
516 CommonScriptMsg::CollectReports,
517 );
518
519 failsafe.neuter();
521 })
522 .expect("Thread spawning failed")
523 }
524}
525
526impl ScriptThread {
527 pub(crate) fn runtime_handle() -> ParentRuntime {
528 with_optional_script_thread(|script_thread| {
529 script_thread.unwrap().js_runtime.prepare_for_new_child()
530 })
531 }
532
533 pub(crate) fn can_continue_running() -> bool {
534 with_script_thread(|script_thread| script_thread.can_continue_running_inner())
535 }
536
537 pub(crate) fn prepare_for_shutdown() {
538 with_script_thread(|script_thread| {
539 script_thread.prepare_for_shutdown_inner();
540 })
541 }
542
543 pub(crate) fn mutation_observers() -> Rc<ScriptMutationObservers> {
544 with_script_thread(|script_thread| script_thread.mutation_observers.clone())
545 }
546
547 pub(crate) fn microtask_queue() -> Rc<MicrotaskQueue> {
548 with_script_thread(|script_thread| script_thread.microtask_queue.clone())
549 }
550
551 pub(crate) fn shared_style_locks(&self) -> &SharedRwLocks {
552 &self.shared_style_locks
553 }
554
555 pub(crate) fn mark_document_with_no_blocked_loads(doc: &Document) {
556 with_script_thread(|script_thread| {
557 script_thread
558 .docs_with_no_blocking_loads
559 .borrow_mut()
560 .insert(Dom::from_ref(doc));
561 })
562 }
563
564 pub(crate) fn page_headers_available(
565 webview_id: WebViewId,
566 pipeline_id: PipelineId,
567 metadata: Option<&Metadata>,
568 origin: MutableOrigin,
569 cx: &mut js::context::JSContext,
570 ) -> Option<DomRoot<ServoParser>> {
571 with_script_thread(|script_thread| {
572 script_thread.handle_page_headers_available(
573 webview_id,
574 pipeline_id,
575 metadata,
576 origin,
577 cx,
578 )
579 })
580 }
581
582 pub(crate) fn process_event(msg: CommonScriptMsg, cx: &mut js::context::JSContext) -> bool {
586 with_script_thread(|script_thread| {
587 if !script_thread.can_continue_running_inner() {
588 return false;
589 }
590 script_thread.handle_msg_from_script(MainThreadScriptMsg::Common(msg), cx);
591 true
592 })
593 }
594
595 pub(crate) fn schedule_timer(&self, request: TimerEventRequest) -> TimerId {
597 self.timer_scheduler.borrow_mut().schedule_timer(request)
598 }
599
600 pub(crate) fn cancel_timer(&self, timer_id: TimerId) {
603 self.timer_scheduler.borrow_mut().cancel_timer(timer_id)
604 }
605
606 pub(crate) fn await_stable_state(task: Microtask) {
608 with_script_thread(|script_thread| {
609 script_thread
610 .microtask_queue
611 .enqueue(task, script_thread.get_cx());
612 });
613 }
614
615 fn check_load_origin(source: &LoadOrigin, target: &OriginSnapshot) -> bool {
620 match (source, target.immutable()) {
621 (LoadOrigin::Constellation, _) | (LoadOrigin::WebDriver, _) => {
622 true
624 },
625 (_, ImmutableOrigin::Opaque(_)) => {
626 true
630 },
631 (LoadOrigin::Script(source_origin), _) => source_origin.same_origin_domain(target),
632 }
633 }
634
635 pub(crate) fn set_needs_rendering_update(&self) {
639 self.needs_rendering_update.store(true, Ordering::Relaxed);
640 }
641
642 pub(crate) fn can_navigate_to_javascript_url(
644 cx: &mut js::context::JSContext,
645 initiator_global: &GlobalScope,
646 target_global: &GlobalScope,
647 load_data: &mut LoadData,
648 container: Option<&Element>,
649 ) -> bool {
650 if !Self::check_load_origin(&load_data.load_origin, &target_global.origin().snapshot()) {
654 return false;
655 }
656
657 if initiator_global
660 .get_csp_list()
661 .should_navigation_request_be_blocked(cx, initiator_global, load_data, container)
662 {
663 return false;
664 }
665
666 true
667 }
668
669 pub(crate) fn navigate_to_javascript_url(
672 cx: &mut js::context::JSContext,
673 initiator_global: &GlobalScope,
674 target_global: &GlobalScope,
675 load_data: &mut LoadData,
676 container: Option<&Element>,
677 initial_insertion: Option<bool>,
678 ) -> bool {
679 if !Self::can_navigate_to_javascript_url(
681 cx,
682 initiator_global,
683 target_global,
684 load_data,
685 container,
686 ) {
687 return false;
688 }
689
690 let Some(body) = Self::eval_js_url(cx, target_global, &load_data.url) else {
693 let window_proxy = target_global.as_window().window_proxy();
695 if let Some(frame_element) = window_proxy
696 .frame_element()
697 .and_then(Castable::downcast::<HTMLIFrameElement>)
698 {
699 if initial_insertion == Some(true) && frame_element.is_initial_blank_document() {
701 frame_element.run_iframe_load_event_steps(cx);
702 }
703 }
704 return false;
706 };
707
708 load_data.js_eval_result = Some(body);
714 load_data.url = target_global.get_url();
715 load_data
716 .headers
717 .typed_insert(headers::ContentType::from(mime::TEXT_HTML_UTF_8));
718 true
719 }
720
721 pub(crate) fn get_top_level_for_browsing_context(
722 sender_webview_id: WebViewId,
723 sender_pipeline_id: PipelineId,
724 browsing_context_id: BrowsingContextId,
725 ) -> Option<WebViewId> {
726 with_script_thread(|script_thread| {
727 script_thread.ask_constellation_for_top_level_info(
728 sender_webview_id,
729 sender_pipeline_id,
730 browsing_context_id,
731 )
732 })
733 }
734
735 pub(crate) fn find_window(id: PipelineId) -> Option<DomRoot<Window>> {
736 with_script_thread(|script_thread| script_thread.documents.borrow().find_window(id))
737 }
738
739 pub(crate) fn find_document(id: PipelineId) -> Option<DomRoot<Document>> {
740 with_script_thread(|script_thread| script_thread.documents.borrow().find_document(id))
741 }
742
743 #[must_use]
747 pub(crate) fn user_interacting_guard() -> ScriptUserInteractingGuard {
748 with_script_thread(|script_thread| {
749 ScriptUserInteractingGuard::new(script_thread.is_user_interacting.clone())
750 })
751 }
752
753 pub(crate) fn is_user_interacting() -> bool {
754 with_script_thread(|script_thread| script_thread.is_user_interacting.get())
755 }
756
757 pub(crate) fn get_fully_active_document_ids(&self) -> FxHashSet<PipelineId> {
758 self.documents
759 .borrow()
760 .iter()
761 .filter_map(|(id, document)| {
762 if document.is_fully_active() {
763 Some(id)
764 } else {
765 None
766 }
767 })
768 .fold(FxHashSet::default(), |mut set, id| {
769 let _ = set.insert(id);
770 set
771 })
772 }
773
774 pub(crate) fn window_proxies() -> Rc<ScriptWindowProxies> {
775 with_script_thread(|script_thread| script_thread.window_proxies.clone())
776 }
777
778 pub(crate) fn find_window_proxy_by_name(name: &DOMString) -> Option<DomRoot<WindowProxy>> {
779 with_script_thread(|script_thread| {
780 script_thread.window_proxies.find_window_proxy_by_name(name)
781 })
782 }
783
784 pub(crate) fn worklet_thread_pool(image_cache: Arc<dyn ImageCache>) -> Rc<WorkletThreadPool> {
786 with_optional_script_thread(|script_thread| {
787 let script_thread = script_thread.unwrap();
788 script_thread
789 .worklet_thread_pool
790 .borrow_mut()
791 .get_or_insert_with(|| {
792 let init = WorkletGlobalScopeInit {
793 to_script_thread_sender: script_thread.senders.self_sender.clone(),
794 resource_threads: script_thread.resource_threads.clone(),
795 storage_threads: script_thread.storage_threads.clone(),
796 mem_profiler_chan: script_thread.senders.memory_profiler_sender.clone(),
797 time_profiler_chan: script_thread.senders.time_profiler_sender.clone(),
798 devtools_chan: script_thread.senders.devtools_server_sender.clone(),
799 to_constellation_sender: script_thread
800 .senders
801 .pipeline_to_constellation_sender
802 .clone(),
803 to_embedder_sender: script_thread
804 .senders
805 .pipeline_to_embedder_sender
806 .clone(),
807 image_cache,
808 #[cfg(feature = "webgpu")]
809 gpu_id_hub: script_thread.gpu_id_hub.clone(),
810 };
811 Rc::new(WorkletThreadPool::spawn(init))
812 })
813 .clone()
814 })
815 }
816
817 fn handle_register_paint_worklet(
818 &self,
819 pipeline_id: PipelineId,
820 name: Atom,
821 properties: Vec<Atom>,
822 painter: Box<dyn Painter>,
823 ) {
824 let Some(window) = self.documents.borrow().find_window(pipeline_id) else {
825 warn!("Paint worklet registered after pipeline {pipeline_id} closed.");
826 return;
827 };
828
829 window
830 .layout_mut()
831 .register_paint_worklet_modules(name, properties, painter);
832 }
833
834 pub(crate) fn custom_element_reaction_stack() -> Rc<CustomElementReactionStack> {
835 with_optional_script_thread(|script_thread| {
836 script_thread
837 .as_ref()
838 .unwrap()
839 .custom_element_reaction_stack
840 .clone()
841 })
842 }
843
844 pub(crate) fn enqueue_callback_reaction(
845 element: &Element,
846 reaction: CallbackReaction,
847 definition: Option<Rc<CustomElementDefinition>>,
848 ) {
849 with_script_thread(|script_thread| {
850 script_thread
851 .custom_element_reaction_stack
852 .enqueue_callback_reaction(element, reaction, definition);
853 })
854 }
855
856 pub(crate) fn enqueue_upgrade_reaction(
857 element: &Element,
858 definition: Rc<CustomElementDefinition>,
859 ) {
860 with_script_thread(|script_thread| {
861 script_thread
862 .custom_element_reaction_stack
863 .enqueue_upgrade_reaction(element, definition);
864 })
865 }
866
867 pub(crate) fn invoke_backup_element_queue(cx: &mut js::context::JSContext) {
868 with_script_thread(|script_thread| {
869 script_thread
870 .custom_element_reaction_stack
871 .invoke_backup_element_queue(cx);
872 })
873 }
874
875 pub(crate) fn save_node_id(pipeline: PipelineId, node_id: String) {
876 with_script_thread(|script_thread| {
877 script_thread
878 .pipeline_to_node_ids
879 .borrow_mut()
880 .entry(pipeline)
881 .or_default()
882 .insert(node_id);
883 })
884 }
885
886 pub(crate) fn has_node_id(pipeline: PipelineId, node_id: &str) -> bool {
887 with_script_thread(|script_thread| {
888 script_thread
889 .pipeline_to_node_ids
890 .borrow()
891 .get(&pipeline)
892 .is_some_and(|node_ids| node_ids.contains(node_id))
893 })
894 }
895
896 #[servo_tracing::instrument(name = "ScripThread::new", level = "debug", skip_all)]
898 pub(crate) fn new(
899 state: InitialScriptState,
900 layout_factory: Arc<dyn LayoutFactory>,
901 image_cache_factory: Arc<dyn ImageCacheFactory>,
902 background_hang_monitor_register: Box<dyn BackgroundHangMonitorRegister>,
903 ) -> (Rc<ScriptThread>, js::context::JSContext) {
904 let (self_sender, self_receiver) = unbounded();
905 let mut runtime =
906 Runtime::new(Some(ScriptEventLoopSender::MainThread(self_sender.clone())));
907
908 let mut cx = unsafe { runtime.cx() };
911
912 unsafe {
913 SetWindowProxyClass(&cx, GetWindowProxyClass());
914 JS_AddInterruptCallback(&cx, Some(interrupt_callback));
915 }
916
917 let constellation_receiver = state
918 .constellation_to_script_receiver
919 .route_preserving_errors();
920
921 let devtools_server_sender = state.devtools_server_sender;
923 let (ipc_devtools_sender, ipc_devtools_receiver) = generic_channel::channel().unwrap();
924 let devtools_server_receiver = ipc_devtools_receiver.route_preserving_errors();
925
926 let task_queue = TaskQueue::new(self_receiver, self_sender.clone());
927
928 let closing = Arc::new(AtomicBool::new(false));
929 let background_hang_monitor_exit_signal = BHMExitSignal {
930 closing: closing.clone(),
931 js_context: runtime.thread_safe_js_context(),
932 };
933
934 let background_hang_monitor = background_hang_monitor_register.register_component(
935 MonitoredComponentId(state.id, MonitoredComponentType::Script),
938 Duration::from_millis(1000),
939 Duration::from_millis(5000),
940 Box::new(background_hang_monitor_exit_signal),
941 );
942
943 let (image_cache_sender, image_cache_receiver) = unbounded();
944
945 let receivers = ScriptThreadReceivers {
946 constellation_receiver,
947 image_cache_receiver,
948 devtools_server_receiver,
949 #[cfg(feature = "webgpu")]
951 webgpu_receiver: RefCell::new(crossbeam_channel::never()),
952 };
953
954 let opts = opts::get();
955 let senders = ScriptThreadSenders {
956 self_sender,
957 #[cfg(feature = "bluetooth")]
958 bluetooth_sender: state.bluetooth_sender,
959 constellation_sender: state.constellation_to_script_sender,
960 pipeline_to_constellation_sender: state.script_to_constellation_sender,
961 pipeline_to_embedder_sender: state.script_to_embedder_sender.clone(),
962 image_cache_sender,
963 time_profiler_sender: state.time_profiler_sender,
964 memory_profiler_sender: state.memory_profiler_sender,
965 devtools_server_sender,
966 devtools_client_to_script_thread_sender: ipc_devtools_sender,
967 };
968
969 let microtask_queue = runtime.microtask_queue.clone();
970 #[cfg(feature = "webgpu")]
971 let gpu_id_hub = Arc::new(IdentityHub::default());
972
973 let debugger_pipeline_id = PipelineId::new();
974 let script_to_constellation_chan = ScriptToConstellationChan {
975 sender: senders.pipeline_to_constellation_sender.clone(),
976 webview_id: TEST_WEBVIEW_ID,
980 pipeline_id: debugger_pipeline_id,
981 };
982 let debugger_global = DebuggerGlobalScope::new(
983 PipelineId::new(),
984 senders.devtools_server_sender.clone(),
985 senders.devtools_client_to_script_thread_sender.clone(),
986 senders.memory_profiler_sender.clone(),
987 senders.time_profiler_sender.clone(),
988 script_to_constellation_chan,
989 senders.pipeline_to_embedder_sender.clone(),
990 state.resource_threads.clone(),
991 state.storage_threads.clone(),
992 #[cfg(feature = "webgpu")]
993 gpu_id_hub.clone(),
994 &mut cx,
995 );
996
997 debugger_global.execute(&mut cx);
998
999 let shared_style_locks = Default::default();
1000 let user_contents_for_manager_id =
1001 FxHashMap::from_iter(state.user_contents_for_manager_id.into_iter().map(
1002 |(user_content_manager_id, user_contents)| {
1003 (
1004 user_content_manager_id,
1005 ScriptThreadUserContents::new(user_contents, &shared_style_locks),
1006 )
1007 },
1008 ));
1009
1010 (
1011 Rc::new_cyclic(|weak_script_thread| {
1012 runtime.set_script_thread(weak_script_thread.clone());
1013 Self {
1014 documents: DomRefCell::new(DocumentCollection::default()),
1015 last_render_opportunity_time: Default::default(),
1016 window_proxies: Default::default(),
1017 incomplete_loads: DomRefCell::new(vec![]),
1018 incomplete_parser_contexts: IncompleteParserContexts(RefCell::new(vec![])),
1019 senders,
1020 receivers,
1021 image_cache_factory,
1022 resource_threads: state.resource_threads,
1023 storage_threads: state.storage_threads,
1024 task_queue,
1025 background_hang_monitor,
1026 closing,
1027 timer_scheduler: Default::default(),
1028 microtask_queue,
1029 js_runtime: Rc::new(runtime),
1030 closed_pipelines: DomRefCell::new(FxHashSet::default()),
1031 mutation_observers: Default::default(),
1032 system_font_service: Arc::new(state.system_font_service.to_proxy()),
1033 webgl_chan: state.webgl_chan,
1034 #[cfg(feature = "webxr")]
1035 webxr_registry: state.webxr_registry,
1036 worklet_thread_pool: Default::default(),
1037 docs_with_no_blocking_loads: Default::default(),
1038 custom_element_reaction_stack: Rc::new(CustomElementReactionStack::new()),
1039 paint_api: state.cross_process_paint_api,
1040 profile_script_events: opts
1041 .debug
1042 .is_enabled(DiagnosticsLoggingOption::ProfileScriptEvents),
1043 unminify_js: opts.unminify_js,
1044 local_script_source: opts.local_script_source.clone(),
1045 unminify_css: opts.unminify_css,
1046 shared_style_locks,
1047 user_contents_for_manager_id: RefCell::new(user_contents_for_manager_id),
1048 player_context: state.player_context,
1049 pipeline_to_node_ids: Default::default(),
1050 is_user_interacting: Rc::new(Cell::new(false)),
1051 #[cfg(feature = "webgpu")]
1052 gpu_id_hub,
1053 layout_factory,
1054 scheduled_update_the_rendering: Default::default(),
1055 needs_rendering_update: Arc::new(AtomicBool::new(false)),
1056 debugger_global: debugger_global.as_traced(),
1057 debugger_paused: Cell::new(false),
1058 privileged_urls: state.privileged_urls,
1059 this: weak_script_thread.clone(),
1060 devtools_state: Default::default(),
1061 }
1062 }),
1063 cx,
1064 )
1065 }
1066
1067 #[expect(unsafe_code)]
1068 pub(crate) fn get_cx(&self) -> JSContext {
1069 unsafe { JSContext::from_ptr(js::rust::Runtime::get().unwrap().as_ptr()) }
1070 }
1071
1072 fn can_continue_running_inner(&self) -> bool {
1074 if self.closing.load(Ordering::SeqCst) {
1075 return false;
1076 }
1077 true
1078 }
1079
1080 fn prepare_for_shutdown_inner(&self) {
1082 let docs = self.documents.borrow();
1083 for (_, document) in docs.iter() {
1084 document
1085 .owner_global()
1086 .task_manager()
1087 .cancel_all_tasks_and_ignore_future_tasks();
1088 }
1089 }
1090
1091 pub(crate) fn start(&self, cx: &mut js::context::JSContext) {
1094 debug!("Starting script thread.");
1095 while self.handle_msgs(cx) {
1096 debug!("Running script thread.");
1098 }
1099 debug!("Stopped script thread.");
1100 }
1101
1102 fn process_pending_input_events(
1104 &self,
1105 cx: &mut js::context::JSContext,
1106 pipeline_id: PipelineId,
1107 ) {
1108 let Some(document) = self.documents.borrow().find_document(pipeline_id) else {
1109 warn!("Processing pending input events for closed pipeline {pipeline_id}.");
1110 return;
1111 };
1112 if document.window().Closed() {
1114 warn!("Input event sent to a pipeline with a closed window {pipeline_id}.");
1115 return;
1116 }
1117 if !document.event_handler().has_pending_input_events() {
1118 return;
1119 }
1120
1121 let _guard = ScriptUserInteractingGuard::new(self.is_user_interacting.clone());
1122 document.event_handler().handle_pending_input_events(cx);
1123 }
1124
1125 fn cancel_scheduled_update_the_rendering(&self) {
1126 if let Some(timer_id) = self.scheduled_update_the_rendering.borrow_mut().take() {
1127 self.timer_scheduler.borrow_mut().cancel_timer(timer_id);
1128 }
1129 }
1130
1131 fn schedule_update_the_rendering_timer_if_necessary(&self, delay: Duration) {
1132 if self.scheduled_update_the_rendering.borrow().is_some() {
1133 return;
1134 }
1135
1136 debug!("Scheduling ScriptThread animation frame.");
1137 let trigger_script_thread_animation = self.needs_rendering_update.clone();
1138 let timer_id = self.schedule_timer(TimerEventRequest {
1139 callback: Box::new(move || {
1140 trigger_script_thread_animation.store(true, Ordering::Relaxed);
1141 }),
1142 duration: delay,
1143 });
1144
1145 *self.scheduled_update_the_rendering.borrow_mut() = Some(timer_id);
1146 }
1147
1148 pub(crate) fn update_the_rendering(&self, cx: &mut js::context::JSContext) -> bool {
1155 self.last_render_opportunity_time.set(Some(Instant::now()));
1156 self.cancel_scheduled_update_the_rendering();
1157 self.needs_rendering_update.store(false, Ordering::Relaxed);
1158
1159 if !self.can_continue_running_inner() {
1160 return false;
1161 }
1162
1163 let documents_in_order = self.documents.borrow().documents_in_order();
1182
1183 let mut painters_generating_frames = FxHashSet::default();
1188 for pipeline_id in documents_in_order.iter() {
1189 let document = self
1190 .documents
1191 .borrow()
1192 .find_document(*pipeline_id)
1193 .expect("Got pipeline for Document not managed by this ScriptThread.");
1194
1195 if !document.is_fully_active() {
1196 continue;
1197 }
1198
1199 if document.waiting_on_canvas_image_updates() {
1200 continue;
1201 }
1202
1203 if
1206 document.is_render_blocked()
1208 {
1219 continue;
1220 }
1221
1222 document.clear_rendering_update_reasons();
1225
1226 self.process_pending_input_events(cx, *pipeline_id);
1233
1234 let resized = document.window().run_the_resize_steps(cx);
1236
1237 document.run_the_scroll_steps(cx);
1239
1240 let media_features_changed = document.window().take_pending_media_query_evaluation();
1247 if resized || media_features_changed {
1248 document
1249 .window()
1250 .evaluate_media_queries_and_report_changes(cx);
1251 }
1252 if resized {
1253 document.react_to_environment_changes();
1256 }
1257
1258 let mut realm = enter_auto_realm(cx, &*document);
1259 let cx = &mut realm.current_realm();
1260
1261 document.update_animations_and_send_events(cx);
1265
1266 document.run_the_animation_frame_callbacks(cx);
1276
1277 let mut depth = Default::default();
1279 while document.gather_active_resize_observations_at_depth(&depth) {
1280 depth = document.broadcast_active_resize_observations(cx);
1282 }
1283
1284 if document.has_skipped_resize_observations() {
1285 document.deliver_resize_loop_error_notification(cx);
1286 document.add_rendering_update_reason(
1289 RenderingUpdateReason::ResizeObserverStartedObservingTarget,
1290 );
1291 }
1292
1293 document.focus_handler().perform_focus_fixup_rule(cx);
1298
1299 document.update_intersection_observer_steps(cx, CrossProcessInstant::now());
1307
1308 if document.update_the_rendering(cx).0.needs_frame() {
1313 painters_generating_frames.insert(document.webview_id().into());
1314 }
1315
1316 }
1319
1320 let should_generate_frame = !painters_generating_frames.is_empty();
1321 if should_generate_frame {
1322 self.paint_api
1323 .generate_frame(painters_generating_frames.into_iter().collect());
1324 }
1325
1326 self.perform_a_microtask_checkpoint(cx);
1329 should_generate_frame
1330 }
1331
1332 fn maybe_schedule_rendering_opportunity_after_ipc_message(
1339 &self,
1340 built_any_display_lists: bool,
1341 ) {
1342 let needs_rendering_update = self
1343 .documents
1344 .borrow()
1345 .iter()
1346 .any(|(_, document)| document.needs_rendering_update());
1347 let running_animations = self.documents.borrow().iter().any(|(_, document)| {
1348 document.is_fully_active() &&
1349 !document.window().throttled() &&
1350 (document.animations().running_animation_count() != 0 ||
1351 document.has_active_request_animation_frame_callbacks())
1352 });
1353
1354 if !needs_rendering_update && !running_animations {
1358 return;
1359 }
1360
1361 if running_animations && built_any_display_lists {
1365 return;
1366 }
1367
1368 let animation_delay = if running_animations && !needs_rendering_update {
1376 Duration::from_millis(30)
1380 } else {
1381 Duration::from_millis(20)
1384 };
1385
1386 let time_since_last_rendering_opportunity = self
1387 .last_render_opportunity_time
1388 .get()
1389 .map(|last_render_opportunity_time| Instant::now() - last_render_opportunity_time)
1390 .unwrap_or(Duration::MAX)
1391 .min(animation_delay);
1392 self.schedule_update_the_rendering_timer_if_necessary(
1393 animation_delay - time_since_last_rendering_opportunity,
1394 );
1395 }
1396
1397 fn maybe_fulfill_font_ready_promises(&self, cx: &mut js::context::JSContext) {
1400 let mut sent_message = false;
1401 for (_, document) in self.documents.borrow().iter() {
1402 sent_message = document.maybe_fulfill_font_ready_promise(cx) || sent_message;
1403 }
1404
1405 if sent_message {
1406 self.perform_a_microtask_checkpoint(cx);
1407 }
1408 }
1409
1410 fn maybe_resolve_pending_screenshot_readiness_requests(&self, cx: &mut js::context::JSContext) {
1414 for (_, document) in self.documents.borrow().iter() {
1415 document
1416 .window()
1417 .maybe_resolve_pending_screenshot_readiness_requests(cx);
1418 }
1419 }
1420
1421 fn handle_msgs(&self, cx: &mut js::context::JSContext) -> bool {
1423 let mut sequential = vec![];
1425
1426 self.background_hang_monitor.notify_wait();
1428
1429 debug!("Waiting for event.");
1431 let fully_active = self.get_fully_active_document_ids();
1432 let mut event = self.receivers.recv(
1433 &self.task_queue,
1434 &self.timer_scheduler.borrow(),
1435 &fully_active,
1436 );
1437
1438 loop {
1439 debug!("Handling event: {event:?}");
1440
1441 self.timer_scheduler
1443 .borrow_mut()
1444 .dispatch_completed_timers();
1445
1446 match event {
1448 MixedMessage::FromConstellation(ScriptThreadMessage::SpawnPipeline(
1452 new_pipeline_info,
1453 )) => {
1454 self.spawn_pipeline(cx, new_pipeline_info);
1455 },
1456 MixedMessage::FromScript(MainThreadScriptMsg::Inactive) => {
1457 },
1460 MixedMessage::FromConstellation(ScriptThreadMessage::ExitFullScreen(id)) => self
1461 .profile_event(ScriptThreadEventCategory::ExitFullscreen, Some(id), || {
1462 self.handle_exit_fullscreen(id, cx);
1463 }),
1464 _ => {
1465 sequential.push(event);
1466 },
1467 }
1468
1469 match self.receivers.try_recv(&self.task_queue, &fully_active) {
1473 Some(new_event) => event = new_event,
1474 None => break,
1475 }
1476 }
1477
1478 debug!("Processing events.");
1480 for msg in sequential {
1481 debug!("Processing event {:?}.", msg);
1482 let category = self.categorize_msg(&msg);
1483 let pipeline_id = msg.pipeline_id();
1484 let _realm = pipeline_id.and_then(|id| {
1485 let global = self.documents.borrow().find_global(id);
1486 global.map(|global| enter_realm(&*global))
1487 });
1488
1489 if self.closing.load(Ordering::SeqCst) {
1490 match msg {
1492 MixedMessage::FromConstellation(ScriptThreadMessage::ExitScriptThread) => {
1493 self.handle_exit_script_thread_msg(cx);
1494 return false;
1495 },
1496 MixedMessage::FromConstellation(ScriptThreadMessage::ExitPipeline(
1497 webview_id,
1498 pipeline_id,
1499 discard_browsing_context,
1500 )) => {
1501 self.handle_exit_pipeline_msg(
1502 webview_id,
1503 pipeline_id,
1504 discard_browsing_context,
1505 cx,
1506 );
1507 },
1508 _ => {},
1509 }
1510 continue;
1511 }
1512
1513 let exiting = self.profile_event(category, pipeline_id, || {
1514 match msg {
1515 MixedMessage::FromConstellation(ScriptThreadMessage::ExitScriptThread) => {
1516 self.handle_exit_script_thread_msg(cx);
1517 return true;
1518 },
1519 MixedMessage::FromConstellation(inner_msg) => {
1520 self.handle_msg_from_constellation(inner_msg, cx)
1521 },
1522 MixedMessage::FromScript(inner_msg) => {
1523 self.handle_msg_from_script(inner_msg, cx)
1524 },
1525 MixedMessage::FromDevtools(inner_msg) => {
1526 self.handle_msg_from_devtools(inner_msg, cx)
1527 },
1528 MixedMessage::FromImageCache(inner_msg) => {
1529 self.handle_msg_from_image_cache(inner_msg, cx)
1530 },
1531 #[cfg(feature = "webgpu")]
1532 MixedMessage::FromWebGPUServer(inner_msg) => {
1533 self.handle_msg_from_webgpu_server(inner_msg, cx)
1534 },
1535 MixedMessage::TimerFired => {},
1536 }
1537
1538 false
1539 });
1540
1541 if exiting {
1543 return false;
1544 }
1545
1546 self.perform_a_microtask_checkpoint(cx);
1549 }
1550
1551 for (_, doc) in self.documents.borrow().iter() {
1552 let window = doc.window();
1553 window
1554 .upcast::<GlobalScope>()
1555 .perform_a_dom_garbage_collection_checkpoint();
1556 }
1557
1558 {
1559 let mut docs = self.docs_with_no_blocking_loads.borrow_mut();
1561 for document in docs.iter() {
1562 let mut realm = enter_auto_realm(cx, &**document);
1563 let cx = &mut realm.current_realm();
1564 document.maybe_queue_document_completion(cx);
1565 }
1566 docs.clear();
1567 }
1568
1569 let built_any_display_lists =
1570 self.needs_rendering_update.load(Ordering::Relaxed) && self.update_the_rendering(cx);
1571
1572 self.maybe_fulfill_font_ready_promises(cx);
1573 self.maybe_resolve_pending_screenshot_readiness_requests(cx);
1574
1575 self.maybe_schedule_rendering_opportunity_after_ipc_message(built_any_display_lists);
1577
1578 true
1579 }
1580
1581 fn categorize_msg(&self, msg: &MixedMessage) -> ScriptThreadEventCategory {
1582 match *msg {
1583 MixedMessage::FromConstellation(ref inner_msg) => match *inner_msg {
1584 ScriptThreadMessage::SendInputEvent(..) => ScriptThreadEventCategory::InputEvent,
1585 _ => ScriptThreadEventCategory::ConstellationMsg,
1586 },
1587 MixedMessage::FromDevtools(_) => ScriptThreadEventCategory::DevtoolsMsg,
1588 MixedMessage::FromImageCache(_) => ScriptThreadEventCategory::ImageCacheMsg,
1589 MixedMessage::FromScript(ref inner_msg) => match *inner_msg {
1590 MainThreadScriptMsg::Common(CommonScriptMsg::Task(category, ..)) => category,
1591 MainThreadScriptMsg::RegisterPaintWorklet { .. } => {
1592 ScriptThreadEventCategory::WorkletEvent
1593 },
1594 _ => ScriptThreadEventCategory::ScriptEvent,
1595 },
1596 #[cfg(feature = "webgpu")]
1597 MixedMessage::FromWebGPUServer(_) => ScriptThreadEventCategory::WebGPUMsg,
1598 MixedMessage::TimerFired => ScriptThreadEventCategory::TimerEvent,
1599 }
1600 }
1601
1602 fn profile_event<F, R>(
1603 &self,
1604 category: ScriptThreadEventCategory,
1605 pipeline_id: Option<PipelineId>,
1606 f: F,
1607 ) -> R
1608 where
1609 F: FnOnce() -> R,
1610 {
1611 self.background_hang_monitor
1612 .notify_activity(HangAnnotation::Script(category.into()));
1613 let start = Instant::now();
1614 let value = if self.profile_script_events {
1615 let profiler_chan = self.senders.time_profiler_sender.clone();
1616 match category {
1617 ScriptThreadEventCategory::SpawnPipeline => {
1618 time_profile!(
1619 ProfilerCategory::ScriptSpawnPipeline,
1620 None,
1621 profiler_chan,
1622 f
1623 )
1624 },
1625 ScriptThreadEventCategory::ConstellationMsg => time_profile!(
1626 ProfilerCategory::ScriptConstellationMsg,
1627 None,
1628 profiler_chan,
1629 f
1630 ),
1631 ScriptThreadEventCategory::DatabaseAccessEvent => time_profile!(
1632 ProfilerCategory::ScriptDatabaseAccessEvent,
1633 None,
1634 profiler_chan,
1635 f
1636 ),
1637 ScriptThreadEventCategory::DevtoolsMsg => {
1638 time_profile!(ProfilerCategory::ScriptDevtoolsMsg, None, profiler_chan, f)
1639 },
1640 ScriptThreadEventCategory::DocumentEvent => time_profile!(
1641 ProfilerCategory::ScriptDocumentEvent,
1642 None,
1643 profiler_chan,
1644 f
1645 ),
1646 ScriptThreadEventCategory::InputEvent => {
1647 time_profile!(ProfilerCategory::ScriptInputEvent, None, profiler_chan, f)
1648 },
1649 ScriptThreadEventCategory::FileRead => {
1650 time_profile!(ProfilerCategory::ScriptFileRead, None, profiler_chan, f)
1651 },
1652 ScriptThreadEventCategory::FontLoading => {
1653 time_profile!(ProfilerCategory::ScriptFontLoading, None, profiler_chan, f)
1654 },
1655 ScriptThreadEventCategory::FormPlannedNavigation => time_profile!(
1656 ProfilerCategory::ScriptPlannedNavigation,
1657 None,
1658 profiler_chan,
1659 f
1660 ),
1661 ScriptThreadEventCategory::GeolocationEvent => {
1662 time_profile!(
1663 ProfilerCategory::ScriptGeolocationEvent,
1664 None,
1665 profiler_chan,
1666 f
1667 )
1668 },
1669 ScriptThreadEventCategory::NavigationAndTraversalEvent => {
1670 time_profile!(
1671 ProfilerCategory::ScriptNavigationAndTraversalEvent,
1672 None,
1673 profiler_chan,
1674 f
1675 )
1676 },
1677 ScriptThreadEventCategory::ImageCacheMsg => time_profile!(
1678 ProfilerCategory::ScriptImageCacheMsg,
1679 None,
1680 profiler_chan,
1681 f
1682 ),
1683 ScriptThreadEventCategory::NetworkEvent => {
1684 time_profile!(ProfilerCategory::ScriptNetworkEvent, None, profiler_chan, f)
1685 },
1686 ScriptThreadEventCategory::PortMessage => {
1687 time_profile!(ProfilerCategory::ScriptPortMessage, None, profiler_chan, f)
1688 },
1689 ScriptThreadEventCategory::Resize => {
1690 time_profile!(ProfilerCategory::ScriptResize, None, profiler_chan, f)
1691 },
1692 ScriptThreadEventCategory::ScriptEvent => {
1693 time_profile!(ProfilerCategory::ScriptEvent, None, profiler_chan, f)
1694 },
1695 ScriptThreadEventCategory::SetScrollState => time_profile!(
1696 ProfilerCategory::ScriptSetScrollState,
1697 None,
1698 profiler_chan,
1699 f
1700 ),
1701 ScriptThreadEventCategory::UpdateReplacedElement => time_profile!(
1702 ProfilerCategory::ScriptUpdateReplacedElement,
1703 None,
1704 profiler_chan,
1705 f
1706 ),
1707 ScriptThreadEventCategory::StylesheetLoad => time_profile!(
1708 ProfilerCategory::ScriptStylesheetLoad,
1709 None,
1710 profiler_chan,
1711 f
1712 ),
1713 ScriptThreadEventCategory::SetViewport => {
1714 time_profile!(ProfilerCategory::ScriptSetViewport, None, profiler_chan, f)
1715 },
1716 ScriptThreadEventCategory::TimerEvent => {
1717 time_profile!(ProfilerCategory::ScriptTimerEvent, None, profiler_chan, f)
1718 },
1719 ScriptThreadEventCategory::WebSocketEvent => time_profile!(
1720 ProfilerCategory::ScriptWebSocketEvent,
1721 None,
1722 profiler_chan,
1723 f
1724 ),
1725 ScriptThreadEventCategory::WorkerEvent => {
1726 time_profile!(ProfilerCategory::ScriptWorkerEvent, None, profiler_chan, f)
1727 },
1728 ScriptThreadEventCategory::WorkletEvent => {
1729 time_profile!(ProfilerCategory::ScriptWorkletEvent, None, profiler_chan, f)
1730 },
1731 ScriptThreadEventCategory::ServiceWorkerEvent => time_profile!(
1732 ProfilerCategory::ScriptServiceWorkerEvent,
1733 None,
1734 profiler_chan,
1735 f
1736 ),
1737 ScriptThreadEventCategory::EnterFullscreen => time_profile!(
1738 ProfilerCategory::ScriptEnterFullscreen,
1739 None,
1740 profiler_chan,
1741 f
1742 ),
1743 ScriptThreadEventCategory::ExitFullscreen => time_profile!(
1744 ProfilerCategory::ScriptExitFullscreen,
1745 None,
1746 profiler_chan,
1747 f
1748 ),
1749 ScriptThreadEventCategory::PerformanceTimelineTask => time_profile!(
1750 ProfilerCategory::ScriptPerformanceEvent,
1751 None,
1752 profiler_chan,
1753 f
1754 ),
1755 ScriptThreadEventCategory::Rendering => {
1756 time_profile!(ProfilerCategory::ScriptRendering, None, profiler_chan, f)
1757 },
1758 #[cfg(feature = "webgpu")]
1759 ScriptThreadEventCategory::WebGPUMsg => {
1760 time_profile!(ProfilerCategory::ScriptWebGPUMsg, None, profiler_chan, f)
1761 },
1762 }
1763 } else {
1764 f()
1765 };
1766 let task_duration = start.elapsed();
1767 for (doc_id, doc) in self.documents.borrow().iter() {
1768 if let Some(pipeline_id) = pipeline_id &&
1769 pipeline_id == doc_id &&
1770 task_duration.as_nanos() > MAX_TASK_NS
1771 {
1772 if opts::get()
1773 .debug
1774 .is_enabled(DiagnosticsLoggingOption::ProgressiveWebMetrics)
1775 {
1776 println!(
1777 "Task took longer than max allowed ({category:?}) {:?}",
1778 task_duration.as_nanos()
1779 );
1780 }
1781 doc.start_tti();
1782 }
1783 doc.record_tti_if_necessary();
1784 }
1785 value
1786 }
1787
1788 fn handle_msg_from_constellation(
1789 &self,
1790 msg: ScriptThreadMessage,
1791 cx: &mut js::context::JSContext,
1792 ) {
1793 match msg {
1794 ScriptThreadMessage::StopDelayingLoadEventsMode(pipeline_id) => {
1795 self.handle_stop_delaying_load_events_mode(pipeline_id)
1796 },
1797 ScriptThreadMessage::NavigateIframe(
1798 parent_pipeline_id,
1799 browsing_context_id,
1800 load_data,
1801 history_handling,
1802 target_snapshot_params,
1803 ) => self.handle_navigate_iframe(
1804 parent_pipeline_id,
1805 browsing_context_id,
1806 load_data,
1807 history_handling,
1808 target_snapshot_params,
1809 cx,
1810 ),
1811 ScriptThreadMessage::UnloadDocument(pipeline_id) => {
1812 self.handle_unload_document(cx, pipeline_id)
1813 },
1814 ScriptThreadMessage::ResizeInactive(id, new_size) => {
1815 self.handle_resize_inactive_msg(id, new_size)
1816 },
1817 ScriptThreadMessage::ThemeChange(_, theme) => {
1818 self.handle_theme_change_msg(theme);
1819 },
1820 ScriptThreadMessage::GetDocumentOrigin(pipeline_id, result_sender) => {
1821 self.handle_get_document_origin(pipeline_id, result_sender);
1822 },
1823 ScriptThreadMessage::GetTitle(pipeline_id) => self.handle_get_title_msg(pipeline_id),
1824 ScriptThreadMessage::SetDocumentActivity(pipeline_id, activity) => {
1825 self.handle_set_document_activity_msg(cx, pipeline_id, activity)
1826 },
1827 ScriptThreadMessage::SetThrottled(webview_id, pipeline_id, throttled) => {
1828 self.handle_set_throttled_msg(webview_id, pipeline_id, throttled)
1829 },
1830 ScriptThreadMessage::SetThrottledInContainingIframe(
1831 _,
1832 parent_pipeline_id,
1833 browsing_context_id,
1834 throttled,
1835 ) => self.handle_set_throttled_in_containing_iframe_msg(
1836 parent_pipeline_id,
1837 browsing_context_id,
1838 throttled,
1839 ),
1840 ScriptThreadMessage::PostMessage {
1841 target: target_pipeline_id,
1842 source_webview,
1843 source_with_ancestry,
1844 target_origin: origin,
1845 source_origin,
1846 data,
1847 } => self.handle_post_message_msg(
1848 cx,
1849 target_pipeline_id,
1850 source_webview,
1851 source_with_ancestry,
1852 origin,
1853 source_origin,
1854 *data,
1855 ),
1856 ScriptThreadMessage::UpdatePipelineId(
1857 parent_pipeline_id,
1858 browsing_context_id,
1859 webview_id,
1860 new_pipeline_id,
1861 reason,
1862 ) => self.handle_update_pipeline_id(
1863 parent_pipeline_id,
1864 browsing_context_id,
1865 webview_id,
1866 new_pipeline_id,
1867 reason,
1868 cx,
1869 ),
1870 ScriptThreadMessage::UpdateHistoryState(pipeline_id, history_state_id, url) => {
1871 self.handle_update_history_state_msg(cx, pipeline_id, history_state_id, url)
1872 },
1873 ScriptThreadMessage::RemoveHistoryStates(pipeline_id, history_states) => {
1874 self.handle_remove_history_states(pipeline_id, history_states)
1875 },
1876 ScriptThreadMessage::FocusDocumentAsPartOfFocusingSteps(
1877 pipeline_id,
1878 sequence,
1879 iframe_browsing_context_id,
1880 ) => self.handle_focus_document_as_part_of_focusing_steps(
1881 cx,
1882 pipeline_id,
1883 sequence,
1884 iframe_browsing_context_id,
1885 ),
1886 ScriptThreadMessage::UnfocusDocumentAsPartOfFocusingSteps(pipeline_id, sequence) => {
1887 self.handle_unfocus_document_as_part_of_focusing_steps(cx, pipeline_id, sequence);
1888 },
1889 ScriptThreadMessage::FocusDocument(pipeline_id, remote_focus_operation) => {
1890 self.handle_focus_document(cx, pipeline_id, remote_focus_operation);
1891 },
1892 ScriptThreadMessage::WebDriverScriptCommand(pipeline_id, msg) => {
1893 self.handle_webdriver_msg(pipeline_id, msg, cx)
1894 },
1895 ScriptThreadMessage::WebFontLoaded(pipeline_id) => {
1896 self.handle_web_font_loaded(pipeline_id)
1897 },
1898 ScriptThreadMessage::DispatchIFrameLoadEvent {
1899 target: browsing_context_id,
1900 parent: parent_id,
1901 child: child_id,
1902 } => self.handle_iframe_load_event(parent_id, browsing_context_id, child_id, cx),
1903 ScriptThreadMessage::DispatchStorageEvent(
1904 pipeline_id,
1905 storage,
1906 url,
1907 key,
1908 old_value,
1909 new_value,
1910 ) => {
1911 self.handle_storage_event(pipeline_id, storage, url, key, old_value, new_value, cx)
1912 },
1913 ScriptThreadMessage::ReportCSSError(pipeline_id, filename, line, column, msg) => {
1914 self.handle_css_error_reporting(pipeline_id, filename, line, column, msg)
1915 },
1916 ScriptThreadMessage::Reload(pipeline_id) => self.handle_reload(pipeline_id, cx),
1917 ScriptThreadMessage::Resize(id, size, size_type) => {
1918 self.handle_resize_message(id, size, size_type);
1919 },
1920 ScriptThreadMessage::ExitPipeline(
1921 webview_id,
1922 pipeline_id,
1923 discard_browsing_context,
1924 ) => {
1925 self.handle_exit_pipeline_msg(webview_id, pipeline_id, discard_browsing_context, cx)
1926 },
1927 ScriptThreadMessage::PaintMetric(
1928 pipeline_id,
1929 metric_type,
1930 metric_value,
1931 first_reflow,
1932 ) => self.handle_paint_metric(
1933 pipeline_id,
1934 metric_type,
1935 metric_value,
1936 first_reflow,
1937 CanGc::from_cx(cx),
1938 ),
1939 ScriptThreadMessage::MediaSessionAction(pipeline_id, action) => {
1940 self.handle_media_session_action(cx, pipeline_id, action)
1941 },
1942 ScriptThreadMessage::SendInputEvent(webview_id, id, event) => {
1943 self.handle_input_event(webview_id, id, event)
1944 },
1945 #[cfg(feature = "webgpu")]
1946 ScriptThreadMessage::SetWebGPUPort(port) => {
1947 *self.receivers.webgpu_receiver.borrow_mut() = port.route_preserving_errors();
1948 },
1949 ScriptThreadMessage::TickAllAnimations(_webviews) => {
1950 self.set_needs_rendering_update();
1951 },
1952 ScriptThreadMessage::NoLongerWaitingOnAsychronousImageUpdates(pipeline_id) => {
1953 if let Some(document) = self.documents.borrow().find_document(pipeline_id) {
1954 document.handle_no_longer_waiting_on_asynchronous_image_updates();
1955 }
1956 },
1957 msg @ ScriptThreadMessage::SpawnPipeline(..) |
1958 msg @ ScriptThreadMessage::ExitFullScreen(..) |
1959 msg @ ScriptThreadMessage::ExitScriptThread => {
1960 panic!("should have handled {:?} already", msg)
1961 },
1962 ScriptThreadMessage::SetScrollStates(pipeline_id, scroll_states) => {
1963 self.handle_set_scroll_states(pipeline_id, scroll_states)
1964 },
1965 ScriptThreadMessage::EvaluateJavaScript(
1966 webview_id,
1967 pipeline_id,
1968 evaluation_id,
1969 script,
1970 ) => {
1971 self.handle_evaluate_javascript(webview_id, pipeline_id, evaluation_id, script, cx);
1972 },
1973 ScriptThreadMessage::SendImageKeysBatch(pipeline_id, image_keys) => {
1974 if let Some(window) = self.documents.borrow().find_window(pipeline_id) {
1975 window
1976 .image_cache()
1977 .fill_key_cache_with_batch_of_keys(image_keys);
1978 } else {
1979 warn!(
1980 "Could not find window corresponding to an image cache to send image keys to pipeline {:?}",
1981 pipeline_id
1982 );
1983 }
1984 },
1985 ScriptThreadMessage::RefreshCursor(pipeline_id) => {
1986 self.handle_refresh_cursor(pipeline_id);
1987 },
1988 ScriptThreadMessage::PreferencesUpdated(updates) => {
1989 let mut current_preferences = prefs::get().clone();
1990 for (name, value) in updates {
1991 current_preferences.set_value(&name, value);
1992 }
1993 prefs::set(current_preferences);
1994 },
1995 ScriptThreadMessage::ForwardKeyboardScroll(pipeline_id, scroll) => {
1996 if let Some(document) = self.documents.borrow().find_document(pipeline_id) {
1997 document.event_handler().do_keyboard_scroll(cx, scroll);
1998 }
1999 },
2000 ScriptThreadMessage::RequestScreenshotReadiness(webview_id, pipeline_id) => {
2001 self.handle_request_screenshot_readiness(webview_id, pipeline_id, cx);
2002 },
2003 ScriptThreadMessage::EmbedderControlResponse(id, response) => {
2004 self.handle_embedder_control_response(id, response, cx);
2005 },
2006 ScriptThreadMessage::SetUserContents(user_content_manager_id, user_contents) => {
2007 self.user_contents_for_manager_id.borrow_mut().insert(
2008 user_content_manager_id,
2009 ScriptThreadUserContents::new(user_contents, &self.shared_style_locks),
2010 );
2011 },
2012 ScriptThreadMessage::DestroyUserContentManager(user_content_manager_id) => {
2013 self.user_contents_for_manager_id
2014 .borrow_mut()
2015 .remove(&user_content_manager_id);
2016 },
2017 ScriptThreadMessage::UpdatePinchZoomInfos(id, pinch_zoom_infos) => {
2018 self.handle_update_pinch_zoom_infos(id, pinch_zoom_infos, CanGc::from_cx(cx));
2019 },
2020 ScriptThreadMessage::SetAccessibilityActive(pipeline_id, active, epoch) => {
2021 self.set_accessibility_active(pipeline_id, active, epoch);
2022 },
2023 ScriptThreadMessage::TriggerGarbageCollection => unsafe {
2024 JS_GC(*GlobalScope::get_cx(), GCReason::API);
2025 },
2026 }
2027 }
2028
2029 fn handle_set_scroll_states(&self, pipeline_id: PipelineId, scroll_states: ScrollStateUpdate) {
2030 let Some(window) = self.documents.borrow().find_window(pipeline_id) else {
2031 warn!("Received scroll states for closed pipeline {pipeline_id}");
2032 return;
2033 };
2034
2035 self.profile_event(
2036 ScriptThreadEventCategory::SetScrollState,
2037 Some(pipeline_id),
2038 || {
2039 window
2040 .layout_mut()
2041 .set_scroll_offsets_from_renderer(&scroll_states.offsets);
2042 },
2043 );
2044
2045 window
2046 .Document()
2047 .event_handler()
2048 .handle_embedder_scroll_event(scroll_states.scrolled_node);
2049 }
2050
2051 #[cfg(feature = "webgpu")]
2052 fn handle_msg_from_webgpu_server(&self, msg: WebGPUMsg, cx: &mut js::context::JSContext) {
2053 match msg {
2054 WebGPUMsg::FreeAdapter(id) => self.gpu_id_hub.free_adapter_id(id),
2055 WebGPUMsg::FreeDevice {
2056 device_id,
2057 pipeline_id,
2058 } => {
2059 self.gpu_id_hub.free_device_id(device_id);
2060 if let Some(global) = self.documents.borrow().find_global(pipeline_id) {
2061 global.remove_gpu_device(WebGPUDevice(device_id));
2062 } },
2064 WebGPUMsg::FreeBuffer(id) => self.gpu_id_hub.free_buffer_id(id),
2065 WebGPUMsg::FreePipelineLayout(id) => self.gpu_id_hub.free_pipeline_layout_id(id),
2066 WebGPUMsg::FreeComputePipeline(id) => self.gpu_id_hub.free_compute_pipeline_id(id),
2067 WebGPUMsg::FreeBindGroup(id) => self.gpu_id_hub.free_bind_group_id(id),
2068 WebGPUMsg::FreeBindGroupLayout(id) => self.gpu_id_hub.free_bind_group_layout_id(id),
2069 WebGPUMsg::FreeCommandBuffer(id) => self.gpu_id_hub.free_command_buffer_id(id),
2070 WebGPUMsg::FreeSampler(id) => self.gpu_id_hub.free_sampler_id(id),
2071 WebGPUMsg::FreeShaderModule(id) => self.gpu_id_hub.free_shader_module_id(id),
2072 WebGPUMsg::FreeRenderBundle(id) => self.gpu_id_hub.free_render_bundle_id(id),
2073 WebGPUMsg::FreeRenderPipeline(id) => self.gpu_id_hub.free_render_pipeline_id(id),
2074 WebGPUMsg::FreeTexture(id) => self.gpu_id_hub.free_texture_id(id),
2075 WebGPUMsg::FreeTextureView(id) => self.gpu_id_hub.free_texture_view_id(id),
2076 WebGPUMsg::FreeComputePass(id) => self.gpu_id_hub.free_compute_pass_id(id),
2077 WebGPUMsg::FreeRenderPass(id) => self.gpu_id_hub.free_render_pass_id(id),
2078 WebGPUMsg::Exit => {
2079 *self.receivers.webgpu_receiver.borrow_mut() = crossbeam_channel::never()
2080 },
2081 WebGPUMsg::DeviceLost {
2082 pipeline_id,
2083 device,
2084 reason,
2085 msg,
2086 } => {
2087 let global = self.documents.borrow().find_global(pipeline_id).unwrap();
2088 global.gpu_device_lost(device, reason, msg);
2089 },
2090 WebGPUMsg::UncapturedError {
2091 device,
2092 pipeline_id,
2093 error,
2094 } => {
2095 let global = self.documents.borrow().find_global(pipeline_id).unwrap();
2096 let _ac = enter_auto_realm(cx, &*global);
2097 global.handle_uncaptured_gpu_error(device, error);
2098 },
2099 _ => {},
2100 }
2101 }
2102
2103 fn handle_msg_from_script(&self, msg: MainThreadScriptMsg, cx: &mut js::context::JSContext) {
2104 match msg {
2105 MainThreadScriptMsg::Common(CommonScriptMsg::Task(_, task, pipeline_id, _)) => {
2106 let _realm = pipeline_id.and_then(|id| {
2107 let global = self.documents.borrow().find_global(id);
2108 global.map(|global| enter_realm(&*global))
2109 });
2110 task.run_box(cx)
2111 },
2112 MainThreadScriptMsg::Common(CommonScriptMsg::CollectReports(chan)) => {
2113 self.collect_reports(cx, chan)
2114 },
2115 MainThreadScriptMsg::Common(CommonScriptMsg::ReportCspViolations(
2116 pipeline_id,
2117 violations,
2118 )) => {
2119 if let Some(global) = self.documents.borrow().find_global(pipeline_id) {
2120 global.report_csp_violations(violations, None, None);
2121 }
2122 },
2123 MainThreadScriptMsg::NavigationResponse {
2124 pipeline_id,
2125 message,
2126 } => {
2127 self.handle_navigation_response(cx, pipeline_id, *message);
2128 },
2129 MainThreadScriptMsg::WorkletLoaded(pipeline_id) => {
2130 self.handle_worklet_loaded(pipeline_id)
2131 },
2132 MainThreadScriptMsg::RegisterPaintWorklet {
2133 pipeline_id,
2134 name,
2135 properties,
2136 painter,
2137 } => self.handle_register_paint_worklet(pipeline_id, name, properties, painter),
2138 MainThreadScriptMsg::Inactive => {},
2139 MainThreadScriptMsg::WakeUp => {},
2140 MainThreadScriptMsg::ForwardEmbedderControlResponseFromFileManager(
2141 control_id,
2142 response,
2143 ) => {
2144 self.handle_embedder_control_response(control_id, response, cx);
2145 },
2146 }
2147 }
2148
2149 fn handle_msg_from_devtools(
2150 &self,
2151 msg: DevtoolScriptControlMsg,
2152 cx: &mut js::context::JSContext,
2153 ) {
2154 let documents = self.documents.borrow();
2155 match msg {
2156 DevtoolScriptControlMsg::GetEventListenerInfo(id, node, reply) => {
2157 devtools::handle_get_event_listener_info(&self.devtools_state, id, &node, reply)
2158 },
2159 DevtoolScriptControlMsg::GetRootNode(id, reply) => {
2160 devtools::handle_get_root_node(cx, &self.devtools_state, &documents, id, reply)
2161 },
2162 DevtoolScriptControlMsg::GetDocumentElement(id, reply) => {
2163 devtools::handle_get_document_element(
2164 cx,
2165 &self.devtools_state,
2166 &documents,
2167 id,
2168 reply,
2169 )
2170 },
2171 DevtoolScriptControlMsg::GetStyleSheets(id, reply) => {
2172 devtools::handle_get_stylesheets(&documents, id, reply);
2173 },
2174 DevtoolScriptControlMsg::GetStyleSheetText(id, index, reply) => {
2175 devtools::handle_get_stylesheet_text(cx, &documents, id, index, reply);
2176 },
2177 DevtoolScriptControlMsg::GetChildren(id, node_id, reply) => {
2178 devtools::handle_get_children(cx, &self.devtools_state, id, &node_id, reply)
2179 },
2180 DevtoolScriptControlMsg::GetAttributeStyle(id, node_id, reply) => {
2181 devtools::handle_get_attribute_style(cx, &self.devtools_state, id, &node_id, reply)
2182 },
2183 DevtoolScriptControlMsg::GetStylesheetStyle(id, node_id, matched_rule, reply) => {
2184 devtools::handle_get_stylesheet_style(
2185 cx,
2186 &self.devtools_state,
2187 &documents,
2188 id,
2189 &node_id,
2190 matched_rule,
2191 reply,
2192 )
2193 },
2194 DevtoolScriptControlMsg::GetSelectors(id, node_id, reply) => {
2195 devtools::handle_get_selectors(
2196 cx,
2197 &self.devtools_state,
2198 &documents,
2199 id,
2200 &node_id,
2201 reply,
2202 )
2203 },
2204 DevtoolScriptControlMsg::GetComputedStyle(id, node_id, reply) => {
2205 devtools::handle_get_computed_style(cx, &self.devtools_state, id, &node_id, reply)
2206 },
2207 DevtoolScriptControlMsg::GetLayout(id, node_id, reply) => {
2208 devtools::handle_get_layout(cx, &self.devtools_state, id, &node_id, reply)
2209 },
2210 DevtoolScriptControlMsg::GetXPath(id, node_id, reply) => {
2211 devtools::handle_get_xpath(&self.devtools_state, id, &node_id, reply)
2212 },
2213 DevtoolScriptControlMsg::ModifyAttribute(id, node_id, modifications) => {
2214 devtools::handle_modify_attribute(
2215 cx,
2216 &self.devtools_state,
2217 &documents,
2218 id,
2219 &node_id,
2220 modifications,
2221 )
2222 },
2223 DevtoolScriptControlMsg::ModifyRule(id, node_id, modifications) => {
2224 devtools::handle_modify_rule(
2225 cx,
2226 &self.devtools_state,
2227 &documents,
2228 id,
2229 &node_id,
2230 modifications,
2231 )
2232 },
2233 DevtoolScriptControlMsg::WantsLiveNotifications(id, to_send) => {
2234 match documents.find_window(id) {
2235 Some(window) => {
2236 window.set_devtools_wants_updates(to_send);
2237 },
2238 None => warn!("Message sent to closed pipeline {}.", id),
2239 }
2240 },
2241 DevtoolScriptControlMsg::SetTimelineMarkers(id, marker_types, reply) => {
2242 devtools::handle_set_timeline_markers(&documents, id, marker_types, reply)
2243 },
2244 DevtoolScriptControlMsg::DropTimelineMarkers(id, marker_types) => {
2245 devtools::handle_drop_timeline_markers(&documents, id, marker_types)
2246 },
2247 DevtoolScriptControlMsg::RequestAnimationFrame(id, name) => {
2248 devtools::handle_request_animation_frame(&documents, id, name)
2249 },
2250 DevtoolScriptControlMsg::NavigateTo(pipeline_id, url) => {
2251 self.handle_navigate_to(pipeline_id, url)
2252 },
2253 DevtoolScriptControlMsg::GoBack(pipeline_id) => {
2254 self.handle_traverse_history(pipeline_id, TraversalDirection::Back(1))
2255 },
2256 DevtoolScriptControlMsg::GoForward(pipeline_id) => {
2257 self.handle_traverse_history(pipeline_id, TraversalDirection::Forward(1))
2258 },
2259 DevtoolScriptControlMsg::Reload(id) => self.handle_reload(id, cx),
2260 DevtoolScriptControlMsg::GetCssDatabase(reply) => {
2261 devtools::handle_get_css_database(reply)
2262 },
2263 DevtoolScriptControlMsg::SimulateColorScheme(id, theme) => {
2264 match documents.find_window(id) {
2265 Some(window) => {
2266 window.set_theme(theme);
2267 },
2268 None => warn!("Message sent to closed pipeline {}.", id),
2269 }
2270 },
2271 DevtoolScriptControlMsg::HighlightDomNode(id, node_id) => {
2272 devtools::handle_highlight_dom_node(
2273 &self.devtools_state,
2274 &documents,
2275 id,
2276 node_id.as_deref(),
2277 )
2278 },
2279 DevtoolScriptControlMsg::Eval(code, id, frame_actor_id, reply) => {
2280 self.debugger_global
2281 .fire_eval(cx, code.into(), id, None, frame_actor_id, reply);
2282 },
2283 DevtoolScriptControlMsg::GetPossibleBreakpoints(spidermonkey_id, result_sender) => {
2284 self.debugger_global.fire_get_possible_breakpoints(
2285 cx,
2286 spidermonkey_id,
2287 result_sender,
2288 );
2289 },
2290 DevtoolScriptControlMsg::SetBreakpoint(spidermonkey_id, script_id, offset) => {
2291 self.debugger_global
2292 .fire_set_breakpoint(cx, spidermonkey_id, script_id, offset);
2293 },
2294 DevtoolScriptControlMsg::ClearBreakpoint(spidermonkey_id, script_id, offset) => {
2295 self.debugger_global
2296 .fire_clear_breakpoint(cx, spidermonkey_id, script_id, offset);
2297 },
2298 DevtoolScriptControlMsg::Interrupt => {
2299 self.debugger_global.fire_interrupt(cx);
2300 },
2301 DevtoolScriptControlMsg::ListFrames(pipeline_id, start, count, result_sender) => {
2302 self.debugger_global
2303 .fire_list_frames(cx, pipeline_id, start, count, result_sender);
2304 },
2305 DevtoolScriptControlMsg::GetEnvironment(frame_actor_id, result_sender) => {
2306 self.debugger_global
2307 .fire_get_environment(cx, frame_actor_id, result_sender);
2308 },
2309 DevtoolScriptControlMsg::Resume(resume_limit_type, frame_actor_id) => {
2310 self.debugger_global
2311 .fire_resume(cx, resume_limit_type, frame_actor_id);
2312 self.debugger_paused.set(false);
2313 },
2314 DevtoolScriptControlMsg::Blackbox(spidermonkey_id, coverage) => {
2315 self.debugger_global
2316 .fire_blackbox(cx, spidermonkey_id, coverage);
2317 },
2318 DevtoolScriptControlMsg::Unblackbox(spidermonkey_id, coverage) => {
2319 self.debugger_global
2320 .fire_unblackbox(cx, spidermonkey_id, coverage);
2321 },
2322 }
2323 }
2324
2325 pub(crate) fn enter_debugger_pause_loop(&self) {
2328 self.debugger_paused.set(true);
2329
2330 #[allow(unsafe_code)]
2331 let mut cx = unsafe { js::context::JSContext::from_ptr(js::rust::Runtime::get().unwrap()) };
2332
2333 while self.debugger_paused.get() {
2334 match self.receivers.devtools_server_receiver.recv() {
2335 Ok(Ok(msg)) => self.handle_msg_from_devtools(msg, &mut cx),
2336 _ => {
2337 self.debugger_paused.set(false);
2338 break;
2339 },
2340 }
2341 }
2342 }
2343
2344 fn handle_msg_from_image_cache(
2345 &self,
2346 response: ImageCacheResponseMessage,
2347 cx: &mut js::context::JSContext,
2348 ) {
2349 match response {
2350 ImageCacheResponseMessage::NotifyPendingImageLoadStatus(pending_image_response) => {
2351 let window = self
2352 .documents
2353 .borrow()
2354 .find_window(pending_image_response.pipeline_id);
2355 if let Some(ref window) = window {
2356 window.pending_image_notification(pending_image_response, cx);
2357 }
2358 },
2359 ImageCacheResponseMessage::VectorImageRasterizationComplete(response) => {
2360 let window = self.documents.borrow().find_window(response.pipeline_id);
2361 if let Some(ref window) = window {
2362 window.handle_image_rasterization_complete_notification(response);
2363 }
2364 },
2365 };
2366 }
2367
2368 fn handle_webdriver_msg(
2369 &self,
2370 pipeline_id: PipelineId,
2371 msg: WebDriverScriptCommand,
2372 cx: &mut js::context::JSContext,
2373 ) {
2374 let documents = self.documents.borrow();
2375 match msg {
2376 WebDriverScriptCommand::AddCookie(params, reply) => {
2377 webdriver_handlers::handle_add_cookie(&documents, pipeline_id, params, reply)
2378 },
2379 WebDriverScriptCommand::DeleteCookies(reply) => {
2380 webdriver_handlers::handle_delete_cookies(&documents, pipeline_id, reply)
2381 },
2382 WebDriverScriptCommand::DeleteCookie(name, reply) => {
2383 webdriver_handlers::handle_delete_cookie(&documents, pipeline_id, name, reply)
2384 },
2385 WebDriverScriptCommand::ElementClear(element_id, reply) => {
2386 webdriver_handlers::handle_element_clear(
2387 cx,
2388 &documents,
2389 pipeline_id,
2390 element_id,
2391 reply,
2392 )
2393 },
2394 WebDriverScriptCommand::FindElementsCSSSelector(selector, reply) => {
2395 webdriver_handlers::handle_find_elements_css_selector(
2396 cx,
2397 &documents,
2398 pipeline_id,
2399 selector,
2400 reply,
2401 )
2402 },
2403 WebDriverScriptCommand::FindElementsLinkText(selector, partial, reply) => {
2404 webdriver_handlers::handle_find_elements_link_text(
2405 cx,
2406 &documents,
2407 pipeline_id,
2408 selector,
2409 partial,
2410 reply,
2411 )
2412 },
2413 WebDriverScriptCommand::FindElementsTagName(selector, reply) => {
2414 webdriver_handlers::handle_find_elements_tag_name(
2415 cx,
2416 &documents,
2417 pipeline_id,
2418 selector,
2419 reply,
2420 )
2421 },
2422 WebDriverScriptCommand::FindElementsXpathSelector(selector, reply) => {
2423 webdriver_handlers::handle_find_elements_xpath_selector(
2424 cx,
2425 &documents,
2426 pipeline_id,
2427 selector,
2428 reply,
2429 )
2430 },
2431 WebDriverScriptCommand::FindElementElementsCSSSelector(selector, element_id, reply) => {
2432 webdriver_handlers::handle_find_element_elements_css_selector(
2433 cx,
2434 &documents,
2435 pipeline_id,
2436 element_id,
2437 selector,
2438 reply,
2439 )
2440 },
2441 WebDriverScriptCommand::FindElementElementsLinkText(
2442 selector,
2443 element_id,
2444 partial,
2445 reply,
2446 ) => webdriver_handlers::handle_find_element_elements_link_text(
2447 cx,
2448 &documents,
2449 pipeline_id,
2450 element_id,
2451 selector,
2452 partial,
2453 reply,
2454 ),
2455 WebDriverScriptCommand::FindElementElementsTagName(selector, element_id, reply) => {
2456 webdriver_handlers::handle_find_element_elements_tag_name(
2457 cx,
2458 &documents,
2459 pipeline_id,
2460 element_id,
2461 selector,
2462 reply,
2463 )
2464 },
2465 WebDriverScriptCommand::FindElementElementsXPathSelector(
2466 selector,
2467 element_id,
2468 reply,
2469 ) => webdriver_handlers::handle_find_element_elements_xpath_selector(
2470 cx,
2471 &documents,
2472 pipeline_id,
2473 element_id,
2474 selector,
2475 reply,
2476 ),
2477 WebDriverScriptCommand::FindShadowElementsCSSSelector(
2478 selector,
2479 shadow_root_id,
2480 reply,
2481 ) => webdriver_handlers::handle_find_shadow_elements_css_selector(
2482 cx,
2483 &documents,
2484 pipeline_id,
2485 shadow_root_id,
2486 selector,
2487 reply,
2488 ),
2489 WebDriverScriptCommand::FindShadowElementsLinkText(
2490 selector,
2491 shadow_root_id,
2492 partial,
2493 reply,
2494 ) => webdriver_handlers::handle_find_shadow_elements_link_text(
2495 cx,
2496 &documents,
2497 pipeline_id,
2498 shadow_root_id,
2499 selector,
2500 partial,
2501 reply,
2502 ),
2503 WebDriverScriptCommand::FindShadowElementsTagName(selector, shadow_root_id, reply) => {
2504 webdriver_handlers::handle_find_shadow_elements_tag_name(
2505 cx,
2506 &documents,
2507 pipeline_id,
2508 shadow_root_id,
2509 selector,
2510 reply,
2511 )
2512 },
2513 WebDriverScriptCommand::FindShadowElementsXPathSelector(
2514 selector,
2515 shadow_root_id,
2516 reply,
2517 ) => webdriver_handlers::handle_find_shadow_elements_xpath_selector(
2518 cx,
2519 &documents,
2520 pipeline_id,
2521 shadow_root_id,
2522 selector,
2523 reply,
2524 ),
2525 WebDriverScriptCommand::GetElementShadowRoot(element_id, reply) => {
2526 webdriver_handlers::handle_get_element_shadow_root(
2527 &documents,
2528 pipeline_id,
2529 element_id,
2530 reply,
2531 )
2532 },
2533 WebDriverScriptCommand::ElementClick(element_id, reply) => {
2534 webdriver_handlers::handle_element_click(
2535 cx,
2536 &documents,
2537 pipeline_id,
2538 element_id,
2539 reply,
2540 )
2541 },
2542 WebDriverScriptCommand::GetKnownElement(element_id, reply) => {
2543 webdriver_handlers::handle_get_known_element(
2544 &documents,
2545 pipeline_id,
2546 element_id,
2547 reply,
2548 )
2549 },
2550 WebDriverScriptCommand::GetKnownWindow(webview_id, reply) => {
2551 webdriver_handlers::handle_get_known_window(
2552 &documents,
2553 pipeline_id,
2554 webview_id,
2555 reply,
2556 )
2557 },
2558 WebDriverScriptCommand::GetKnownShadowRoot(element_id, reply) => {
2559 webdriver_handlers::handle_get_known_shadow_root(
2560 &documents,
2561 pipeline_id,
2562 element_id,
2563 reply,
2564 )
2565 },
2566 WebDriverScriptCommand::GetActiveElement(reply) => {
2567 webdriver_handlers::handle_get_active_element(&documents, pipeline_id, reply)
2568 },
2569 WebDriverScriptCommand::GetComputedRole(node_id, reply) => {
2570 webdriver_handlers::handle_get_computed_role(
2571 &documents,
2572 pipeline_id,
2573 node_id,
2574 reply,
2575 )
2576 },
2577 WebDriverScriptCommand::GetPageSource(reply) => {
2578 webdriver_handlers::handle_get_page_source(cx, &documents, pipeline_id, reply)
2579 },
2580 WebDriverScriptCommand::GetCookies(reply) => {
2581 webdriver_handlers::handle_get_cookies(&documents, pipeline_id, reply)
2582 },
2583 WebDriverScriptCommand::GetCookie(name, reply) => {
2584 webdriver_handlers::handle_get_cookie(&documents, pipeline_id, name, reply)
2585 },
2586 WebDriverScriptCommand::GetElementTagName(node_id, reply) => {
2587 webdriver_handlers::handle_get_name(&documents, pipeline_id, node_id, reply)
2588 },
2589 WebDriverScriptCommand::GetElementAttribute(node_id, name, reply) => {
2590 webdriver_handlers::handle_get_attribute(
2591 cx,
2592 &documents,
2593 pipeline_id,
2594 node_id,
2595 name,
2596 reply,
2597 )
2598 },
2599 WebDriverScriptCommand::GetElementProperty(node_id, name, reply) => {
2600 webdriver_handlers::handle_get_property(
2601 &documents,
2602 pipeline_id,
2603 node_id,
2604 name,
2605 reply,
2606 cx,
2607 )
2608 },
2609 WebDriverScriptCommand::GetElementCSS(node_id, name, reply) => {
2610 webdriver_handlers::handle_get_css(
2611 cx,
2612 &documents,
2613 pipeline_id,
2614 node_id,
2615 name,
2616 reply,
2617 )
2618 },
2619 WebDriverScriptCommand::GetElementRect(node_id, reply) => {
2620 webdriver_handlers::handle_get_rect(cx, &documents, pipeline_id, node_id, reply)
2621 },
2622 WebDriverScriptCommand::ScrollAndGetBoundingClientRect(node_id, reply) => {
2623 webdriver_handlers::handle_scroll_and_get_bounding_client_rect(
2624 cx,
2625 &documents,
2626 pipeline_id,
2627 node_id,
2628 reply,
2629 )
2630 },
2631 WebDriverScriptCommand::GetElementText(node_id, reply) => {
2632 webdriver_handlers::handle_get_text(&documents, pipeline_id, node_id, reply)
2633 },
2634 WebDriverScriptCommand::GetElementInViewCenterPoint(node_id, reply) => {
2635 webdriver_handlers::handle_get_element_in_view_center_point(
2636 cx,
2637 &documents,
2638 pipeline_id,
2639 node_id,
2640 reply,
2641 )
2642 },
2643 WebDriverScriptCommand::GetParentFrameId(reply) => {
2644 webdriver_handlers::handle_get_parent_frame_id(&documents, pipeline_id, reply)
2645 },
2646 WebDriverScriptCommand::GetBrowsingContextId(webdriver_frame_id, reply) => {
2647 webdriver_handlers::handle_get_browsing_context_id(
2648 &documents,
2649 pipeline_id,
2650 webdriver_frame_id,
2651 reply,
2652 )
2653 },
2654 WebDriverScriptCommand::GetUrl(reply) => {
2655 webdriver_handlers::handle_get_url(&documents, pipeline_id, reply)
2656 },
2657 WebDriverScriptCommand::IsEnabled(element_id, reply) => {
2658 webdriver_handlers::handle_is_enabled(&documents, pipeline_id, element_id, reply)
2659 },
2660 WebDriverScriptCommand::IsSelected(element_id, reply) => {
2661 webdriver_handlers::handle_is_selected(&documents, pipeline_id, element_id, reply)
2662 },
2663 WebDriverScriptCommand::GetTitle(reply) => {
2664 webdriver_handlers::handle_get_title(&documents, pipeline_id, reply)
2665 },
2666 WebDriverScriptCommand::WillSendKeys(
2667 element_id,
2668 text,
2669 strict_file_interactability,
2670 reply,
2671 ) => webdriver_handlers::handle_will_send_keys(
2672 cx,
2673 &documents,
2674 pipeline_id,
2675 element_id,
2676 text,
2677 strict_file_interactability,
2678 reply,
2679 ),
2680 WebDriverScriptCommand::AddLoadStatusSender(_, response_sender) => {
2681 webdriver_handlers::handle_add_load_status_sender(
2682 &documents,
2683 pipeline_id,
2684 response_sender,
2685 )
2686 },
2687 WebDriverScriptCommand::RemoveLoadStatusSender(_) => {
2688 webdriver_handlers::handle_remove_load_status_sender(&documents, pipeline_id)
2689 },
2690 WebDriverScriptCommand::ExecuteScriptWithCallback(script, reply) => {
2697 let window = documents.find_window(pipeline_id);
2698 drop(documents);
2699 webdriver_handlers::handle_execute_async_script(window, script, reply, cx);
2700 },
2701 WebDriverScriptCommand::SetProtocolHandlerAutomationMode(mode) => {
2702 webdriver_handlers::set_protocol_handler_automation_mode(
2703 &documents,
2704 pipeline_id,
2705 mode,
2706 )
2707 },
2708 }
2709 }
2710
2711 pub(crate) fn handle_resize_message(
2714 &self,
2715 id: PipelineId,
2716 viewport_details: ViewportDetails,
2717 size_type: WindowSizeType,
2718 ) {
2719 self.profile_event(ScriptThreadEventCategory::Resize, Some(id), || {
2720 let window = self.documents.borrow().find_window(id);
2721 if let Some(ref window) = window {
2722 window.add_resize_event(viewport_details, size_type);
2723 return;
2724 }
2725 let mut loads = self.incomplete_loads.borrow_mut();
2726 if let Some(ref mut load) = loads.iter_mut().find(|load| load.pipeline_id == id) {
2727 load.viewport_details = viewport_details;
2728 }
2729 })
2730 }
2731
2732 fn handle_theme_change_msg(&self, theme: Theme) {
2734 for (_, document) in self.documents.borrow().iter() {
2735 document.window().set_theme(theme);
2736 }
2737 let mut loads = self.incomplete_loads.borrow_mut();
2738 for load in loads.iter_mut() {
2739 load.theme = theme;
2740 }
2741 }
2742
2743 fn handle_get_document_origin(
2744 &self,
2745 id: PipelineId,
2746 result_sender: GenericSender<Option<String>>,
2747 ) {
2748 let _ = result_sender.send(
2749 self.documents
2750 .borrow()
2751 .find_document(id)
2752 .map(|document| document.origin().immutable().ascii_serialization()),
2753 );
2754 }
2755
2756 fn handle_exit_fullscreen(&self, id: PipelineId, cx: &mut js::context::JSContext) {
2758 let document = self.documents.borrow().find_document(id);
2759 if let Some(document) = document {
2760 let mut realm = enter_auto_realm(cx, &*document);
2761 document.exit_fullscreen(&mut realm);
2762 }
2763 }
2764
2765 pub(crate) fn spawn_pipeline(
2766 &self,
2767 cx: &mut js::context::JSContext,
2768 new_pipeline_info: NewPipelineInfo,
2769 ) {
2770 self.profile_event(
2771 ScriptThreadEventCategory::SpawnPipeline,
2772 Some(new_pipeline_info.new_pipeline_id),
2773 || {
2774 self.devtools_state
2775 .notify_pipeline_created(new_pipeline_info.new_pipeline_id);
2776
2777 self.pre_page_load(cx, InProgressLoad::new(new_pipeline_info));
2779 },
2780 );
2781 }
2782
2783 fn collect_reports(&self, cx: &mut js::context::JSContext, reports_chan: ReportsChan) {
2784 let documents = self.documents.borrow();
2785 let urls = itertools::join(documents.iter().map(|(_, d)| d.url().to_string()), ", ");
2786
2787 let mut reports = vec![];
2788 perform_memory_report(|ops| {
2789 for (_, document) in documents.iter() {
2790 document
2791 .window()
2792 .layout()
2793 .collect_reports(&mut reports, ops);
2794 }
2795
2796 let prefix = format!("url({urls})");
2797 reports.extend(get_reports(cx, prefix, ops));
2798 });
2799
2800 reports_chan.send(ProcessReports::new(reports));
2801 }
2802
2803 fn handle_set_throttled_in_containing_iframe_msg(
2805 &self,
2806 parent_pipeline_id: PipelineId,
2807 browsing_context_id: BrowsingContextId,
2808 throttled: bool,
2809 ) {
2810 let iframe = self
2811 .documents
2812 .borrow()
2813 .find_iframe(parent_pipeline_id, browsing_context_id);
2814 if let Some(iframe) = iframe {
2815 iframe.set_throttled(throttled);
2816 }
2817 }
2818
2819 fn handle_set_throttled_msg(
2820 &self,
2821 webview_id: WebViewId,
2822 pipeline_id: PipelineId,
2823 throttled: bool,
2824 ) {
2825 self.senders
2828 .pipeline_to_constellation_sender
2829 .send((
2830 webview_id,
2831 pipeline_id,
2832 ScriptToConstellationMessage::SetThrottledComplete(throttled),
2833 ))
2834 .unwrap();
2835
2836 let window = self.documents.borrow().find_window(pipeline_id);
2837 match window {
2838 Some(window) => {
2839 window.set_throttled(throttled);
2840 return;
2841 },
2842 None => {
2843 let mut loads = self.incomplete_loads.borrow_mut();
2844 if let Some(ref mut load) = loads
2845 .iter_mut()
2846 .find(|load| load.pipeline_id == pipeline_id)
2847 {
2848 load.throttled = throttled;
2849 return;
2850 }
2851 },
2852 }
2853
2854 warn!("SetThrottled sent to nonexistent pipeline");
2855 }
2856
2857 fn handle_set_document_activity_msg(
2859 &self,
2860 cx: &mut js::context::JSContext,
2861 id: PipelineId,
2862 activity: DocumentActivity,
2863 ) {
2864 debug!(
2865 "Setting activity of {} to be {:?} in {:?}.",
2866 id,
2867 activity,
2868 thread::current().name()
2869 );
2870 let document = self.documents.borrow().find_document(id);
2871 if let Some(document) = document {
2872 document.set_activity(cx, activity);
2873 return;
2874 }
2875 let mut loads = self.incomplete_loads.borrow_mut();
2876 if let Some(ref mut load) = loads.iter_mut().find(|load| load.pipeline_id == id) {
2877 load.activity = activity;
2878 return;
2879 }
2880 warn!("change of activity sent to nonexistent pipeline");
2881 }
2882
2883 fn handle_focus_document_as_part_of_focusing_steps(
2884 &self,
2885 cx: &mut js::context::JSContext,
2886 pipeline_id: PipelineId,
2887 sequence: FocusSequenceNumber,
2888 browsing_context_id: Option<BrowsingContextId>,
2889 ) {
2890 let Some(document) = self.documents.borrow().find_document(pipeline_id) else {
2891 warn!("Unknown {pipeline_id:?} for FocusDocumentAsPartOfFocusingSteps message.");
2892 return;
2893 };
2894
2895 let focus_handler = document.focus_handler();
2896 if focus_handler.focus_sequence() > sequence {
2897 debug!(
2898 "Disregarding the FocusDocumentAsPartOfFocusingSteps message because \
2899 the contained sequence number is too old ({sequence:?} < {:?})",
2900 focus_handler.focus_sequence()
2901 );
2902 return;
2903 }
2904
2905 let iframe_element = browsing_context_id.and_then(|browsing_context_id| {
2908 document
2909 .iframes()
2910 .get(browsing_context_id)
2911 .map(|iframe| iframe.element.as_rooted())
2912 });
2913 let focusable_area = iframe_element
2914 .map(|iframe_element| {
2915 let kind = iframe_element.upcast::<Element>().focusable_area_kind();
2916 FocusableArea::IFrameViewport {
2917 iframe_element,
2918 kind,
2919 }
2920 })
2921 .unwrap_or(FocusableArea::Viewport);
2922
2923 focus_handler.focus_update_steps(
2924 cx,
2925 focusable_area.focus_chain(),
2926 focus_handler.current_focus_chain(),
2927 &focusable_area,
2928 );
2929 }
2930
2931 fn handle_focus_document(
2932 &self,
2933 cx: &mut js::context::JSContext,
2934 pipeline_id: PipelineId,
2935 remote_focus_operation: RemoteFocusOperation,
2936 ) {
2937 let Some(document) = self.documents.borrow().find_document(pipeline_id) else {
2938 warn!("Unknown {pipeline_id:?} for FocusDocument message.");
2939 return;
2940 };
2941 match remote_focus_operation {
2942 RemoteFocusOperation::Viewport => document.window().Focus(cx),
2943 RemoteFocusOperation::Sequential(direction, iframe_browsing_context_id) => document
2944 .focus_handler()
2945 .sequential_focus_from_another_document(cx, iframe_browsing_context_id, direction),
2946 }
2947 }
2948
2949 fn handle_unfocus_document_as_part_of_focusing_steps(
2950 &self,
2951 cx: &mut js::context::JSContext,
2952 pipeline_id: PipelineId,
2953 sequence: FocusSequenceNumber,
2954 ) {
2955 let Some(document) = self.documents.borrow().find_document(pipeline_id) else {
2956 warn!("Unknown {pipeline_id:?} for UnfocusDocumentAsPartOfFocusingSteps");
2957 return;
2958 };
2959
2960 let window = document.window();
2963 if window.is_top_level() {
2964 return;
2965 }
2966
2967 let focus_handler = document.focus_handler();
2968 if focus_handler.focus_sequence() > sequence {
2969 debug!(
2970 "Disregarding the Unfocus message because the contained sequence number is \
2971 too old ({:?} < {:?})",
2972 sequence,
2973 focus_handler.focus_sequence()
2974 );
2975 return;
2976 }
2977
2978 focus_handler.focus_update_steps(
2979 cx,
2980 vec![],
2981 focus_handler.current_focus_chain(),
2982 &FocusableArea::Viewport,
2983 );
2984 }
2985
2986 #[expect(clippy::too_many_arguments)]
2987 fn handle_post_message_msg(
2989 &self,
2990 cx: &mut js::context::JSContext,
2991 pipeline_id: PipelineId,
2992 source_webview: WebViewId,
2993 source_with_ancestry: Vec<BrowsingContextId>,
2994 origin: Option<ImmutableOrigin>,
2995 source_origin: ImmutableOrigin,
2996 data: StructuredSerializedData,
2997 ) {
2998 let window = self.documents.borrow().find_window(pipeline_id);
2999 match window {
3000 None => warn!("postMessage after target pipeline {} closed.", pipeline_id),
3001 Some(window) => {
3002 let mut last = None;
3003 for browsing_context_id in source_with_ancestry.into_iter().rev() {
3004 if let Some(window_proxy) =
3005 self.window_proxies.find_window_proxy(browsing_context_id)
3006 {
3007 last = Some(window_proxy);
3008 continue;
3009 }
3010 let window_proxy = WindowProxy::new_dissimilar_origin(
3011 cx,
3012 window.upcast::<GlobalScope>(),
3013 browsing_context_id,
3014 source_webview,
3015 last.as_deref(),
3016 None,
3017 CreatorBrowsingContextInfo::from(last.as_deref(), None),
3018 );
3019 self.window_proxies
3020 .insert(browsing_context_id, window_proxy.clone());
3021 last = Some(window_proxy);
3022 }
3023
3024 let source = last.expect("Source with ancestry should contain at least one bc.");
3027
3028 window.post_message(origin, source_origin, &source, data)
3030 },
3031 }
3032 }
3033
3034 fn handle_stop_delaying_load_events_mode(&self, pipeline_id: PipelineId) {
3035 let window = self.documents.borrow().find_window(pipeline_id);
3036 if let Some(window) = window {
3037 match window.undiscarded_window_proxy() {
3038 Some(window_proxy) => window_proxy.stop_delaying_load_events_mode(),
3039 None => warn!(
3040 "Attempted to take {} of 'delaying-load-events-mode' after having been discarded.",
3041 pipeline_id
3042 ),
3043 };
3044 }
3045 }
3046
3047 fn handle_unload_document(&self, cx: &mut js::context::JSContext, pipeline_id: PipelineId) {
3048 let document = self.documents.borrow().find_document(pipeline_id);
3049 if let Some(document) = document {
3050 document.unload(cx, false);
3051 }
3052 }
3053
3054 fn handle_update_pipeline_id(
3055 &self,
3056 parent_pipeline_id: PipelineId,
3057 browsing_context_id: BrowsingContextId,
3058 webview_id: WebViewId,
3059 new_pipeline_id: PipelineId,
3060 reason: UpdatePipelineIdReason,
3061 cx: &mut js::context::JSContext,
3062 ) {
3063 let frame_element = self
3064 .documents
3065 .borrow()
3066 .find_iframe(parent_pipeline_id, browsing_context_id);
3067 let Some(frame_element) = frame_element else {
3068 return;
3069 };
3070 if !frame_element.update_pipeline_id(new_pipeline_id, reason, cx) {
3071 return;
3072 };
3073
3074 let Some(window) = self.documents.borrow().find_window(new_pipeline_id) else {
3075 return;
3076 };
3077 let _ = self.window_proxies.local_window_proxy(
3080 cx,
3081 &self.senders,
3082 &self.documents,
3083 &window,
3084 browsing_context_id,
3085 webview_id,
3086 Some(parent_pipeline_id),
3087 None,
3091 );
3092 }
3093
3094 fn handle_update_history_state_msg(
3095 &self,
3096 cx: &mut js::context::JSContext,
3097 pipeline_id: PipelineId,
3098 history_state_id: Option<HistoryStateId>,
3099 url: ServoUrl,
3100 ) {
3101 let Some(window) = self.documents.borrow().find_window(pipeline_id) else {
3102 return warn!("update history state after pipeline {pipeline_id} closed.",);
3103 };
3104 window.History().activate_state(cx, history_state_id, url);
3105 }
3106
3107 fn handle_remove_history_states(
3108 &self,
3109 pipeline_id: PipelineId,
3110 history_states: Vec<HistoryStateId>,
3111 ) {
3112 let Some(window) = self.documents.borrow().find_window(pipeline_id) else {
3113 return warn!("update history state after pipeline {pipeline_id} closed.",);
3114 };
3115 window.History().remove_states(history_states);
3116 }
3117
3118 fn handle_resize_inactive_msg(&self, id: PipelineId, new_viewport_details: ViewportDetails) {
3120 let window = self.documents.borrow().find_window(id)
3121 .expect("ScriptThread: received a resize msg for a pipeline not in this script thread. This is a bug.");
3122 window.set_viewport_details(new_viewport_details);
3123 }
3124
3125 fn handle_page_headers_available(
3128 &self,
3129 webview_id: WebViewId,
3130 pipeline_id: PipelineId,
3131 metadata: Option<&Metadata>,
3132 origin: MutableOrigin,
3133 cx: &mut js::context::JSContext,
3134 ) -> Option<DomRoot<ServoParser>> {
3135 if self.closed_pipelines.borrow().contains(&pipeline_id) {
3136 return None;
3138 }
3139
3140 let Some(idx) = self
3141 .incomplete_loads
3142 .borrow()
3143 .iter()
3144 .position(|load| load.pipeline_id == pipeline_id)
3145 else {
3146 unreachable!("Pipeline shouldn't have finished loading.");
3147 };
3148
3149 let is_204_205 = match metadata {
3154 Some(metadata) => metadata.status.in_range(204..=205),
3155 _ => false,
3156 };
3157
3158 if is_204_205 {
3159 if let Some(window) = self.documents.borrow().find_window(pipeline_id) {
3161 let window_proxy = window.window_proxy();
3162 if window_proxy.parent().is_some() {
3165 window_proxy.stop_delaying_load_events_mode();
3171 }
3172 }
3173 self.senders
3174 .pipeline_to_constellation_sender
3175 .send((
3176 webview_id,
3177 pipeline_id,
3178 ScriptToConstellationMessage::AbortLoadUrl,
3179 ))
3180 .unwrap();
3181 return None;
3182 };
3183
3184 let load = self.incomplete_loads.borrow_mut().remove(idx);
3185 metadata.map(|meta| self.load(meta, load, origin, cx))
3186 }
3187
3188 fn handle_get_title_msg(&self, pipeline_id: PipelineId) {
3190 let Some(document) = self.documents.borrow().find_document(pipeline_id) else {
3191 return warn!("Message sent to closed pipeline {pipeline_id}.");
3192 };
3193 document.send_title_to_embedder();
3194 }
3195
3196 fn handle_exit_pipeline_msg(
3198 &self,
3199 webview_id: WebViewId,
3200 pipeline_id: PipelineId,
3201 discard_bc: DiscardBrowsingContext,
3202 cx: &mut js::context::JSContext,
3203 ) {
3204 debug!("{pipeline_id}: Starting pipeline exit.");
3205
3206 let document = self.documents.borrow_mut().remove(pipeline_id);
3209 if let Some(document) = document {
3210 debug_assert!(
3212 !self
3213 .incomplete_loads
3214 .borrow()
3215 .iter()
3216 .any(|load| load.pipeline_id == pipeline_id)
3217 );
3218
3219 if let Some(parser) = document.get_current_parser() {
3220 parser.abort(cx);
3221 }
3222
3223 debug!("{pipeline_id}: Shutting down layout");
3224 document.window().layout_mut().exit_now();
3225
3226 debug!("{pipeline_id}: Clearing animations");
3228 document.animations().clear();
3229
3230 let window = document.window();
3233 if discard_bc == DiscardBrowsingContext::Yes {
3234 window.discard_browsing_context();
3235 }
3236
3237 window.image_cache().clear();
3240
3241 debug!("{pipeline_id}: Clearing JavaScript runtime");
3242 window.clear_js_runtime();
3243 }
3244
3245 self.closed_pipelines.borrow_mut().insert(pipeline_id);
3247
3248 debug!("{pipeline_id}: Sending PipelineExited message to constellation");
3249 self.senders
3250 .pipeline_to_constellation_sender
3251 .send((
3252 webview_id,
3253 pipeline_id,
3254 ScriptToConstellationMessage::PipelineExited,
3255 ))
3256 .ok();
3257
3258 self.paint_api
3259 .pipeline_exited(webview_id, pipeline_id, PipelineExitSource::Script);
3260
3261 self.devtools_state.notify_pipeline_exited(pipeline_id);
3262
3263 debug!("{pipeline_id}: Finished pipeline exit");
3264 }
3265
3266 fn handle_exit_script_thread_msg(&self, cx: &mut js::context::JSContext) {
3268 debug!("Exiting script thread.");
3269
3270 let mut webview_and_pipeline_ids = Vec::new();
3271 webview_and_pipeline_ids.extend(
3272 self.incomplete_loads
3273 .borrow()
3274 .iter()
3275 .next()
3276 .map(|load| (load.webview_id, load.pipeline_id)),
3277 );
3278 webview_and_pipeline_ids.extend(
3279 self.documents
3280 .borrow()
3281 .iter()
3282 .next()
3283 .map(|(pipeline_id, document)| (document.webview_id(), pipeline_id)),
3284 );
3285
3286 for (webview_id, pipeline_id) in webview_and_pipeline_ids {
3287 self.handle_exit_pipeline_msg(webview_id, pipeline_id, DiscardBrowsingContext::Yes, cx);
3288 }
3289
3290 self.background_hang_monitor.unregister();
3291
3292 if opts::get().multiprocess {
3294 debug!("Exiting IPC router thread in script thread.");
3295 ROUTER.shutdown();
3296 }
3297
3298 debug!("Exited script thread.");
3299 }
3300
3301 pub(crate) fn handle_tick_all_animations_for_testing(id: PipelineId) {
3303 with_script_thread(|script_thread| {
3304 let Some(document) = script_thread.documents.borrow().find_document(id) else {
3305 warn!("Animation tick for tests for closed pipeline {id}.");
3306 return;
3307 };
3308 document.maybe_mark_animating_nodes_as_dirty();
3309 });
3310 }
3311
3312 fn handle_web_font_loaded(&self, pipeline_id: PipelineId) {
3314 let Some(document) = self.documents.borrow().find_document(pipeline_id) else {
3315 warn!("Web font loaded in closed pipeline {}.", pipeline_id);
3316 return;
3317 };
3318
3319 document.dirty_all_nodes();
3321 }
3322
3323 fn handle_worklet_loaded(&self, pipeline_id: PipelineId) {
3326 if let Some(document) = self.documents.borrow().find_document(pipeline_id) {
3327 document.add_restyle_reason(RestyleReason::PaintWorkletLoaded);
3328 }
3329 }
3330
3331 #[allow(clippy::too_many_arguments)]
3333 fn handle_storage_event(
3334 &self,
3335 pipeline_id: PipelineId,
3336 storage_type: WebStorageType,
3337 url: ServoUrl,
3338 key: Option<String>,
3339 old_value: Option<String>,
3340 new_value: Option<String>,
3341 cx: &mut js::context::JSContext,
3342 ) {
3343 let Some(window) = self.documents.borrow().find_window(pipeline_id) else {
3344 return warn!("Storage event sent to closed pipeline {pipeline_id}.");
3345 };
3346
3347 let storage = match storage_type {
3348 WebStorageType::Local => window.GetLocalStorage(cx),
3349 WebStorageType::Session => window.GetSessionStorage(cx),
3350 };
3351 let Ok(storage) = storage else {
3352 return;
3353 };
3354
3355 storage.queue_storage_event(url, key, old_value, new_value);
3356 }
3357
3358 fn handle_iframe_load_event(
3360 &self,
3361 parent_id: PipelineId,
3362 browsing_context_id: BrowsingContextId,
3363 child_id: PipelineId,
3364 cx: &mut js::context::JSContext,
3365 ) {
3366 let iframe = self
3367 .documents
3368 .borrow()
3369 .find_iframe(parent_id, browsing_context_id);
3370 match iframe {
3371 Some(iframe) => iframe.iframe_load_event_steps(child_id, cx),
3372 None => warn!("Message sent to closed pipeline {}.", parent_id),
3373 }
3374 }
3375
3376 fn ask_constellation_for_top_level_info(
3377 &self,
3378 sender_webview_id: WebViewId,
3379 sender_pipeline_id: PipelineId,
3380 browsing_context_id: BrowsingContextId,
3381 ) -> Option<WebViewId> {
3382 let (result_sender, result_receiver) = generic_channel::channel().unwrap();
3383 let msg = ScriptToConstellationMessage::GetTopForBrowsingContext(
3384 browsing_context_id,
3385 result_sender,
3386 );
3387 self.senders
3388 .pipeline_to_constellation_sender
3389 .send((sender_webview_id, sender_pipeline_id, msg))
3390 .expect("Failed to send to constellation.");
3391 result_receiver
3392 .recv()
3393 .expect("Failed to get top-level id from constellation.")
3394 }
3395
3396 fn load(
3399 &self,
3400 metadata: &Metadata,
3401 incomplete: InProgressLoad,
3402 origin: MutableOrigin,
3403 cx: &mut js::context::JSContext,
3404 ) -> DomRoot<ServoParser> {
3405 let script_to_constellation_chan = ScriptToConstellationChan {
3406 sender: self.senders.pipeline_to_constellation_sender.clone(),
3407 webview_id: incomplete.webview_id,
3408 pipeline_id: incomplete.pipeline_id,
3409 };
3410
3411 let final_url = metadata.final_url.clone();
3412 let _ = script_to_constellation_chan
3413 .send(ScriptToConstellationMessage::SetFinalUrl(final_url.clone()));
3414
3415 debug!(
3416 "ScriptThread: loading {} on pipeline {:?}",
3417 incomplete.load_data.url, incomplete.pipeline_id
3418 );
3419
3420 let font_context = Arc::new(FontContext::new(
3421 self.system_font_service.clone(),
3422 self.paint_api.clone(),
3423 self.resource_threads.clone(),
3424 ));
3425
3426 let image_cache = self.image_cache_factory.create(
3427 incomplete.webview_id,
3428 incomplete.pipeline_id,
3429 &self.paint_api,
3430 );
3431
3432 let (user_contents, user_stylesheets) = incomplete
3433 .user_content_manager_id
3434 .and_then(|user_content_manager_id| {
3435 self.user_contents_for_manager_id
3436 .borrow()
3437 .get(&user_content_manager_id)
3438 .map(|script_thread_user_contents| {
3439 (
3440 script_thread_user_contents.user_scripts.clone(),
3441 script_thread_user_contents.user_stylesheets.clone(),
3442 )
3443 })
3444 })
3445 .unwrap_or_default();
3446
3447 let layout_config = LayoutConfig {
3448 id: incomplete.pipeline_id,
3449 webview_id: incomplete.webview_id,
3450 url: final_url.clone(),
3451 is_iframe: incomplete.parent_info.is_some(),
3452 script_chan: self.senders.constellation_sender.clone(),
3453 image_cache: image_cache.clone(),
3454 font_context: font_context.clone(),
3455 time_profiler_chan: self.senders.time_profiler_sender.clone(),
3456 paint_api: self.paint_api.clone(),
3457 viewport_details: incomplete.viewport_details,
3458 user_stylesheets,
3459 theme: incomplete.theme,
3460 embedder_chan: self.senders.pipeline_to_embedder_sender.clone(),
3461 };
3462
3463 let window = Window::new(
3465 cx,
3466 incomplete.webview_id,
3467 self.js_runtime.clone(),
3468 self.senders.self_sender.clone(),
3469 self.layout_factory.create(layout_config),
3470 font_context,
3471 self.senders.image_cache_sender.clone(),
3472 image_cache.clone(),
3473 self.resource_threads.clone(),
3474 self.storage_threads.clone(),
3475 #[cfg(feature = "bluetooth")]
3476 self.senders.bluetooth_sender.clone(),
3477 self.senders.memory_profiler_sender.clone(),
3478 self.senders.time_profiler_sender.clone(),
3479 self.senders.devtools_server_sender.clone(),
3480 script_to_constellation_chan,
3481 self.senders.pipeline_to_embedder_sender.clone(),
3482 self.senders.constellation_sender.clone(),
3483 incomplete.pipeline_id,
3484 incomplete.parent_info,
3485 incomplete.viewport_details,
3486 origin.clone(),
3487 final_url.clone(),
3488 final_url.clone(),
3493 incomplete.navigation_start,
3494 self.webgl_chan.as_ref().map(|chan| chan.channel()),
3495 #[cfg(feature = "webxr")]
3496 self.webxr_registry.clone(),
3497 self.paint_api.clone(),
3498 self.unminify_js,
3499 self.unminify_css,
3500 self.local_script_source.clone(),
3501 user_contents,
3502 self.player_context.clone(),
3503 #[cfg(feature = "webgpu")]
3504 self.gpu_id_hub.clone(),
3505 incomplete.load_data.inherited_secure_context,
3506 incomplete.theme,
3507 self.this.clone(),
3508 );
3509 if self.senders.devtools_server_sender.is_some() {
3510 self.debugger_global.fire_add_debuggee(
3511 cx,
3512 window.upcast(),
3513 incomplete.pipeline_id,
3514 None,
3515 );
3516 }
3517
3518 let mut realm = enter_auto_realm(cx, &*window);
3519 let cx = &mut realm;
3520
3521 let window_proxy = self.window_proxies.local_window_proxy(
3523 cx,
3524 &self.senders,
3525 &self.documents,
3526 &window,
3527 incomplete.browsing_context_id,
3528 incomplete.webview_id,
3529 incomplete.parent_info,
3530 incomplete.opener,
3531 );
3532 if window_proxy.parent().is_some() {
3533 window_proxy.stop_delaying_load_events_mode();
3538 }
3539 window.init_window_proxy(&window_proxy);
3540
3541 let last_modified = metadata.headers.as_ref().and_then(|headers| {
3549 headers.typed_get::<LastModified>().map(|tm| {
3550 let tm: SystemTime = tm.into();
3551 let local_time: DateTime<Local> = tm.into();
3552 local_time.format("%m/%d/%Y %H:%M:%S").to_string()
3553 })
3554 });
3555
3556 let loader = DocumentLoader::new_with_threads(
3557 self.resource_threads.clone(),
3558 Some(final_url.clone()),
3559 );
3560
3561 let content_type: Option<Mime> = metadata
3562 .content_type
3563 .clone()
3564 .map(Serde::into_inner)
3565 .map(Mime::from_ct);
3566 let encoding_hint_from_content_type = content_type
3567 .as_ref()
3568 .and_then(|mime| mime.get_parameter(CHARSET))
3569 .and_then(|charset| Encoding::for_label(charset.as_bytes()));
3570
3571 let is_html_document = match content_type {
3572 Some(ref mime) if mime.type_ == APPLICATION && mime.has_suffix("xml") => {
3573 IsHTMLDocument::NonHTMLDocument
3574 },
3575
3576 Some(ref mime) if mime.matches(TEXT, XML) || mime.matches(APPLICATION, XML) => {
3577 IsHTMLDocument::NonHTMLDocument
3578 },
3579 _ => IsHTMLDocument::HTMLDocument,
3580 };
3581
3582 let referrer = metadata
3583 .referrer
3584 .as_ref()
3585 .map(|referrer| referrer.clone().into_string());
3586
3587 let is_initial_about_blank = final_url.as_str() == "about:blank";
3588
3589 let document = Document::new(
3590 &window,
3591 HasBrowsingContext::Yes,
3592 Some(final_url.clone()),
3593 incomplete.load_data.about_base_url,
3594 origin,
3595 is_html_document,
3596 content_type,
3597 last_modified,
3598 incomplete.activity,
3599 DocumentSource::FromParser,
3600 loader,
3601 referrer,
3602 Some(metadata.status.raw_code()),
3603 incomplete.canceller,
3604 is_initial_about_blank,
3605 true,
3606 incomplete.load_data.inherited_insecure_requests_policy,
3607 incomplete.load_data.has_trustworthy_ancestor_origin,
3608 self.custom_element_reaction_stack.clone(),
3609 incomplete.load_data.creation_sandboxing_flag_set,
3610 CanGc::from_cx(cx),
3611 );
3612
3613 let referrer_policy = metadata
3614 .headers
3615 .as_deref()
3616 .and_then(|h| h.typed_get::<ReferrerPolicyHeader>())
3617 .into();
3618 document.set_referrer_policy(referrer_policy);
3619
3620 let refresh_header = metadata.headers.as_deref().and_then(|h| h.get(REFRESH));
3621 if let Some(refresh_val) = refresh_header {
3622 document.shared_declarative_refresh_steps(
3624 refresh_val.as_bytes(),
3625 false,
3626 );
3627 }
3628
3629 document.set_ready_state(cx, DocumentReadyState::Loading);
3630
3631 self.documents
3632 .borrow_mut()
3633 .insert(incomplete.pipeline_id, &document);
3634
3635 window.init_document(&document);
3636
3637 if let Some(frame) = window_proxy
3640 .frame_element()
3641 .and_then(|e| e.downcast::<HTMLIFrameElement>())
3642 {
3643 let parent_pipeline = frame.global().pipeline_id();
3644 self.handle_update_pipeline_id(
3645 parent_pipeline,
3646 window_proxy.browsing_context_id(),
3647 window_proxy.webview_id(),
3648 incomplete.pipeline_id,
3649 UpdatePipelineIdReason::Navigation,
3650 cx,
3651 );
3652 }
3653
3654 self.senders
3655 .pipeline_to_constellation_sender
3656 .send((
3657 incomplete.webview_id,
3658 incomplete.pipeline_id,
3659 ScriptToConstellationMessage::ActivateDocument,
3660 ))
3661 .unwrap();
3662
3663 let incomplete_browsing_context_id: BrowsingContextId = incomplete.webview_id.into();
3665 let is_top_level_global = incomplete_browsing_context_id == incomplete.browsing_context_id;
3666 self.notify_devtools(
3667 document.Title(),
3668 final_url.clone(),
3669 is_top_level_global,
3670 (
3671 incomplete.browsing_context_id,
3672 incomplete.pipeline_id,
3673 None,
3674 incomplete.webview_id,
3675 ),
3676 );
3677
3678 document.set_navigation_start(incomplete.navigation_start);
3679
3680 if is_html_document == IsHTMLDocument::NonHTMLDocument {
3681 ServoParser::parse_xml_document(
3682 cx,
3683 &document,
3684 None,
3685 final_url,
3686 encoding_hint_from_content_type,
3687 );
3688 } else {
3689 ServoParser::parse_html_document(
3690 cx,
3691 &document,
3692 None,
3693 final_url,
3694 encoding_hint_from_content_type,
3695 incomplete.load_data.container_document_encoding,
3696 );
3697 }
3698
3699 if incomplete.activity == DocumentActivity::FullyActive {
3700 window.resume(CanGc::from_cx(cx));
3701 } else {
3702 window.suspend(cx);
3703 }
3704
3705 if incomplete.throttled {
3706 window.set_throttled(true);
3707 }
3708
3709 document.get_current_parser().unwrap()
3710 }
3711
3712 fn notify_devtools(
3713 &self,
3714 title: DOMString,
3715 url: ServoUrl,
3716 is_top_level_global: bool,
3717 (browsing_context_id, pipeline_id, worker_id, webview_id): (
3718 BrowsingContextId,
3719 PipelineId,
3720 Option<WorkerId>,
3721 WebViewId,
3722 ),
3723 ) {
3724 if let Some(ref chan) = self.senders.devtools_server_sender {
3725 let page_info = DevtoolsPageInfo {
3726 title: String::from(title),
3727 url,
3728 is_top_level_global,
3729 is_service_worker: false,
3730 };
3731 chan.send(ScriptToDevtoolsControlMsg::NewGlobal(
3732 (browsing_context_id, pipeline_id, worker_id, webview_id),
3733 self.senders.devtools_client_to_script_thread_sender.clone(),
3734 page_info.clone(),
3735 ))
3736 .unwrap();
3737
3738 let state = NavigationState::Stop(pipeline_id, page_info);
3739 let _ = chan.send(ScriptToDevtoolsControlMsg::Navigate(
3740 browsing_context_id,
3741 state,
3742 ));
3743 }
3744 }
3745
3746 fn handle_input_event(
3748 &self,
3749 webview_id: WebViewId,
3750 pipeline_id: PipelineId,
3751 event: ConstellationInputEvent,
3752 ) {
3753 let Some(document) = self.documents.borrow().find_document(pipeline_id) else {
3754 warn!("Input event sent to closed pipeline {pipeline_id}.");
3755 let _ = self
3756 .senders
3757 .pipeline_to_embedder_sender
3758 .send(EmbedderMsg::InputEventsHandled(
3759 webview_id,
3760 vec![InputEventOutcome {
3761 id: event.event.id,
3762 result: Default::default(),
3763 }],
3764 ));
3765 return;
3766 };
3767 document.event_handler().note_pending_input_event(event);
3768 }
3769
3770 fn set_accessibility_active(&self, pipeline_id: PipelineId, active: bool, epoch: Epoch) {
3772 if !(pref!(accessibility_enabled)) {
3773 return;
3774 }
3775
3776 let Some(document) = self.documents.borrow().find_document(pipeline_id) else {
3777 if active {
3778 error!("Trying to set accessibility active on stale document: {pipeline_id}");
3779 }
3780 return;
3781 };
3782
3783 document
3784 .window()
3785 .layout()
3786 .set_accessibility_active(active, epoch);
3787 }
3788
3789 fn handle_navigate_iframe(
3791 &self,
3792 parent_pipeline_id: PipelineId,
3793 browsing_context_id: BrowsingContextId,
3794 load_data: LoadData,
3795 history_handling: NavigationHistoryBehavior,
3796 target_snapshot_params: TargetSnapshotParams,
3797 cx: &mut js::context::JSContext,
3798 ) {
3799 let iframe = self
3800 .documents
3801 .borrow()
3802 .find_iframe(parent_pipeline_id, browsing_context_id);
3803 if let Some(iframe) = iframe {
3804 iframe.navigate_or_reload_child_browsing_context(
3805 load_data,
3806 history_handling,
3807 ProcessingMode::NotFirstTime,
3808 target_snapshot_params,
3809 cx,
3810 );
3811 }
3812 }
3813
3814 fn eval_js_url(
3818 cx: &mut js::context::JSContext,
3819 global_scope: &GlobalScope,
3820 url: &ServoUrl,
3821 ) -> Option<String> {
3822 let encoded = &url[Position::AfterScheme..][1..];
3825
3826 let script_source = percent_decode(encoded.as_bytes()).decode_utf8_lossy();
3828
3829 let mut realm = enter_auto_realm(cx, global_scope);
3834 let cx = &mut realm.current_realm();
3835
3836 rooted!(&in(cx) let mut jsval = UndefinedValue());
3837 let evaluation_status = global_scope.evaluate_js_on_global(
3839 cx,
3840 script_source,
3841 "",
3842 Some(IntroductionType::JAVASCRIPT_URL),
3843 Some(jsval.handle_mut()),
3844 );
3845
3846 if evaluation_status.is_err() || !jsval.get().is_string() {
3850 return None;
3851 }
3852
3853 let strval = DOMString::safe_from_jsval(cx, jsval.handle(), StringificationBehavior::Empty);
3854 match strval {
3855 Ok(ConversionResult::Success(s)) => {
3856 Some(String::from(s))
3859 },
3860 _ => unreachable!("Couldn't get a string from a JS string??"),
3861 }
3862 }
3863
3864 #[servo_tracing::instrument(skip_all)]
3867 fn pre_page_load(&self, cx: &mut js::context::JSContext, mut incomplete: InProgressLoad) {
3868 let url_str = incomplete.load_data.url.as_str();
3869 if url_str == "about:blank" || incomplete.load_data.js_eval_result.is_some() {
3870 self.start_synchronous_page_load(cx, incomplete);
3871 return;
3872 }
3873 if url_str == "about:srcdoc" {
3874 self.page_load_about_srcdoc(cx, incomplete);
3875 return;
3876 }
3877
3878 let context = ParserContext::new(
3879 incomplete.webview_id,
3880 incomplete.pipeline_id,
3881 incomplete.load_data.url.clone(),
3882 incomplete.load_data.creation_sandboxing_flag_set,
3883 incomplete.parent_info,
3884 incomplete.target_snapshot_params,
3885 incomplete.load_data.load_origin.clone(),
3886 );
3887 self.incomplete_parser_contexts
3888 .0
3889 .borrow_mut()
3890 .push((incomplete.pipeline_id, context));
3891
3892 let request_builder = incomplete.request_builder();
3893 incomplete.canceller = FetchCanceller::new(
3894 request_builder.id,
3895 false,
3896 self.resource_threads.core_thread.clone(),
3897 );
3898 NavigationListener::new(request_builder, self.senders.self_sender.clone())
3899 .initiate_fetch(&self.resource_threads.core_thread, None);
3900 self.incomplete_loads.borrow_mut().push(incomplete);
3901 }
3902
3903 fn handle_navigation_response(
3904 &self,
3905 cx: &mut js::context::JSContext,
3906 pipeline_id: PipelineId,
3907 message: FetchResponseMsg,
3908 ) {
3909 if let Some(metadata) = NavigationListener::http_redirect_metadata(&message) {
3910 self.handle_navigation_redirect(pipeline_id, metadata);
3911 return;
3912 };
3913
3914 match message {
3915 FetchResponseMsg::ProcessResponse(request_id, metadata) => {
3916 self.handle_fetch_metadata(cx, pipeline_id, request_id, metadata)
3917 },
3918 FetchResponseMsg::ProcessResponseChunk(request_id, chunk) => {
3919 self.handle_fetch_chunk(cx, pipeline_id, request_id, chunk.0)
3920 },
3921 FetchResponseMsg::ProcessResponseEOF(request_id, eof, timing) => {
3922 self.handle_fetch_eof(cx, pipeline_id, request_id, eof, timing)
3923 },
3924 FetchResponseMsg::ProcessCspViolations(request_id, violations) => {
3925 self.handle_csp_violations(pipeline_id, request_id, violations)
3926 },
3927 FetchResponseMsg::ProcessRequestBody(..) => {},
3928 }
3929 }
3930
3931 fn handle_fetch_metadata(
3932 &self,
3933 cx: &mut js::context::JSContext,
3934 id: PipelineId,
3935 request_id: RequestId,
3936 fetch_metadata: Result<FetchMetadata, NetworkError>,
3937 ) {
3938 match fetch_metadata {
3939 Ok(_) => (),
3940 Err(NetworkError::Crash(..)) => (),
3941 Err(ref e) => {
3942 warn!("Network error: {:?}", e);
3943 },
3944 };
3945
3946 let mut incomplete_parser_contexts = self.incomplete_parser_contexts.0.borrow_mut();
3947 let parser = incomplete_parser_contexts
3948 .iter_mut()
3949 .find(|&&mut (pipeline_id, _)| pipeline_id == id);
3950 if let Some(&mut (_, ref mut ctxt)) = parser {
3951 ctxt.process_response(cx, request_id, fetch_metadata);
3952 }
3953 }
3954
3955 fn handle_fetch_chunk(
3956 &self,
3957 cx: &mut js::context::JSContext,
3958 pipeline_id: PipelineId,
3959 request_id: RequestId,
3960 chunk: Vec<u8>,
3961 ) {
3962 let mut incomplete_parser_contexts = self.incomplete_parser_contexts.0.borrow_mut();
3963 let parser = incomplete_parser_contexts
3964 .iter_mut()
3965 .find(|&&mut (parser_pipeline_id, _)| parser_pipeline_id == pipeline_id);
3966 if let Some(&mut (_, ref mut ctxt)) = parser {
3967 ctxt.process_response_chunk(cx, request_id, chunk);
3968 }
3969 }
3970
3971 #[expect(clippy::redundant_clone, reason = "False positive")]
3972 fn handle_fetch_eof(
3973 &self,
3974 cx: &mut js::context::JSContext,
3975 id: PipelineId,
3976 request_id: RequestId,
3977 eof: Result<(), NetworkError>,
3978 timing: ResourceFetchTiming,
3979 ) {
3980 let idx = self
3981 .incomplete_parser_contexts
3982 .0
3983 .borrow()
3984 .iter()
3985 .position(|&(pipeline_id, _)| pipeline_id == id);
3986
3987 if let Some(idx) = idx {
3988 let (_, context) = self.incomplete_parser_contexts.0.borrow_mut().remove(idx);
3989
3990 if let Some(window_proxy) = context
3992 .get_document()
3993 .and_then(|document| document.browsing_context()) &&
3994 let Some(frame_element) = window_proxy.frame_element()
3995 {
3996 let iframe_ctx = IframeContext::new(
3997 frame_element
3998 .downcast::<HTMLIFrameElement>()
3999 .expect("WindowProxy::frame_element should be an HTMLIFrameElement"),
4000 );
4001
4002 let mut resource_timing = timing.clone();
4004 resource_timing.timing_type = ResourceTimingType::Resource;
4005 submit_timing(cx, &iframe_ctx, &eof, &resource_timing);
4006 }
4007
4008 context.process_response_eof(cx, request_id, eof, timing);
4009 }
4010 }
4011
4012 fn handle_csp_violations(
4013 &self,
4014 pipeline_id: PipelineId,
4015 _request_id: RequestId,
4016 violations: Vec<Violation>,
4017 ) {
4018 let mut incomplete_parser_contexts = self.incomplete_parser_contexts.0.borrow_mut();
4019 let parser = incomplete_parser_contexts
4020 .iter_mut()
4021 .find(|&&mut (parser_pipeline_id, _)| parser_pipeline_id == pipeline_id);
4022 let Some(&mut (_, ref mut ctxt)) = parser else {
4023 return;
4024 };
4025 let pipeline_id = ctxt.parent_info().unwrap_or(pipeline_id);
4027 if let Some(global) = self.documents.borrow().find_global(pipeline_id) {
4028 global.report_csp_violations(violations, None, None);
4029 }
4030 }
4031
4032 fn handle_navigation_redirect(&self, id: PipelineId, metadata: &Metadata) {
4033 assert!(metadata.location_url.is_some());
4037
4038 let mut incomplete_loads = self.incomplete_loads.borrow_mut();
4039 let Some(incomplete_load) = incomplete_loads
4040 .iter_mut()
4041 .find(|incomplete_load| incomplete_load.pipeline_id == id)
4042 else {
4043 return;
4044 };
4045
4046 incomplete_load.url_list.push(metadata.final_url.clone());
4049
4050 let mut request_builder = incomplete_load.request_builder();
4051 request_builder.referrer = metadata
4052 .referrer
4053 .clone()
4054 .map(Referrer::ReferrerUrl)
4055 .unwrap_or(Referrer::NoReferrer);
4056 request_builder.referrer_policy = metadata.referrer_policy;
4057 request_builder.origin = request_builder
4058 .client
4059 .as_ref()
4060 .expect("Must have a client during redirect")
4061 .origin
4062 .clone();
4063
4064 let headers = metadata
4065 .headers
4066 .as_ref()
4067 .map(|headers| headers.clone().into_inner())
4068 .unwrap_or_default();
4069
4070 let response_init = Some(ResponseInit {
4071 url: metadata.final_url.clone(),
4072 location_url: metadata.location_url.clone(),
4073 headers,
4074 referrer: metadata.referrer.clone(),
4075 status_code: metadata
4076 .status
4077 .try_code()
4078 .map(|code| code.as_u16())
4079 .unwrap_or(200),
4080 });
4081
4082 incomplete_load.canceller = FetchCanceller::new(
4083 request_builder.id,
4084 false,
4085 self.resource_threads.core_thread.clone(),
4086 );
4087 NavigationListener::new(request_builder, self.senders.self_sender.clone())
4088 .initiate_fetch(&self.resource_threads.core_thread, response_init);
4089 }
4090
4091 fn start_synchronous_page_load(
4094 &self,
4095 cx: &mut js::context::JSContext,
4096 mut incomplete: InProgressLoad,
4097 ) {
4098 let mut context = ParserContext::new(
4099 incomplete.webview_id,
4100 incomplete.pipeline_id,
4101 incomplete.load_data.url.clone(),
4102 incomplete.load_data.creation_sandboxing_flag_set,
4103 incomplete.parent_info,
4104 incomplete.target_snapshot_params,
4105 incomplete.load_data.load_origin.clone(),
4106 );
4107
4108 let mut meta = Metadata::default(incomplete.load_data.url.clone());
4109 meta.set_content_type(Some(&mime::TEXT_HTML));
4110 meta.set_referrer_policy(incomplete.load_data.referrer_policy);
4111
4112 let chunk = match incomplete.load_data.js_eval_result {
4115 Some(ref mut content) => std::mem::take(content),
4116 None => String::new(),
4117 };
4118
4119 let policy_container = incomplete.load_data.policy_container.clone();
4120 let about_base_url = incomplete.load_data.about_base_url.clone();
4121 self.incomplete_loads.borrow_mut().push(incomplete);
4122
4123 let dummy_request_id = RequestId::default();
4124 context.process_response(cx, dummy_request_id, Ok(FetchMetadata::Unfiltered(meta)));
4125 context.set_policy_container(policy_container.as_ref());
4126 context.set_about_base_url(about_base_url);
4127 context.process_response_chunk(cx, dummy_request_id, chunk.into());
4128 context.process_response_eof(
4129 cx,
4130 dummy_request_id,
4131 Ok(()),
4132 ResourceFetchTiming::new(ResourceTimingType::None),
4133 );
4134 }
4135
4136 fn page_load_about_srcdoc(
4138 &self,
4139 cx: &mut js::context::JSContext,
4140 mut incomplete: InProgressLoad,
4141 ) {
4142 let url = ServoUrl::parse("about:srcdoc").unwrap();
4143 let mut meta = Metadata::default(url.clone());
4144 meta.set_content_type(Some(&mime::TEXT_HTML));
4145 meta.set_referrer_policy(incomplete.load_data.referrer_policy);
4146
4147 let srcdoc = std::mem::take(&mut incomplete.load_data.srcdoc);
4148 let chunk = srcdoc.into_bytes();
4149
4150 let policy_container = incomplete.load_data.policy_container.clone();
4151 let creation_sandboxing_flag_set = incomplete.load_data.creation_sandboxing_flag_set;
4152
4153 let webview_id = incomplete.webview_id;
4154 let pipeline_id = incomplete.pipeline_id;
4155 let parent_info = incomplete.parent_info;
4156 let about_base_url = incomplete.load_data.about_base_url.clone();
4157 let target_snapshot_params = incomplete.target_snapshot_params;
4158 let load_origin = incomplete.load_data.load_origin.clone();
4159 self.incomplete_loads.borrow_mut().push(incomplete);
4160
4161 let mut context = ParserContext::new(
4162 webview_id,
4163 pipeline_id,
4164 url,
4165 creation_sandboxing_flag_set,
4166 parent_info,
4167 target_snapshot_params,
4168 load_origin,
4169 );
4170 let dummy_request_id = RequestId::default();
4171
4172 context.process_response(cx, dummy_request_id, Ok(FetchMetadata::Unfiltered(meta)));
4173 context.set_policy_container(policy_container.as_ref());
4174 context.set_about_base_url(about_base_url);
4175 context.process_response_chunk(cx, dummy_request_id, chunk);
4176 context.process_response_eof(
4177 cx,
4178 dummy_request_id,
4179 Ok(()),
4180 ResourceFetchTiming::new(ResourceTimingType::None),
4181 );
4182 }
4183
4184 fn handle_css_error_reporting(
4185 &self,
4186 pipeline_id: PipelineId,
4187 filename: String,
4188 line: u32,
4189 column: u32,
4190 msg: String,
4191 ) {
4192 let Some(ref sender) = self.senders.devtools_server_sender else {
4193 return;
4194 };
4195
4196 if let Some(window) = self.documents.borrow().find_window(pipeline_id) &&
4197 window.live_devtools_updates()
4198 {
4199 let css_error = CSSError {
4200 filename,
4201 line,
4202 column,
4203 msg,
4204 };
4205 let message = ScriptToDevtoolsControlMsg::ReportCSSError(pipeline_id, css_error);
4206 sender.send(message).unwrap();
4207 }
4208 }
4209
4210 fn handle_navigate_to(&self, pipeline_id: PipelineId, url: ServoUrl) {
4211 if let Some(document) = self.documents.borrow().find_document(pipeline_id) {
4214 self.senders
4215 .pipeline_to_constellation_sender
4216 .send((
4217 document.webview_id(),
4218 pipeline_id,
4219 ScriptToConstellationMessage::LoadUrl(
4220 LoadData::new_for_new_unrelated_webview(url),
4221 NavigationHistoryBehavior::Push,
4222 TargetSnapshotParams::default(),
4223 ),
4224 ))
4225 .unwrap();
4226 }
4227 }
4228
4229 fn handle_traverse_history(&self, pipeline_id: PipelineId, direction: TraversalDirection) {
4230 if let Some(document) = self.documents.borrow().find_document(pipeline_id) {
4233 self.senders
4234 .pipeline_to_constellation_sender
4235 .send((
4236 document.webview_id(),
4237 pipeline_id,
4238 ScriptToConstellationMessage::TraverseHistory(direction),
4239 ))
4240 .unwrap();
4241 }
4242 }
4243
4244 fn handle_reload(&self, pipeline_id: PipelineId, cx: &mut js::context::JSContext) {
4245 let window = self.documents.borrow().find_window(pipeline_id);
4246 if let Some(window) = window {
4247 window.Location(cx).reload_without_origin_check(cx);
4248 }
4249 }
4250
4251 fn handle_paint_metric(
4252 &self,
4253 pipeline_id: PipelineId,
4254 metric_type: ProgressiveWebMetricType,
4255 metric_value: CrossProcessInstant,
4256 first_reflow: bool,
4257 can_gc: CanGc,
4258 ) {
4259 match self.documents.borrow().find_document(pipeline_id) {
4260 Some(document) => {
4261 document.handle_paint_metric(metric_type, metric_value, first_reflow, can_gc)
4262 },
4263 None => warn!(
4264 "Received paint metric ({metric_type:?}) for unknown document: {pipeline_id:?}"
4265 ),
4266 }
4267 }
4268
4269 fn handle_media_session_action(
4270 &self,
4271 cx: &mut js::context::JSContext,
4272 pipeline_id: PipelineId,
4273 action: MediaSessionActionType,
4274 ) {
4275 if let Some(window) = self.documents.borrow().find_window(pipeline_id) {
4276 let media_session = window.Navigator().MediaSession();
4277 media_session.handle_action(cx, action);
4278 } else {
4279 warn!("No MediaSession for this pipeline ID");
4280 };
4281 }
4282
4283 pub(crate) fn enqueue_microtask(job: Microtask) {
4284 with_script_thread(|script_thread| {
4285 script_thread
4286 .microtask_queue
4287 .enqueue(job, script_thread.get_cx());
4288 });
4289 }
4290
4291 pub(crate) fn perform_a_microtask_checkpoint(&self, cx: &mut js::context::JSContext) {
4292 if self.can_continue_running_inner() {
4294 let globals = self
4295 .documents
4296 .borrow()
4297 .iter()
4298 .map(|(_id, document)| DomRoot::from_ref(document.window().upcast()))
4299 .collect();
4300
4301 self.microtask_queue.checkpoint(
4302 cx,
4303 |id| self.documents.borrow().find_global(id),
4304 globals,
4305 )
4306 }
4307 }
4308
4309 fn handle_evaluate_javascript(
4310 &self,
4311 webview_id: WebViewId,
4312 pipeline_id: PipelineId,
4313 evaluation_id: JavaScriptEvaluationId,
4314 script: String,
4315 cx: &mut js::context::JSContext,
4316 ) {
4317 let Some(window) = self.documents.borrow().find_window(pipeline_id) else {
4318 let _ = self.senders.pipeline_to_constellation_sender.send((
4319 webview_id,
4320 pipeline_id,
4321 ScriptToConstellationMessage::FinishJavaScriptEvaluation(
4322 evaluation_id,
4323 Err(JavaScriptEvaluationError::WebViewNotReady),
4324 ),
4325 ));
4326 return;
4327 };
4328
4329 let global_scope = window.as_global_scope();
4330 let mut realm = enter_auto_realm(cx, global_scope);
4331 let cx = &mut realm.current_realm();
4332
4333 rooted!(&in(cx) let mut return_value = UndefinedValue());
4334 if let Err(err) = global_scope.evaluate_js_on_global(
4335 cx,
4336 script.into(),
4337 "",
4338 None, Some(return_value.handle_mut()),
4340 ) {
4341 _ = self.senders.pipeline_to_constellation_sender.send((
4342 webview_id,
4343 pipeline_id,
4344 ScriptToConstellationMessage::FinishJavaScriptEvaluation(evaluation_id, Err(err)),
4345 ));
4346 return;
4347 };
4348
4349 let result = jsval_to_webdriver(cx, global_scope, return_value.handle());
4350 let _ = self.senders.pipeline_to_constellation_sender.send((
4351 webview_id,
4352 pipeline_id,
4353 ScriptToConstellationMessage::FinishJavaScriptEvaluation(evaluation_id, result),
4354 ));
4355 }
4356
4357 fn handle_refresh_cursor(&self, pipeline_id: PipelineId) {
4358 let Some(document) = self.documents.borrow().find_document(pipeline_id) else {
4359 return;
4360 };
4361 document.event_handler().handle_refresh_cursor();
4362 }
4363
4364 pub(crate) fn is_servo_privileged(url: ServoUrl) -> bool {
4365 with_script_thread(|script_thread| script_thread.privileged_urls.contains(&url))
4366 }
4367
4368 fn handle_request_screenshot_readiness(
4369 &self,
4370 webview_id: WebViewId,
4371 pipeline_id: PipelineId,
4372 cx: &mut js::context::JSContext,
4373 ) {
4374 let Some(window) = self.documents.borrow().find_window(pipeline_id) else {
4375 let _ = self.senders.pipeline_to_constellation_sender.send((
4376 webview_id,
4377 pipeline_id,
4378 ScriptToConstellationMessage::RespondToScreenshotReadinessRequest(
4379 ScreenshotReadinessResponse::NoLongerActive,
4380 ),
4381 ));
4382 return;
4383 };
4384 window.request_screenshot_readiness(cx);
4385 }
4386
4387 fn handle_embedder_control_response(
4388 &self,
4389 id: EmbedderControlId,
4390 response: EmbedderControlResponse,
4391 cx: &mut js::context::JSContext,
4392 ) {
4393 let Some(document) = self.documents.borrow().find_document(id.pipeline_id) else {
4394 return;
4395 };
4396 document
4397 .embedder_controls()
4398 .handle_embedder_control_response(cx, id, response);
4399 }
4400
4401 pub(crate) fn handle_update_pinch_zoom_infos(
4402 &self,
4403 pipeline_id: PipelineId,
4404 pinch_zoom_infos: PinchZoomInfos,
4405 can_gc: CanGc,
4406 ) {
4407 let Some(window) = self.documents.borrow().find_window(pipeline_id) else {
4408 warn!("Visual viewport update for closed pipeline {pipeline_id}.");
4409 return;
4410 };
4411
4412 window.maybe_update_visual_viewport(pinch_zoom_infos, can_gc);
4413 }
4414
4415 pub(crate) fn devtools_want_updates_for_node(pipeline: PipelineId, node: &Node) -> bool {
4416 with_script_thread(|script_thread| {
4417 script_thread
4418 .devtools_state
4419 .wants_updates_for_node(pipeline, node)
4420 })
4421 }
4422}
4423
4424impl Drop for ScriptThread {
4425 fn drop(&mut self) {
4426 SCRIPT_THREAD_ROOT.with(|root| {
4427 root.set(None);
4428 });
4429 }
4430}