Replace uses of SCRIPT_THREAD_ROOT with accessor helpers. (#34036)

Signed-off-by: Josh Matthews <josh@joshmatthews.net>
This commit is contained in:
Josh Matthews 2024-10-28 12:28:24 -04:00 committed by GitHub
parent 1d6ede7b48
commit 216296840a
No known key found for this signature in database
GPG key ID: B5690EEEBB952194

View file

@ -170,18 +170,28 @@ pub type ImageCacheMsg = (PipelineId, PendingImageResponse);
thread_local!(static SCRIPT_THREAD_ROOT: Cell<Option<*const ScriptThread>> = const { Cell::new(None) }); thread_local!(static SCRIPT_THREAD_ROOT: Cell<Option<*const ScriptThread>> = const { Cell::new(None) });
fn with_optional_script_thread<R>(f: impl FnOnce(Option<&ScriptThread>) -> R) -> R {
SCRIPT_THREAD_ROOT.with(|root| {
f(root
.get()
.and_then(|script_thread| unsafe { script_thread.as_ref() }))
})
}
fn with_script_thread<R: Default>(f: impl FnOnce(&ScriptThread) -> R) -> R {
with_optional_script_thread(|script_thread| script_thread.map(f).unwrap_or_default())
}
/// # Safety /// # Safety
/// ///
/// The `JSTracer` argument must point to a valid `JSTracer` in memory. In addition, /// The `JSTracer` argument must point to a valid `JSTracer` in memory. In addition,
/// implementors of this method must ensure that all active objects are properly traced /// implementors of this method must ensure that all active objects are properly traced
/// or else the garbage collector may end up collecting objects that are still reachable. /// or else the garbage collector may end up collecting objects that are still reachable.
pub unsafe fn trace_thread(tr: *mut JSTracer) { pub unsafe fn trace_thread(tr: *mut JSTracer) {
SCRIPT_THREAD_ROOT.with(|root| { with_script_thread(|script_thread| {
if let Some(script_thread) = root.get() {
debug!("tracing fields of ScriptThread"); debug!("tracing fields of ScriptThread");
(*script_thread).trace(tr); script_thread.trace(tr);
} })
});
} }
/// A document load that is in the process of fetching the requested resource. Contains /// A document load that is in the process of fetching the requested resource. Contains
@ -863,50 +873,39 @@ impl ScriptThreadFactory for ScriptThread {
impl ScriptThread { impl ScriptThread {
pub fn note_rendering_opportunity(pipeline_id: PipelineId) { pub fn note_rendering_opportunity(pipeline_id: PipelineId) {
SCRIPT_THREAD_ROOT.with(|root| { with_script_thread(|script_thread| {
let script_thread = unsafe { &*root.get().unwrap() };
script_thread.rendering_opportunity(pipeline_id); script_thread.rendering_opportunity(pipeline_id);
}) })
} }
pub fn runtime_handle() -> ParentRuntime { pub fn runtime_handle() -> ParentRuntime {
SCRIPT_THREAD_ROOT.with(|root| { with_optional_script_thread(|script_thread| {
let script_thread = unsafe { &*root.get().unwrap() }; script_thread.unwrap().js_runtime.prepare_for_new_child()
script_thread.js_runtime.prepare_for_new_child()
}) })
} }
pub fn can_continue_running() -> bool { pub fn can_continue_running() -> bool {
SCRIPT_THREAD_ROOT.with(|root| { with_script_thread(|script_thread| script_thread.can_continue_running_inner())
let script_thread = unsafe { &*root.get().unwrap() };
script_thread.can_continue_running_inner()
})
} }
pub fn prepare_for_shutdown() { pub fn prepare_for_shutdown() {
SCRIPT_THREAD_ROOT.with(|root| { with_script_thread(|script_thread| {
let script_thread = unsafe { &*root.get().unwrap() };
script_thread.prepare_for_shutdown_inner(); script_thread.prepare_for_shutdown_inner();
}) })
} }
pub fn set_mutation_observer_microtask_queued(value: bool) { pub fn set_mutation_observer_microtask_queued(value: bool) {
SCRIPT_THREAD_ROOT.with(|root| { with_script_thread(|script_thread| {
let script_thread = unsafe { &*root.get().unwrap() };
script_thread.mutation_observer_microtask_queued.set(value); script_thread.mutation_observer_microtask_queued.set(value);
}) })
} }
pub fn is_mutation_observer_microtask_queued() -> bool { pub fn is_mutation_observer_microtask_queued() -> bool {
SCRIPT_THREAD_ROOT.with(|root| { with_script_thread(|script_thread| script_thread.mutation_observer_microtask_queued.get())
let script_thread = unsafe { &*root.get().unwrap() };
script_thread.mutation_observer_microtask_queued.get()
})
} }
pub fn add_mutation_observer(observer: &MutationObserver) { pub fn add_mutation_observer(observer: &MutationObserver) {
SCRIPT_THREAD_ROOT.with(|root| { with_script_thread(|script_thread| {
let script_thread = unsafe { &*root.get().unwrap() };
script_thread script_thread
.mutation_observers .mutation_observers
.borrow_mut() .borrow_mut()
@ -915,8 +914,7 @@ impl ScriptThread {
} }
pub fn get_mutation_observers() -> Vec<DomRoot<MutationObserver>> { pub fn get_mutation_observers() -> Vec<DomRoot<MutationObserver>> {
SCRIPT_THREAD_ROOT.with(|root| { with_script_thread(|script_thread| {
let script_thread = unsafe { &*root.get().unwrap() };
script_thread script_thread
.mutation_observers .mutation_observers
.borrow() .borrow()
@ -927,14 +925,11 @@ impl ScriptThread {
} }
pub fn mark_document_with_no_blocked_loads(doc: &Document) { pub fn mark_document_with_no_blocked_loads(doc: &Document) {
SCRIPT_THREAD_ROOT.with(|root| { with_script_thread(|script_thread| {
if let Some(script_thread) = root.get() {
let script_thread = unsafe { &*script_thread };
script_thread script_thread
.docs_with_no_blocking_loads .docs_with_no_blocking_loads
.borrow_mut() .borrow_mut()
.insert(Dom::from_ref(doc)); .insert(Dom::from_ref(doc));
}
}) })
} }
@ -943,8 +938,7 @@ impl ScriptThread {
metadata: Option<Metadata>, metadata: Option<Metadata>,
can_gc: CanGc, can_gc: CanGc,
) -> Option<DomRoot<ServoParser>> { ) -> Option<DomRoot<ServoParser>> {
SCRIPT_THREAD_ROOT.with(|root| { with_script_thread(|script_thread| {
let script_thread = unsafe { &*root.get().unwrap() };
script_thread.handle_page_headers_available(id, metadata, can_gc) script_thread.handle_page_headers_available(id, metadata, can_gc)
}) })
} }
@ -953,29 +947,21 @@ impl ScriptThread {
/// in the queue for this window event-loop. /// in the queue for this window event-loop.
/// Returns a boolean indicating whether further events should be processed. /// Returns a boolean indicating whether further events should be processed.
pub fn process_event(msg: CommonScriptMsg) -> bool { pub fn process_event(msg: CommonScriptMsg) -> bool {
SCRIPT_THREAD_ROOT.with(|root| { with_script_thread(|script_thread| {
if let Some(script_thread) = root.get() {
let script_thread = unsafe { &*script_thread };
if !script_thread.can_continue_running_inner() { if !script_thread.can_continue_running_inner() {
return false; return false;
} else { }
script_thread.handle_msg_from_script(MainThreadScriptMsg::Common(msg)); script_thread.handle_msg_from_script(MainThreadScriptMsg::Common(msg));
return true; true
}
}
false
}) })
} }
// https://html.spec.whatwg.org/multipage/#await-a-stable-state // https://html.spec.whatwg.org/multipage/#await-a-stable-state
pub fn await_stable_state(task: Microtask) { pub fn await_stable_state(task: Microtask) {
SCRIPT_THREAD_ROOT.with(|root| { with_script_thread(|script_thread| {
if let Some(script_thread) = root.get() {
let script_thread = unsafe { &*script_thread };
script_thread script_thread
.microtask_queue .microtask_queue
.enqueue(task, script_thread.get_cx()); .enqueue(task, script_thread.get_cx());
}
}); });
} }
@ -1006,12 +992,7 @@ impl ScriptThread {
mut load_data: LoadData, mut load_data: LoadData,
replace: HistoryEntryReplacement, replace: HistoryEntryReplacement,
) { ) {
SCRIPT_THREAD_ROOT.with(|root| { with_script_thread(|script_thread| {
let script_thread = match root.get() {
None => return,
Some(script) => script,
};
let script_thread = unsafe { &*script_thread };
let is_javascript = load_data.url.scheme() == "javascript"; let is_javascript = load_data.url.scheme() == "javascript";
// If resource is a request whose url's scheme is "javascript" // If resource is a request whose url's scheme is "javascript"
// https://html.spec.whatwg.org/multipage/#javascript-protocol // https://html.spec.whatwg.org/multipage/#javascript-protocol
@ -1042,7 +1023,8 @@ impl ScriptThread {
} else { } else {
if let Some(ref sender) = script_thread.devtools_chan { if let Some(ref sender) = script_thread.devtools_chan {
let _ = sender.send(ScriptToDevtoolsControlMsg::Navigate( let _ = sender.send(ScriptToDevtoolsControlMsg::Navigate(
browsing_context, NavigationState::Start(load_data.url.clone()) browsing_context,
NavigationState::Start(load_data.url.clone()),
)); ));
} }
@ -1055,9 +1037,7 @@ impl ScriptThread {
} }
pub fn process_attach_layout(new_layout_info: NewLayoutInfo, origin: MutableOrigin) { pub fn process_attach_layout(new_layout_info: NewLayoutInfo, origin: MutableOrigin) {
SCRIPT_THREAD_ROOT.with(|root| { with_script_thread(|script_thread| {
if let Some(script_thread) = root.get() {
let script_thread = unsafe { &*script_thread };
let pipeline_id = Some(new_layout_info.new_pipeline_id); let pipeline_id = Some(new_layout_info.new_pipeline_id);
script_thread.profile_event( script_thread.profile_event(
ScriptThreadEventCategory::AttachLayout, ScriptThreadEventCategory::AttachLayout,
@ -1066,7 +1046,6 @@ impl ScriptThread {
script_thread.handle_new_layout(new_layout_info, origin); script_thread.handle_new_layout(new_layout_info, origin);
}, },
) )
}
}); });
} }
@ -1074,46 +1053,27 @@ impl ScriptThread {
sender_pipeline: PipelineId, sender_pipeline: PipelineId,
browsing_context_id: BrowsingContextId, browsing_context_id: BrowsingContextId,
) -> Option<TopLevelBrowsingContextId> { ) -> Option<TopLevelBrowsingContextId> {
SCRIPT_THREAD_ROOT.with(|root| { with_script_thread(|script_thread| {
root.get().and_then(|script_thread| { script_thread.ask_constellation_for_top_level_info(sender_pipeline, browsing_context_id)
let script_thread = unsafe { &*script_thread };
script_thread
.ask_constellation_for_top_level_info(sender_pipeline, browsing_context_id)
})
}) })
} }
pub fn find_document(id: PipelineId) -> Option<DomRoot<Document>> { pub fn find_document(id: PipelineId) -> Option<DomRoot<Document>> {
SCRIPT_THREAD_ROOT.with(|root| { with_script_thread(|script_thread| script_thread.documents.borrow().find_document(id))
root.get().and_then(|script_thread| {
let script_thread = unsafe { &*script_thread };
script_thread.documents.borrow().find_document(id)
})
})
} }
pub fn set_user_interacting(interacting: bool) { pub fn set_user_interacting(interacting: bool) {
SCRIPT_THREAD_ROOT.with(|root| { with_script_thread(|script_thread| {
if let Some(script_thread) = root.get() {
let script_thread = unsafe { &*script_thread };
script_thread.is_user_interacting.set(interacting); script_thread.is_user_interacting.set(interacting);
}
}); });
} }
pub fn is_user_interacting() -> bool { pub fn is_user_interacting() -> bool {
SCRIPT_THREAD_ROOT.with(|root| { with_script_thread(|script_thread| script_thread.is_user_interacting.get())
root.get().is_some_and(|script_thread| {
let script_thread = unsafe { &*script_thread };
script_thread.is_user_interacting.get()
})
})
} }
pub fn get_fully_active_document_ids() -> HashSet<PipelineId> { pub fn get_fully_active_document_ids() -> HashSet<PipelineId> {
SCRIPT_THREAD_ROOT.with(|root| { with_script_thread(|script_thread| {
root.get().map_or(HashSet::new(), |script_thread| {
let script_thread = unsafe { &*script_thread };
script_thread script_thread
.documents .documents
.borrow() .borrow()
@ -1130,26 +1090,20 @@ impl ScriptThread {
set set
}) })
}) })
})
} }
pub fn find_window_proxy(id: BrowsingContextId) -> Option<DomRoot<WindowProxy>> { pub fn find_window_proxy(id: BrowsingContextId) -> Option<DomRoot<WindowProxy>> {
SCRIPT_THREAD_ROOT.with(|root| { with_script_thread(|script_thread| {
root.get().and_then(|script_thread| {
let script_thread = unsafe { &*script_thread };
script_thread script_thread
.window_proxies .window_proxies
.borrow() .borrow()
.get(&id) .get(&id)
.map(|context| DomRoot::from_ref(&**context)) .map(|context| DomRoot::from_ref(&**context))
}) })
})
} }
pub fn find_window_proxy_by_name(name: &DOMString) -> Option<DomRoot<WindowProxy>> { pub fn find_window_proxy_by_name(name: &DOMString) -> Option<DomRoot<WindowProxy>> {
SCRIPT_THREAD_ROOT.with(|root| { with_script_thread(|script_thread| {
root.get().and_then(|script_thread| {
let script_thread = unsafe { &*script_thread };
for (_, proxy) in script_thread.window_proxies.borrow().iter() { for (_, proxy) in script_thread.window_proxies.borrow().iter() {
if proxy.get_name() == *name { if proxy.get_name() == *name {
return Some(DomRoot::from_ref(&**proxy)); return Some(DomRoot::from_ref(&**proxy));
@ -1157,12 +1111,11 @@ impl ScriptThread {
} }
None None
}) })
})
} }
pub fn worklet_thread_pool() -> Rc<WorkletThreadPool> { pub fn worklet_thread_pool() -> Rc<WorkletThreadPool> {
SCRIPT_THREAD_ROOT.with(|root| { with_optional_script_thread(|script_thread| {
let script_thread = unsafe { &*root.get().unwrap() }; let script_thread = script_thread.unwrap();
script_thread script_thread
.worklet_thread_pool .worklet_thread_pool
.borrow_mut() .borrow_mut()
@ -1205,24 +1158,18 @@ impl ScriptThread {
} }
pub fn push_new_element_queue() { pub fn push_new_element_queue() {
SCRIPT_THREAD_ROOT.with(|root| { with_script_thread(|script_thread| {
if let Some(script_thread) = root.get() {
let script_thread = unsafe { &*script_thread };
script_thread script_thread
.custom_element_reaction_stack .custom_element_reaction_stack
.push_new_element_queue(); .push_new_element_queue();
}
}) })
} }
pub fn pop_current_element_queue(can_gc: CanGc) { pub fn pop_current_element_queue(can_gc: CanGc) {
SCRIPT_THREAD_ROOT.with(|root| { with_script_thread(|script_thread| {
if let Some(script_thread) = root.get() {
let script_thread = unsafe { &*script_thread };
script_thread script_thread
.custom_element_reaction_stack .custom_element_reaction_stack
.pop_current_element_queue(can_gc); .pop_current_element_queue(can_gc);
}
}) })
} }
@ -1231,55 +1178,37 @@ impl ScriptThread {
reaction: CallbackReaction, reaction: CallbackReaction,
definition: Option<Rc<CustomElementDefinition>>, definition: Option<Rc<CustomElementDefinition>>,
) { ) {
SCRIPT_THREAD_ROOT.with(|root| { with_script_thread(|script_thread| {
if let Some(script_thread) = root.get() {
let script_thread = unsafe { &*script_thread };
script_thread script_thread
.custom_element_reaction_stack .custom_element_reaction_stack
.enqueue_callback_reaction(element, reaction, definition); .enqueue_callback_reaction(element, reaction, definition);
}
}) })
} }
pub fn enqueue_upgrade_reaction(element: &Element, definition: Rc<CustomElementDefinition>) { pub fn enqueue_upgrade_reaction(element: &Element, definition: Rc<CustomElementDefinition>) {
SCRIPT_THREAD_ROOT.with(|root| { with_script_thread(|script_thread| {
if let Some(script_thread) = root.get() {
let script_thread = unsafe { &*script_thread };
script_thread script_thread
.custom_element_reaction_stack .custom_element_reaction_stack
.enqueue_upgrade_reaction(element, definition); .enqueue_upgrade_reaction(element, definition);
}
}) })
} }
pub fn invoke_backup_element_queue(can_gc: CanGc) { pub fn invoke_backup_element_queue(can_gc: CanGc) {
SCRIPT_THREAD_ROOT.with(|root| { with_script_thread(|script_thread| {
if let Some(script_thread) = root.get() {
let script_thread = unsafe { &*script_thread };
script_thread script_thread
.custom_element_reaction_stack .custom_element_reaction_stack
.invoke_backup_element_queue(can_gc); .invoke_backup_element_queue(can_gc);
}
}) })
} }
pub fn save_node_id(node_id: String) { pub fn save_node_id(node_id: String) {
SCRIPT_THREAD_ROOT.with(|root| { with_script_thread(|script_thread| {
if let Some(script_thread) = root.get() {
let script_thread = unsafe { &*script_thread };
script_thread.node_ids.borrow_mut().insert(node_id); script_thread.node_ids.borrow_mut().insert(node_id);
}
}) })
} }
pub fn has_node_id(node_id: &str) -> bool { pub fn has_node_id(node_id: &str) -> bool {
SCRIPT_THREAD_ROOT.with(|root| match root.get() { with_script_thread(|script_thread| script_thread.node_ids.borrow().contains(node_id))
Some(script_thread) => {
let script_thread = unsafe { &*script_thread };
script_thread.node_ids.borrow().contains(node_id)
},
None => false,
})
} }
/// Creates a new script thread. /// Creates a new script thread.
@ -1790,11 +1719,8 @@ impl ScriptThread {
task!(update_the_rendering: move || { task!(update_the_rendering: move || {
// Note: spec says to queue a task using the navigable's active window, // Note: spec says to queue a task using the navigable's active window,
// but then updates the rendering for all docs in the same event-loop. // but then updates the rendering for all docs in the same event-loop.
SCRIPT_THREAD_ROOT.with(|root| { with_script_thread(|script_thread| {
if let Some(script_thread) = root.get() {
let script_thread = unsafe {&*script_thread};
script_thread.update_the_rendering(CanGc::note()); script_thread.update_the_rendering(CanGc::note());
}
}) })
}), }),
&canceller, &canceller,
@ -3428,8 +3354,7 @@ impl ScriptThread {
/// Handles animation tick requested during testing. /// Handles animation tick requested during testing.
pub fn handle_tick_all_animations_for_testing(id: PipelineId) { pub fn handle_tick_all_animations_for_testing(id: PipelineId) {
SCRIPT_THREAD_ROOT.with(|root| { with_script_thread(|script_thread| {
let script_thread = unsafe { &*root.get().unwrap() };
let Some(document) = script_thread.documents.borrow().find_document(id) else { let Some(document) = script_thread.documents.borrow().find_document(id) else {
warn!("Animation tick for tests for closed pipeline {id}."); warn!("Animation tick for tests for closed pipeline {id}.");
return; return;
@ -4319,8 +4244,7 @@ impl ScriptThread {
} }
pub fn enqueue_microtask(job: Microtask) { pub fn enqueue_microtask(job: Microtask) {
SCRIPT_THREAD_ROOT.with(|root| { with_script_thread(|script_thread| {
let script_thread = unsafe { &*root.get().unwrap() };
script_thread script_thread
.microtask_queue .microtask_queue
.enqueue(job, script_thread.get_cx()); .enqueue(job, script_thread.get_cx());