script: Expose NodeTraits::owner_global / Window::as_global_scope (#34843)

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>
This commit is contained in:
Martin Robinson 2025-01-07 10:56:02 +01:00 committed by GitHub
parent 17e2ca3f01
commit e42b4b793d
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
33 changed files with 262 additions and 258 deletions

View file

@ -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();

View file

@ -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,

View file

@ -91,7 +91,6 @@ 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;
@ -99,7 +98,7 @@ impl BluetoothAdvertisingEventMethods<crate::DomTypeHolder> for BluetoothAdverti
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,

View file

@ -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;
}
@ -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);
}
@ -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);
}

View file

@ -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 || {
@ -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,
));
}
@ -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()
@ -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()
@ -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() {
@ -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 || {
@ -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 || {
@ -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 || {
@ -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(),
@ -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(
@ -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);
@ -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);
@ -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> {
@ -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().`
@ -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();
@ -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(())
@ -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());
@ -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 } => {

View file

@ -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(())
@ -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()
@ -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());
@ -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));
}
@ -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
@ -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()),
);
@ -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");
}
@ -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())

View file

@ -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;
@ -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)
}
@ -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
})

View file

@ -82,16 +82,16 @@ impl VirtualMethods for HTMLDetailsElement {
let counter = self.toggle_counter.get() + 1;
self.toggle_counter.set(counter);
let window = self.owner_window();
let this = Trusted::new(self);
window.task_manager().dom_manipulation_task_source().queue(
task!(details_notification_task_steps: move || {
self.owner_global()
.task_manager()
.dom_manipulation_task_source()
.queue(task!(details_notification_task_steps: move || {
let this = this.root();
if counter == this.toggle_counter.get() {
this.upcast::<EventTarget>().fire_event(atom!("toggle"), CanGc::note());
}
}),
);
}));
self.upcast::<Node>().dirty(NodeDamage::OtherNodeDamage)
}
}

View file

@ -102,7 +102,6 @@ impl HTMLDialogElementMethods<crate::DomTypeHolder> for HTMLDialogElement {
fn Close(&self, return_value: Option<DOMString>) {
let element = self.upcast::<Element>();
let target = self.upcast::<EventTarget>();
let win = self.owner_window();
// Step 1 & 2
if element
@ -120,7 +119,8 @@ impl HTMLDialogElementMethods<crate::DomTypeHolder> for HTMLDialogElement {
// TODO: Step 4 implement pending dialog stack removal
// Step 5
win.task_manager()
self.owner_global()
.task_manager()
.dom_manipulation_task_source()
.queue_simple_event(target, atom!("close"));
}

View file

@ -57,7 +57,6 @@ use crate::dom::eventtarget::EventTarget;
use crate::dom::file::File;
use crate::dom::formdata::FormData;
use crate::dom::formdataevent::FormDataEvent;
use crate::dom::globalscope::GlobalScope;
use crate::dom::htmlbuttonelement::HTMLButtonElement;
use crate::dom::htmlcollection::CollectionFilter;
use crate::dom::htmldatalistelement::HTMLDataListElement;
@ -856,9 +855,9 @@ impl HTMLFormElement {
LoadOrigin::Script(doc.origin().immutable().clone()),
action_components,
None,
target_window.upcast::<GlobalScope>().get_referrer(),
target_window.as_global_scope().get_referrer(),
target_document.get_referrer_policy(),
Some(target_window.upcast::<GlobalScope>().is_secure_context()),
Some(target_window.as_global_scope().is_secure_context()),
);
// Step 22
@ -1009,12 +1008,11 @@ impl HTMLFormElement {
Some(ref link_types) if link_types.Value().contains("noreferrer") => {
Referrer::NoReferrer
},
_ => target.upcast::<GlobalScope>().get_referrer(),
_ => target.as_global_scope().get_referrer(),
};
let referrer_policy = target.Document().get_referrer_policy();
let pipeline_id = target.upcast::<GlobalScope>().pipeline_id();
load_data.creator_pipeline_id = Some(pipeline_id);
load_data.creator_pipeline_id = Some(target.pipeline_id());
load_data.referrer = referrer;
load_data.referrer_policy = referrer_policy;
@ -1037,6 +1035,7 @@ impl HTMLFormElement {
// Step 3.
target
.global()
.task_manager()
.dom_manipulation_task_source()
.queue(task)

View file

@ -185,9 +185,8 @@ impl HTMLIFrameElement {
let new_pipeline_id = PipelineId::new();
self.pending_pipeline_id.set(Some(new_pipeline_id));
let global_scope = window.upcast::<GlobalScope>();
let load_info = IFrameLoadInfo {
parent_pipeline_id: global_scope.pipeline_id(),
parent_pipeline_id: window.pipeline_id(),
browsing_context_id,
top_level_browsing_context_id,
new_pipeline_id,
@ -214,13 +213,14 @@ impl HTMLIFrameElement {
sandbox: sandboxed,
window_size,
};
global_scope
window
.as_global_scope()
.script_to_constellation_chan()
.send(ScriptMsg::ScriptNewIFrame(load_info))
.unwrap();
let new_layout_info = NewLayoutInfo {
parent_info: Some(global_scope.pipeline_id()),
parent_info: Some(window.pipeline_id()),
new_pipeline_id,
browsing_context_id,
top_level_browsing_context_id,
@ -240,7 +240,8 @@ impl HTMLIFrameElement {
sandbox: sandboxed,
window_size,
};
global_scope
window
.as_global_scope()
.script_to_constellation_chan()
.send(ScriptMsg::ScriptLoadedURLInIFrame(load_info))
.unwrap();
@ -258,14 +259,14 @@ impl HTMLIFrameElement {
let url = ServoUrl::parse("about:srcdoc").unwrap();
let document = self.owner_document();
let window = self.owner_window();
let pipeline_id = Some(window.upcast::<GlobalScope>().pipeline_id());
let pipeline_id = Some(window.pipeline_id());
let mut load_data = LoadData::new(
LoadOrigin::Script(document.origin().immutable().clone()),
url,
pipeline_id,
window.upcast::<GlobalScope>().get_referrer(),
window.as_global_scope().get_referrer(),
document.get_referrer_policy(),
Some(window.upcast::<GlobalScope>().is_secure_context()),
Some(window.as_global_scope().is_secure_context()),
);
let element = self.upcast::<Element>();
load_data.srcdoc = String::from(element.get_string_attribute(&local_name!("srcdoc")));
@ -344,7 +345,7 @@ impl HTMLIFrameElement {
}
let creator_pipeline_id = if url.as_str() == "about:blank" {
Some(window.upcast::<GlobalScope>().pipeline_id())
Some(window.pipeline_id())
} else {
None
};
@ -353,9 +354,9 @@ impl HTMLIFrameElement {
LoadOrigin::Script(document.origin().immutable().clone()),
url,
creator_pipeline_id,
window.upcast::<GlobalScope>().get_referrer(),
window.as_global_scope().get_referrer(),
referrer_policy,
Some(window.upcast::<GlobalScope>().is_secure_context()),
Some(window.as_global_scope().is_secure_context()),
);
let pipeline_id = self.pipeline_id();
@ -392,14 +393,14 @@ impl HTMLIFrameElement {
let url = ServoUrl::parse("about:blank").unwrap();
let document = self.owner_document();
let window = self.owner_window();
let pipeline_id = Some(window.upcast::<GlobalScope>().pipeline_id());
let pipeline_id = Some(window.pipeline_id());
let load_data = LoadData::new(
LoadOrigin::Script(document.origin().immutable().clone()),
url,
pipeline_id,
window.upcast::<GlobalScope>().get_referrer(),
window.as_global_scope().get_referrer(),
document.get_referrer_policy(),
Some(window.upcast::<GlobalScope>().is_secure_context()),
Some(window.as_global_scope().is_secure_context()),
);
let browsing_context_id = BrowsingContextId::new();
let top_level_browsing_context_id = window.window_proxy().top_level_browsing_context_id();
@ -777,7 +778,7 @@ impl VirtualMethods for HTMLIFrameElement {
let msg = ScriptMsg::RemoveIFrame(browsing_context_id, sender);
window
.upcast::<GlobalScope>()
.as_global_scope()
.script_to_constellation_chan()
.send(msg)
.unwrap();

View file

@ -881,8 +881,9 @@ impl HTMLImageElement {
/// Step 8-12 of html.spec.whatwg.org/multipage/#update-the-image-data
fn update_the_image_data_sync_steps(&self, can_gc: CanGc) {
let document = self.owner_document();
let window = document.window();
let task_source = window.task_manager().dom_manipulation_task_source();
let global = self.owner_global();
let task_manager = global.task_manager();
let task_source = task_manager.dom_manipulation_task_source();
let this = Trusted::new(self);
let (src, pixel_density) = match self.select_image_source() {
// Step 8
@ -1014,8 +1015,10 @@ impl HTMLImageElement {
let this = Trusted::new(self);
let src = src.0;
window.task_manager().dom_manipulation_task_source().queue(
task!(image_load_event: move || {
self.owner_global()
.task_manager()
.dom_manipulation_task_source()
.queue(task!(image_load_event: move || {
let this = this.root();
{
let mut current_request =
@ -1025,8 +1028,7 @@ impl HTMLImageElement {
}
// TODO: restart animation, if set.
this.upcast::<EventTarget>().fire_event(atom!("load"), CanGc::note());
}),
);
}));
return;
}
}
@ -1062,7 +1064,7 @@ impl HTMLImageElement {
let trusted_node = Trusted::new(elem);
let (responder_sender, responder_receiver) = ipc::channel().unwrap();
let task_source = elem
.owner_window()
.owner_global()
.task_manager()
.networking_task_source()
.to_sendable();
@ -1240,9 +1242,8 @@ impl HTMLImageElement {
selected_pixel_density: f64,
) {
let this = Trusted::new(self);
let window = self.owner_window();
let src = src.0;
window.task_manager().dom_manipulation_task_source().queue(
self.owner_global().task_manager().dom_manipulation_task_source().queue(
task!(image_load_event: move || {
let this = this.root();
let relevant_mutation = this.generation.get() != generation;

View file

@ -286,7 +286,7 @@ impl HTMLInputElement {
) -> HTMLInputElement {
let chan = document
.window()
.upcast::<GlobalScope>()
.as_global_scope()
.script_to_constellation_chan()
.clone();
HTMLInputElement {
@ -1843,7 +1843,7 @@ impl HTMLInputElement {
fn select_files(&self, opt_test_paths: Option<Vec<DOMString>>, can_gc: CanGc) {
let window = self.owner_window();
let origin = get_blob_origin(&window.get_url());
let resource_threads = window.upcast::<GlobalScope>().resource_threads();
let resource_threads = window.as_global_scope().resource_threads();
let mut files: Vec<DomRoot<File>> = vec![];
let mut error = None;
@ -2576,7 +2576,7 @@ impl VirtualMethods for HTMLInputElement {
self.input_type().is_textual_or_password()
{
if event.IsTrusted() {
self.owner_window()
self.owner_global()
.task_manager()
.user_interaction_task_source()
.queue_event(

View file

@ -523,7 +523,7 @@ impl HTMLMediaElement {
fn time_marches_on(&self) {
// Step 6.
if Instant::now() > self.next_timeupdate_event.get() {
self.owner_window()
self.owner_global()
.task_manager()
.media_element_task_source()
.queue_simple_event(self.upcast(), atom!("timeupdate"));
@ -548,7 +548,7 @@ impl HTMLMediaElement {
// Step 2.3.
let this = Trusted::new(self);
let generation_id = self.generation_id.get();
self.owner_window()
self.owner_global()
.task_manager()
.media_element_task_source()
.queue(task!(internal_pause_steps: move || {
@ -594,7 +594,7 @@ impl HTMLMediaElement {
// Step 2.
let this = Trusted::new(self);
let generation_id = self.generation_id.get();
self.owner_window()
self.owner_global()
.task_manager()
.media_element_task_source()
.queue(task!(notify_about_playing: move || {
@ -629,8 +629,8 @@ impl HTMLMediaElement {
return;
}
let owner_window = self.owner_window();
let task_manager = owner_window.task_manager();
let owner_global = self.owner_global();
let task_manager = owner_global.task_manager();
let task_source = task_manager.media_element_task_source();
// Step 1.
@ -780,7 +780,7 @@ impl HTMLMediaElement {
self.network_state.set(NetworkState::Loading);
// Step 8.
self.owner_window()
self.owner_global()
.task_manager()
.media_element_task_source()
.queue_simple_event(self.upcast(), atom!("loadstart"));
@ -929,19 +929,16 @@ impl HTMLMediaElement {
self.network_state.set(NetworkState::Idle);
// Step 4.remote.1.2.
let window = self.owner_window();
window
.task_manager()
.media_element_task_source()
.queue_simple_event(self.upcast(), atom!("suspend"));
let owner_global = self.owner_global();
let task_manager = owner_global.task_manager();
let task_source = task_manager.media_element_task_source();
task_source.queue_simple_event(self.upcast(), atom!("suspend"));
// Step 4.remote.1.3.
let this = Trusted::new(self);
window.task_manager().media_element_task_source().queue(
task!(set_media_delay_load_event_flag_to_false: move || {
this.root().delay_load_event(false, CanGc::note());
}),
);
task_source.queue(task!(set_media_delay_load_event_flag_to_false: move || {
this.root().delay_load_event(false, CanGc::note());
}));
// Steps 4.remote.1.4.
// FIXME(nox): Somehow we should wait for the task from previous
@ -997,7 +994,7 @@ impl HTMLMediaElement {
let this = Trusted::new(self);
let generation_id = self.generation_id.get();
self.take_pending_play_promises(Err(Error::NotSupported));
self.owner_window()
self.owner_global()
.task_manager()
.media_element_task_source()
.queue(task!(dedicated_media_source_failure_steps: move || {
@ -1043,7 +1040,7 @@ impl HTMLMediaElement {
}
fn queue_ratechange_event(&self) {
self.owner_window()
self.owner_global()
.task_manager()
.media_element_task_source()
.queue_simple_event(self.upcast(), atom!("ratechange"));
@ -1096,8 +1093,8 @@ impl HTMLMediaElement {
self.fulfill_in_flight_play_promises(|| ());
}
let window = self.owner_window();
let task_manager = window.task_manager();
let global = self.owner_global();
let task_manager = global.task_manager();
let task_source = task_manager.media_element_task_source();
// Step 5.
@ -1278,7 +1275,7 @@ impl HTMLMediaElement {
// servo-media with gstreamer does not support inaccurate seeking for now.
// Step 10.
self.owner_window()
self.owner_global()
.task_manager()
.media_element_task_source()
.queue_simple_event(self.upcast(), atom!("seeking"));
@ -1304,16 +1301,13 @@ impl HTMLMediaElement {
self.time_marches_on();
// Step 16.
let window = self.owner_window();
let task_manager = window.task_manager();
task_manager
.media_element_task_source()
.queue_simple_event(self.upcast(), atom!("timeupdate"));
let global = self.owner_global();
let task_manager = global.task_manager();
let task_source = task_manager.media_element_task_source();
task_source.queue_simple_event(self.upcast(), atom!("timeupdate"));
// Step 17.
task_manager
.media_element_task_source()
.queue_simple_event(self.upcast(), atom!("seeked"));
task_source.queue_simple_event(self.upcast(), atom!("seeked"));
}
/// <https://html.spec.whatwg.org/multipage/#poster-frame>
@ -1331,7 +1325,7 @@ impl HTMLMediaElement {
self.upcast::<Node>().dirty(NodeDamage::OtherNodeDamage);
if pref!(media.testing.enabled) {
self.owner_window()
self.owner_global()
.task_manager()
.media_element_task_source()
.queue_simple_event(self.upcast(), atom!("postershown"));
@ -1378,7 +1372,8 @@ impl HTMLMediaElement {
*self.player.borrow_mut() = Some(player);
let trusted_node = Trusted::new(self);
let task_source = window
let task_source = self
.owner_global()
.task_manager()
.media_element_task_source()
.to_sendable();
@ -1417,7 +1412,8 @@ impl HTMLMediaElement {
if let Some(image_receiver) = image_receiver {
let trusted_node = Trusted::new(self);
let task_source = window
let task_source = self
.owner_global()
.task_manager()
.media_element_task_source()
.to_sendable();
@ -1500,7 +1496,7 @@ impl HTMLMediaElement {
// Step 3.
let this = Trusted::new(self);
self.owner_window().task_manager().media_element_task_source().queue(
self.owner_global().task_manager().media_element_task_source().queue(
task!(reaches_the_end_steps: move || {
let this = this.root();
// Step 3.1.
@ -1531,7 +1527,7 @@ impl HTMLMediaElement {
PlaybackDirection::Backwards => {
if self.playback_position.get() <= self.earliest_possible_position() {
self.owner_window()
self.owner_global()
.task_manager()
.media_element_task_source()
.queue_simple_event(self.upcast(), atom!("ended"));
@ -1718,7 +1714,7 @@ impl HTMLMediaElement {
self.duration.set(f64::INFINITY);
}
if previous_duration != self.duration.get() {
self.owner_window()
self.owner_global()
.task_manager()
.media_element_task_source()
.queue_simple_event(self.upcast(), atom!("durationchange"));
@ -2112,7 +2108,7 @@ impl HTMLMediaElementMethods<crate::DomTypeHolder> for HTMLMediaElement {
}
self.muted.set(value);
self.owner_window()
self.owner_global()
.task_manager()
.media_element_task_source()
.queue_simple_event(self.upcast(), atom!("volumechange"));
@ -2210,8 +2206,8 @@ impl HTMLMediaElementMethods<crate::DomTypeHolder> for HTMLMediaElement {
let state = self.ready_state.get();
let owner_window = self.owner_window();
let task_manager = owner_window.task_manager();
let global = self.owner_global();
let task_manager = global.task_manager();
let task_source = task_manager.media_element_task_source();
if self.Paused() {
// Step 6.1.
@ -2454,7 +2450,7 @@ impl HTMLMediaElementMethods<crate::DomTypeHolder> for HTMLMediaElement {
if *value != self.volume.get() {
self.volume.set(*value);
self.owner_window()
self.owner_global()
.task_manager()
.media_element_task_source()
.queue_simple_event(self.upcast(), atom!("volumechange"));
@ -2784,7 +2780,7 @@ impl FetchResponseListener for HTMLMediaElementFetchListener {
// https://html.spec.whatwg.org/multipage/#concept-media-load-resource step 4,
// => "If mode is remote" step 2
if Instant::now() > self.next_progress_event {
elem.owner_window()
elem.owner_global()
.task_manager()
.media_element_task_source()
.queue_simple_event(elem.upcast(), atom!("progress"));

View file

@ -23,7 +23,6 @@ use crate::dom::bindings::root::DomRoot;
use crate::dom::bindings::str::DOMString;
use crate::dom::document::{DeclarativeRefresh, Document};
use crate::dom::element::{AttributeMutation, Element};
use crate::dom::globalscope::GlobalScope;
use crate::dom::htmlelement::HTMLElement;
use crate::dom::htmlheadelement::HTMLHeadElement;
use crate::dom::location::NavigationType;
@ -207,7 +206,7 @@ impl HTMLMetaElement {
if document.completely_loaded() {
// TODO: handle active sandboxing flag
let window = self.owner_window();
window.upcast::<GlobalScope>().schedule_callback(
window.as_global_scope().schedule_callback(
OneshotTimerCallback::RefreshRedirectDue(RefreshRedirectDue {
window: window.clone(),
url: url_record,

View file

@ -474,7 +474,7 @@ impl FetchResponseListener for ClassicContext {
script_kind: self.kind,
final_url,
url: self.url.clone(),
task_source: global.task_manager().dom_manipulation_task_source(),
task_source: elem.owner_global().task_manager().dom_manipulation_task_source(),
script_text: source_string,
fetch_options: self.fetch_options.clone(),
});
@ -997,16 +997,17 @@ impl HTMLScriptElement {
self.line_number as u32
};
rooted!(in(*GlobalScope::get_cx()) let mut rval = UndefinedValue());
let global = window.upcast::<GlobalScope>();
global.evaluate_script_on_global_with_result(
&script.code,
script.url.as_str(),
rval.handle_mut(),
line_number,
script.fetch_options.clone(),
script.url.clone(),
can_gc,
);
window
.as_global_scope()
.evaluate_script_on_global_with_result(
&script.code,
script.url.as_str(),
rval.handle_mut(),
line_number,
script.fetch_options.clone(),
script.url.clone(),
can_gc,
);
}
#[allow(unsafe_code)]
@ -1021,7 +1022,7 @@ impl HTMLScriptElement {
// Step 4
let window = self.owner_window();
let global = window.upcast::<GlobalScope>();
let global = window.as_global_scope();
let _aes = AutoEntryScript::new(global);
let tree = if script.external {
@ -1065,7 +1066,7 @@ impl HTMLScriptElement {
}
pub fn queue_error_event(&self) {
self.owner_window()
self.owner_global()
.task_manager()
.dom_manipulation_task_source()
.queue_simple_event(self.upcast(), atom!("error"));

View file

@ -133,7 +133,7 @@ impl HTMLStyleElement {
// No subresource loads were triggered, queue load event
if self.pending_loads.get() == 0 {
self.owner_window()
self.owner_global()
.task_manager()
.dom_manipulation_task_source()
.queue_simple_event(self.upcast(), atom!("load"));

View file

@ -27,7 +27,6 @@ use crate::dom::compositionevent::CompositionEvent;
use crate::dom::document::Document;
use crate::dom::element::{AttributeMutation, Element, LayoutElementHelpers};
use crate::dom::event::{Event, EventBubbles, EventCancelable};
use crate::dom::globalscope::GlobalScope;
use crate::dom::htmlelement::HTMLElement;
use crate::dom::htmlfieldsetelement::HTMLFieldSetElement;
use crate::dom::htmlformelement::{FormControl, HTMLFormElement};
@ -143,7 +142,7 @@ impl HTMLTextAreaElement {
) -> HTMLTextAreaElement {
let chan = document
.window()
.upcast::<GlobalScope>()
.as_global_scope()
.script_to_constellation_chan()
.clone();
HTMLTextAreaElement {
@ -650,7 +649,7 @@ impl VirtualMethods for HTMLTextAreaElement {
}
} else if event.type_() == atom!("keypress") && !event.DefaultPrevented() {
if event.IsTrusted() {
self.owner_window()
self.owner_global()
.task_manager()
.user_interaction_task_source()
.queue_event(

View file

@ -125,7 +125,7 @@ impl HTMLVideoElement {
let sent_resize = if self.htmlmediaelement.get_ready_state() == ReadyState::HaveNothing {
None
} else {
self.owner_window()
self.owner_global()
.task_manager()
.media_element_task_source()
.queue_simple_event(self.upcast(), atom!("resize"));

View file

@ -89,9 +89,8 @@ impl MediaQueryListEventMethods<crate::DomTypeHolder> for MediaQueryListEvent {
type_: DOMString,
init: &MediaQueryListEventInit,
) -> Fallible<DomRoot<MediaQueryListEvent>> {
let global = window.upcast::<GlobalScope>();
Ok(MediaQueryListEvent::new_with_proto(
global,
window.as_global_scope(),
proto,
Atom::from(type_),
init.parent.bubbles,

View file

@ -45,6 +45,7 @@ use style::stylesheets::{Stylesheet, UrlExtraData};
use uuid::Uuid;
use xml5ever::serialize as xml_serialize;
use super::globalscope::GlobalScope;
use crate::document_loader::DocumentLoader;
use crate::dom::attr::Attr;
use crate::dom::bindings::cell::{DomRefCell, Ref, RefMut};
@ -3346,6 +3347,10 @@ pub(crate) trait NodeTraits {
/// differ from the [`Document`] that the node was created in if it was adopted by a
/// different [`Document`] (the owner).
fn owner_window(&self) -> DomRoot<Window>;
/// Get the [`GlobalScope`] of the [`Document`] that owns this node. Note that this may
/// differ from the [`GlobalScope`] that the node was created in if it was adopted by a
/// different [`Document`] (the owner).
fn owner_global(&self) -> DomRoot<GlobalScope>;
/// If this [`Node`] is contained in a [`ShadowRoot`] return it, otherwise `None`.
fn containing_shadow_root(&self) -> Option<DomRoot<ShadowRoot>>;
/// Get the stylesheet owner for this node: either the [`Document`] or the [`ShadowRoot`]
@ -3363,6 +3368,10 @@ impl<T: DerivedFrom<Node> + DomObject> NodeTraits for T {
DomRoot::from_ref(self.owner_document().window())
}
fn owner_global(&self) -> DomRoot<GlobalScope> {
DomRoot::from_ref(self.owner_window().upcast())
}
fn containing_shadow_root(&self) -> Option<DomRoot<ShadowRoot>> {
Node::containing_shadow_root(self.upcast())
}

View file

@ -17,7 +17,7 @@ use crate::dom::bindings::root::{Dom, DomRoot, MutNullableDom};
use crate::dom::bindings::str::DOMString;
use crate::dom::document::Document;
use crate::dom::eventtarget::EventTarget;
use crate::dom::node::Node;
use crate::dom::node::{Node, NodeTraits};
use crate::dom::range::Range;
use crate::script_runtime::CanGc;
@ -89,7 +89,7 @@ impl Selection {
}
let this = Trusted::new(self);
self.document
.window()
.owner_global()
.task_manager()
.user_interaction_task_source() // w3c/selection-api#117
.queue(

View file

@ -55,7 +55,6 @@ use crate::dom::comment::Comment;
use crate::dom::document::{Document, DocumentSource, HasBrowsingContext, IsHTMLDocument};
use crate::dom::documenttype::DocumentType;
use crate::dom::element::{CustomElementCreationMode, Element, ElementCreator};
use crate::dom::globalscope::GlobalScope;
use crate::dom::htmlformelement::{FormControlElementHelpers, HTMLFormElement};
use crate::dom::htmlimageelement::HTMLImageElement;
use crate::dom::htmlinputelement::HTMLInputElement;
@ -366,7 +365,7 @@ impl ServoParser {
let profiler_chan = self
.document
.window()
.upcast::<GlobalScope>()
.as_global_scope()
.time_profiler_chan()
.clone();
let profiler_metadata = TimerMetadata {
@ -564,7 +563,7 @@ impl ServoParser {
let profiler_chan = self
.document
.window()
.upcast::<GlobalScope>()
.as_global_scope()
.time_profiler_chan()
.clone();
let profiler_metadata = TimerMetadata {
@ -637,7 +636,7 @@ impl ServoParser {
if is_execution_stack_empty() {
self.document
.window()
.upcast::<GlobalScope>()
.as_global_scope()
.perform_a_microtask_checkpoint(can_gc);
}
@ -1401,7 +1400,7 @@ fn create_element_for_token(
if is_execution_stack_empty() {
document
.window()
.upcast::<GlobalScope>()
.as_global_scope()
.perform_a_microtask_checkpoint(can_gc);
}
// Step 6.3

View file

@ -301,7 +301,7 @@ impl<'a, E: TextControlElement> TextControlSelection<'a, E> {
// Step 6
if textinput.selection_state() != original_selection_state {
self.element
.owner_window()
.owner_global()
.task_manager()
.user_interaction_task_source()
.queue_event(

View file

@ -9,10 +9,8 @@ use std::rc::Rc;
use js::jsval::UndefinedValue;
use crate::dom::bindings::inheritance::Castable;
use crate::dom::bindings::refcounted::Trusted;
use crate::dom::bindings::str::DOMString;
use crate::dom::globalscope::GlobalScope;
use crate::dom::htmlheadelement::HTMLHeadElement;
use crate::dom::htmlscriptelement::SourceCode;
use crate::dom::node::NodeTraits;
@ -25,9 +23,9 @@ pub fn load_script(head: &HTMLHeadElement) {
Some(p) => p,
None => return,
};
let win = Trusted::new(doc.window());
let window = Trusted::new(doc.window());
doc.add_delayed_task(task!(UserScriptExecute: move || {
let win = win.root();
let win = window.root();
let cx = win.get_cx();
rooted!(in(*cx) let mut rval = UndefinedValue());
@ -47,14 +45,15 @@ pub fn load_script(head: &HTMLHeadElement) {
let script_text = SourceCode::Text(
Rc::new(DOMString::from_string(String::from_utf8_lossy(&contents).to_string()))
);
let global = win.upcast::<GlobalScope>();
global.evaluate_script_on_global_with_result(
let global_scope = win.as_global_scope();
global_scope.evaluate_script_on_global_with_result(
&script_text,
&file.to_string_lossy(),
rval.handle_mut(),
1,
ScriptFetchOptions::default_classic_script(global),
global.api_base_url(),
ScriptFetchOptions::default_classic_script(global_scope),
global_scope.api_base_url(),
CanGc::note(),
);
}

View file

@ -155,7 +155,6 @@ use crate::microtask::MicrotaskQueue;
use crate::realms::{enter_realm, InRealm};
use crate::script_runtime::{CanGc, JSContext, Runtime, ScriptChan, ScriptPort};
use crate::script_thread::ScriptThread;
use crate::task_manager::TaskManager;
use crate::timers::{IsInterval, TimerCallback};
use crate::unminify::unminified_path;
use crate::webdriver_handlers::jsval_to_webdriver;
@ -384,6 +383,10 @@ pub struct Window {
}
impl Window {
pub(crate) fn as_global_scope(&self) -> &GlobalScope {
self.upcast::<GlobalScope>()
}
pub fn layout(&self) -> Ref<Box<dyn Layout>> {
self.layout.borrow()
}
@ -402,13 +405,14 @@ impl Window {
#[allow(unsafe_code)]
pub fn clear_js_runtime_for_script_deallocation(&self) {
self.upcast::<GlobalScope>()
self.as_global_scope()
.remove_web_messaging_and_dedicated_workers_infra();
unsafe {
*self.js_runtime.borrow_for_script_deallocation() = None;
self.window_proxy.set(None);
self.current_state.set(WindowState::Zombie);
self.task_manager()
self.as_global_scope()
.task_manager()
.cancel_all_tasks_and_ignore_future_tasks();
}
}
@ -424,7 +428,8 @@ impl Window {
// Step 4 of https://html.spec.whatwg.org/multipage/#discard-a-document
// Other steps performed when the `PipelineExit` message
// is handled by the ScriptThread.
self.task_manager()
self.as_global_scope()
.task_manager()
.cancel_all_tasks_and_ignore_future_tasks();
}
@ -562,10 +567,6 @@ impl Window {
pub fn dispatch_event_with_target_override(&self, event: &Event, can_gc: CanGc) -> EventStatus {
event.dispatch(self.upcast(), true, can_gc)
}
pub(crate) fn task_manager(&self) -> &TaskManager {
self.upcast::<GlobalScope>().task_manager()
}
}
// https://html.spec.whatwg.org/multipage/#atob
@ -819,7 +820,7 @@ impl WindowMethods<crate::DomTypeHolder> for Window {
window.send_to_constellation(ScriptMsg::DiscardTopLevelBrowsingContext);
}
});
self.global()
self.as_global_scope()
.task_manager()
.dom_manipulation_task_source()
.queue(task);
@ -864,7 +865,7 @@ impl WindowMethods<crate::DomTypeHolder> for Window {
// https://dvcs.w3.org/hg/webcrypto-api/raw-file/tip/spec/Overview.html#dfn-GlobalCrypto
fn Crypto(&self) -> DomRoot<Crypto> {
self.upcast::<GlobalScope>().crypto()
self.as_global_scope().crypto()
}
// https://html.spec.whatwg.org/multipage/#dom-frameelement
@ -908,7 +909,7 @@ impl WindowMethods<crate::DomTypeHolder> for Window {
StringOrFunction::String(i) => TimerCallback::StringTimerCallback(i),
StringOrFunction::Function(i) => TimerCallback::FunctionTimerCallback(i),
};
self.upcast::<GlobalScope>().set_timeout_or_interval(
self.as_global_scope().set_timeout_or_interval(
callback,
args,
Duration::from_millis(timeout.max(0) as u64),
@ -918,8 +919,7 @@ impl WindowMethods<crate::DomTypeHolder> for Window {
// https://html.spec.whatwg.org/multipage/#dom-windowtimers-cleartimeout
fn ClearTimeout(&self, handle: i32) {
self.upcast::<GlobalScope>()
.clear_timeout_or_interval(handle);
self.as_global_scope().clear_timeout_or_interval(handle);
}
// https://html.spec.whatwg.org/multipage/#dom-windowtimers-setinterval
@ -934,7 +934,7 @@ impl WindowMethods<crate::DomTypeHolder> for Window {
StringOrFunction::String(i) => TimerCallback::StringTimerCallback(i),
StringOrFunction::Function(i) => TimerCallback::FunctionTimerCallback(i),
};
self.upcast::<GlobalScope>().set_timeout_or_interval(
self.as_global_scope().set_timeout_or_interval(
callback,
args,
Duration::from_millis(timeout.max(0) as u64),
@ -949,8 +949,7 @@ impl WindowMethods<crate::DomTypeHolder> for Window {
// https://html.spec.whatwg.org/multipage/#dom-queuemicrotask
fn QueueMicrotask(&self, callback: Rc<VoidFunction>) {
self.upcast::<GlobalScope>()
.queue_function_as_microtask(callback);
self.as_global_scope().queue_function_as_microtask(callback);
}
// https://html.spec.whatwg.org/multipage/#dom-createimagebitmap
@ -961,7 +960,7 @@ impl WindowMethods<crate::DomTypeHolder> for Window {
can_gc: CanGc,
) -> Rc<Promise> {
let p = self
.upcast::<GlobalScope>()
.as_global_scope()
.create_image_bitmap(image, options, can_gc);
p
}
@ -1011,10 +1010,8 @@ impl WindowMethods<crate::DomTypeHolder> for Window {
// https://dvcs.w3.org/hg/webperf/raw-file/tip/specs/
// NavigationTiming/Overview.html#sec-window.performance-attribute
fn Performance(&self) -> DomRoot<Performance> {
self.performance.or_init(|| {
let global_scope = self.upcast::<GlobalScope>();
Performance::new(global_scope, self.navigation_start.get())
})
self.performance
.or_init(|| Performance::new(self.as_global_scope(), self.navigation_start.get()))
}
// https://html.spec.whatwg.org/multipage/#globaleventhandlers
@ -1415,7 +1412,7 @@ impl WindowMethods<crate::DomTypeHolder> for Window {
}
fn IsSecureContext(&self) -> bool {
self.upcast::<GlobalScope>().is_secure_context()
self.as_global_scope().is_secure_context()
}
// https://html.spec.whatwg.org/multipage/#named-access-on-the-window-object
@ -1587,7 +1584,7 @@ impl WindowMethods<crate::DomTypeHolder> for Window {
options: RootedTraceableBox<StructuredSerializeOptions>,
retval: MutableHandleValue,
) -> Fallible<()> {
self.upcast::<GlobalScope>()
self.as_global_scope()
.structured_clone(cx, value, options, retval)
}
}
@ -1652,7 +1649,7 @@ impl Window {
}
pub fn clear_js_runtime(&self) {
self.upcast::<GlobalScope>()
self.as_global_scope()
.remove_web_messaging_and_dedicated_workers_infra();
// Clean up any active promises
@ -1681,7 +1678,7 @@ impl Window {
// If this is the currently active pipeline,
// nullify the window_proxy.
if let Some(proxy) = self.window_proxy.get() {
let pipeline_id = self.upcast::<GlobalScope>().pipeline_id();
let pipeline_id = self.pipeline_id();
if let Some(currently_active) = proxy.currently_active() {
if currently_active == pipeline_id {
self.window_proxy.set(None);
@ -1692,7 +1689,8 @@ impl Window {
if let Some(performance) = self.performance.get() {
performance.clear_and_disable_performance_entry_buffer();
}
self.task_manager()
self.as_global_scope()
.task_manager()
.cancel_all_tasks_and_ignore_future_tasks();
}
@ -1733,7 +1731,7 @@ impl Window {
self.perform_a_scroll(
x,
y,
self.upcast::<GlobalScope>().pipeline_id().root_scroll_id(),
self.pipeline_id().root_scroll_id(),
behavior,
None,
can_gc,
@ -1791,10 +1789,9 @@ impl Window {
/// layout animation clock.
#[allow(unsafe_code)]
pub fn advance_animation_clock(&self, delta_ms: i32) {
let pipeline_id = self.upcast::<GlobalScope>().pipeline_id();
self.Document()
.advance_animation_timeline_for_testing(delta_ms as f64 / 1000.);
ScriptThread::handle_tick_all_animations_for_testing(pipeline_id);
ScriptThread::handle_tick_all_animations_for_testing(self.pipeline_id());
}
/// Reflows the page unconditionally if possible and not suppressed. This method will wait for
@ -1818,7 +1815,7 @@ impl Window {
// layouts (for queries and scrolling) are not blocked, as they do not display
// anything and script excpects the layout to be up-to-date after they run.
let layout_blocked = self.layout_blocker.get().layout_blocked();
let pipeline_id = self.upcast::<GlobalScope>().pipeline_id();
let pipeline_id = self.pipeline_id();
if reflow_goal == ReflowGoal::UpdateTheRendering && layout_blocked {
debug!("Suppressing pre-load-event reflow pipeline {pipeline_id}");
return false;
@ -2339,7 +2336,8 @@ impl Window {
CanGc::note());
event.upcast::<Event>().fire(this.upcast::<EventTarget>(), CanGc::note());
});
self.task_manager()
self.as_global_scope()
.task_manager()
.dom_manipulation_task_source()
.queue(task);
doc.set_url(load_data.url.clone());
@ -2347,9 +2345,8 @@ impl Window {
}
}
let pipeline_id = self.upcast::<GlobalScope>().pipeline_id();
// Step 4 and 5
let pipeline_id = self.pipeline_id();
let window_proxy = self.window_proxy();
if let Some(active) = window_proxy.currently_active() {
if pipeline_id == active && doc.is_prompting_or_unloading() {
@ -2476,7 +2473,7 @@ impl Window {
pub fn suspend(&self) {
// Suspend timer events.
self.upcast::<GlobalScope>().suspend();
self.as_global_scope().suspend();
// Set the window proxy to be a cross-origin window.
if self.window_proxy().currently_active() == Some(self.global().pipeline_id()) {
@ -2492,7 +2489,7 @@ impl Window {
pub fn resume(&self) {
// Resume timer events.
self.upcast::<GlobalScope>().resume();
self.as_global_scope().resume();
// Set the window proxy to be this object.
self.window_proxy().set_currently_active(self);
@ -2620,9 +2617,9 @@ impl Window {
pub fn set_throttled(&self, throttled: bool) {
self.throttled.set(throttled);
if throttled {
self.upcast::<GlobalScope>().slow_down_timers();
self.as_global_scope().slow_down_timers();
} else {
self.upcast::<GlobalScope>().speed_up_timers();
self.as_global_scope().speed_up_timers();
}
}
@ -2647,7 +2644,7 @@ impl Window {
}
pub fn send_to_constellation(&self, msg: ScriptMsg) {
self.upcast::<GlobalScope>()
self.as_global_scope()
.script_to_constellation_chan()
.send(msg)
.unwrap();
@ -2807,8 +2804,8 @@ impl Window {
Box::new(self.script_chan.clone())
}
pub fn pipeline_id(&self) -> PipelineId {
self.upcast::<GlobalScope>().pipeline_id()
pub(crate) fn pipeline_id(&self) -> PipelineId {
self.as_global_scope().pipeline_id()
}
/// Create a new cached instance of the given value.
@ -2951,7 +2948,8 @@ impl Window {
}
});
// TODO(#12718): Use the "posted message task source".
self.task_manager()
self.as_global_scope()
.task_manager()
.dom_manipulation_task_source()
.queue(task);
}

View file

@ -512,12 +512,12 @@ impl WindowProxy {
let referrer = if noreferrer {
Referrer::NoReferrer
} else {
target_window.upcast::<GlobalScope>().get_referrer()
target_window.as_global_scope().get_referrer()
};
// Step 14.5
let referrer_policy = target_document.get_referrer_policy();
let pipeline_id = target_window.upcast::<GlobalScope>().pipeline_id();
let secure = target_window.upcast::<GlobalScope>().is_secure_context();
let pipeline_id = target_window.pipeline_id();
let secure = target_window.as_global_scope().is_secure_context();
let load_data = LoadData::new(
LoadOrigin::Script(existing_document.origin().immutable().clone()),
url,
@ -675,17 +675,17 @@ impl WindowProxy {
}
pub fn set_currently_active(&self, window: &Window) {
let globalscope = window.upcast::<GlobalScope>();
let dest_pipeline_id = globalscope.pipeline_id();
if let Some(pipeline_id) = self.currently_active() {
if pipeline_id == dest_pipeline_id {
if pipeline_id == window.pipeline_id() {
return debug!(
"Attempt to set the currently active window to the currently active window."
);
}
}
self.set_window(globalscope, WindowProxyHandler::proxy_handler());
self.currently_active.set(Some(globalscope.pipeline_id()));
let global_scope = window.as_global_scope();
self.set_window(global_scope, WindowProxyHandler::proxy_handler());
self.currently_active.set(Some(global_scope.pipeline_id()));
}
pub fn unset_currently_active(&self) {
@ -867,14 +867,13 @@ unsafe fn GetSubframeWindowProxy(
let browsing_context_id = win.window_proxy().browsing_context_id();
let (result_sender, result_receiver) = ipc::channel().unwrap();
let _ = win
.upcast::<GlobalScope>()
.script_to_constellation_chan()
.send(ScriptMsg::GetChildBrowsingContextId(
let _ = win.as_global_scope().script_to_constellation_chan().send(
ScriptMsg::GetChildBrowsingContextId(
browsing_context_id,
index as usize,
result_sender,
));
),
);
return result_receiver
.recv()
.ok()

View file

@ -145,17 +145,16 @@ impl WorkletMethods<crate::DomTypeHolder> for Worklet {
// Steps 6-12 in parallel.
let pending_tasks_struct = PendingTasksStruct::new();
let global = self.window.upcast::<GlobalScope>();
self.droppable_field
.thread_pool
.get_or_init(ScriptThread::worklet_thread_pool)
.fetch_and_invoke_a_worklet_script(
global.pipeline_id(),
self.window.pipeline_id(),
self.droppable_field.worklet_id,
self.global_type,
self.window.origin().immutable().clone(),
global.api_base_url(),
self.window.as_global_scope().api_base_url(),
module_url_record,
options.credentials,
pending_tasks_struct,

View file

@ -27,7 +27,7 @@ pub fn generate_cache_listener_for_element<
let (responder_sender, responder_receiver) = ipc::channel().unwrap();
let task_source = elem
.owner_window()
.owner_global()
.task_manager()
.networking_task_source()
.to_sendable();

View file

@ -20,7 +20,7 @@ use crate::dom::htmlareaelement::HTMLAreaElement;
use crate::dom::htmlformelement::HTMLFormElement;
use crate::dom::htmllinkelement::HTMLLinkElement;
use crate::dom::node::NodeTraits;
use crate::dom::types::{Element, GlobalScope};
use crate::dom::types::Element;
use crate::script_runtime::CanGc;
bitflags::bitflags! {
@ -412,12 +412,12 @@ pub fn follow_hyperlink(
let referrer = if relations.contains(LinkRelations::NO_REFERRER) {
Referrer::NoReferrer
} else {
target_window.upcast::<GlobalScope>().get_referrer()
target_window.as_global_scope().get_referrer()
};
// Step 14
let pipeline_id = target_window.upcast::<GlobalScope>().pipeline_id();
let secure = target_window.upcast::<GlobalScope>().is_secure_context();
let pipeline_id = target_window.as_global_scope().pipeline_id();
let secure = target_window.as_global_scope().is_secure_context();
let load_data = LoadData::new(
LoadOrigin::Script(document.origin().immutable().clone()),
url,
@ -431,7 +431,8 @@ pub fn follow_hyperlink(
debug!("following hyperlink to {}", load_data.url);
target.root().load_url(history_handling, false, load_data, CanGc::note());
});
target_window
target_document
.owner_global()
.task_manager()
.dom_manipulation_task_source()
.queue(task);

View file

@ -942,7 +942,7 @@ pub(crate) enum ModuleOwner {
}
impl ModuleOwner {
pub fn global(&self) -> DomRoot<GlobalScope> {
pub(crate) fn global(&self) -> DomRoot<GlobalScope> {
match &self {
ModuleOwner::Worker(worker) => (*worker.root().clone()).global(),
ModuleOwner::Window(script) => (*script.root()).global(),

View file

@ -671,7 +671,7 @@ impl ScriptThread {
None => return,
Some(window) => window,
};
let global = window.upcast::<GlobalScope>();
let global = window.as_global_scope();
let trusted_global = Trusted::new(global);
let sender = script_thread
.senders
@ -1033,7 +1033,7 @@ impl ScriptThread {
let docs = self.documents.borrow();
for (_, document) in docs.iter() {
document
.window()
.owner_global()
.task_manager()
.cancel_all_tasks_and_ignore_future_tasks();
}
@ -1218,8 +1218,7 @@ impl ScriptThread {
},
CompositorEvent::GamepadEvent(gamepad_event) => {
let global = window.upcast::<GlobalScope>();
global.handle_gamepad_event(gamepad_event);
window.as_global_scope().handle_gamepad_event(gamepad_event);
},
}
}
@ -1410,7 +1409,7 @@ impl ScriptThread {
// rendering update when animations are not running.
let _realm = enter_realm(&*document);
document
.window()
.owner_global()
.task_manager()
.rendering_task_source()
.queue_unconditionally(task!(update_the_rendering: move || { }));
@ -2098,7 +2097,7 @@ impl ScriptThread {
match msg {
DevtoolScriptControlMsg::EvaluateJS(id, s, reply) => match documents.find_window(id) {
Some(window) => {
let global = window.upcast::<GlobalScope>();
let global = window.as_global_scope();
let _aes = AutoEntryScript::new(global);
devtools::handle_evaluate_js(global, s, reply, can_gc)
},
@ -3697,11 +3696,8 @@ impl ScriptThread {
) {
let window = self.documents.borrow().find_window(pipeline_id);
if let Some(window) = window {
let entry = PerformancePaintTiming::new(
window.upcast::<GlobalScope>(),
metric_type,
metric_value,
);
let entry =
PerformancePaintTiming::new(window.as_global_scope(), metric_type, metric_value);
window
.Performance()
.queue_entry(entry.upcast::<PerformanceEntry>(), can_gc);

View file

@ -331,7 +331,7 @@ pub fn handle_execute_script(
let result = unsafe {
let cx = window.get_cx();
rooted!(in(*cx) let mut rval = UndefinedValue());
let global = window.upcast::<GlobalScope>();
let global = window.as_global_scope();
global.evaluate_js_on_global_with_result(
&eval,
rval.handle_mut(),
@ -339,7 +339,7 @@ pub fn handle_execute_script(
global.api_base_url(),
can_gc,
);
jsval_to_webdriver(*cx, window.upcast::<GlobalScope>(), rval.handle())
jsval_to_webdriver(*cx, global, rval.handle())
};
reply.send(result).unwrap();
@ -363,12 +363,13 @@ pub fn handle_execute_async_script(
let cx = window.get_cx();
window.set_webdriver_script_chan(Some(reply));
rooted!(in(*cx) let mut rval = UndefinedValue());
let global = window.upcast::<GlobalScope>();
global.evaluate_js_on_global_with_result(
let global_scope = window.as_global_scope();
global_scope.evaluate_js_on_global_with_result(
&eval,
rval.handle_mut(),
ScriptFetchOptions::default_classic_script(global),
global.api_base_url(),
ScriptFetchOptions::default_classic_script(global_scope),
global_scope.api_base_url(),
can_gc,
);
},
@ -792,7 +793,7 @@ pub fn handle_get_cookies(
let (sender, receiver) = ipc::channel().unwrap();
let _ = document
.window()
.upcast::<GlobalScope>()
.as_global_scope()
.resource_threads()
.send(GetCookiesDataForUrl(url, sender, NonHTTP));
receiver.recv().unwrap()
@ -819,7 +820,7 @@ pub fn handle_get_cookie(
let (sender, receiver) = ipc::channel().unwrap();
let _ = document
.window()
.upcast::<GlobalScope>()
.as_global_scope()
.resource_threads()
.send(GetCookiesDataForUrl(url, sender, NonHTTP));
let cookies = receiver.recv().unwrap();
@ -864,7 +865,7 @@ pub fn handle_add_cookie(
(false, Some(ref domain)) if url.host_str().map(|x| x == domain).unwrap_or(false) => {
let _ = document
.window()
.upcast::<GlobalScope>()
.as_global_scope()
.resource_threads()
.send(SetCookieForUrl(url, Serde(cookie), method));
Ok(())
@ -872,7 +873,7 @@ pub fn handle_add_cookie(
(false, None) => {
let _ = document
.window()
.upcast::<GlobalScope>()
.as_global_scope()
.resource_threads()
.send(SetCookieForUrl(url, Serde(cookie), method));
Ok(())
@ -896,7 +897,7 @@ pub fn handle_delete_cookies(
let url = document.url();
document
.window()
.upcast::<GlobalScope>()
.as_global_scope()
.resource_threads()
.send(DeleteCookies(url))
.unwrap();