Skip to content

Commit

Permalink
script: Expose NodeTraits::owner_global / Window::as_global_scope
Browse files Browse the repository at this point in the history
Expose two new helpers and start using them as much as possible.

- `NodeTraits::owner_global`: which gets the `GlobalScope` that currenty
 owns a `Node`. This may be different than `.global()` in the case that
 the `Node` was adopted by a different `Document`.
- `Window::as_global_scope`: A helper to avoid having to cast so much
  when treating a `Window` like a `GlobalScope`.

Signed-off-by: Martin Robinson <mrobinson@igalia.com>
  • Loading branch information
mrobinson committed Jan 7, 2025
1 parent ab52cda commit e6415e9
Show file tree
Hide file tree
Showing 33 changed files with 262 additions and 258 deletions.
1 change: 1 addition & 0 deletions components/script/dom/analysernode.rs
Original file line number Diff line number Diff line change
Expand Up @@ -111,6 +111,7 @@ impl AnalyserNode {
let (node, recv) = AnalyserNode::new_inherited(window, context, options)?;
let object = reflect_dom_object_with_proto(Box::new(node), window, proto, can_gc);
let task_source = window
.as_global_scope()
.task_manager()
.dom_manipulation_task_source()
.to_sendable();
Expand Down
4 changes: 3 additions & 1 deletion components/script/dom/bindings/reflector.rs
Original file line number Diff line number Diff line change
Expand Up @@ -100,7 +100,9 @@ pub trait DomObject: JSTraceable + 'static {
/// Returns the receiver's reflector.
fn reflector(&self) -> &Reflector;

/// Returns the global scope of the realm that the DomObject was created in.
/// Returns the [`GlobalScope`] of the realm that the [`DomObject`] was created in. If this
/// object is a `Node`, this will be different from it's owning `Document` if adopted by. For
/// `Node`s it's almost always better to use `NodeTraits::owning_global`.
fn global(&self) -> DomRoot<GlobalScope>
where
Self: Sized,
Expand Down
3 changes: 1 addition & 2 deletions components/script/dom/bluetoothadvertisingevent.rs
Original file line number Diff line number Diff line change
Expand Up @@ -91,15 +91,14 @@ impl BluetoothAdvertisingEventMethods<crate::DomTypeHolder> for BluetoothAdverti
type_: DOMString,
init: &BluetoothAdvertisingEventInit,
) -> Fallible<DomRoot<BluetoothAdvertisingEvent>> {
let global = window.upcast::<GlobalScope>();
let name = init.name.clone();
let appearance = init.appearance;
let txPower = init.txPower;
let rssi = init.rssi;
let bubbles = EventBubbles::from(init.parent.bubbles);
let cancelable = EventCancelable::from(init.parent.cancelable);
Ok(BluetoothAdvertisingEvent::new(
global,
window.as_global_scope(),
proto,
Atom::from(type_),
bubbles,
Expand Down
10 changes: 6 additions & 4 deletions components/script/dom/customelementregistry.rs
Original file line number Diff line number Diff line change
Expand Up @@ -571,13 +571,15 @@ impl CustomElementRegistryMethods<crate::DomTypeHolder> for CustomElementRegistr
/// <https://html.spec.whatwg.org/multipage/#dom-customelementregistry-whendefined>
#[allow(unsafe_code)]
fn WhenDefined(&self, name: DOMString, comp: InRealm, can_gc: CanGc) -> Rc<Promise> {
let global_scope = self.window.upcast::<GlobalScope>();
let name = LocalName::from(&*name);

// Step 1
if !is_valid_custom_element_name(&name) {
let promise = Promise::new_in_current_realm(comp, can_gc);
promise.reject_native(&DOMException::new(global_scope, DOMErrorName::SyntaxError));
promise.reject_native(&DOMException::new(
self.window.as_global_scope(),
DOMErrorName::SyntaxError,
));
return promise;
}

Expand Down Expand Up @@ -733,7 +735,7 @@ impl CustomElementDefinition {
// https://html.spec.whatwg.org/multipage/#clean-up-after-running-script
if is_execution_stack_empty() {
window
.upcast::<GlobalScope>()
.as_global_scope()
.perform_a_microtask_checkpoint(can_gc);
}

Expand Down Expand Up @@ -925,7 +927,7 @@ fn run_upgrade_constructor(
// https://html.spec.whatwg.org/multipage/#clean-up-after-running-script
if is_execution_stack_empty() {
window
.upcast::<GlobalScope>()
.as_global_scope()
.perform_a_microtask_checkpoint(can_gc);
}

Expand Down
59 changes: 29 additions & 30 deletions components/script/dom/document.rs
Original file line number Diff line number Diff line change
Expand Up @@ -696,7 +696,7 @@ impl Document {
// But it's now Step 4 in https://html.spec.whatwg.org/multipage/#reactivate-a-document
// TODO: See #32687 for more information.
let document = Trusted::new(self);
self.window()
self.owner_global()
.task_manager()
.dom_manipulation_task_source()
.queue(task!(fire_pageshow_event: move || {
Expand Down Expand Up @@ -1166,10 +1166,9 @@ impl Document {
self.window.pipeline_id(),
title.clone(),
));
let global = self.window.upcast::<GlobalScope>();
if let Some(chan) = global.devtools_chan() {
if let Some(chan) = self.window.as_global_scope().devtools_chan() {
let _ = chan.send(ScriptToDevtoolsControlMsg::TitleChanged(
global.pipeline_id(),
self.window.pipeline_id(),
title,
));
}
Expand Down Expand Up @@ -2127,7 +2126,11 @@ impl Document {
) {
let callback = NetworkListener {
context: std::sync::Arc::new(Mutex::new(listener)),
task_source: self.window().task_manager().networking_task_source().into(),
task_source: self
.owner_global()
.task_manager()
.networking_task_source()
.into(),
}
.into_callback();
self.loader_mut()
Expand All @@ -2142,7 +2145,11 @@ impl Document {
) {
let callback = NetworkListener {
context: std::sync::Arc::new(Mutex::new(listener)),
task_source: self.window().task_manager().networking_task_source().into(),
task_source: self
.owner_global()
.task_manager()
.networking_task_source()
.into(),
}
.into_callback();
self.loader_mut()
Expand Down Expand Up @@ -2326,7 +2333,7 @@ impl Document {
}
}

let global_scope = self.window.upcast::<GlobalScope>();
let global_scope = self.window.as_global_scope();
// Step 10, 14
// https://html.spec.whatwg.org/multipage/#unloading-document-cleanup-steps
if !self.salvageable.get() {
Expand Down Expand Up @@ -2370,7 +2377,7 @@ impl Document {
// Step 7.
debug!("Document loads are complete.");
let document = Trusted::new(self);
self.window()
self.owner_global()
.task_manager()
.dom_manipulation_task_source()
.queue(task!(fire_load_event: move || {
Expand Down Expand Up @@ -2413,7 +2420,7 @@ impl Document {
// Step 8.
let document = Trusted::new(self);
if document.root().browsing_context().is_some() {
self.window()
self.owner_global()
.task_manager()
.dom_manipulation_task_source()
.queue(task!(fire_pageshow_event: move || {
Expand Down Expand Up @@ -2464,7 +2471,7 @@ impl Document {
// TODO: fully implement "completely loaded".
let document = Trusted::new(self);
if document.root().browsing_context().is_some() {
self.window()
self.owner_global()
.task_manager()
.dom_manipulation_task_source()
.queue(task!(completely_loaded: move || {
Expand All @@ -2475,7 +2482,7 @@ impl Document {
time
}) = &*document.declarative_refresh.borrow() {
// https://html.spec.whatwg.org/multipage/#shared-declarative-refresh-steps
document.window.upcast::<GlobalScope>().schedule_callback(
document.window.as_global_scope().schedule_callback(
OneshotTimerCallback::RefreshRedirectDue(RefreshRedirectDue {
window: DomRoot::from_ref(document.window()),
url: url.clone(),
Expand Down Expand Up @@ -2632,7 +2639,7 @@ impl Document {

// Step 4.1.
let document = Trusted::new(self);
self.window()
self.owner_global()
.task_manager()
.dom_manipulation_task_source()
.queue(
Expand Down Expand Up @@ -2672,9 +2679,8 @@ impl Document {
*self.asap_scripts_set.borrow_mut() = vec![];
self.asap_in_order_scripts_list.clear();
self.deferred_scripts.clear();
let global_scope = self.window.upcast::<GlobalScope>();
let loads_cancelled = self.loader.borrow_mut().cancel_all_loads();
let event_sources_canceled = global_scope.close_event_sources();
let event_sources_canceled = self.window.as_global_scope().close_event_sources();
if loads_cancelled || event_sources_canceled {
// If any loads were canceled.
self.salvageable.set(false);
Expand All @@ -2684,7 +2690,7 @@ impl Document {
// Note: the spec says to discard any tasks queued for fetch.
// This cancels all tasks on the networking task source, which might be too broad.
// See https://github.com/whatwg/html/issues/3837
self.window()
self.owner_global()
.task_manager()
.cancel_pending_tasks_for_source(TaskSourceName::Networking);

Expand Down Expand Up @@ -3013,12 +3019,13 @@ impl Document {

/// <https://drafts.csswg.org/resize-observer/#deliver-resize-loop-error-notification>
pub(crate) fn deliver_resize_loop_error_notification(&self, can_gc: CanGc) {
let global_scope = self.window.upcast::<GlobalScope>();
let error_info: ErrorInfo = crate::dom::bindings::error::ErrorInfo {
message: "ResizeObserver loop completed with undelivered notifications.".to_string(),
..Default::default()
};
global_scope.report_an_error(error_info, HandleValue::null(), can_gc);
self.window
.as_global_scope()
.report_an_error(error_info, HandleValue::null(), can_gc);
}

pub(crate) fn status_code(&self) -> Option<u16> {
Expand Down Expand Up @@ -4102,7 +4109,7 @@ impl Document {

// > 3. Perform a microtask checkpoint.
self.window()
.upcast::<GlobalScope>()
.as_global_scope()
.perform_a_microtask_checkpoint(can_gc);

// Steps 4 through 7 occur inside `send_pending_events().`
Expand Down Expand Up @@ -5003,7 +5010,7 @@ impl DocumentMethods<crate::DomTypeHolder> for Document {
let (tx, rx) = profile_ipc::channel(self.global().time_profiler_chan().clone()).unwrap();
let _ = self
.window
.upcast::<GlobalScope>()
.as_global_scope()
.resource_threads()
.send(GetCookiesForUrl(url, tx, NonHTTP));
let cookies = rx.recv().unwrap();
Expand All @@ -5028,7 +5035,7 @@ impl DocumentMethods<crate::DomTypeHolder> for Document {

let _ = self
.window
.upcast::<GlobalScope>()
.as_global_scope()
.resource_threads()
.send(SetCookiesForUrl(self.url(), cookies, NonHTTP));
Ok(())
Expand Down Expand Up @@ -5347,11 +5354,7 @@ impl DocumentMethods<crate::DomTypeHolder> for Document {
// document.close() methods, and that the tokenizer will wait for an explicit call to
// document.close() before emitting an end-of-file token). The encoding confidence is
// irrelevant.
let resource_threads = self
.window
.upcast::<GlobalScope>()
.resource_threads()
.clone();
let resource_threads = self.window.as_global_scope().resource_threads().clone();
*self.loader.borrow_mut() =
DocumentLoader::new_with_threads(resource_threads, Some(self.url()));
ServoParser::parse_html_script_input(self, self.url());
Expand Down Expand Up @@ -5648,11 +5651,7 @@ impl AnimationFrameCallback {
match *self {
AnimationFrameCallback::DevtoolsFramerateTick { ref actor_name } => {
let msg = ScriptToDevtoolsControlMsg::FramerateTick(actor_name.clone(), now);
let devtools_sender = document
.window()
.upcast::<GlobalScope>()
.devtools_chan()
.unwrap();
let devtools_sender = document.window().as_global_scope().devtools_chan().unwrap();
devtools_sender.send(msg).unwrap();
},
AnimationFrameCallback::FrameRequestCallback { ref callback } => {
Expand Down
28 changes: 17 additions & 11 deletions components/script/dom/history.rs
Original file line number Diff line number Diff line change
Expand Up @@ -78,7 +78,7 @@ impl History {
let msg = ScriptMsg::TraverseHistory(direction);
let _ = self
.window
.upcast::<GlobalScope>()
.as_global_scope()
.script_to_constellation_chan()
.send(msg);
Ok(())
Expand Down Expand Up @@ -109,7 +109,7 @@ impl History {
let (tx, rx) = ipc::channel(self.global().time_profiler_chan().clone()).unwrap();
let _ = self
.window
.upcast::<GlobalScope>()
.as_global_scope()
.resource_threads()
.send(CoreResourceMsg::GetHistoryState(state_id, tx));
rx.recv().unwrap()
Expand All @@ -124,9 +124,10 @@ impl History {
ports: None,
blobs: None,
};
let global_scope = self.window.upcast::<GlobalScope>();
rooted!(in(*GlobalScope::get_cx()) let mut state = UndefinedValue());
if structuredclone::read(global_scope, data, state.handle_mut()).is_err() {
if structuredclone::read(self.window.as_global_scope(), data, state.handle_mut())
.is_err()
{
warn!("Error reading structuredclone data");
}
self.state.set(state.get());
Expand Down Expand Up @@ -167,7 +168,7 @@ impl History {
pub fn remove_states(&self, states: Vec<HistoryStateId>) {
let _ = self
.window
.upcast::<GlobalScope>()
.as_global_scope()
.resource_threads()
.send(CoreResourceMsg::RemoveHistoryStates(states));
}
Expand Down Expand Up @@ -240,7 +241,7 @@ impl History {
let msg = ScriptMsg::PushHistoryState(state_id, new_url.clone());
let _ = self
.window
.upcast::<GlobalScope>()
.as_global_scope()
.script_to_constellation_chan()
.send(msg);
state_id
Expand All @@ -257,14 +258,14 @@ impl History {
let msg = ScriptMsg::ReplaceHistoryState(state_id, new_url.clone());
let _ = self
.window
.upcast::<GlobalScope>()
.as_global_scope()
.script_to_constellation_chan()
.send(msg);
state_id
},
};

let _ = self.window.upcast::<GlobalScope>().resource_threads().send(
let _ = self.window.as_global_scope().resource_threads().send(
CoreResourceMsg::SetHistoryState(state_id, serialized_data.serialized.clone()),
);

Expand All @@ -275,9 +276,14 @@ impl History {
document.set_url(new_url);

// Step 11
let global_scope = self.window.upcast::<GlobalScope>();
rooted!(in(*cx) let mut state = UndefinedValue());
if structuredclone::read(global_scope, serialized_data, state.handle_mut()).is_err() {
if structuredclone::read(
self.window.as_global_scope(),
serialized_data,
state.handle_mut(),
)
.is_err()
{
warn!("Error reading structuredclone data");
}

Expand Down Expand Up @@ -311,7 +317,7 @@ impl HistoryMethods<crate::DomTypeHolder> for History {
let msg = ScriptMsg::JointSessionHistoryLength(sender);
let _ = self
.window
.upcast::<GlobalScope>()
.as_global_scope()
.script_to_constellation_chan()
.send(msg);
Ok(recv.recv().unwrap())
Expand Down
11 changes: 5 additions & 6 deletions components/script/dom/htmlcanvaselement.rs
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,6 @@ use crate::dom::canvasrenderingcontext2d::{
};
use crate::dom::document::Document;
use crate::dom::element::{AttributeMutation, Element, LayoutElementHelpers};
use crate::dom::globalscope::GlobalScope;
#[cfg(not(feature = "webgpu"))]
use crate::dom::gpucanvascontext::GPUCanvasContext;
use crate::dom::htmlelement::HTMLElement;
Expand Down Expand Up @@ -197,9 +196,10 @@ impl HTMLCanvasElement {
_ => None,
};
}

let window = self.owner_window();
let size = self.get_size();
let context = CanvasRenderingContext2D::new(window.upcast::<GlobalScope>(), self, size);
let context = CanvasRenderingContext2D::new(window.as_global_scope(), self, size);
*self.context.borrow_mut() = Some(CanvasContext::Context2d(Dom::from_ref(&*context)));
Some(context)
}
Expand Down Expand Up @@ -271,16 +271,15 @@ impl HTMLCanvasElement {
};
}
let (sender, receiver) = ipcchan::channel().unwrap();
let _ = self
.global()
let global_scope = self.owner_global();
let _ = global_scope
.script_to_constellation_chan()
.send(ScriptMsg::GetWebGPUChan(sender));
receiver
.recv()
.expect("Failed to get WebGPU channel")
.map(|channel| {
let window = self.owner_window();
let context = GPUCanvasContext::new(window.upcast::<GlobalScope>(), self, channel);
let context = GPUCanvasContext::new(&global_scope, self, channel);
*self.context.borrow_mut() = Some(CanvasContext::WebGPU(Dom::from_ref(&*context)));
context
})
Expand Down
Loading

0 comments on commit e6415e9

Please sign in to comment.