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