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