1use std::cell::{Cell, RefCell};
21use std::collections::HashSet;
22use std::default::Default;
23use std::option::Option;
24use std::rc::Rc;
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, HangAnnotation, MonitoredComponentId,
33 MonitoredComponentType,
34};
35use base::cross_process_instant::CrossProcessInstant;
36use base::id::{BrowsingContextId, HistoryStateId, PipelineId, PipelineNamespace, WebViewId};
37use canvas_traits::webgl::WebGLPipeline;
38use chrono::{DateTime, Local};
39use compositing_traits::{CrossProcessCompositorApi, PipelineExitSource};
40use constellation_traits::{
41 JsEvalResult, LoadData, LoadOrigin, NavigationHistoryBehavior, ScriptToConstellationChan,
42 ScriptToConstellationMessage, StructuredSerializedData, WindowSizeType,
43};
44use crossbeam_channel::unbounded;
45use data_url::mime::Mime;
46use devtools_traits::{
47 CSSError, DevtoolScriptControlMsg, DevtoolsPageInfo, NavigationState,
48 ScriptToDevtoolsControlMsg, WorkerId,
49};
50use embedder_traits::user_content_manager::UserContentManager;
51use embedder_traits::{
52 FocusSequenceNumber, InputEvent, JavaScriptEvaluationError, JavaScriptEvaluationId,
53 MediaSessionActionType, MouseButton, MouseButtonAction, MouseButtonEvent, Theme,
54 ViewportDetails, WebDriverScriptCommand,
55};
56use euclid::Point2D;
57use euclid::default::Rect;
58use fonts::{FontContext, SystemFontServiceProxy};
59use headers::{HeaderMapExt, LastModified, ReferrerPolicy as ReferrerPolicyHeader};
60use http::header::REFRESH;
61use hyper_serde::Serde;
62use ipc_channel::ipc;
63use ipc_channel::router::ROUTER;
64use js::glue::GetWindowProxyClass;
65use js::jsapi::{
66 JS_AddInterruptCallback, JSContext as UnsafeJSContext, JSTracer, SetWindowProxyClass,
67};
68use js::jsval::UndefinedValue;
69use js::rust::ParentRuntime;
70use layout_api::{LayoutConfig, LayoutFactory, RestyleReason, ScriptThreadFactory};
71use media::WindowGLContext;
72use metrics::MAX_TASK_NS;
73use net_traits::image_cache::{ImageCache, ImageCacheResponseMessage};
74use net_traits::request::{Referrer, RequestId};
75use net_traits::response::ResponseInit;
76use net_traits::storage_thread::StorageType;
77use net_traits::{
78 FetchMetadata, FetchResponseListener, FetchResponseMsg, Metadata, NetworkError,
79 ResourceFetchTiming, ResourceThreads, ResourceTimingType,
80};
81use percent_encoding::percent_decode;
82use profile_traits::mem::{ProcessReports, ReportsChan, perform_memory_report};
83use profile_traits::time::ProfilerCategory;
84use profile_traits::time_profile;
85use rustc_hash::{FxBuildHasher, FxHashMap, FxHashSet};
86use script_traits::{
87 ConstellationInputEvent, DiscardBrowsingContext, DocumentActivity, InitialScriptState,
88 NewLayoutInfo, Painter, ProgressiveWebMetricType, ScriptThreadMessage, UpdatePipelineIdReason,
89};
90use servo_config::{opts, prefs};
91use servo_url::{ImmutableOrigin, MutableOrigin, ServoUrl};
92use style::thread_state::{self, ThreadState};
93use stylo_atoms::Atom;
94use timers::{TimerEventRequest, TimerId, TimerScheduler};
95use url::Position;
96#[cfg(feature = "webgpu")]
97use webgpu_traits::{WebGPUDevice, WebGPUMsg};
98use webrender_api::ExternalScrollId;
99use webrender_api::units::{DevicePixel, LayoutVector2D};
100
101use crate::document_collection::DocumentCollection;
102use crate::document_loader::DocumentLoader;
103use crate::dom::bindings::cell::DomRefCell;
104use crate::dom::bindings::codegen::Bindings::DocumentBinding::{
105 DocumentMethods, DocumentReadyState,
106};
107use crate::dom::bindings::codegen::Bindings::NavigatorBinding::NavigatorMethods;
108use crate::dom::bindings::codegen::Bindings::WindowBinding::WindowMethods;
109use crate::dom::bindings::conversions::{
110 ConversionResult, SafeFromJSValConvertible, StringificationBehavior,
111};
112use crate::dom::bindings::inheritance::Castable;
113use crate::dom::bindings::refcounted::Trusted;
114use crate::dom::bindings::reflector::DomGlobal;
115use crate::dom::bindings::root::{Dom, DomRoot};
116use crate::dom::bindings::settings_stack::AutoEntryScript;
117use crate::dom::bindings::str::DOMString;
118use crate::dom::bindings::trace::{HashMapTracedValues, JSTraceable};
119use crate::dom::csp::{CspReporting, GlobalCspReporting, Violation};
120use crate::dom::customelementregistry::{
121 CallbackReaction, CustomElementDefinition, CustomElementReactionStack,
122};
123use crate::dom::document::{
124 Document, DocumentSource, FocusInitiator, HasBrowsingContext, IsHTMLDocument,
125};
126use crate::dom::element::Element;
127use crate::dom::globalscope::GlobalScope;
128use crate::dom::html::htmliframeelement::HTMLIFrameElement;
129use crate::dom::node::NodeTraits;
130use crate::dom::servoparser::{ParserContext, ServoParser};
131use crate::dom::types::DebuggerGlobalScope;
132#[cfg(feature = "webgpu")]
133use crate::dom::webgpu::identityhub::IdentityHub;
134use crate::dom::window::Window;
135use crate::dom::windowproxy::{CreatorBrowsingContextInfo, WindowProxy};
136use crate::dom::worklet::WorkletThreadPool;
137use crate::dom::workletglobalscope::WorkletGlobalScopeInit;
138use crate::fetch::FetchCanceller;
139use crate::messaging::{
140 CommonScriptMsg, MainThreadScriptMsg, MixedMessage, ScriptEventLoopSender,
141 ScriptThreadReceivers, ScriptThreadSenders,
142};
143use crate::microtask::{Microtask, MicrotaskQueue};
144use crate::mime::{APPLICATION, MimeExt, TEXT, XML};
145use crate::navigation::{InProgressLoad, NavigationListener};
146use crate::realms::enter_realm;
147use crate::script_module::ScriptFetchOptions;
148use crate::script_mutation_observers::ScriptMutationObservers;
149use crate::script_runtime::{
150 CanGc, IntroductionType, JSContext, JSContextHelper, Runtime, ScriptThreadEventCategory,
151 ThreadSafeJSContext,
152};
153use crate::task_queue::TaskQueue;
154use crate::task_source::{SendableTaskSource, TaskSourceName};
155use crate::webdriver_handlers::jsval_to_webdriver;
156use crate::{devtools, webdriver_handlers};
157
158thread_local!(static SCRIPT_THREAD_ROOT: Cell<Option<*const ScriptThread>> = const { Cell::new(None) });
159
160fn with_optional_script_thread<R>(f: impl FnOnce(Option<&ScriptThread>) -> R) -> R {
161 SCRIPT_THREAD_ROOT.with(|root| {
162 f(root
163 .get()
164 .and_then(|script_thread| unsafe { script_thread.as_ref() }))
165 })
166}
167
168pub(crate) fn with_script_thread<R: Default>(f: impl FnOnce(&ScriptThread) -> R) -> R {
169 with_optional_script_thread(|script_thread| script_thread.map(f).unwrap_or_default())
170}
171
172pub(crate) unsafe fn trace_thread(tr: *mut JSTracer) {
178 with_script_thread(|script_thread| {
179 trace!("tracing fields of ScriptThread");
180 unsafe { script_thread.trace(tr) };
181 })
182}
183
184pub(crate) struct IncompleteParserContexts(RefCell<Vec<(PipelineId, ParserContext)>>);
190
191unsafe_no_jsmanaged_fields!(TaskQueue<MainThreadScriptMsg>);
192
193type NodeIdSet = HashSet<String>;
194
195#[derive(Default)]
197pub(crate) struct ScriptUserInteractingGuard {
198 was_interacting: bool,
199 user_interaction_cell: Rc<Cell<bool>>,
200}
201
202impl ScriptUserInteractingGuard {
203 fn new(user_interaction_cell: Rc<Cell<bool>>) -> Self {
204 let was_interacting = user_interaction_cell.get();
205 user_interaction_cell.set(true);
206 Self {
207 was_interacting,
208 user_interaction_cell,
209 }
210 }
211}
212
213impl Drop for ScriptUserInteractingGuard {
214 fn drop(&mut self) {
215 self.user_interaction_cell.set(self.was_interacting)
216 }
217}
218
219#[derive(JSTraceable)]
220#[cfg_attr(crown, allow(crown::unrooted_must_root))]
222pub struct ScriptThread {
223 last_render_opportunity_time: Cell<Option<Instant>>,
225
226 documents: DomRefCell<DocumentCollection>,
228 window_proxies:
231 DomRefCell<HashMapTracedValues<BrowsingContextId, Dom<WindowProxy>, FxBuildHasher>>,
232 incomplete_loads: DomRefCell<Vec<InProgressLoad>>,
234 incomplete_parser_contexts: IncompleteParserContexts,
236 #[no_trace]
238 image_cache: Arc<dyn ImageCache>,
239
240 receivers: ScriptThreadReceivers,
243
244 senders: ScriptThreadSenders,
247
248 #[no_trace]
251 resource_threads: ResourceThreads,
252
253 task_queue: TaskQueue<MainThreadScriptMsg>,
255
256 #[no_trace]
258 background_hang_monitor: Box<dyn BackgroundHangMonitor>,
259 closing: Arc<AtomicBool>,
261
262 #[no_trace]
265 timer_scheduler: RefCell<TimerScheduler>,
266
267 #[no_trace]
269 system_font_service: Arc<SystemFontServiceProxy>,
270
271 js_runtime: Rc<Runtime>,
273
274 #[no_trace]
276 closed_pipelines: DomRefCell<FxHashSet<PipelineId>>,
277
278 microtask_queue: Rc<MicrotaskQueue>,
280
281 mutation_observers: Rc<ScriptMutationObservers>,
282
283 #[no_trace]
285 webgl_chan: Option<WebGLPipeline>,
286
287 #[no_trace]
289 #[cfg(feature = "webxr")]
290 webxr_registry: Option<webxr_api::Registry>,
291
292 worklet_thread_pool: DomRefCell<Option<Rc<WorkletThreadPool>>>,
294
295 docs_with_no_blocking_loads: DomRefCell<HashSet<Dom<Document>>>,
298
299 custom_element_reaction_stack: Rc<CustomElementReactionStack>,
301
302 #[no_trace]
304 compositor_api: CrossProcessCompositorApi,
305
306 profile_script_events: bool,
308
309 print_pwm: bool,
311
312 unminify_js: bool,
314
315 local_script_source: Option<String>,
317
318 unminify_css: bool,
320
321 #[no_trace]
323 user_content_manager: UserContentManager,
324
325 #[no_trace]
327 player_context: WindowGLContext,
328
329 #[no_trace]
331 pipeline_to_node_ids: DomRefCell<FxHashMap<PipelineId, NodeIdSet>>,
332
333 is_user_interacting: Rc<Cell<bool>>,
335
336 #[no_trace]
338 #[cfg(feature = "webgpu")]
339 gpu_id_hub: Arc<IdentityHub>,
340
341 inherited_secure_context: Option<bool>,
343
344 #[no_trace]
346 layout_factory: Arc<dyn LayoutFactory>,
347
348 #[no_trace]
350 relative_mouse_down_point: Cell<Point2D<f32, DevicePixel>>,
351
352 #[no_trace]
356 scheduled_update_the_rendering: RefCell<Option<TimerId>>,
357
358 needs_rendering_update: Arc<AtomicBool>,
365
366 debugger_global: Dom<DebuggerGlobalScope>,
367
368 #[no_trace]
370 privileged_urls: Vec<ServoUrl>,
371}
372
373struct BHMExitSignal {
374 closing: Arc<AtomicBool>,
375 js_context: ThreadSafeJSContext,
376}
377
378impl BackgroundHangMonitorExitSignal for BHMExitSignal {
379 fn signal_to_exit(&self) {
380 self.closing.store(true, Ordering::SeqCst);
381 self.js_context.request_interrupt_callback();
382 }
383}
384
385#[allow(unsafe_code)]
386unsafe extern "C" fn interrupt_callback(_cx: *mut UnsafeJSContext) -> bool {
387 let res = ScriptThread::can_continue_running();
388 if !res {
389 ScriptThread::prepare_for_shutdown();
390 }
391 res
392}
393
394struct ScriptMemoryFailsafe<'a> {
399 owner: Option<&'a ScriptThread>,
400}
401
402impl<'a> ScriptMemoryFailsafe<'a> {
403 fn neuter(&mut self) {
404 self.owner = None;
405 }
406
407 fn new(owner: &'a ScriptThread) -> ScriptMemoryFailsafe<'a> {
408 ScriptMemoryFailsafe { owner: Some(owner) }
409 }
410}
411
412impl Drop for ScriptMemoryFailsafe<'_> {
413 #[cfg_attr(crown, allow(crown::unrooted_must_root))]
414 fn drop(&mut self) {
415 if let Some(owner) = self.owner {
416 for (_, document) in owner.documents.borrow().iter() {
417 document.window().clear_js_runtime_for_script_deallocation();
418 }
419 }
420 }
421}
422
423impl ScriptThreadFactory for ScriptThread {
424 fn create(
425 state: InitialScriptState,
426 layout_factory: Arc<dyn LayoutFactory>,
427 system_font_service: Arc<SystemFontServiceProxy>,
428 load_data: LoadData,
429 ) -> JoinHandle<()> {
430 thread::Builder::new()
431 .name(format!("Script{:?}", state.id))
432 .spawn(move || {
433 thread_state::initialize(ThreadState::SCRIPT | ThreadState::LAYOUT);
434 PipelineNamespace::install(state.pipeline_namespace_id);
435 WebViewId::install(state.webview_id);
436 let memory_profiler_sender = state.memory_profiler_sender.clone();
437
438 let in_progress_load = InProgressLoad::new(
439 state.id,
440 state.browsing_context_id,
441 state.webview_id,
442 state.parent_info,
443 state.opener,
444 state.viewport_details,
445 state.theme,
446 MutableOrigin::new(load_data.url.origin()),
447 load_data,
448 );
449 let reporter_name = format!("script-reporter-{:?}", state.id);
450 let script_thread = ScriptThread::new(state, layout_factory, system_font_service);
451
452 SCRIPT_THREAD_ROOT.with(|root| {
453 root.set(Some(&script_thread as *const _));
454 });
455
456 let mut failsafe = ScriptMemoryFailsafe::new(&script_thread);
457
458 script_thread.pre_page_load(in_progress_load);
459
460 memory_profiler_sender.run_with_memory_reporting(
461 || {
462 script_thread.start(CanGc::note());
463
464 let _ = script_thread
465 .senders
466 .content_process_shutdown_sender
467 .send(());
468 },
469 reporter_name,
470 ScriptEventLoopSender::MainThread(script_thread.senders.self_sender.clone()),
471 CommonScriptMsg::CollectReports,
472 );
473
474 failsafe.neuter();
476 })
477 .expect("Thread spawning failed")
478 }
479}
480
481impl ScriptThread {
482 pub(crate) fn runtime_handle() -> ParentRuntime {
483 with_optional_script_thread(|script_thread| {
484 script_thread.unwrap().js_runtime.prepare_for_new_child()
485 })
486 }
487
488 pub(crate) fn can_continue_running() -> bool {
489 with_script_thread(|script_thread| script_thread.can_continue_running_inner())
490 }
491
492 pub(crate) fn prepare_for_shutdown() {
493 with_script_thread(|script_thread| {
494 script_thread.prepare_for_shutdown_inner();
495 })
496 }
497
498 pub(crate) fn mutation_observers() -> Rc<ScriptMutationObservers> {
499 with_script_thread(|script_thread| script_thread.mutation_observers.clone())
500 }
501
502 pub(crate) fn microtask_queue() -> Rc<MicrotaskQueue> {
503 with_script_thread(|script_thread| script_thread.microtask_queue.clone())
504 }
505
506 pub(crate) fn mark_document_with_no_blocked_loads(doc: &Document) {
507 with_script_thread(|script_thread| {
508 script_thread
509 .docs_with_no_blocking_loads
510 .borrow_mut()
511 .insert(Dom::from_ref(doc));
512 })
513 }
514
515 pub(crate) fn page_headers_available(
516 id: &PipelineId,
517 metadata: Option<Metadata>,
518 can_gc: CanGc,
519 ) -> Option<DomRoot<ServoParser>> {
520 with_script_thread(|script_thread| {
521 script_thread.handle_page_headers_available(id, metadata, can_gc)
522 })
523 }
524
525 pub(crate) fn process_event(msg: CommonScriptMsg) -> bool {
529 with_script_thread(|script_thread| {
530 if !script_thread.can_continue_running_inner() {
531 return false;
532 }
533 script_thread.handle_msg_from_script(MainThreadScriptMsg::Common(msg));
534 true
535 })
536 }
537
538 pub(crate) fn schedule_timer(&self, request: TimerEventRequest) -> TimerId {
540 self.timer_scheduler.borrow_mut().schedule_timer(request)
541 }
542
543 pub(crate) fn cancel_timer(&self, timer_id: TimerId) {
546 self.timer_scheduler.borrow_mut().cancel_timer(timer_id)
547 }
548
549 pub(crate) fn await_stable_state(task: Microtask) {
551 with_script_thread(|script_thread| {
552 script_thread
553 .microtask_queue
554 .enqueue(task, script_thread.get_cx());
555 });
556 }
557
558 pub(crate) fn check_load_origin(source: &LoadOrigin, target: &ImmutableOrigin) -> bool {
563 match (source, target) {
564 (LoadOrigin::Constellation, _) | (LoadOrigin::WebDriver, _) => {
565 true
567 },
568 (_, ImmutableOrigin::Opaque(_)) => {
569 true
573 },
574 (LoadOrigin::Script(source_origin), _) => source_origin == target,
575 }
576 }
577
578 pub(crate) fn set_needs_rendering_update(&self) {
582 self.needs_rendering_update.store(true, Ordering::Relaxed);
583 }
584
585 pub(crate) fn navigate(
587 pipeline_id: PipelineId,
588 mut load_data: LoadData,
589 history_handling: NavigationHistoryBehavior,
590 ) {
591 with_script_thread(|script_thread| {
592 let is_javascript = load_data.url.scheme() == "javascript";
593 if is_javascript {
596 let window = match script_thread.documents.borrow().find_window(pipeline_id) {
597 None => return,
598 Some(window) => window,
599 };
600 let global = window.as_global_scope();
601 let trusted_global = Trusted::new(global);
602 let sender = script_thread
603 .senders
604 .pipeline_to_constellation_sender
605 .clone();
606 let task = task!(navigate_javascript: move || {
607 if trusted_global.root().is::<Window>() {
609 let global = &trusted_global.root();
610 if Self::navigate_to_javascript_url(global, global, &mut load_data, None, CanGc::note()) {
611 sender
612 .send((pipeline_id, ScriptToConstellationMessage::LoadUrl(load_data, history_handling)))
613 .unwrap();
614 }
615 }
616 });
617 global
619 .task_manager()
620 .dom_manipulation_task_source()
621 .queue(task);
622 } else {
623 script_thread
624 .senders
625 .pipeline_to_constellation_sender
626 .send((
627 pipeline_id,
628 ScriptToConstellationMessage::LoadUrl(load_data, history_handling),
629 ))
630 .expect("Sending a LoadUrl message to the constellation failed");
631 }
632 });
633 }
634
635 pub(crate) fn navigate_to_javascript_url(
637 global: &GlobalScope,
638 containing_global: &GlobalScope,
639 load_data: &mut LoadData,
640 container: Option<&Element>,
641 can_gc: CanGc,
642 ) -> bool {
643 if !Self::check_load_origin(&load_data.load_origin, &global.get_url().origin()) {
647 return false;
648 }
649
650 if global
653 .get_csp_list()
654 .should_navigation_request_be_blocked(global, load_data, container, can_gc)
655 {
656 return false;
657 }
658
659 Self::eval_js_url(containing_global, load_data, can_gc);
662 true
663 }
664
665 pub(crate) fn process_attach_layout(new_layout_info: NewLayoutInfo, origin: MutableOrigin) {
666 with_script_thread(|script_thread| {
667 let pipeline_id = Some(new_layout_info.new_pipeline_id);
668 script_thread.profile_event(
669 ScriptThreadEventCategory::AttachLayout,
670 pipeline_id,
671 || {
672 script_thread.handle_new_layout(new_layout_info, origin);
673 },
674 )
675 });
676 }
677
678 pub(crate) fn get_top_level_for_browsing_context(
679 sender_pipeline: PipelineId,
680 browsing_context_id: BrowsingContextId,
681 ) -> Option<WebViewId> {
682 with_script_thread(|script_thread| {
683 script_thread.ask_constellation_for_top_level_info(sender_pipeline, browsing_context_id)
684 })
685 }
686
687 pub(crate) fn find_document(id: PipelineId) -> Option<DomRoot<Document>> {
688 with_script_thread(|script_thread| script_thread.documents.borrow().find_document(id))
689 }
690
691 #[must_use]
695 pub(crate) fn user_interacting_guard() -> ScriptUserInteractingGuard {
696 with_script_thread(|script_thread| {
697 ScriptUserInteractingGuard::new(script_thread.is_user_interacting.clone())
698 })
699 }
700
701 pub(crate) fn is_user_interacting() -> bool {
702 with_script_thread(|script_thread| script_thread.is_user_interacting.get())
703 }
704
705 pub(crate) fn get_fully_active_document_ids(&self) -> FxHashSet<PipelineId> {
706 self.documents
707 .borrow()
708 .iter()
709 .filter_map(|(id, document)| {
710 if document.is_fully_active() {
711 Some(id)
712 } else {
713 None
714 }
715 })
716 .fold(FxHashSet::default(), |mut set, id| {
717 let _ = set.insert(id);
718 set
719 })
720 }
721
722 pub(crate) fn find_window_proxy(id: BrowsingContextId) -> Option<DomRoot<WindowProxy>> {
723 with_script_thread(|script_thread| {
724 script_thread
725 .window_proxies
726 .borrow()
727 .get(&id)
728 .map(|context| DomRoot::from_ref(&**context))
729 })
730 }
731
732 pub(crate) fn find_window_proxy_by_name(name: &DOMString) -> Option<DomRoot<WindowProxy>> {
733 with_script_thread(|script_thread| {
734 for (_, proxy) in script_thread.window_proxies.borrow().iter() {
735 if proxy.get_name() == *name {
736 return Some(DomRoot::from_ref(&**proxy));
737 }
738 }
739 None
740 })
741 }
742
743 pub(crate) fn worklet_thread_pool(image_cache: Arc<dyn ImageCache>) -> Rc<WorkletThreadPool> {
745 with_optional_script_thread(|script_thread| {
746 let script_thread = script_thread.unwrap();
747 script_thread
748 .worklet_thread_pool
749 .borrow_mut()
750 .get_or_insert_with(|| {
751 let init = WorkletGlobalScopeInit {
752 to_script_thread_sender: script_thread.senders.self_sender.clone(),
753 resource_threads: script_thread.resource_threads.clone(),
754 mem_profiler_chan: script_thread.senders.memory_profiler_sender.clone(),
755 time_profiler_chan: script_thread.senders.time_profiler_sender.clone(),
756 devtools_chan: script_thread.senders.devtools_server_sender.clone(),
757 to_constellation_sender: script_thread
758 .senders
759 .pipeline_to_constellation_sender
760 .clone(),
761 to_embedder_sender: script_thread
762 .senders
763 .pipeline_to_embedder_sender
764 .clone(),
765 image_cache,
766 #[cfg(feature = "webgpu")]
767 gpu_id_hub: script_thread.gpu_id_hub.clone(),
768 inherited_secure_context: script_thread.inherited_secure_context,
769 };
770 Rc::new(WorkletThreadPool::spawn(init))
771 })
772 .clone()
773 })
774 }
775
776 fn handle_register_paint_worklet(
777 &self,
778 pipeline_id: PipelineId,
779 name: Atom,
780 properties: Vec<Atom>,
781 painter: Box<dyn Painter>,
782 ) {
783 let Some(window) = self.documents.borrow().find_window(pipeline_id) else {
784 warn!("Paint worklet registered after pipeline {pipeline_id} closed.");
785 return;
786 };
787
788 window
789 .layout_mut()
790 .register_paint_worklet_modules(name, properties, painter);
791 }
792
793 pub(crate) fn custom_element_reaction_stack() -> Rc<CustomElementReactionStack> {
794 with_optional_script_thread(|script_thread| {
795 script_thread
796 .as_ref()
797 .unwrap()
798 .custom_element_reaction_stack
799 .clone()
800 })
801 }
802
803 pub(crate) fn enqueue_callback_reaction(
804 element: &Element,
805 reaction: CallbackReaction,
806 definition: Option<Rc<CustomElementDefinition>>,
807 ) {
808 with_script_thread(|script_thread| {
809 script_thread
810 .custom_element_reaction_stack
811 .enqueue_callback_reaction(element, reaction, definition);
812 })
813 }
814
815 pub(crate) fn enqueue_upgrade_reaction(
816 element: &Element,
817 definition: Rc<CustomElementDefinition>,
818 ) {
819 with_script_thread(|script_thread| {
820 script_thread
821 .custom_element_reaction_stack
822 .enqueue_upgrade_reaction(element, definition);
823 })
824 }
825
826 pub(crate) fn invoke_backup_element_queue(can_gc: CanGc) {
827 with_script_thread(|script_thread| {
828 script_thread
829 .custom_element_reaction_stack
830 .invoke_backup_element_queue(can_gc);
831 })
832 }
833
834 pub(crate) fn save_node_id(pipeline: PipelineId, node_id: String) {
835 with_script_thread(|script_thread| {
836 script_thread
837 .pipeline_to_node_ids
838 .borrow_mut()
839 .entry(pipeline)
840 .or_default()
841 .insert(node_id);
842 })
843 }
844
845 pub(crate) fn has_node_id(pipeline: PipelineId, node_id: &str) -> bool {
846 with_script_thread(|script_thread| {
847 script_thread
848 .pipeline_to_node_ids
849 .borrow()
850 .get(&pipeline)
851 .is_some_and(|node_ids| node_ids.contains(node_id))
852 })
853 }
854
855 pub(crate) fn new(
857 state: InitialScriptState,
858 layout_factory: Arc<dyn LayoutFactory>,
859 system_font_service: Arc<SystemFontServiceProxy>,
860 ) -> ScriptThread {
861 let (self_sender, self_receiver) = unbounded();
862 let runtime = Runtime::new(Some(SendableTaskSource {
863 sender: ScriptEventLoopSender::MainThread(self_sender.clone()),
864 pipeline_id: state.id,
865 name: TaskSourceName::Networking,
866 canceller: Default::default(),
867 }));
868 let cx = runtime.cx();
869
870 unsafe {
871 SetWindowProxyClass(cx, GetWindowProxyClass());
872 JS_AddInterruptCallback(cx, Some(interrupt_callback));
873 }
874
875 let constellation_receiver = state.constellation_receiver.route_preserving_errors();
876
877 let devtools_server_sender = state.devtools_server_sender;
879 let (ipc_devtools_sender, ipc_devtools_receiver) = ipc::channel().unwrap();
880 let devtools_server_receiver = devtools_server_sender
881 .as_ref()
882 .map(|_| ROUTER.route_ipc_receiver_to_new_crossbeam_receiver(ipc_devtools_receiver))
883 .unwrap_or_else(crossbeam_channel::never);
884
885 let task_queue = TaskQueue::new(self_receiver, self_sender.clone());
886
887 let closing = Arc::new(AtomicBool::new(false));
888 let background_hang_monitor_exit_signal = BHMExitSignal {
889 closing: closing.clone(),
890 js_context: runtime.thread_safe_js_context(),
891 };
892
893 let background_hang_monitor = state.background_hang_monitor_register.register_component(
894 MonitoredComponentId(state.id, MonitoredComponentType::Script),
895 Duration::from_millis(1000),
896 Duration::from_millis(5000),
897 Box::new(background_hang_monitor_exit_signal),
898 );
899
900 let (image_cache_sender, image_cache_receiver) = unbounded();
901 let (ipc_image_cache_sender, ipc_image_cache_receiver) = ipc::channel().unwrap();
902 ROUTER.add_typed_route(
903 ipc_image_cache_receiver,
904 Box::new(move |message| {
905 let _ = image_cache_sender.send(message.unwrap());
906 }),
907 );
908
909 let receivers = ScriptThreadReceivers {
910 constellation_receiver,
911 image_cache_receiver,
912 devtools_server_receiver,
913 #[cfg(feature = "webgpu")]
915 webgpu_receiver: RefCell::new(crossbeam_channel::never()),
916 };
917
918 let opts = opts::get();
919 let senders = ScriptThreadSenders {
920 self_sender,
921 #[cfg(feature = "bluetooth")]
922 bluetooth_sender: state.bluetooth_sender,
923 constellation_sender: state.constellation_sender,
924 pipeline_to_constellation_sender: state.pipeline_to_constellation_sender.sender.clone(),
925 pipeline_to_embedder_sender: state.pipeline_to_embedder_sender.clone(),
926 image_cache_sender: ipc_image_cache_sender,
927 time_profiler_sender: state.time_profiler_sender,
928 memory_profiler_sender: state.memory_profiler_sender,
929 devtools_server_sender,
930 devtools_client_to_script_thread_sender: ipc_devtools_sender,
931 content_process_shutdown_sender: state.content_process_shutdown_sender,
932 };
933
934 let microtask_queue = runtime.microtask_queue.clone();
935 let js_runtime = Rc::new(runtime);
936 #[cfg(feature = "webgpu")]
937 let gpu_id_hub = Arc::new(IdentityHub::default());
938
939 let pipeline_id = PipelineId::new();
940 let script_to_constellation_chan = ScriptToConstellationChan {
941 sender: senders.pipeline_to_constellation_sender.clone(),
942 pipeline_id,
943 };
944 let debugger_global = DebuggerGlobalScope::new(
945 PipelineId::new(),
946 senders.devtools_server_sender.clone(),
947 senders.devtools_client_to_script_thread_sender.clone(),
948 senders.memory_profiler_sender.clone(),
949 senders.time_profiler_sender.clone(),
950 script_to_constellation_chan,
951 senders.pipeline_to_embedder_sender.clone(),
952 state.resource_threads.clone(),
953 #[cfg(feature = "webgpu")]
954 gpu_id_hub.clone(),
955 CanGc::note(),
956 );
957 debugger_global.execute(CanGc::note());
958
959 ScriptThread {
960 documents: DomRefCell::new(DocumentCollection::default()),
961 last_render_opportunity_time: Default::default(),
962 window_proxies: DomRefCell::new(HashMapTracedValues::new_fx()),
963 incomplete_loads: DomRefCell::new(vec![]),
964 incomplete_parser_contexts: IncompleteParserContexts(RefCell::new(vec![])),
965 senders,
966 receivers,
967 image_cache: state.image_cache.clone(),
968 resource_threads: state.resource_threads,
969 task_queue,
970 background_hang_monitor,
971 closing,
972 timer_scheduler: Default::default(),
973 microtask_queue,
974 js_runtime,
975 closed_pipelines: DomRefCell::new(FxHashSet::default()),
976 mutation_observers: Default::default(),
977 system_font_service,
978 webgl_chan: state.webgl_chan,
979 #[cfg(feature = "webxr")]
980 webxr_registry: state.webxr_registry,
981 worklet_thread_pool: Default::default(),
982 docs_with_no_blocking_loads: Default::default(),
983 custom_element_reaction_stack: Rc::new(CustomElementReactionStack::new()),
984 compositor_api: state.compositor_api,
985 profile_script_events: opts.debug.profile_script_events,
986 print_pwm: opts.print_pwm,
987 unminify_js: opts.unminify_js,
988 local_script_source: opts.local_script_source.clone(),
989 unminify_css: opts.unminify_css,
990 user_content_manager: state.user_content_manager,
991 player_context: state.player_context,
992 pipeline_to_node_ids: Default::default(),
993 is_user_interacting: Rc::new(Cell::new(false)),
994 #[cfg(feature = "webgpu")]
995 gpu_id_hub,
996 inherited_secure_context: state.inherited_secure_context,
997 layout_factory,
998 relative_mouse_down_point: Cell::new(Point2D::zero()),
999 scheduled_update_the_rendering: Default::default(),
1000 needs_rendering_update: Arc::new(AtomicBool::new(false)),
1001 debugger_global: debugger_global.as_traced(),
1002 privileged_urls: state.privileged_urls,
1003 }
1004 }
1005
1006 #[allow(unsafe_code)]
1007 pub(crate) fn get_cx(&self) -> JSContext {
1008 unsafe { JSContext::from_ptr(self.js_runtime.cx()) }
1009 }
1010
1011 fn can_continue_running_inner(&self) -> bool {
1013 if self.closing.load(Ordering::SeqCst) {
1014 return false;
1015 }
1016 true
1017 }
1018
1019 fn prepare_for_shutdown_inner(&self) {
1021 let docs = self.documents.borrow();
1022 for (_, document) in docs.iter() {
1023 document
1024 .owner_global()
1025 .task_manager()
1026 .cancel_all_tasks_and_ignore_future_tasks();
1027 }
1028 }
1029
1030 pub(crate) fn start(&self, can_gc: CanGc) {
1033 debug!("Starting script thread.");
1034 while self.handle_msgs(can_gc) {
1035 debug!("Running script thread.");
1037 }
1038 debug!("Stopped script thread.");
1039 }
1040
1041 fn process_pending_input_events(&self, pipeline_id: PipelineId, can_gc: CanGc) {
1043 let Some(document) = self.documents.borrow().find_document(pipeline_id) else {
1044 warn!("Processing pending compositor events for closed pipeline {pipeline_id}.");
1045 return;
1046 };
1047 if document.window().Closed() {
1049 warn!("Compositor event sent to a pipeline with a closed window {pipeline_id}.");
1050 return;
1051 }
1052
1053 let _guard = ScriptUserInteractingGuard::new(self.is_user_interacting.clone());
1054 document.event_handler().handle_pending_input_events(can_gc);
1055 }
1056
1057 fn cancel_scheduled_update_the_rendering(&self) {
1058 if let Some(timer_id) = self.scheduled_update_the_rendering.borrow_mut().take() {
1059 self.timer_scheduler.borrow_mut().cancel_timer(timer_id);
1060 }
1061 }
1062
1063 fn schedule_update_the_rendering_timer_if_necessary(&self, delay: Duration) {
1064 if self.scheduled_update_the_rendering.borrow().is_some() {
1065 return;
1066 }
1067
1068 debug!("Scheduling ScriptThread animation frame.");
1069 let trigger_script_thread_animation = self.needs_rendering_update.clone();
1070 let timer_id = self.schedule_timer(TimerEventRequest {
1071 callback: Box::new(move || {
1072 trigger_script_thread_animation.store(true, Ordering::Relaxed);
1073 }),
1074 duration: delay,
1075 });
1076
1077 *self.scheduled_update_the_rendering.borrow_mut() = Some(timer_id);
1078 }
1079
1080 pub(crate) fn update_the_rendering(&self, can_gc: CanGc) -> bool {
1087 self.last_render_opportunity_time.set(Some(Instant::now()));
1088 self.cancel_scheduled_update_the_rendering();
1089 self.needs_rendering_update.store(false, Ordering::Relaxed);
1090
1091 if !self.can_continue_running_inner() {
1092 return false;
1093 }
1094
1095 let documents_in_order = self.documents.borrow().documents_in_order();
1118
1119 let mut should_generate_frame = false;
1124 for pipeline_id in documents_in_order.iter() {
1125 let document = self
1126 .documents
1127 .borrow()
1128 .find_document(*pipeline_id)
1129 .expect("Got pipeline for Document not managed by this ScriptThread.");
1130
1131 if !document.is_fully_active() {
1132 continue;
1133 }
1134
1135 if document.waiting_on_canvas_image_updates() {
1136 continue;
1137 }
1138
1139 self.process_pending_input_events(*pipeline_id, can_gc);
1146
1147 let resized = document.window().run_the_resize_steps(can_gc);
1149
1150 document.run_the_scroll_steps(can_gc);
1152
1153 if resized {
1155 document
1157 .window()
1158 .evaluate_media_queries_and_report_changes(can_gc);
1159
1160 document.react_to_environment_changes()
1163 }
1164
1165 document.update_animations_and_send_events(can_gc);
1169
1170 document.run_the_animation_frame_callbacks(can_gc);
1180
1181 let _realm = enter_realm(&*document);
1183 let mut depth = Default::default();
1184 while document.gather_active_resize_observations_at_depth(&depth) {
1185 depth = document.broadcast_active_resize_observations(can_gc);
1187 }
1188
1189 if document.has_skipped_resize_observations() {
1190 document.deliver_resize_loop_error_notification(can_gc);
1191 }
1192 document.set_resize_observer_started_observing_target(false);
1193
1194 document.update_intersection_observer_steps(CrossProcessInstant::now(), can_gc);
1205
1206 should_generate_frame =
1211 document.update_the_rendering().needs_frame() || should_generate_frame;
1212
1213 }
1216
1217 if should_generate_frame {
1218 self.compositor_api.generate_frame();
1219 }
1220
1221 self.perform_a_microtask_checkpoint(can_gc);
1224 should_generate_frame
1225 }
1226
1227 fn maybe_schedule_rendering_opportunity_after_ipc_message(
1234 &self,
1235 built_any_display_lists: bool,
1236 ) {
1237 let needs_rendering_update = self
1238 .documents
1239 .borrow()
1240 .iter()
1241 .any(|(_, document)| document.needs_rendering_update());
1242 let running_animations = self.documents.borrow().iter().any(|(_, document)| {
1243 document.is_fully_active() &&
1244 !document.window().throttled() &&
1245 (document.animations().running_animation_count() != 0 ||
1246 document.has_active_request_animation_frame_callbacks())
1247 });
1248
1249 if !needs_rendering_update && !running_animations {
1253 return;
1254 }
1255
1256 if running_animations && built_any_display_lists {
1260 return;
1261 }
1262
1263 let animation_delay = if running_animations && !needs_rendering_update {
1271 Duration::from_millis(30)
1275 } else {
1276 Duration::from_millis(20)
1279 };
1280
1281 let time_since_last_rendering_opportunity = self
1282 .last_render_opportunity_time
1283 .get()
1284 .map(|last_render_opportunity_time| Instant::now() - last_render_opportunity_time)
1285 .unwrap_or(Duration::MAX)
1286 .min(animation_delay);
1287 self.schedule_update_the_rendering_timer_if_necessary(
1288 animation_delay - time_since_last_rendering_opportunity,
1289 );
1290 }
1291
1292 fn maybe_fulfill_font_ready_promises(&self, can_gc: CanGc) {
1295 let mut sent_message = false;
1296 for (_, document) in self.documents.borrow().iter() {
1297 sent_message = document.maybe_fulfill_font_ready_promise(can_gc) || sent_message;
1298 }
1299
1300 if sent_message {
1301 self.perform_a_microtask_checkpoint(can_gc);
1302 }
1303 }
1304
1305 fn maybe_send_idle_document_state_to_constellation(&self) {
1309 if !opts::get().wait_for_stable_image {
1310 return;
1311 }
1312 for (_, document) in self.documents.borrow().iter() {
1313 document
1314 .window()
1315 .maybe_send_idle_document_state_to_constellation();
1316 }
1317 }
1318
1319 fn handle_msgs(&self, can_gc: CanGc) -> bool {
1321 let mut sequential = vec![];
1323
1324 self.background_hang_monitor.notify_wait();
1326
1327 debug!("Waiting for event.");
1329 let fully_active = self.get_fully_active_document_ids();
1330 let mut event = self.receivers.recv(
1331 &self.task_queue,
1332 &self.timer_scheduler.borrow(),
1333 &fully_active,
1334 );
1335
1336 loop {
1337 debug!("Handling event: {event:?}");
1338
1339 self.timer_scheduler
1341 .borrow_mut()
1342 .dispatch_completed_timers();
1343
1344 let _realm = event.pipeline_id().map(|id| {
1345 let global = self.documents.borrow().find_global(id);
1346 global.map(|global| enter_realm(&*global))
1347 });
1348
1349 match event {
1351 MixedMessage::FromConstellation(ScriptThreadMessage::AttachLayout(
1355 new_layout_info,
1356 )) => {
1357 let pipeline_id = new_layout_info.new_pipeline_id;
1358 self.profile_event(
1359 ScriptThreadEventCategory::AttachLayout,
1360 Some(pipeline_id),
1361 || {
1362 let not_an_about_blank_and_about_srcdoc_load =
1366 new_layout_info.load_data.url.as_str() != "about:blank" &&
1367 new_layout_info.load_data.url.as_str() != "about:srcdoc";
1368 let origin = if not_an_about_blank_and_about_srcdoc_load {
1369 MutableOrigin::new(new_layout_info.load_data.url.origin())
1370 } else if let Some(parent) =
1371 new_layout_info.parent_info.and_then(|pipeline_id| {
1372 self.documents.borrow().find_document(pipeline_id)
1373 })
1374 {
1375 parent.origin().clone()
1376 } else if let Some(creator) = new_layout_info
1377 .load_data
1378 .creator_pipeline_id
1379 .and_then(|pipeline_id| {
1380 self.documents.borrow().find_document(pipeline_id)
1381 })
1382 {
1383 creator.origin().clone()
1384 } else {
1385 MutableOrigin::new(ImmutableOrigin::new_opaque())
1386 };
1387
1388 self.handle_new_layout(new_layout_info, origin);
1389 },
1390 )
1391 },
1392 MixedMessage::FromConstellation(ScriptThreadMessage::Resize(
1393 id,
1394 size,
1395 size_type,
1396 )) => {
1397 self.handle_resize_message(id, size, size_type);
1398 },
1399 MixedMessage::FromConstellation(ScriptThreadMessage::Viewport(id, rect)) => self
1400 .profile_event(ScriptThreadEventCategory::SetViewport, Some(id), || {
1401 self.handle_viewport(id, rect);
1402 }),
1403 MixedMessage::FromConstellation(ScriptThreadMessage::TickAllAnimations(
1404 _webviews,
1405 )) => {
1406 self.set_needs_rendering_update();
1407 },
1408 MixedMessage::FromConstellation(
1409 ScriptThreadMessage::NoLongerWaitingOnAsychronousImageUpdates(pipeline_id),
1410 ) => {
1411 if let Some(document) = self.documents.borrow().find_document(pipeline_id) {
1412 document.handle_no_longer_waiting_on_asynchronous_image_updates();
1413 }
1414 },
1415 MixedMessage::FromConstellation(ScriptThreadMessage::SendInputEvent(id, event)) => {
1416 self.handle_input_event(id, event)
1417 },
1418 MixedMessage::FromScript(MainThreadScriptMsg::Common(CommonScriptMsg::Task(
1419 _,
1420 _,
1421 _,
1422 TaskSourceName::Rendering,
1423 ))) => {
1424 },
1428 MixedMessage::FromScript(MainThreadScriptMsg::Inactive) => {
1429 },
1432 MixedMessage::FromConstellation(ScriptThreadMessage::ExitFullScreen(id)) => self
1433 .profile_event(ScriptThreadEventCategory::ExitFullscreen, Some(id), || {
1434 self.handle_exit_fullscreen(id, can_gc);
1435 }),
1436 _ => {
1437 sequential.push(event);
1438 },
1439 }
1440
1441 match self.receivers.try_recv(&self.task_queue, &fully_active) {
1445 Some(new_event) => event = new_event,
1446 None => break,
1447 }
1448 }
1449
1450 debug!("Processing events.");
1452 for msg in sequential {
1453 debug!("Processing event {:?}.", msg);
1454 let category = self.categorize_msg(&msg);
1455 let pipeline_id = msg.pipeline_id();
1456 let _realm = pipeline_id.and_then(|id| {
1457 let global = self.documents.borrow().find_global(id);
1458 global.map(|global| enter_realm(&*global))
1459 });
1460
1461 if self.closing.load(Ordering::SeqCst) {
1462 match msg {
1464 MixedMessage::FromConstellation(ScriptThreadMessage::ExitScriptThread) => {
1465 self.handle_exit_script_thread_msg(can_gc);
1466 return false;
1467 },
1468 MixedMessage::FromConstellation(ScriptThreadMessage::ExitPipeline(
1469 webview_id,
1470 pipeline_id,
1471 discard_browsing_context,
1472 )) => {
1473 self.handle_exit_pipeline_msg(
1474 webview_id,
1475 pipeline_id,
1476 discard_browsing_context,
1477 can_gc,
1478 );
1479 },
1480 _ => {},
1481 }
1482 continue;
1483 }
1484
1485 let exiting = self.profile_event(category, pipeline_id, move || {
1486 match msg {
1487 MixedMessage::FromConstellation(ScriptThreadMessage::ExitScriptThread) => {
1488 self.handle_exit_script_thread_msg(can_gc);
1489 return true;
1490 },
1491 MixedMessage::FromConstellation(inner_msg) => {
1492 self.handle_msg_from_constellation(inner_msg, can_gc)
1493 },
1494 MixedMessage::FromScript(inner_msg) => self.handle_msg_from_script(inner_msg),
1495 MixedMessage::FromDevtools(inner_msg) => {
1496 self.handle_msg_from_devtools(inner_msg, can_gc)
1497 },
1498 MixedMessage::FromImageCache(inner_msg) => {
1499 self.handle_msg_from_image_cache(inner_msg)
1500 },
1501 #[cfg(feature = "webgpu")]
1502 MixedMessage::FromWebGPUServer(inner_msg) => {
1503 self.handle_msg_from_webgpu_server(inner_msg)
1504 },
1505 MixedMessage::TimerFired => {},
1506 }
1507
1508 false
1509 });
1510
1511 if exiting {
1513 return false;
1514 }
1515
1516 self.perform_a_microtask_checkpoint(can_gc);
1519 }
1520
1521 for (_, doc) in self.documents.borrow().iter() {
1522 let window = doc.window();
1523 window
1524 .upcast::<GlobalScope>()
1525 .perform_a_dom_garbage_collection_checkpoint();
1526 }
1527
1528 {
1529 let mut docs = self.docs_with_no_blocking_loads.borrow_mut();
1531 for document in docs.iter() {
1532 let _realm = enter_realm(&**document);
1533 document.maybe_queue_document_completion();
1534 }
1535 docs.clear();
1536 }
1537
1538 let built_any_display_lists = self.needs_rendering_update.load(Ordering::Relaxed) &&
1539 self.update_the_rendering(can_gc);
1540
1541 self.maybe_fulfill_font_ready_promises(can_gc);
1542 self.maybe_send_idle_document_state_to_constellation();
1543
1544 self.maybe_schedule_rendering_opportunity_after_ipc_message(built_any_display_lists);
1546
1547 true
1548 }
1549
1550 fn categorize_msg(&self, msg: &MixedMessage) -> ScriptThreadEventCategory {
1551 match *msg {
1552 MixedMessage::FromConstellation(ref inner_msg) => match *inner_msg {
1553 ScriptThreadMessage::SendInputEvent(_, _) => ScriptThreadEventCategory::InputEvent,
1554 _ => ScriptThreadEventCategory::ConstellationMsg,
1555 },
1556 MixedMessage::FromDevtools(_) => ScriptThreadEventCategory::DevtoolsMsg,
1558 MixedMessage::FromImageCache(_) => ScriptThreadEventCategory::ImageCacheMsg,
1559 MixedMessage::FromScript(ref inner_msg) => match *inner_msg {
1560 MainThreadScriptMsg::Common(CommonScriptMsg::Task(category, ..)) => category,
1561 MainThreadScriptMsg::RegisterPaintWorklet { .. } => {
1562 ScriptThreadEventCategory::WorkletEvent
1563 },
1564 _ => ScriptThreadEventCategory::ScriptEvent,
1565 },
1566 #[cfg(feature = "webgpu")]
1567 MixedMessage::FromWebGPUServer(_) => ScriptThreadEventCategory::WebGPUMsg,
1568 MixedMessage::TimerFired => ScriptThreadEventCategory::TimerEvent,
1569 }
1570 }
1571
1572 fn profile_event<F, R>(
1573 &self,
1574 category: ScriptThreadEventCategory,
1575 pipeline_id: Option<PipelineId>,
1576 f: F,
1577 ) -> R
1578 where
1579 F: FnOnce() -> R,
1580 {
1581 self.background_hang_monitor
1582 .notify_activity(HangAnnotation::Script(category.into()));
1583 let start = Instant::now();
1584 let value = if self.profile_script_events {
1585 let profiler_chan = self.senders.time_profiler_sender.clone();
1586 match category {
1587 ScriptThreadEventCategory::AttachLayout => {
1588 time_profile!(ProfilerCategory::ScriptAttachLayout, None, profiler_chan, f)
1589 },
1590 ScriptThreadEventCategory::ConstellationMsg => time_profile!(
1591 ProfilerCategory::ScriptConstellationMsg,
1592 None,
1593 profiler_chan,
1594 f
1595 ),
1596 ScriptThreadEventCategory::DatabaseAccessEvent => time_profile!(
1597 ProfilerCategory::ScriptDatabaseAccessEvent,
1598 None,
1599 profiler_chan,
1600 f
1601 ),
1602 ScriptThreadEventCategory::DevtoolsMsg => {
1603 time_profile!(ProfilerCategory::ScriptDevtoolsMsg, None, profiler_chan, f)
1604 },
1605 ScriptThreadEventCategory::DocumentEvent => time_profile!(
1606 ProfilerCategory::ScriptDocumentEvent,
1607 None,
1608 profiler_chan,
1609 f
1610 ),
1611 ScriptThreadEventCategory::InputEvent => {
1612 time_profile!(ProfilerCategory::ScriptInputEvent, None, profiler_chan, f)
1613 },
1614 ScriptThreadEventCategory::FileRead => {
1615 time_profile!(ProfilerCategory::ScriptFileRead, None, profiler_chan, f)
1616 },
1617 ScriptThreadEventCategory::FontLoading => {
1618 time_profile!(ProfilerCategory::ScriptFontLoading, None, profiler_chan, f)
1619 },
1620 ScriptThreadEventCategory::FormPlannedNavigation => time_profile!(
1621 ProfilerCategory::ScriptPlannedNavigation,
1622 None,
1623 profiler_chan,
1624 f
1625 ),
1626 ScriptThreadEventCategory::HistoryEvent => {
1627 time_profile!(ProfilerCategory::ScriptHistoryEvent, None, profiler_chan, f)
1628 },
1629 ScriptThreadEventCategory::ImageCacheMsg => time_profile!(
1630 ProfilerCategory::ScriptImageCacheMsg,
1631 None,
1632 profiler_chan,
1633 f
1634 ),
1635 ScriptThreadEventCategory::NetworkEvent => {
1636 time_profile!(ProfilerCategory::ScriptNetworkEvent, None, profiler_chan, f)
1637 },
1638 ScriptThreadEventCategory::PortMessage => {
1639 time_profile!(ProfilerCategory::ScriptPortMessage, None, profiler_chan, f)
1640 },
1641 ScriptThreadEventCategory::Resize => {
1642 time_profile!(ProfilerCategory::ScriptResize, None, profiler_chan, f)
1643 },
1644 ScriptThreadEventCategory::ScriptEvent => {
1645 time_profile!(ProfilerCategory::ScriptEvent, None, profiler_chan, f)
1646 },
1647 ScriptThreadEventCategory::SetScrollState => time_profile!(
1648 ProfilerCategory::ScriptSetScrollState,
1649 None,
1650 profiler_chan,
1651 f
1652 ),
1653 ScriptThreadEventCategory::UpdateReplacedElement => time_profile!(
1654 ProfilerCategory::ScriptUpdateReplacedElement,
1655 None,
1656 profiler_chan,
1657 f
1658 ),
1659 ScriptThreadEventCategory::StylesheetLoad => time_profile!(
1660 ProfilerCategory::ScriptStylesheetLoad,
1661 None,
1662 profiler_chan,
1663 f
1664 ),
1665 ScriptThreadEventCategory::SetViewport => {
1666 time_profile!(ProfilerCategory::ScriptSetViewport, None, profiler_chan, f)
1667 },
1668 ScriptThreadEventCategory::TimerEvent => {
1669 time_profile!(ProfilerCategory::ScriptTimerEvent, None, profiler_chan, f)
1670 },
1671 ScriptThreadEventCategory::WebSocketEvent => time_profile!(
1672 ProfilerCategory::ScriptWebSocketEvent,
1673 None,
1674 profiler_chan,
1675 f
1676 ),
1677 ScriptThreadEventCategory::WorkerEvent => {
1678 time_profile!(ProfilerCategory::ScriptWorkerEvent, None, profiler_chan, f)
1679 },
1680 ScriptThreadEventCategory::WorkletEvent => {
1681 time_profile!(ProfilerCategory::ScriptWorkletEvent, None, profiler_chan, f)
1682 },
1683 ScriptThreadEventCategory::ServiceWorkerEvent => time_profile!(
1684 ProfilerCategory::ScriptServiceWorkerEvent,
1685 None,
1686 profiler_chan,
1687 f
1688 ),
1689 ScriptThreadEventCategory::EnterFullscreen => time_profile!(
1690 ProfilerCategory::ScriptEnterFullscreen,
1691 None,
1692 profiler_chan,
1693 f
1694 ),
1695 ScriptThreadEventCategory::ExitFullscreen => time_profile!(
1696 ProfilerCategory::ScriptExitFullscreen,
1697 None,
1698 profiler_chan,
1699 f
1700 ),
1701 ScriptThreadEventCategory::PerformanceTimelineTask => time_profile!(
1702 ProfilerCategory::ScriptPerformanceEvent,
1703 None,
1704 profiler_chan,
1705 f
1706 ),
1707 ScriptThreadEventCategory::Rendering => {
1708 time_profile!(ProfilerCategory::ScriptRendering, None, profiler_chan, f)
1709 },
1710 #[cfg(feature = "webgpu")]
1711 ScriptThreadEventCategory::WebGPUMsg => {
1712 time_profile!(ProfilerCategory::ScriptWebGPUMsg, None, profiler_chan, f)
1713 },
1714 }
1715 } else {
1716 f()
1717 };
1718 let task_duration = start.elapsed();
1719 for (doc_id, doc) in self.documents.borrow().iter() {
1720 if let Some(pipeline_id) = pipeline_id {
1721 if pipeline_id == doc_id && task_duration.as_nanos() > MAX_TASK_NS {
1722 if self.print_pwm {
1723 println!(
1724 "Task took longer than max allowed ({:?}) {:?}",
1725 category,
1726 task_duration.as_nanos()
1727 );
1728 }
1729 doc.start_tti();
1730 }
1731 }
1732 doc.record_tti_if_necessary();
1733 }
1734 value
1735 }
1736
1737 fn handle_msg_from_constellation(&self, msg: ScriptThreadMessage, can_gc: CanGc) {
1738 match msg {
1739 ScriptThreadMessage::StopDelayingLoadEventsMode(pipeline_id) => {
1740 self.handle_stop_delaying_load_events_mode(pipeline_id)
1741 },
1742 ScriptThreadMessage::NavigateIframe(
1743 parent_pipeline_id,
1744 browsing_context_id,
1745 load_data,
1746 history_handling,
1747 ) => self.handle_navigate_iframe(
1748 parent_pipeline_id,
1749 browsing_context_id,
1750 load_data,
1751 history_handling,
1752 can_gc,
1753 ),
1754 ScriptThreadMessage::UnloadDocument(pipeline_id) => {
1755 self.handle_unload_document(pipeline_id, can_gc)
1756 },
1757 ScriptThreadMessage::ResizeInactive(id, new_size) => {
1758 self.handle_resize_inactive_msg(id, new_size)
1759 },
1760 ScriptThreadMessage::ThemeChange(_, theme) => {
1761 self.handle_theme_change_msg(theme);
1762 },
1763 ScriptThreadMessage::GetTitle(pipeline_id) => self.handle_get_title_msg(pipeline_id),
1764 ScriptThreadMessage::SetDocumentActivity(pipeline_id, activity) => {
1765 self.handle_set_document_activity_msg(pipeline_id, activity, can_gc)
1766 },
1767 ScriptThreadMessage::SetThrottled(pipeline_id, throttled) => {
1768 self.handle_set_throttled_msg(pipeline_id, throttled)
1769 },
1770 ScriptThreadMessage::SetThrottledInContainingIframe(
1771 parent_pipeline_id,
1772 browsing_context_id,
1773 throttled,
1774 ) => self.handle_set_throttled_in_containing_iframe_msg(
1775 parent_pipeline_id,
1776 browsing_context_id,
1777 throttled,
1778 ),
1779 ScriptThreadMessage::PostMessage {
1780 target: target_pipeline_id,
1781 source: source_pipeline_id,
1782 source_browsing_context,
1783 target_origin: origin,
1784 source_origin,
1785 data,
1786 } => self.handle_post_message_msg(
1787 target_pipeline_id,
1788 source_pipeline_id,
1789 source_browsing_context,
1790 origin,
1791 source_origin,
1792 *data,
1793 ),
1794 ScriptThreadMessage::UpdatePipelineId(
1795 parent_pipeline_id,
1796 browsing_context_id,
1797 webview_id,
1798 new_pipeline_id,
1799 reason,
1800 ) => self.handle_update_pipeline_id(
1801 parent_pipeline_id,
1802 browsing_context_id,
1803 webview_id,
1804 new_pipeline_id,
1805 reason,
1806 can_gc,
1807 ),
1808 ScriptThreadMessage::UpdateHistoryState(pipeline_id, history_state_id, url) => {
1809 self.handle_update_history_state_msg(pipeline_id, history_state_id, url, can_gc)
1810 },
1811 ScriptThreadMessage::RemoveHistoryStates(pipeline_id, history_states) => {
1812 self.handle_remove_history_states(pipeline_id, history_states)
1813 },
1814 ScriptThreadMessage::FocusIFrame(parent_pipeline_id, frame_id, sequence) => {
1815 self.handle_focus_iframe_msg(parent_pipeline_id, frame_id, sequence, can_gc)
1816 },
1817 ScriptThreadMessage::FocusDocument(pipeline_id, sequence) => {
1818 self.handle_focus_document_msg(pipeline_id, sequence, can_gc)
1819 },
1820 ScriptThreadMessage::Unfocus(pipeline_id, sequence) => {
1821 self.handle_unfocus_msg(pipeline_id, sequence, can_gc)
1822 },
1823 ScriptThreadMessage::WebDriverScriptCommand(pipeline_id, msg) => {
1824 self.handle_webdriver_msg(pipeline_id, msg, can_gc)
1825 },
1826 ScriptThreadMessage::WebFontLoaded(pipeline_id, success) => {
1827 self.handle_web_font_loaded(pipeline_id, success)
1828 },
1829 ScriptThreadMessage::DispatchIFrameLoadEvent {
1830 target: browsing_context_id,
1831 parent: parent_id,
1832 child: child_id,
1833 } => self.handle_iframe_load_event(parent_id, browsing_context_id, child_id, can_gc),
1834 ScriptThreadMessage::DispatchStorageEvent(
1835 pipeline_id,
1836 storage,
1837 url,
1838 key,
1839 old_value,
1840 new_value,
1841 ) => self.handle_storage_event(pipeline_id, storage, url, key, old_value, new_value),
1842 ScriptThreadMessage::ReportCSSError(pipeline_id, filename, line, column, msg) => {
1843 self.handle_css_error_reporting(pipeline_id, filename, line, column, msg)
1844 },
1845 ScriptThreadMessage::Reload(pipeline_id) => self.handle_reload(pipeline_id, can_gc),
1846 ScriptThreadMessage::ExitPipeline(
1847 webview_id,
1848 pipeline_id,
1849 discard_browsing_context,
1850 ) => self.handle_exit_pipeline_msg(
1851 webview_id,
1852 pipeline_id,
1853 discard_browsing_context,
1854 can_gc,
1855 ),
1856 ScriptThreadMessage::PaintMetric(
1857 pipeline_id,
1858 metric_type,
1859 metric_value,
1860 first_reflow,
1861 ) => self.handle_paint_metric(
1862 pipeline_id,
1863 metric_type,
1864 metric_value,
1865 first_reflow,
1866 can_gc,
1867 ),
1868 ScriptThreadMessage::MediaSessionAction(pipeline_id, action) => {
1869 self.handle_media_session_action(pipeline_id, action, can_gc)
1870 },
1871 #[cfg(feature = "webgpu")]
1872 ScriptThreadMessage::SetWebGPUPort(port) => {
1873 *self.receivers.webgpu_receiver.borrow_mut() =
1874 ROUTER.route_ipc_receiver_to_new_crossbeam_receiver(port);
1875 },
1876 msg @ ScriptThreadMessage::AttachLayout(..) |
1877 msg @ ScriptThreadMessage::Viewport(..) |
1878 msg @ ScriptThreadMessage::Resize(..) |
1879 msg @ ScriptThreadMessage::ExitFullScreen(..) |
1880 msg @ ScriptThreadMessage::SendInputEvent(..) |
1881 msg @ ScriptThreadMessage::TickAllAnimations(..) |
1882 msg @ ScriptThreadMessage::NoLongerWaitingOnAsychronousImageUpdates(..) |
1883 msg @ ScriptThreadMessage::ExitScriptThread => {
1884 panic!("should have handled {:?} already", msg)
1885 },
1886 ScriptThreadMessage::SetScrollStates(pipeline_id, scroll_states) => {
1887 self.handle_set_scroll_states(pipeline_id, scroll_states)
1888 },
1889 ScriptThreadMessage::EvaluateJavaScript(pipeline_id, evaluation_id, script) => {
1890 self.handle_evaluate_javascript(pipeline_id, evaluation_id, script, can_gc);
1891 },
1892 ScriptThreadMessage::SendImageKeysBatch(pipeline_id, image_keys) => {
1893 if let Some(window) = self.documents.borrow().find_window(pipeline_id) {
1894 window
1895 .image_cache()
1896 .fill_key_cache_with_batch_of_keys(image_keys);
1897 } else {
1898 warn!(
1899 "Could not find window corresponding to an image cache to send image keys to pipeline {:?}",
1900 pipeline_id
1901 );
1902 }
1903 },
1904 ScriptThreadMessage::RefreshCursor(pipeline_id) => {
1905 self.handle_refresh_cursor(pipeline_id);
1906 },
1907 ScriptThreadMessage::PreferencesUpdated(updates) => {
1908 let mut current_preferences = prefs::get().clone();
1909 for (name, value) in updates {
1910 current_preferences.set_value(&name, value);
1911 }
1912 prefs::set(current_preferences);
1913 },
1914 }
1915 }
1916
1917 fn handle_set_scroll_states(
1918 &self,
1919 pipeline_id: PipelineId,
1920 scroll_states: FxHashMap<ExternalScrollId, LayoutVector2D>,
1921 ) {
1922 let Some(window) = self.documents.borrow().find_window(pipeline_id) else {
1923 warn!("Received scroll states for closed pipeline {pipeline_id}");
1924 return;
1925 };
1926
1927 self.profile_event(
1928 ScriptThreadEventCategory::SetScrollState,
1929 Some(pipeline_id),
1930 || {
1931 window
1932 .layout_mut()
1933 .set_scroll_offsets_from_renderer(&scroll_states);
1934 },
1935 )
1936 }
1937
1938 #[cfg(feature = "webgpu")]
1939 fn handle_msg_from_webgpu_server(&self, msg: WebGPUMsg) {
1940 match msg {
1941 WebGPUMsg::FreeAdapter(id) => self.gpu_id_hub.free_adapter_id(id),
1942 WebGPUMsg::FreeDevice {
1943 device_id,
1944 pipeline_id,
1945 } => {
1946 self.gpu_id_hub.free_device_id(device_id);
1947 if let Some(global) = self.documents.borrow().find_global(pipeline_id) {
1948 global.remove_gpu_device(WebGPUDevice(device_id));
1949 } },
1951 WebGPUMsg::FreeBuffer(id) => self.gpu_id_hub.free_buffer_id(id),
1952 WebGPUMsg::FreePipelineLayout(id) => self.gpu_id_hub.free_pipeline_layout_id(id),
1953 WebGPUMsg::FreeComputePipeline(id) => self.gpu_id_hub.free_compute_pipeline_id(id),
1954 WebGPUMsg::FreeBindGroup(id) => self.gpu_id_hub.free_bind_group_id(id),
1955 WebGPUMsg::FreeBindGroupLayout(id) => self.gpu_id_hub.free_bind_group_layout_id(id),
1956 WebGPUMsg::FreeCommandBuffer(id) => self
1957 .gpu_id_hub
1958 .free_command_buffer_id(id.into_command_encoder_id()),
1959 WebGPUMsg::FreeSampler(id) => self.gpu_id_hub.free_sampler_id(id),
1960 WebGPUMsg::FreeShaderModule(id) => self.gpu_id_hub.free_shader_module_id(id),
1961 WebGPUMsg::FreeRenderBundle(id) => self.gpu_id_hub.free_render_bundle_id(id),
1962 WebGPUMsg::FreeRenderPipeline(id) => self.gpu_id_hub.free_render_pipeline_id(id),
1963 WebGPUMsg::FreeTexture(id) => self.gpu_id_hub.free_texture_id(id),
1964 WebGPUMsg::FreeTextureView(id) => self.gpu_id_hub.free_texture_view_id(id),
1965 WebGPUMsg::FreeComputePass(id) => self.gpu_id_hub.free_compute_pass_id(id),
1966 WebGPUMsg::FreeRenderPass(id) => self.gpu_id_hub.free_render_pass_id(id),
1967 WebGPUMsg::Exit => {
1968 *self.receivers.webgpu_receiver.borrow_mut() = crossbeam_channel::never()
1969 },
1970 WebGPUMsg::DeviceLost {
1971 pipeline_id,
1972 device,
1973 reason,
1974 msg,
1975 } => {
1976 let global = self.documents.borrow().find_global(pipeline_id).unwrap();
1977 global.gpu_device_lost(device, reason, msg);
1978 },
1979 WebGPUMsg::UncapturedError {
1980 device,
1981 pipeline_id,
1982 error,
1983 } => {
1984 let global = self.documents.borrow().find_global(pipeline_id).unwrap();
1985 let _ac = enter_realm(&*global);
1986 global.handle_uncaptured_gpu_error(device, error);
1987 },
1988 _ => {},
1989 }
1990 }
1991
1992 fn handle_msg_from_script(&self, msg: MainThreadScriptMsg) {
1993 match msg {
1994 MainThreadScriptMsg::Common(CommonScriptMsg::Task(_, task, pipeline_id, _)) => {
1995 let _realm = pipeline_id.and_then(|id| {
1996 let global = self.documents.borrow().find_global(id);
1997 global.map(|global| enter_realm(&*global))
1998 });
1999 task.run_box()
2000 },
2001 MainThreadScriptMsg::Common(CommonScriptMsg::CollectReports(chan)) => {
2002 self.collect_reports(chan)
2003 },
2004 MainThreadScriptMsg::Common(CommonScriptMsg::ReportCspViolations(
2005 pipeline_id,
2006 violations,
2007 )) => {
2008 if let Some(global) = self.documents.borrow().find_global(pipeline_id) {
2009 global.report_csp_violations(violations, None, None);
2010 }
2011 },
2012 MainThreadScriptMsg::NavigationResponse {
2013 pipeline_id,
2014 message,
2015 } => {
2016 self.handle_navigation_response(pipeline_id, *message);
2017 },
2018 MainThreadScriptMsg::WorkletLoaded(pipeline_id) => {
2019 self.handle_worklet_loaded(pipeline_id)
2020 },
2021 MainThreadScriptMsg::RegisterPaintWorklet {
2022 pipeline_id,
2023 name,
2024 properties,
2025 painter,
2026 } => self.handle_register_paint_worklet(pipeline_id, name, properties, painter),
2027 MainThreadScriptMsg::Inactive => {},
2028 MainThreadScriptMsg::WakeUp => {},
2029 }
2030 }
2031
2032 fn handle_msg_from_devtools(&self, msg: DevtoolScriptControlMsg, can_gc: CanGc) {
2033 let documents = self.documents.borrow();
2034 match msg {
2035 DevtoolScriptControlMsg::EvaluateJS(id, s, reply) => match documents.find_window(id) {
2036 Some(window) => {
2037 let global = window.as_global_scope();
2038 let _aes = AutoEntryScript::new(global);
2039 devtools::handle_evaluate_js(global, s, reply, can_gc)
2040 },
2041 None => warn!("Message sent to closed pipeline {}.", id),
2042 },
2043 DevtoolScriptControlMsg::GetRootNode(id, reply) => {
2044 devtools::handle_get_root_node(&documents, id, reply, can_gc)
2045 },
2046 DevtoolScriptControlMsg::GetDocumentElement(id, reply) => {
2047 devtools::handle_get_document_element(&documents, id, reply, can_gc)
2048 },
2049 DevtoolScriptControlMsg::GetChildren(id, node_id, reply) => {
2050 devtools::handle_get_children(&documents, id, node_id, reply, can_gc)
2051 },
2052 DevtoolScriptControlMsg::GetAttributeStyle(id, node_id, reply) => {
2053 devtools::handle_get_attribute_style(&documents, id, node_id, reply, can_gc)
2054 },
2055 DevtoolScriptControlMsg::GetStylesheetStyle(
2056 id,
2057 node_id,
2058 selector,
2059 stylesheet,
2060 reply,
2061 ) => devtools::handle_get_stylesheet_style(
2062 &documents, id, node_id, selector, stylesheet, reply, can_gc,
2063 ),
2064 DevtoolScriptControlMsg::GetSelectors(id, node_id, reply) => {
2065 devtools::handle_get_selectors(&documents, id, node_id, reply, can_gc)
2066 },
2067 DevtoolScriptControlMsg::GetComputedStyle(id, node_id, reply) => {
2068 devtools::handle_get_computed_style(&documents, id, node_id, reply)
2069 },
2070 DevtoolScriptControlMsg::GetLayout(id, node_id, reply) => {
2071 devtools::handle_get_layout(&documents, id, node_id, reply, can_gc)
2072 },
2073 DevtoolScriptControlMsg::ModifyAttribute(id, node_id, modifications) => {
2074 devtools::handle_modify_attribute(&documents, id, node_id, modifications, can_gc)
2075 },
2076 DevtoolScriptControlMsg::ModifyRule(id, node_id, modifications) => {
2077 devtools::handle_modify_rule(&documents, id, node_id, modifications, can_gc)
2078 },
2079 DevtoolScriptControlMsg::WantsLiveNotifications(id, to_send) => match documents
2080 .find_window(id)
2081 {
2082 Some(window) => devtools::handle_wants_live_notifications(window.upcast(), to_send),
2083 None => warn!("Message sent to closed pipeline {}.", id),
2084 },
2085 DevtoolScriptControlMsg::SetTimelineMarkers(id, marker_types, reply) => {
2086 devtools::handle_set_timeline_markers(&documents, id, marker_types, reply)
2087 },
2088 DevtoolScriptControlMsg::DropTimelineMarkers(id, marker_types) => {
2089 devtools::handle_drop_timeline_markers(&documents, id, marker_types)
2090 },
2091 DevtoolScriptControlMsg::RequestAnimationFrame(id, name) => {
2092 devtools::handle_request_animation_frame(&documents, id, name)
2093 },
2094 DevtoolScriptControlMsg::Reload(id) => devtools::handle_reload(&documents, id, can_gc),
2095 DevtoolScriptControlMsg::GetCssDatabase(reply) => {
2096 devtools::handle_get_css_database(reply)
2097 },
2098 DevtoolScriptControlMsg::SimulateColorScheme(id, theme) => {
2099 match documents.find_window(id) {
2100 Some(window) => {
2101 window.handle_theme_change(theme);
2102 },
2103 None => warn!("Message sent to closed pipeline {}.", id),
2104 }
2105 },
2106 DevtoolScriptControlMsg::HighlightDomNode(id, node_id) => {
2107 devtools::handle_highlight_dom_node(&documents, id, node_id)
2108 },
2109 DevtoolScriptControlMsg::GetPossibleBreakpoints(spidermonkey_id, result_sender) => {
2110 self.debugger_global.fire_get_possible_breakpoints(
2111 can_gc,
2112 spidermonkey_id,
2113 result_sender,
2114 );
2115 },
2116 }
2117 }
2118
2119 fn handle_msg_from_image_cache(&self, response: ImageCacheResponseMessage) {
2120 match response {
2121 ImageCacheResponseMessage::NotifyPendingImageLoadStatus(pending_image_response) => {
2122 let window = self
2123 .documents
2124 .borrow()
2125 .find_window(pending_image_response.pipeline_id);
2126 if let Some(ref window) = window {
2127 window.pending_image_notification(pending_image_response);
2128 }
2129 },
2130 ImageCacheResponseMessage::VectorImageRasterizationComplete(response) => {
2131 let window = self.documents.borrow().find_window(response.pipeline_id);
2132 if let Some(ref window) = window {
2133 window.handle_image_rasterization_complete_notification(response);
2134 }
2135 },
2136 };
2137 }
2138
2139 fn handle_webdriver_msg(
2140 &self,
2141 pipeline_id: PipelineId,
2142 msg: WebDriverScriptCommand,
2143 can_gc: CanGc,
2144 ) {
2145 match msg {
2150 WebDriverScriptCommand::ExecuteScript(script, reply) => {
2151 let window = self.documents.borrow().find_window(pipeline_id);
2152 return webdriver_handlers::handle_execute_script(window, script, reply, can_gc);
2153 },
2154 WebDriverScriptCommand::ExecuteAsyncScript(script, reply) => {
2155 let window = self.documents.borrow().find_window(pipeline_id);
2156 return webdriver_handlers::handle_execute_async_script(
2157 window, script, reply, can_gc,
2158 );
2159 },
2160 _ => (),
2161 }
2162
2163 let documents = self.documents.borrow();
2164 match msg {
2165 WebDriverScriptCommand::AddCookie(params, reply) => {
2166 webdriver_handlers::handle_add_cookie(&documents, pipeline_id, params, reply)
2167 },
2168 WebDriverScriptCommand::DeleteCookies(reply) => {
2169 webdriver_handlers::handle_delete_cookies(&documents, pipeline_id, reply)
2170 },
2171 WebDriverScriptCommand::DeleteCookie(name, reply) => {
2172 webdriver_handlers::handle_delete_cookie(&documents, pipeline_id, name, reply)
2173 },
2174 WebDriverScriptCommand::ElementClear(element_id, reply) => {
2175 webdriver_handlers::handle_element_clear(
2176 &documents,
2177 pipeline_id,
2178 element_id,
2179 reply,
2180 can_gc,
2181 )
2182 },
2183 WebDriverScriptCommand::FindElementsCSSSelector(selector, reply) => {
2184 webdriver_handlers::handle_find_elements_css_selector(
2185 &documents,
2186 pipeline_id,
2187 selector,
2188 reply,
2189 )
2190 },
2191 WebDriverScriptCommand::FindElementsLinkText(selector, partial, reply) => {
2192 webdriver_handlers::handle_find_elements_link_text(
2193 &documents,
2194 pipeline_id,
2195 selector,
2196 partial,
2197 reply,
2198 )
2199 },
2200 WebDriverScriptCommand::FindElementsTagName(selector, reply) => {
2201 webdriver_handlers::handle_find_elements_tag_name(
2202 &documents,
2203 pipeline_id,
2204 selector,
2205 reply,
2206 can_gc,
2207 )
2208 },
2209 WebDriverScriptCommand::FindElementsXpathSelector(selector, reply) => {
2210 webdriver_handlers::handle_find_elements_xpath_selector(
2211 &documents,
2212 pipeline_id,
2213 selector,
2214 reply,
2215 can_gc,
2216 )
2217 },
2218 WebDriverScriptCommand::FindElementElementsCSSSelector(selector, element_id, reply) => {
2219 webdriver_handlers::handle_find_element_elements_css_selector(
2220 &documents,
2221 pipeline_id,
2222 element_id,
2223 selector,
2224 reply,
2225 )
2226 },
2227 WebDriverScriptCommand::FindElementElementsLinkText(
2228 selector,
2229 element_id,
2230 partial,
2231 reply,
2232 ) => webdriver_handlers::handle_find_element_elements_link_text(
2233 &documents,
2234 pipeline_id,
2235 element_id,
2236 selector,
2237 partial,
2238 reply,
2239 ),
2240 WebDriverScriptCommand::FindElementElementsTagName(selector, element_id, reply) => {
2241 webdriver_handlers::handle_find_element_elements_tag_name(
2242 &documents,
2243 pipeline_id,
2244 element_id,
2245 selector,
2246 reply,
2247 can_gc,
2248 )
2249 },
2250 WebDriverScriptCommand::FindElementElementsXPathSelector(
2251 selector,
2252 element_id,
2253 reply,
2254 ) => webdriver_handlers::handle_find_element_elements_xpath_selector(
2255 &documents,
2256 pipeline_id,
2257 element_id,
2258 selector,
2259 reply,
2260 can_gc,
2261 ),
2262 WebDriverScriptCommand::FindShadowElementsCSSSelector(
2263 selector,
2264 shadow_root_id,
2265 reply,
2266 ) => webdriver_handlers::handle_find_shadow_elements_css_selector(
2267 &documents,
2268 pipeline_id,
2269 shadow_root_id,
2270 selector,
2271 reply,
2272 ),
2273 WebDriverScriptCommand::FindShadowElementsLinkText(
2274 selector,
2275 shadow_root_id,
2276 partial,
2277 reply,
2278 ) => webdriver_handlers::handle_find_shadow_elements_link_text(
2279 &documents,
2280 pipeline_id,
2281 shadow_root_id,
2282 selector,
2283 partial,
2284 reply,
2285 ),
2286 WebDriverScriptCommand::FindShadowElementsTagName(selector, shadow_root_id, reply) => {
2287 webdriver_handlers::handle_find_shadow_elements_tag_name(
2288 &documents,
2289 pipeline_id,
2290 shadow_root_id,
2291 selector,
2292 reply,
2293 )
2294 },
2295 WebDriverScriptCommand::FindShadowElementsXPathSelector(
2296 selector,
2297 shadow_root_id,
2298 reply,
2299 ) => webdriver_handlers::handle_find_shadow_elements_xpath_selector(
2300 &documents,
2301 pipeline_id,
2302 shadow_root_id,
2303 selector,
2304 reply,
2305 can_gc,
2306 ),
2307 WebDriverScriptCommand::GetElementShadowRoot(element_id, reply) => {
2308 webdriver_handlers::handle_get_element_shadow_root(
2309 &documents,
2310 pipeline_id,
2311 element_id,
2312 reply,
2313 )
2314 },
2315 WebDriverScriptCommand::ElementClick(element_id, reply) => {
2316 webdriver_handlers::handle_element_click(
2317 &documents,
2318 pipeline_id,
2319 element_id,
2320 reply,
2321 can_gc,
2322 )
2323 },
2324 WebDriverScriptCommand::GetKnownElement(element_id, reply) => {
2325 webdriver_handlers::handle_get_known_element(
2326 &documents,
2327 pipeline_id,
2328 element_id,
2329 reply,
2330 )
2331 },
2332 WebDriverScriptCommand::GetKnownShadowRoot(element_id, reply) => {
2333 webdriver_handlers::handle_get_known_shadow_root(
2334 &documents,
2335 pipeline_id,
2336 element_id,
2337 reply,
2338 )
2339 },
2340 WebDriverScriptCommand::GetActiveElement(reply) => {
2341 webdriver_handlers::handle_get_active_element(&documents, pipeline_id, reply)
2342 },
2343 WebDriverScriptCommand::GetComputedRole(node_id, reply) => {
2344 webdriver_handlers::handle_get_computed_role(
2345 &documents,
2346 pipeline_id,
2347 node_id,
2348 reply,
2349 )
2350 },
2351 WebDriverScriptCommand::GetPageSource(reply) => {
2352 webdriver_handlers::handle_get_page_source(&documents, pipeline_id, reply, can_gc)
2353 },
2354 WebDriverScriptCommand::GetCookies(reply) => {
2355 webdriver_handlers::handle_get_cookies(&documents, pipeline_id, reply)
2356 },
2357 WebDriverScriptCommand::GetCookie(name, reply) => {
2358 webdriver_handlers::handle_get_cookie(&documents, pipeline_id, name, reply)
2359 },
2360 WebDriverScriptCommand::GetElementTagName(node_id, reply) => {
2361 webdriver_handlers::handle_get_name(&documents, pipeline_id, node_id, reply)
2362 },
2363 WebDriverScriptCommand::GetElementAttribute(node_id, name, reply) => {
2364 webdriver_handlers::handle_get_attribute(
2365 &documents,
2366 pipeline_id,
2367 node_id,
2368 name,
2369 reply,
2370 )
2371 },
2372 WebDriverScriptCommand::GetElementProperty(node_id, name, reply) => {
2373 webdriver_handlers::handle_get_property(
2374 &documents,
2375 pipeline_id,
2376 node_id,
2377 name,
2378 reply,
2379 can_gc,
2380 )
2381 },
2382 WebDriverScriptCommand::GetElementCSS(node_id, name, reply) => {
2383 webdriver_handlers::handle_get_css(&documents, pipeline_id, node_id, name, reply)
2384 },
2385 WebDriverScriptCommand::GetElementRect(node_id, reply) => {
2386 webdriver_handlers::handle_get_rect(&documents, pipeline_id, node_id, reply, can_gc)
2387 },
2388 WebDriverScriptCommand::ScrollAndGetBoundingClientRect(node_id, reply) => {
2389 webdriver_handlers::handle_scroll_and_get_bounding_client_rect(
2390 &documents,
2391 pipeline_id,
2392 node_id,
2393 reply,
2394 can_gc,
2395 )
2396 },
2397 WebDriverScriptCommand::GetElementText(node_id, reply) => {
2398 webdriver_handlers::handle_get_text(&documents, pipeline_id, node_id, reply)
2399 },
2400 WebDriverScriptCommand::GetElementInViewCenterPoint(node_id, reply) => {
2401 webdriver_handlers::handle_get_element_in_view_center_point(
2402 &documents,
2403 pipeline_id,
2404 node_id,
2405 reply,
2406 can_gc,
2407 )
2408 },
2409 WebDriverScriptCommand::GetParentFrameId(reply) => {
2410 webdriver_handlers::handle_get_parent_frame_id(&documents, pipeline_id, reply)
2411 },
2412 WebDriverScriptCommand::GetBrowsingContextId(webdriver_frame_id, reply) => {
2413 webdriver_handlers::handle_get_browsing_context_id(
2414 &documents,
2415 pipeline_id,
2416 webdriver_frame_id,
2417 reply,
2418 )
2419 },
2420 WebDriverScriptCommand::GetUrl(reply) => {
2421 webdriver_handlers::handle_get_url(&documents, pipeline_id, reply, can_gc)
2422 },
2423 WebDriverScriptCommand::IsEnabled(element_id, reply) => {
2424 webdriver_handlers::handle_is_enabled(&documents, pipeline_id, element_id, reply)
2425 },
2426 WebDriverScriptCommand::IsSelected(element_id, reply) => {
2427 webdriver_handlers::handle_is_selected(&documents, pipeline_id, element_id, reply)
2428 },
2429 WebDriverScriptCommand::GetTitle(reply) => {
2430 webdriver_handlers::handle_get_title(&documents, pipeline_id, reply)
2431 },
2432 WebDriverScriptCommand::WillSendKeys(
2433 element_id,
2434 text,
2435 strict_file_interactability,
2436 reply,
2437 ) => webdriver_handlers::handle_will_send_keys(
2438 &documents,
2439 pipeline_id,
2440 element_id,
2441 text,
2442 strict_file_interactability,
2443 reply,
2444 can_gc,
2445 ),
2446 WebDriverScriptCommand::AddLoadStatusSender(_, response_sender) => {
2447 webdriver_handlers::handle_add_load_status_sender(
2448 &documents,
2449 pipeline_id,
2450 response_sender,
2451 )
2452 },
2453 WebDriverScriptCommand::RemoveLoadStatusSender(_) => {
2454 webdriver_handlers::handle_remove_load_status_sender(&documents, pipeline_id)
2455 },
2456 _ => (),
2457 }
2458 }
2459
2460 pub(crate) fn handle_resize_message(
2463 &self,
2464 id: PipelineId,
2465 viewport_details: ViewportDetails,
2466 size_type: WindowSizeType,
2467 ) {
2468 self.profile_event(ScriptThreadEventCategory::Resize, Some(id), || {
2469 let window = self.documents.borrow().find_window(id);
2470 if let Some(ref window) = window {
2471 window.add_resize_event(viewport_details, size_type);
2472 return;
2473 }
2474 let mut loads = self.incomplete_loads.borrow_mut();
2475 if let Some(ref mut load) = loads.iter_mut().find(|load| load.pipeline_id == id) {
2476 load.viewport_details = viewport_details;
2477 }
2478 })
2479 }
2480
2481 fn handle_theme_change_msg(&self, theme: Theme) {
2483 for (_, document) in self.documents.borrow().iter() {
2484 document.window().handle_theme_change(theme);
2485 }
2486 }
2487
2488 fn handle_exit_fullscreen(&self, id: PipelineId, can_gc: CanGc) {
2490 let document = self.documents.borrow().find_document(id);
2491 if let Some(document) = document {
2492 let _ac = enter_realm(&*document);
2493 document.exit_fullscreen(can_gc);
2494 }
2495 }
2496
2497 fn handle_viewport(&self, id: PipelineId, rect: Rect<f32>) {
2498 let document = self.documents.borrow().find_document(id);
2499 if let Some(document) = document {
2500 document.window().set_viewport_size(rect.size);
2501 return;
2502 }
2503 let loads = self.incomplete_loads.borrow();
2504 if loads.iter().any(|load| load.pipeline_id == id) {
2505 return;
2506 }
2507 warn!("Page rect message sent to nonexistent pipeline");
2508 }
2509
2510 fn handle_new_layout(&self, new_layout_info: NewLayoutInfo, origin: MutableOrigin) {
2511 let NewLayoutInfo {
2512 parent_info,
2513 new_pipeline_id,
2514 browsing_context_id,
2515 webview_id,
2516 opener,
2517 load_data,
2518 viewport_details,
2519 theme,
2520 } = new_layout_info;
2521
2522 let url = load_data.url.clone();
2524 let new_load = InProgressLoad::new(
2525 new_pipeline_id,
2526 browsing_context_id,
2527 webview_id,
2528 parent_info,
2529 opener,
2530 viewport_details,
2531 theme,
2532 origin,
2533 load_data,
2534 );
2535 if url.as_str() == "about:blank" {
2536 self.start_page_load_about_blank(new_load);
2537 } else if url.as_str() == "about:srcdoc" {
2538 self.page_load_about_srcdoc(new_load);
2539 } else {
2540 self.pre_page_load(new_load);
2541 }
2542 }
2543
2544 fn collect_reports(&self, reports_chan: ReportsChan) {
2545 let documents = self.documents.borrow();
2546 let urls = itertools::join(documents.iter().map(|(_, d)| d.url().to_string()), ", ");
2547
2548 let mut reports = vec![];
2549 perform_memory_report(|ops| {
2550 for (_, document) in documents.iter() {
2551 document
2552 .window()
2553 .layout()
2554 .collect_reports(&mut reports, ops);
2555 }
2556
2557 let prefix = format!("url({urls})");
2558 reports.extend(self.get_cx().get_reports(prefix.clone(), ops));
2559 });
2560
2561 reports_chan.send(ProcessReports::new(reports));
2562 }
2563
2564 fn handle_set_throttled_in_containing_iframe_msg(
2566 &self,
2567 parent_pipeline_id: PipelineId,
2568 browsing_context_id: BrowsingContextId,
2569 throttled: bool,
2570 ) {
2571 let iframe = self
2572 .documents
2573 .borrow()
2574 .find_iframe(parent_pipeline_id, browsing_context_id);
2575 if let Some(iframe) = iframe {
2576 iframe.set_throttled(throttled);
2577 }
2578 }
2579
2580 fn handle_set_throttled_msg(&self, id: PipelineId, throttled: bool) {
2581 self.senders
2584 .pipeline_to_constellation_sender
2585 .send((
2586 id,
2587 ScriptToConstellationMessage::SetThrottledComplete(throttled),
2588 ))
2589 .unwrap();
2590
2591 let window = self.documents.borrow().find_window(id);
2592 match window {
2593 Some(window) => {
2594 window.set_throttled(throttled);
2595 return;
2596 },
2597 None => {
2598 let mut loads = self.incomplete_loads.borrow_mut();
2599 if let Some(ref mut load) = loads.iter_mut().find(|load| load.pipeline_id == id) {
2600 load.throttled = throttled;
2601 return;
2602 }
2603 },
2604 }
2605
2606 warn!("SetThrottled sent to nonexistent pipeline");
2607 }
2608
2609 fn handle_set_document_activity_msg(
2611 &self,
2612 id: PipelineId,
2613 activity: DocumentActivity,
2614 can_gc: CanGc,
2615 ) {
2616 debug!(
2617 "Setting activity of {} to be {:?} in {:?}.",
2618 id,
2619 activity,
2620 thread::current().name()
2621 );
2622 let document = self.documents.borrow().find_document(id);
2623 if let Some(document) = document {
2624 document.set_activity(activity, can_gc);
2625 return;
2626 }
2627 let mut loads = self.incomplete_loads.borrow_mut();
2628 if let Some(ref mut load) = loads.iter_mut().find(|load| load.pipeline_id == id) {
2629 load.activity = activity;
2630 return;
2631 }
2632 warn!("change of activity sent to nonexistent pipeline");
2633 }
2634
2635 fn handle_focus_iframe_msg(
2636 &self,
2637 parent_pipeline_id: PipelineId,
2638 browsing_context_id: BrowsingContextId,
2639 sequence: FocusSequenceNumber,
2640 can_gc: CanGc,
2641 ) {
2642 let document = self
2643 .documents
2644 .borrow()
2645 .find_document(parent_pipeline_id)
2646 .unwrap();
2647
2648 let Some(iframe_element_root) = ({
2649 let iframes = document.iframes();
2652 iframes
2653 .get(browsing_context_id)
2654 .map(|iframe| DomRoot::from_ref(iframe.element.upcast()))
2655 }) else {
2656 return;
2657 };
2658
2659 if document.get_focus_sequence() > sequence {
2660 debug!(
2661 "Disregarding the FocusIFrame message because the contained sequence number is \
2662 too old ({:?} < {:?})",
2663 sequence,
2664 document.get_focus_sequence()
2665 );
2666 return;
2667 }
2668
2669 document.request_focus(Some(&iframe_element_root), FocusInitiator::Remote, can_gc);
2670 }
2671
2672 fn handle_focus_document_msg(
2673 &self,
2674 pipeline_id: PipelineId,
2675 sequence: FocusSequenceNumber,
2676 can_gc: CanGc,
2677 ) {
2678 if let Some(doc) = self.documents.borrow().find_document(pipeline_id) {
2679 if doc.get_focus_sequence() > sequence {
2680 debug!(
2681 "Disregarding the FocusDocument message because the contained sequence number is \
2682 too old ({:?} < {:?})",
2683 sequence,
2684 doc.get_focus_sequence()
2685 );
2686 return;
2687 }
2688 doc.request_focus(None, FocusInitiator::Remote, can_gc);
2689 } else {
2690 warn!(
2691 "Couldn't find document by pipleline_id:{pipeline_id:?} when handle_focus_document_msg."
2692 );
2693 }
2694 }
2695
2696 fn handle_unfocus_msg(
2697 &self,
2698 pipeline_id: PipelineId,
2699 sequence: FocusSequenceNumber,
2700 can_gc: CanGc,
2701 ) {
2702 if let Some(doc) = self.documents.borrow().find_document(pipeline_id) {
2703 if doc.get_focus_sequence() > sequence {
2704 debug!(
2705 "Disregarding the Unfocus message because the contained sequence number is \
2706 too old ({:?} < {:?})",
2707 sequence,
2708 doc.get_focus_sequence()
2709 );
2710 return;
2711 }
2712 doc.handle_container_unfocus(can_gc);
2713 } else {
2714 warn!(
2715 "Couldn't find document by pipleline_id:{pipeline_id:?} when handle_unfocus_msg."
2716 );
2717 }
2718 }
2719
2720 fn handle_post_message_msg(
2721 &self,
2722 pipeline_id: PipelineId,
2723 source_pipeline_id: PipelineId,
2724 source_browsing_context: WebViewId,
2725 origin: Option<ImmutableOrigin>,
2726 source_origin: ImmutableOrigin,
2727 data: StructuredSerializedData,
2728 ) {
2729 let window = self.documents.borrow().find_window(pipeline_id);
2730 match window {
2731 None => warn!("postMessage after target pipeline {} closed.", pipeline_id),
2732 Some(window) => {
2733 let source = match self.remote_window_proxy(
2736 window.upcast::<GlobalScope>(),
2737 source_browsing_context,
2738 source_pipeline_id,
2739 None,
2740 ) {
2741 None => {
2742 return warn!(
2743 "postMessage after source pipeline {} closed.",
2744 source_pipeline_id,
2745 );
2746 },
2747 Some(source) => source,
2748 };
2749 window.post_message(origin, source_origin, &source, data)
2751 },
2752 }
2753 }
2754
2755 fn handle_stop_delaying_load_events_mode(&self, pipeline_id: PipelineId) {
2756 let window = self.documents.borrow().find_window(pipeline_id);
2757 if let Some(window) = window {
2758 match window.undiscarded_window_proxy() {
2759 Some(window_proxy) => window_proxy.stop_delaying_load_events_mode(),
2760 None => warn!(
2761 "Attempted to take {} of 'delaying-load-events-mode' after having been discarded.",
2762 pipeline_id
2763 ),
2764 };
2765 }
2766 }
2767
2768 fn handle_unload_document(&self, pipeline_id: PipelineId, can_gc: CanGc) {
2769 let document = self.documents.borrow().find_document(pipeline_id);
2770 if let Some(document) = document {
2771 document.unload(false, can_gc);
2772 }
2773 }
2774
2775 fn handle_update_pipeline_id(
2776 &self,
2777 parent_pipeline_id: PipelineId,
2778 browsing_context_id: BrowsingContextId,
2779 webview_id: WebViewId,
2780 new_pipeline_id: PipelineId,
2781 reason: UpdatePipelineIdReason,
2782 can_gc: CanGc,
2783 ) {
2784 let frame_element = self
2785 .documents
2786 .borrow()
2787 .find_iframe(parent_pipeline_id, browsing_context_id);
2788 if let Some(frame_element) = frame_element {
2789 frame_element.update_pipeline_id(new_pipeline_id, reason, can_gc);
2790 }
2791
2792 if let Some(window) = self.documents.borrow().find_window(new_pipeline_id) {
2793 let _ = self.local_window_proxy(
2796 &window,
2797 browsing_context_id,
2798 webview_id,
2799 Some(parent_pipeline_id),
2800 None,
2804 );
2805 }
2806 }
2807
2808 fn handle_update_history_state_msg(
2809 &self,
2810 pipeline_id: PipelineId,
2811 history_state_id: Option<HistoryStateId>,
2812 url: ServoUrl,
2813 can_gc: CanGc,
2814 ) {
2815 let window = self.documents.borrow().find_window(pipeline_id);
2816 match window {
2817 None => {
2818 warn!(
2819 "update history state after pipeline {} closed.",
2820 pipeline_id
2821 );
2822 },
2823 Some(window) => window
2824 .History()
2825 .activate_state(history_state_id, url, can_gc),
2826 }
2827 }
2828
2829 fn handle_remove_history_states(
2830 &self,
2831 pipeline_id: PipelineId,
2832 history_states: Vec<HistoryStateId>,
2833 ) {
2834 let window = self.documents.borrow().find_window(pipeline_id);
2835 match window {
2836 None => {
2837 warn!(
2838 "update history state after pipeline {} closed.",
2839 pipeline_id
2840 );
2841 },
2842 Some(window) => window.History().remove_states(history_states),
2843 }
2844 }
2845
2846 fn handle_resize_inactive_msg(&self, id: PipelineId, new_viewport_details: ViewportDetails) {
2848 let window = self.documents.borrow().find_window(id)
2849 .expect("ScriptThread: received a resize msg for a pipeline not in this script thread. This is a bug.");
2850 window.set_viewport_details(new_viewport_details);
2851 }
2852
2853 fn handle_page_headers_available(
2856 &self,
2857 id: &PipelineId,
2858 metadata: Option<Metadata>,
2859 can_gc: CanGc,
2860 ) -> Option<DomRoot<ServoParser>> {
2861 if self.closed_pipelines.borrow().contains(id) {
2862 return None;
2864 }
2865
2866 let Some(idx) = self
2867 .incomplete_loads
2868 .borrow()
2869 .iter()
2870 .position(|load| load.pipeline_id == *id)
2871 else {
2872 unreachable!("Pipeline shouldn't have finished loading.");
2873 };
2874
2875 let is_204_205 = match metadata {
2878 Some(ref metadata) => metadata.status.in_range(204..=205),
2879 _ => false,
2880 };
2881
2882 if is_204_205 {
2883 if let Some(window) = self.documents.borrow().find_window(*id) {
2885 let window_proxy = window.window_proxy();
2886 if window_proxy.parent().is_some() {
2889 window_proxy.stop_delaying_load_events_mode();
2895 }
2896 }
2897 self.senders
2898 .pipeline_to_constellation_sender
2899 .send((*id, ScriptToConstellationMessage::AbortLoadUrl))
2900 .unwrap();
2901 return None;
2902 };
2903
2904 let load = self.incomplete_loads.borrow_mut().remove(idx);
2905 metadata.map(|meta| self.load(meta, load, can_gc))
2906 }
2907
2908 fn handle_get_title_msg(&self, pipeline_id: PipelineId) {
2910 let document = match self.documents.borrow().find_document(pipeline_id) {
2911 Some(document) => document,
2912 None => return warn!("Message sent to closed pipeline {}.", pipeline_id),
2913 };
2914 document.send_title_to_embedder();
2915 }
2916
2917 fn handle_exit_pipeline_msg(
2919 &self,
2920 webview_id: WebViewId,
2921 id: PipelineId,
2922 discard_bc: DiscardBrowsingContext,
2923 can_gc: CanGc,
2924 ) {
2925 debug!("{id}: Starting pipeline exit.");
2926
2927 let document = self.documents.borrow_mut().remove(id);
2930 if let Some(document) = document {
2931 debug_assert!(
2933 !self
2934 .incomplete_loads
2935 .borrow()
2936 .iter()
2937 .any(|load| load.pipeline_id == id)
2938 );
2939
2940 if let Some(parser) = document.get_current_parser() {
2941 parser.abort(can_gc);
2942 }
2943
2944 debug!("{id}: Shutting down layout");
2945 document.window().layout_mut().exit_now();
2946
2947 debug!("{id}: Clearing animations");
2949 document.animations().clear();
2950
2951 let window = document.window();
2954 if discard_bc == DiscardBrowsingContext::Yes {
2955 window.discard_browsing_context();
2956 }
2957
2958 debug!("{id}: Clearing JavaScript runtime");
2959 window.clear_js_runtime();
2960 }
2961
2962 self.closed_pipelines.borrow_mut().insert(id);
2964
2965 debug!("{id}: Sending PipelineExited message to constellation");
2966 self.senders
2967 .pipeline_to_constellation_sender
2968 .send((id, ScriptToConstellationMessage::PipelineExited))
2969 .ok();
2970
2971 self.compositor_api
2972 .pipeline_exited(webview_id, id, PipelineExitSource::Script);
2973
2974 debug!("{id}: Finished pipeline exit");
2975 }
2976
2977 fn handle_exit_script_thread_msg(&self, can_gc: CanGc) {
2979 debug!("Exiting script thread.");
2980
2981 let mut webview_and_pipeline_ids = Vec::new();
2982 webview_and_pipeline_ids.extend(
2983 self.incomplete_loads
2984 .borrow()
2985 .iter()
2986 .next()
2987 .map(|load| (load.webview_id, load.pipeline_id)),
2988 );
2989 webview_and_pipeline_ids.extend(
2990 self.documents
2991 .borrow()
2992 .iter()
2993 .next()
2994 .map(|(pipeline_id, document)| (document.webview_id(), pipeline_id)),
2995 );
2996
2997 for (webview_id, pipeline_id) in webview_and_pipeline_ids {
2998 self.handle_exit_pipeline_msg(
2999 webview_id,
3000 pipeline_id,
3001 DiscardBrowsingContext::Yes,
3002 can_gc,
3003 );
3004 }
3005
3006 self.background_hang_monitor.unregister();
3007
3008 if opts::get().multiprocess {
3010 debug!("Exiting IPC router thread in script thread.");
3011 ROUTER.shutdown();
3012 }
3013
3014 debug!("Exited script thread.");
3015 }
3016
3017 pub(crate) fn handle_tick_all_animations_for_testing(id: PipelineId) {
3019 with_script_thread(|script_thread| {
3020 let Some(document) = script_thread.documents.borrow().find_document(id) else {
3021 warn!("Animation tick for tests for closed pipeline {id}.");
3022 return;
3023 };
3024 document.maybe_mark_animating_nodes_as_dirty();
3025 });
3026 }
3027
3028 fn handle_web_font_loaded(&self, pipeline_id: PipelineId, _success: bool) {
3030 let Some(document) = self.documents.borrow().find_document(pipeline_id) else {
3031 warn!("Web font loaded in closed pipeline {}.", pipeline_id);
3032 return;
3033 };
3034
3035 document.dirty_all_nodes();
3037 }
3038
3039 fn handle_worklet_loaded(&self, pipeline_id: PipelineId) {
3042 if let Some(document) = self.documents.borrow().find_document(pipeline_id) {
3043 document.add_restyle_reason(RestyleReason::PaintWorkletLoaded);
3044 }
3045 }
3046
3047 fn handle_storage_event(
3049 &self,
3050 pipeline_id: PipelineId,
3051 storage_type: StorageType,
3052 url: ServoUrl,
3053 key: Option<String>,
3054 old_value: Option<String>,
3055 new_value: Option<String>,
3056 ) {
3057 let window = match self.documents.borrow().find_window(pipeline_id) {
3058 None => return warn!("Storage event sent to closed pipeline {}.", pipeline_id),
3059 Some(window) => window,
3060 };
3061
3062 let storage = match storage_type {
3063 StorageType::Local => window.LocalStorage(),
3064 StorageType::Session => window.SessionStorage(),
3065 };
3066
3067 storage.queue_storage_event(url, key, old_value, new_value);
3068 }
3069
3070 fn handle_iframe_load_event(
3072 &self,
3073 parent_id: PipelineId,
3074 browsing_context_id: BrowsingContextId,
3075 child_id: PipelineId,
3076 can_gc: CanGc,
3077 ) {
3078 let iframe = self
3079 .documents
3080 .borrow()
3081 .find_iframe(parent_id, browsing_context_id);
3082 match iframe {
3083 Some(iframe) => iframe.iframe_load_event_steps(child_id, can_gc),
3084 None => warn!("Message sent to closed pipeline {}.", parent_id),
3085 }
3086 }
3087
3088 fn ask_constellation_for_browsing_context_info(
3089 &self,
3090 pipeline_id: PipelineId,
3091 ) -> Option<(BrowsingContextId, Option<PipelineId>)> {
3092 let (result_sender, result_receiver) = ipc::channel().unwrap();
3093 let msg = ScriptToConstellationMessage::GetBrowsingContextInfo(pipeline_id, result_sender);
3094 self.senders
3095 .pipeline_to_constellation_sender
3096 .send((pipeline_id, msg))
3097 .expect("Failed to send to constellation.");
3098 result_receiver
3099 .recv()
3100 .expect("Failed to get browsing context info from constellation.")
3101 }
3102
3103 fn ask_constellation_for_top_level_info(
3104 &self,
3105 sender_pipeline: PipelineId,
3106 browsing_context_id: BrowsingContextId,
3107 ) -> Option<WebViewId> {
3108 let (result_sender, result_receiver) = ipc::channel().unwrap();
3109 let msg = ScriptToConstellationMessage::GetTopForBrowsingContext(
3110 browsing_context_id,
3111 result_sender,
3112 );
3113 self.senders
3114 .pipeline_to_constellation_sender
3115 .send((sender_pipeline, msg))
3116 .expect("Failed to send to constellation.");
3117 result_receiver
3118 .recv()
3119 .expect("Failed to get top-level id from constellation.")
3120 }
3121
3122 fn remote_window_proxy(
3129 &self,
3130 global_to_clone: &GlobalScope,
3131 webview_id: WebViewId,
3132 pipeline_id: PipelineId,
3133 opener: Option<BrowsingContextId>,
3134 ) -> Option<DomRoot<WindowProxy>> {
3135 let (browsing_context_id, parent_pipeline_id) =
3136 self.ask_constellation_for_browsing_context_info(pipeline_id)?;
3137 if let Some(window_proxy) = self.window_proxies.borrow().get(&browsing_context_id) {
3138 return Some(DomRoot::from_ref(window_proxy));
3139 }
3140
3141 let parent_browsing_context = parent_pipeline_id.and_then(|parent_id| {
3142 self.remote_window_proxy(global_to_clone, webview_id, parent_id, opener)
3143 });
3144
3145 let opener_browsing_context = opener.and_then(ScriptThread::find_window_proxy);
3146
3147 let creator = CreatorBrowsingContextInfo::from(
3148 parent_browsing_context.as_deref(),
3149 opener_browsing_context.as_deref(),
3150 );
3151
3152 let window_proxy = WindowProxy::new_dissimilar_origin(
3153 global_to_clone,
3154 browsing_context_id,
3155 webview_id,
3156 parent_browsing_context.as_deref(),
3157 opener,
3158 creator,
3159 );
3160 self.window_proxies
3161 .borrow_mut()
3162 .insert(browsing_context_id, Dom::from_ref(&*window_proxy));
3163 Some(window_proxy)
3164 }
3165
3166 fn local_window_proxy(
3173 &self,
3174 window: &Window,
3175 browsing_context_id: BrowsingContextId,
3176 webview_id: WebViewId,
3177 parent_info: Option<PipelineId>,
3178 opener: Option<BrowsingContextId>,
3179 ) -> DomRoot<WindowProxy> {
3180 if let Some(window_proxy) = self.window_proxies.borrow().get(&browsing_context_id) {
3181 return DomRoot::from_ref(window_proxy);
3184 }
3185 let iframe = parent_info.and_then(|parent_id| {
3186 self.documents
3187 .borrow()
3188 .find_iframe(parent_id, browsing_context_id)
3189 });
3190 let parent_browsing_context = match (parent_info, iframe.as_ref()) {
3191 (_, Some(iframe)) => Some(iframe.owner_window().window_proxy()),
3192 (Some(parent_id), _) => {
3193 self.remote_window_proxy(window.upcast(), webview_id, parent_id, opener)
3194 },
3195 _ => None,
3196 };
3197
3198 let opener_browsing_context = opener.and_then(ScriptThread::find_window_proxy);
3199
3200 let creator = CreatorBrowsingContextInfo::from(
3201 parent_browsing_context.as_deref(),
3202 opener_browsing_context.as_deref(),
3203 );
3204
3205 let window_proxy = WindowProxy::new(
3206 window,
3207 browsing_context_id,
3208 webview_id,
3209 iframe.as_deref().map(Castable::upcast),
3210 parent_browsing_context.as_deref(),
3211 opener,
3212 creator,
3213 );
3214 self.window_proxies
3215 .borrow_mut()
3216 .insert(browsing_context_id, Dom::from_ref(&*window_proxy));
3217 window_proxy
3218 }
3219
3220 fn load(
3223 &self,
3224 metadata: Metadata,
3225 incomplete: InProgressLoad,
3226 can_gc: CanGc,
3227 ) -> DomRoot<ServoParser> {
3228 let final_url = metadata.final_url.clone();
3229 {
3230 self.senders
3231 .pipeline_to_constellation_sender
3232 .send((
3233 incomplete.pipeline_id,
3234 ScriptToConstellationMessage::SetFinalUrl(final_url.clone()),
3235 ))
3236 .unwrap();
3237 }
3238 debug!(
3239 "ScriptThread: loading {} on pipeline {:?}",
3240 incomplete.load_data.url, incomplete.pipeline_id
3241 );
3242
3243 let origin = if final_url.as_str() == "about:blank" || final_url.as_str() == "about:srcdoc"
3244 {
3245 incomplete.origin.clone()
3246 } else {
3247 MutableOrigin::new(final_url.origin())
3248 };
3249
3250 let script_to_constellation_chan = ScriptToConstellationChan {
3251 sender: self.senders.pipeline_to_constellation_sender.clone(),
3252 pipeline_id: incomplete.pipeline_id,
3253 };
3254
3255 let font_context = Arc::new(FontContext::new(
3256 self.system_font_service.clone(),
3257 self.compositor_api.clone(),
3258 self.resource_threads.clone(),
3259 ));
3260
3261 let image_cache = self
3262 .image_cache
3263 .create_new_image_cache(Some(incomplete.pipeline_id), self.compositor_api.clone());
3264
3265 let layout_config = LayoutConfig {
3266 id: incomplete.pipeline_id,
3267 webview_id: incomplete.webview_id,
3268 url: final_url.clone(),
3269 is_iframe: incomplete.parent_info.is_some(),
3270 script_chan: self.senders.constellation_sender.clone(),
3271 image_cache: image_cache.clone(),
3272 font_context: font_context.clone(),
3273 time_profiler_chan: self.senders.time_profiler_sender.clone(),
3274 compositor_api: self.compositor_api.clone(),
3275 viewport_details: incomplete.viewport_details,
3276 theme: incomplete.theme,
3277 };
3278
3279 let window = Window::new(
3281 incomplete.webview_id,
3282 self.js_runtime.clone(),
3283 self.senders.self_sender.clone(),
3284 self.layout_factory.create(layout_config),
3285 font_context,
3286 self.senders.image_cache_sender.clone(),
3287 image_cache.clone(),
3288 self.resource_threads.clone(),
3289 #[cfg(feature = "bluetooth")]
3290 self.senders.bluetooth_sender.clone(),
3291 self.senders.memory_profiler_sender.clone(),
3292 self.senders.time_profiler_sender.clone(),
3293 self.senders.devtools_server_sender.clone(),
3294 script_to_constellation_chan,
3295 self.senders.pipeline_to_embedder_sender.clone(),
3296 self.senders.constellation_sender.clone(),
3297 incomplete.pipeline_id,
3298 incomplete.parent_info,
3299 incomplete.viewport_details,
3300 origin.clone(),
3301 final_url.clone(),
3302 final_url.clone(),
3307 incomplete.navigation_start,
3308 self.webgl_chan.as_ref().map(|chan| chan.channel()),
3309 #[cfg(feature = "webxr")]
3310 self.webxr_registry.clone(),
3311 self.microtask_queue.clone(),
3312 self.compositor_api.clone(),
3313 self.unminify_js,
3314 self.unminify_css,
3315 self.local_script_source.clone(),
3316 self.user_content_manager.clone(),
3317 self.player_context.clone(),
3318 #[cfg(feature = "webgpu")]
3319 self.gpu_id_hub.clone(),
3320 incomplete.load_data.inherited_secure_context,
3321 incomplete.theme,
3322 );
3323 self.debugger_global.fire_add_debuggee(
3324 can_gc,
3325 window.upcast(),
3326 incomplete.pipeline_id,
3327 None,
3328 );
3329
3330 let _realm = enter_realm(&*window);
3331
3332 let window_proxy = self.local_window_proxy(
3334 &window,
3335 incomplete.browsing_context_id,
3336 incomplete.webview_id,
3337 incomplete.parent_info,
3338 incomplete.opener,
3339 );
3340 if window_proxy.parent().is_some() {
3341 window_proxy.stop_delaying_load_events_mode();
3346 }
3347 window.init_window_proxy(&window_proxy);
3348
3349 let last_modified = metadata.headers.as_ref().and_then(|headers| {
3350 headers.typed_get::<LastModified>().map(|tm| {
3351 let tm: SystemTime = tm.into();
3352 let local_time: DateTime<Local> = tm.into();
3353 local_time.format("%m/%d/%Y %H:%M:%S").to_string()
3354 })
3355 });
3356
3357 let loader = DocumentLoader::new_with_threads(
3358 self.resource_threads.clone(),
3359 Some(final_url.clone()),
3360 );
3361
3362 let content_type: Option<Mime> = metadata
3363 .content_type
3364 .map(Serde::into_inner)
3365 .map(Mime::from_ct);
3366
3367 let is_html_document = match content_type {
3368 Some(ref mime) if mime.type_ == APPLICATION && mime.has_suffix("xml") => {
3369 IsHTMLDocument::NonHTMLDocument
3370 },
3371
3372 Some(ref mime) if mime.matches(TEXT, XML) || mime.matches(APPLICATION, XML) => {
3373 IsHTMLDocument::NonHTMLDocument
3374 },
3375 _ => IsHTMLDocument::HTMLDocument,
3376 };
3377
3378 let referrer = metadata
3379 .referrer
3380 .as_ref()
3381 .map(|referrer| referrer.clone().into_string());
3382
3383 let is_initial_about_blank = final_url.as_str() == "about:blank";
3384
3385 let document = Document::new(
3386 &window,
3387 HasBrowsingContext::Yes,
3388 Some(final_url.clone()),
3389 origin,
3390 is_html_document,
3391 content_type,
3392 last_modified,
3393 incomplete.activity,
3394 DocumentSource::FromParser,
3395 loader,
3396 referrer,
3397 Some(metadata.status.raw_code()),
3398 incomplete.canceller,
3399 is_initial_about_blank,
3400 true,
3401 incomplete.load_data.inherited_insecure_requests_policy,
3402 incomplete.load_data.has_trustworthy_ancestor_origin,
3403 self.custom_element_reaction_stack.clone(),
3404 can_gc,
3405 );
3406
3407 let referrer_policy = metadata
3408 .headers
3409 .as_deref()
3410 .and_then(|h| h.typed_get::<ReferrerPolicyHeader>())
3411 .into();
3412 document.set_referrer_policy(referrer_policy);
3413
3414 let refresh_header = metadata.headers.as_deref().and_then(|h| h.get(REFRESH));
3415 if let Some(refresh_val) = refresh_header {
3416 document.shared_declarative_refresh_steps(refresh_val.as_bytes());
3418 }
3419
3420 document.set_ready_state(DocumentReadyState::Loading, can_gc);
3421
3422 self.documents
3423 .borrow_mut()
3424 .insert(incomplete.pipeline_id, &document);
3425
3426 window.init_document(&document);
3427
3428 if let Some(frame) = window_proxy
3431 .frame_element()
3432 .and_then(|e| e.downcast::<HTMLIFrameElement>())
3433 {
3434 let parent_pipeline = frame.global().pipeline_id();
3435 self.handle_update_pipeline_id(
3436 parent_pipeline,
3437 window_proxy.browsing_context_id(),
3438 window_proxy.webview_id(),
3439 incomplete.pipeline_id,
3440 UpdatePipelineIdReason::Navigation,
3441 can_gc,
3442 );
3443 }
3444
3445 self.senders
3446 .pipeline_to_constellation_sender
3447 .send((
3448 incomplete.pipeline_id,
3449 ScriptToConstellationMessage::ActivateDocument,
3450 ))
3451 .unwrap();
3452
3453 let incomplete_browsing_context_id: BrowsingContextId = incomplete.webview_id.into();
3455 let is_top_level_global = incomplete_browsing_context_id == incomplete.browsing_context_id;
3456 self.notify_devtools(
3457 document.Title(),
3458 final_url.clone(),
3459 is_top_level_global,
3460 (
3461 incomplete.browsing_context_id,
3462 incomplete.pipeline_id,
3463 None,
3464 incomplete.webview_id,
3465 ),
3466 );
3467
3468 document.set_https_state(metadata.https_state);
3469 document.set_navigation_start(incomplete.navigation_start);
3470
3471 if is_html_document == IsHTMLDocument::NonHTMLDocument {
3472 ServoParser::parse_xml_document(&document, None, final_url, can_gc);
3473 } else {
3474 ServoParser::parse_html_document(&document, None, final_url, can_gc);
3475 }
3476
3477 if incomplete.activity == DocumentActivity::FullyActive {
3478 window.resume(can_gc);
3479 } else {
3480 window.suspend(can_gc);
3481 }
3482
3483 if incomplete.throttled {
3484 window.set_throttled(true);
3485 }
3486
3487 document.get_current_parser().unwrap()
3488 }
3489
3490 fn notify_devtools(
3491 &self,
3492 title: DOMString,
3493 url: ServoUrl,
3494 is_top_level_global: bool,
3495 (browsing_context_id, pipeline_id, worker_id, webview_id): (
3496 BrowsingContextId,
3497 PipelineId,
3498 Option<WorkerId>,
3499 WebViewId,
3500 ),
3501 ) {
3502 if let Some(ref chan) = self.senders.devtools_server_sender {
3503 let page_info = DevtoolsPageInfo {
3504 title: String::from(title),
3505 url,
3506 is_top_level_global,
3507 };
3508 chan.send(ScriptToDevtoolsControlMsg::NewGlobal(
3509 (browsing_context_id, pipeline_id, worker_id, webview_id),
3510 self.senders.devtools_client_to_script_thread_sender.clone(),
3511 page_info.clone(),
3512 ))
3513 .unwrap();
3514
3515 let state = NavigationState::Stop(pipeline_id, page_info);
3516 let _ = chan.send(ScriptToDevtoolsControlMsg::Navigate(
3517 browsing_context_id,
3518 state,
3519 ));
3520 }
3521 }
3522
3523 fn handle_input_event(&self, pipeline_id: PipelineId, event: ConstellationInputEvent) {
3526 let Some(document) = self.documents.borrow().find_document(pipeline_id) else {
3527 warn!("Compositor event sent to closed pipeline {pipeline_id}.");
3528 return;
3529 };
3530
3531 if let InputEvent::MouseButton(mouse_button_event) = &event.event {
3544 if let MouseButton::Left = mouse_button_event.button {
3545 match mouse_button_event.action {
3546 MouseButtonAction::Up => {
3547 let pixel_dist =
3548 self.relative_mouse_down_point.get() - mouse_button_event.point;
3549 let pixel_dist =
3550 (pixel_dist.x * pixel_dist.x + pixel_dist.y * pixel_dist.y).sqrt();
3551 if pixel_dist < 10.0 * document.window().device_pixel_ratio().get() {
3552 document.event_handler().note_pending_input_event(
3554 ConstellationInputEvent {
3555 hit_test_result: event.hit_test_result.clone(),
3556 pressed_mouse_buttons: event.pressed_mouse_buttons,
3557 active_keyboard_modifiers: event.active_keyboard_modifiers,
3558 event: event.event.clone().with_webdriver_message_id(None),
3559 },
3560 );
3561 document.event_handler().note_pending_input_event(
3562 ConstellationInputEvent {
3563 hit_test_result: event.hit_test_result,
3564 pressed_mouse_buttons: event.pressed_mouse_buttons,
3565 active_keyboard_modifiers: event.active_keyboard_modifiers,
3566 event: InputEvent::MouseButton(MouseButtonEvent::new(
3567 MouseButtonAction::Click,
3568 mouse_button_event.button,
3569 mouse_button_event.point,
3570 ))
3571 .with_webdriver_message_id(event.event.webdriver_message_id()),
3572 },
3573 );
3574 return;
3575 }
3576 },
3577 MouseButtonAction::Down => {
3578 self.relative_mouse_down_point.set(mouse_button_event.point)
3579 },
3580 MouseButtonAction::Click => {},
3581 }
3582 }
3583 }
3584
3585 document.event_handler().note_pending_input_event(event);
3586 }
3587
3588 fn handle_navigate_iframe(
3590 &self,
3591 parent_pipeline_id: PipelineId,
3592 browsing_context_id: BrowsingContextId,
3593 load_data: LoadData,
3594 history_handling: NavigationHistoryBehavior,
3595 can_gc: CanGc,
3596 ) {
3597 let iframe = self
3598 .documents
3599 .borrow()
3600 .find_iframe(parent_pipeline_id, browsing_context_id);
3601 if let Some(iframe) = iframe {
3602 iframe.navigate_or_reload_child_browsing_context(load_data, history_handling, can_gc);
3603 }
3604 }
3605
3606 pub(crate) fn eval_js_url(global_scope: &GlobalScope, load_data: &mut LoadData, can_gc: CanGc) {
3609 let encoded = &load_data.url[Position::AfterScheme..][1..];
3614
3615 let script_source = percent_decode(encoded.as_bytes()).decode_utf8_lossy();
3617
3618 let _ac = enter_realm(global_scope);
3620 rooted!(in(*GlobalScope::get_cx()) let mut jsval = UndefinedValue());
3621 _ = global_scope.evaluate_js_on_global_with_result(
3622 &script_source,
3623 jsval.handle_mut(),
3624 ScriptFetchOptions::default_classic_script(global_scope),
3625 global_scope.api_base_url(),
3626 can_gc,
3627 Some(IntroductionType::JAVASCRIPT_URL),
3628 );
3629
3630 load_data.js_eval_result = if jsval.get().is_string() {
3631 let strval = DOMString::safe_from_jsval(
3632 GlobalScope::get_cx(),
3633 jsval.handle(),
3634 StringificationBehavior::Empty,
3635 );
3636 match strval {
3637 Ok(ConversionResult::Success(s)) => {
3638 Some(JsEvalResult::Ok(String::from(s).as_bytes().to_vec()))
3639 },
3640 _ => None,
3641 }
3642 } else {
3643 Some(JsEvalResult::NoContent)
3644 };
3645
3646 load_data.url = ServoUrl::parse("about:blank").unwrap();
3647 }
3648
3649 fn pre_page_load(&self, mut incomplete: InProgressLoad) {
3652 let context = ParserContext::new(incomplete.pipeline_id, incomplete.load_data.url.clone());
3653 self.incomplete_parser_contexts
3654 .0
3655 .borrow_mut()
3656 .push((incomplete.pipeline_id, context));
3657
3658 let request_builder = incomplete.request_builder();
3659 incomplete.canceller = FetchCanceller::new(
3660 request_builder.id,
3661 self.resource_threads.core_thread.clone(),
3662 );
3663 NavigationListener::new(request_builder, self.senders.self_sender.clone())
3664 .initiate_fetch(&self.resource_threads.core_thread, None);
3665 self.incomplete_loads.borrow_mut().push(incomplete);
3666 }
3667
3668 fn handle_navigation_response(&self, pipeline_id: PipelineId, message: FetchResponseMsg) {
3669 if let Some(metadata) = NavigationListener::http_redirect_metadata(&message) {
3670 self.handle_navigation_redirect(pipeline_id, metadata);
3671 return;
3672 };
3673
3674 match message {
3675 FetchResponseMsg::ProcessResponse(request_id, metadata) => {
3676 self.handle_fetch_metadata(pipeline_id, request_id, metadata)
3677 },
3678 FetchResponseMsg::ProcessResponseChunk(request_id, chunk) => {
3679 self.handle_fetch_chunk(pipeline_id, request_id, chunk)
3680 },
3681 FetchResponseMsg::ProcessResponseEOF(request_id, eof) => {
3682 self.handle_fetch_eof(pipeline_id, request_id, eof)
3683 },
3684 FetchResponseMsg::ProcessCspViolations(request_id, violations) => {
3685 self.handle_csp_violations(pipeline_id, request_id, violations)
3686 },
3687 FetchResponseMsg::ProcessRequestBody(..) | FetchResponseMsg::ProcessRequestEOF(..) => {
3688 },
3689 }
3690 }
3691
3692 fn handle_fetch_metadata(
3693 &self,
3694 id: PipelineId,
3695 request_id: RequestId,
3696 fetch_metadata: Result<FetchMetadata, NetworkError>,
3697 ) {
3698 match fetch_metadata {
3699 Ok(_) => (),
3700 Err(NetworkError::Crash(..)) => (),
3701 Err(ref e) => {
3702 warn!("Network error: {:?}", e);
3703 },
3704 };
3705
3706 let mut incomplete_parser_contexts = self.incomplete_parser_contexts.0.borrow_mut();
3707 let parser = incomplete_parser_contexts
3708 .iter_mut()
3709 .find(|&&mut (pipeline_id, _)| pipeline_id == id);
3710 if let Some(&mut (_, ref mut ctxt)) = parser {
3711 ctxt.process_response(request_id, fetch_metadata);
3712 }
3713 }
3714
3715 fn handle_fetch_chunk(&self, pipeline_id: PipelineId, request_id: RequestId, chunk: Vec<u8>) {
3716 let mut incomplete_parser_contexts = self.incomplete_parser_contexts.0.borrow_mut();
3717 let parser = incomplete_parser_contexts
3718 .iter_mut()
3719 .find(|&&mut (parser_pipeline_id, _)| parser_pipeline_id == pipeline_id);
3720 if let Some(&mut (_, ref mut ctxt)) = parser {
3721 ctxt.process_response_chunk(request_id, chunk);
3722 }
3723 }
3724
3725 fn handle_fetch_eof(
3726 &self,
3727 id: PipelineId,
3728 request_id: RequestId,
3729 eof: Result<ResourceFetchTiming, NetworkError>,
3730 ) {
3731 let idx = self
3732 .incomplete_parser_contexts
3733 .0
3734 .borrow()
3735 .iter()
3736 .position(|&(pipeline_id, _)| pipeline_id == id);
3737
3738 if let Some(idx) = idx {
3739 let (_, mut ctxt) = self.incomplete_parser_contexts.0.borrow_mut().remove(idx);
3740 ctxt.process_response_eof(request_id, eof);
3741 }
3742 }
3743
3744 fn handle_csp_violations(&self, id: PipelineId, _: RequestId, violations: Vec<Violation>) {
3745 if let Some(global) = self.documents.borrow().find_global(id) {
3746 global.report_csp_violations(violations, None, None);
3748 }
3749 }
3750
3751 fn handle_navigation_redirect(&self, id: PipelineId, metadata: &Metadata) {
3752 assert!(metadata.location_url.is_some());
3756
3757 let mut incomplete_loads = self.incomplete_loads.borrow_mut();
3758 let Some(incomplete_load) = incomplete_loads
3759 .iter_mut()
3760 .find(|incomplete_load| incomplete_load.pipeline_id == id)
3761 else {
3762 return;
3763 };
3764
3765 incomplete_load.url_list.push(metadata.final_url.clone());
3768
3769 let mut request_builder = incomplete_load.request_builder();
3770 request_builder.referrer = metadata
3771 .referrer
3772 .clone()
3773 .map(Referrer::ReferrerUrl)
3774 .unwrap_or(Referrer::NoReferrer);
3775 request_builder.referrer_policy = metadata.referrer_policy;
3776
3777 let headers = metadata
3778 .headers
3779 .as_ref()
3780 .map(|headers| headers.clone().into_inner())
3781 .unwrap_or_default();
3782
3783 let response_init = Some(ResponseInit {
3784 url: metadata.final_url.clone(),
3785 location_url: metadata.location_url.clone(),
3786 headers,
3787 referrer: metadata.referrer.clone(),
3788 status_code: metadata
3789 .status
3790 .try_code()
3791 .map(|code| code.as_u16())
3792 .unwrap_or(200),
3793 });
3794
3795 incomplete_load.canceller = FetchCanceller::new(
3796 request_builder.id,
3797 self.resource_threads.core_thread.clone(),
3798 );
3799 NavigationListener::new(request_builder, self.senders.self_sender.clone())
3800 .initiate_fetch(&self.resource_threads.core_thread, response_init);
3801 }
3802
3803 fn start_page_load_about_blank(&self, mut incomplete: InProgressLoad) {
3806 let id = incomplete.pipeline_id;
3807
3808 let url = ServoUrl::parse("about:blank").unwrap();
3809 let mut context = ParserContext::new(id, url.clone());
3810
3811 let mut meta = Metadata::default(url);
3812 meta.set_content_type(Some(&mime::TEXT_HTML));
3813 meta.set_referrer_policy(incomplete.load_data.referrer_policy);
3814
3815 let chunk = match incomplete.load_data.js_eval_result {
3818 Some(JsEvalResult::Ok(ref mut content)) => std::mem::take(content),
3819 Some(JsEvalResult::NoContent) => {
3820 meta.status = http::StatusCode::NO_CONTENT.into();
3821 vec![]
3822 },
3823 None => vec![],
3824 };
3825
3826 let policy_container = incomplete.load_data.policy_container.clone();
3827 self.incomplete_loads.borrow_mut().push(incomplete);
3828
3829 let dummy_request_id = RequestId::default();
3830 context.process_response(dummy_request_id, Ok(FetchMetadata::Unfiltered(meta)));
3831 context.set_policy_container(policy_container.as_ref());
3832 context.process_response_chunk(dummy_request_id, chunk);
3833 context.process_response_eof(
3834 dummy_request_id,
3835 Ok(ResourceFetchTiming::new(ResourceTimingType::None)),
3836 );
3837 }
3838
3839 fn page_load_about_srcdoc(&self, mut incomplete: InProgressLoad) {
3841 let id = incomplete.pipeline_id;
3842
3843 let url = ServoUrl::parse("about:srcdoc").unwrap();
3844 let mut meta = Metadata::default(url.clone());
3845 meta.set_content_type(Some(&mime::TEXT_HTML));
3846 meta.set_referrer_policy(incomplete.load_data.referrer_policy);
3847
3848 let srcdoc = std::mem::take(&mut incomplete.load_data.srcdoc);
3849 let chunk = srcdoc.into_bytes();
3850
3851 let policy_container = incomplete.load_data.policy_container.clone();
3852 self.incomplete_loads.borrow_mut().push(incomplete);
3853
3854 let mut context = ParserContext::new(id, url);
3855 let dummy_request_id = RequestId::default();
3856
3857 context.process_response(dummy_request_id, Ok(FetchMetadata::Unfiltered(meta)));
3858 context.set_policy_container(policy_container.as_ref());
3859 context.process_response_chunk(dummy_request_id, chunk);
3860 context.process_response_eof(
3861 dummy_request_id,
3862 Ok(ResourceFetchTiming::new(ResourceTimingType::None)),
3863 );
3864 }
3865
3866 fn handle_css_error_reporting(
3867 &self,
3868 pipeline_id: PipelineId,
3869 filename: String,
3870 line: u32,
3871 column: u32,
3872 msg: String,
3873 ) {
3874 let sender = match self.senders.devtools_server_sender {
3875 Some(ref sender) => sender,
3876 None => return,
3877 };
3878
3879 if let Some(global) = self.documents.borrow().find_global(pipeline_id) {
3880 if global.live_devtools_updates() {
3881 let css_error = CSSError {
3882 filename,
3883 line,
3884 column,
3885 msg,
3886 };
3887 let message = ScriptToDevtoolsControlMsg::ReportCSSError(pipeline_id, css_error);
3888 sender.send(message).unwrap();
3889 }
3890 }
3891 }
3892
3893 fn handle_reload(&self, pipeline_id: PipelineId, can_gc: CanGc) {
3894 let window = self.documents.borrow().find_window(pipeline_id);
3895 if let Some(window) = window {
3896 window.Location().reload_without_origin_check(can_gc);
3897 }
3898 }
3899
3900 fn handle_paint_metric(
3901 &self,
3902 pipeline_id: PipelineId,
3903 metric_type: ProgressiveWebMetricType,
3904 metric_value: CrossProcessInstant,
3905 first_reflow: bool,
3906 can_gc: CanGc,
3907 ) {
3908 match self.documents.borrow().find_document(pipeline_id) {
3909 Some(document) => {
3910 document.handle_paint_metric(metric_type, metric_value, first_reflow, can_gc)
3911 },
3912 None => warn!(
3913 "Received paint metric ({metric_type:?}) for unknown document: {pipeline_id:?}"
3914 ),
3915 }
3916 }
3917
3918 fn handle_media_session_action(
3919 &self,
3920 pipeline_id: PipelineId,
3921 action: MediaSessionActionType,
3922 can_gc: CanGc,
3923 ) {
3924 if let Some(window) = self.documents.borrow().find_window(pipeline_id) {
3925 let media_session = window.Navigator().MediaSession();
3926 media_session.handle_action(action, can_gc);
3927 } else {
3928 warn!("No MediaSession for this pipeline ID");
3929 };
3930 }
3931
3932 pub(crate) fn enqueue_microtask(job: Microtask) {
3933 with_script_thread(|script_thread| {
3934 script_thread
3935 .microtask_queue
3936 .enqueue(job, script_thread.get_cx());
3937 });
3938 }
3939
3940 fn perform_a_microtask_checkpoint(&self, can_gc: CanGc) {
3941 if self.can_continue_running_inner() {
3943 let globals = self
3944 .documents
3945 .borrow()
3946 .iter()
3947 .map(|(_id, document)| DomRoot::from_ref(document.window().upcast()))
3948 .collect();
3949
3950 self.microtask_queue.checkpoint(
3951 self.get_cx(),
3952 |id| self.documents.borrow().find_global(id),
3953 globals,
3954 can_gc,
3955 )
3956 }
3957 }
3958
3959 fn handle_evaluate_javascript(
3960 &self,
3961 pipeline_id: PipelineId,
3962 evaluation_id: JavaScriptEvaluationId,
3963 script: String,
3964 can_gc: CanGc,
3965 ) {
3966 let Some(window) = self.documents.borrow().find_window(pipeline_id) else {
3967 let _ = self.senders.pipeline_to_constellation_sender.send((
3968 pipeline_id,
3969 ScriptToConstellationMessage::FinishJavaScriptEvaluation(
3970 evaluation_id,
3971 Err(JavaScriptEvaluationError::WebViewNotReady),
3972 ),
3973 ));
3974 return;
3975 };
3976
3977 let global_scope = window.as_global_scope();
3978 let realm = enter_realm(global_scope);
3979 let context = window.get_cx();
3980
3981 rooted!(in(*context) let mut return_value = UndefinedValue());
3982 if let Err(err) = global_scope.evaluate_js_on_global_with_result(
3983 &script,
3984 return_value.handle_mut(),
3985 ScriptFetchOptions::default_classic_script(global_scope),
3986 global_scope.api_base_url(),
3987 can_gc,
3988 None, ) {
3990 _ = self.senders.pipeline_to_constellation_sender.send((
3991 pipeline_id,
3992 ScriptToConstellationMessage::FinishJavaScriptEvaluation(evaluation_id, Err(err)),
3993 ));
3994 return;
3995 };
3996
3997 let result = jsval_to_webdriver(
3998 context,
3999 global_scope,
4000 return_value.handle(),
4001 (&realm).into(),
4002 can_gc,
4003 )
4004 .map_err(|_| JavaScriptEvaluationError::SerializationError);
4005
4006 let _ = self.senders.pipeline_to_constellation_sender.send((
4007 pipeline_id,
4008 ScriptToConstellationMessage::FinishJavaScriptEvaluation(evaluation_id, result),
4009 ));
4010 }
4011
4012 fn handle_refresh_cursor(&self, pipeline_id: PipelineId) {
4013 let Some(document) = self.documents.borrow().find_document(pipeline_id) else {
4014 return;
4015 };
4016 document.event_handler().handle_refresh_cursor();
4017 }
4018
4019 pub(crate) fn is_servo_privileged(url: ServoUrl) -> bool {
4020 with_script_thread(|script_thread| script_thread.privileged_urls.contains(&url))
4021 }
4022}
4023
4024impl Drop for ScriptThread {
4025 fn drop(&mut self) {
4026 SCRIPT_THREAD_ROOT.with(|root| {
4027 root.set(None);
4028 });
4029 }
4030}