From b745866a4d16eeb5de5f05811b7c4e107d644397 Mon Sep 17 00:00:00 2001 From: Anthony Ramine Date: Mon, 26 Sep 2016 15:45:57 +0200 Subject: [PATCH 01/66] Prevent doing use self::FooBinding::{} --- components/script/dom/bindings/codegen/CodegenRust.py | 10 +++++++--- 1 file changed, 7 insertions(+), 3 deletions(-) diff --git a/components/script/dom/bindings/codegen/CodegenRust.py b/components/script/dom/bindings/codegen/CodegenRust.py index 7c6b2fe3718..d5b92569d1a 100644 --- a/components/script/dom/bindings/codegen/CodegenRust.py +++ b/components/script/dom/bindings/codegen/CodegenRust.py @@ -5768,9 +5768,13 @@ class CGDescriptor(CGThing): cgThings = CGWrapper(CGNamespace(toBindingNamespace(descriptor.name), cgThings, public=True), post='\n') - reexports = ', '.join(map(lambda name: reexportedName(name), reexports)) - self.cgRoot = CGList([CGGeneric('pub use self::%s::{%s};' % (toBindingNamespace(descriptor.name), reexports)), - cgThings], '\n') + + if reexports: + reexports = ', '.join(map(lambda name: reexportedName(name), reexports)) + cgThings = CGList([CGGeneric('pub use self::%s::{%s};' % (toBindingNamespace(descriptor.name), reexports)), + cgThings], '\n') + + self.cgRoot = cgThings def define(self): return self.cgRoot.define() From 5a42bb58f9da18426f1d5bb892ccf74525793e01 Mon Sep 17 00:00:00 2001 From: Anthony Ramine Date: Mon, 26 Sep 2016 15:48:09 +0200 Subject: [PATCH 02/66] Implement [Inline] interfaces Inline interfaces just appear as a Rust type and in the TypeId hierarchy. They are completely invisible on the JS side. --- .../dom/bindings/codegen/CodegenRust.py | 56 ++++++++++--------- .../dom/bindings/codegen/Configuration.py | 11 +++- .../dom/bindings/codegen/parser/WebIDL.py | 3 +- .../dom/bindings/codegen/parser/inline.patch | 12 ++++ .../dom/bindings/codegen/parser/update.sh | 1 + components/script/dom/globalscope.rs | 18 ++++++ components/script/dom/mod.rs | 1 + .../script/dom/webidls/GlobalScope.webidl | 10 ++++ components/script/dom/webidls/Window.webidl | 2 +- .../dom/webidls/WorkerGlobalScope.webidl | 2 +- components/script/dom/window.rs | 5 +- components/script/dom/workerglobalscope.rs | 6 +- 12 files changed, 91 insertions(+), 36 deletions(-) create mode 100644 components/script/dom/bindings/codegen/parser/inline.patch create mode 100644 components/script/dom/globalscope.rs create mode 100644 components/script/dom/webidls/GlobalScope.webidl diff --git a/components/script/dom/bindings/codegen/CodegenRust.py b/components/script/dom/bindings/codegen/CodegenRust.py index d5b92569d1a..d30cee0ca93 100644 --- a/components/script/dom/bindings/codegen/CodegenRust.py +++ b/components/script/dom/bindings/codegen/CodegenRust.py @@ -1929,8 +1929,8 @@ class CGImports(CGWrapper): if t.isInterface() or t.isNamespace(): descriptor = descriptorProvider.getDescriptor(getIdentifier(t).name) extras += [descriptor.path] - if descriptor.interface.parent: - parentName = getIdentifier(descriptor.interface.parent).name + parentName = descriptor.getParentName() + if parentName: descriptor = descriptorProvider.getDescriptor(parentName) extras += [descriptor.path, descriptor.bindingPath] elif t.isType() and t.isMozMap(): @@ -2754,7 +2754,7 @@ assert!((*cache)[PrototypeList::Constructor::%(id)s as usize].is_null()); getPrototypeProto = "prototype_proto.set(JS_GetObjectPrototype(cx, global))" else: getPrototypeProto = ("%s::GetProtoObject(cx, global, prototype_proto.handle_mut())" % - toBindingNamespace(self.descriptor.prototypeChain[-2])) + toBindingNamespace(self.descriptor.getParentName())) code = [CGGeneric("""\ rooted!(in(cx) let mut prototype_proto = ptr::null_mut()); @@ -2808,8 +2808,9 @@ assert!((*cache)[PrototypeList::ID::%(id)s as usize].is_null()); properties["length"] = methodLength(self.descriptor.interface.ctor()) else: properties["length"] = 0 - if self.descriptor.interface.parent: - parentName = toBindingNamespace(self.descriptor.getParentName()) + parentName = self.descriptor.getParentName() + if parentName: + parentName = toBindingNamespace(parentName) code.append(CGGeneric(""" rooted!(in(cx) let mut interface_proto = ptr::null_mut()); %s::GetConstructorObject(cx, global, interface_proto.handle_mut());""" % parentName)) @@ -5744,25 +5745,26 @@ class CGDescriptor(CGThing): cgThings.append(CGGeneric(str(properties))) - if not descriptor.interface.isCallback() and not descriptor.interface.isNamespace(): - cgThings.append(CGGetProtoObjectMethod(descriptor)) - reexports.append('GetProtoObject') - cgThings.append(CGPrototypeJSClass(descriptor)) - if descriptor.interface.hasInterfaceObject(): - if descriptor.interface.ctor(): - cgThings.append(CGClassConstructHook(descriptor)) - for ctor in descriptor.interface.namedConstructors: - cgThings.append(CGClassConstructHook(descriptor, ctor)) - if not descriptor.interface.isCallback(): - cgThings.append(CGInterfaceObjectJSClass(descriptor)) - if descriptor.shouldHaveGetConstructorObjectMethod(): - cgThings.append(CGGetConstructorObjectMethod(descriptor)) - reexports.append('GetConstructorObject') - if descriptor.register: - cgThings.append(CGDefineDOMInterfaceMethod(descriptor)) - reexports.append('DefineDOMInterface') - cgThings.append(CGConstructorEnabled(descriptor)) - cgThings.append(CGCreateInterfaceObjectsMethod(descriptor, properties, haveUnscopables)) + if not descriptor.interface.getExtendedAttribute("Inline"): + if not descriptor.interface.isCallback() and not descriptor.interface.isNamespace(): + cgThings.append(CGGetProtoObjectMethod(descriptor)) + reexports.append('GetProtoObject') + cgThings.append(CGPrototypeJSClass(descriptor)) + if descriptor.interface.hasInterfaceObject(): + if descriptor.interface.ctor(): + cgThings.append(CGClassConstructHook(descriptor)) + for ctor in descriptor.interface.namedConstructors: + cgThings.append(CGClassConstructHook(descriptor, ctor)) + if not descriptor.interface.isCallback(): + cgThings.append(CGInterfaceObjectJSClass(descriptor)) + if descriptor.shouldHaveGetConstructorObjectMethod(): + cgThings.append(CGGetConstructorObjectMethod(descriptor)) + reexports.append('GetConstructorObject') + if descriptor.register: + cgThings.append(CGDefineDOMInterfaceMethod(descriptor)) + reexports.append('DefineDOMInterface') + cgThings.append(CGConstructorEnabled(descriptor)) + cgThings.append(CGCreateInterfaceObjectsMethod(descriptor, properties, haveUnscopables)) cgThings = generate_imports(config, CGList(cgThings, '\n'), [descriptor]) cgThings = CGWrapper(CGNamespace(toBindingNamespace(descriptor.name), @@ -6803,7 +6805,7 @@ class GlobalGenRoots(): globals_ = CGWrapper(CGIndenter(global_flags), pre="bitflags! {\n", post="\n}") pairs = [] - for d in config.getDescriptors(hasInterfaceObject=True): + for d in config.getDescriptors(hasInterfaceObject=True, isInline=False): binding = toBindingNamespace(d.name) pairs.append((d.name, binding, binding)) for ctor in d.interface.namedConstructors: @@ -6931,7 +6933,7 @@ class GlobalGenRoots(): allprotos.append(CGGeneric("\n")) if downcast: - hierarchy[descriptor.getParentName()].append(name) + hierarchy[descriptor.interface.parent.identifier.name].append(name) typeIdCode = [] topTypeVariants = [ @@ -6955,7 +6957,7 @@ class GlobalGenRoots(): for base, derived in hierarchy.iteritems(): variants = [] - if not config.getInterface(base).getExtendedAttribute("Abstract"): + if config.getDescriptor(base).concrete: variants.append(CGGeneric(base)) variants += [CGGeneric(type_id_variant(derivedName)) for derivedName in derived] derives = "Clone, Copy, Debug, PartialEq" diff --git a/components/script/dom/bindings/codegen/Configuration.py b/components/script/dom/bindings/codegen/Configuration.py index 9a1120769c8..f2f64e9bee0 100644 --- a/components/script/dom/bindings/codegen/Configuration.py +++ b/components/script/dom/bindings/codegen/Configuration.py @@ -88,6 +88,8 @@ class Configuration: getter = lambda x: x.interface.isJSImplemented() elif key == 'isGlobal': getter = lambda x: x.isGlobal() + elif key == 'isInline': + getter = lambda x: x.interface.getExtendedAttribute('Inline') is not None elif key == 'isExposedConditionally': getter = lambda x: x.interface.isExposedConditionally() elif key == 'isIteratorInterface': @@ -234,6 +236,7 @@ class Descriptor(DescriptorProvider): self.concrete = (not self.interface.isCallback() and not self.interface.isNamespace() and not self.interface.getExtendedAttribute("Abstract") and + not self.interface.getExtendedAttribute("Inline") and not spiderMonkeyInterface) self.hasUnforgeableMembers = (self.concrete and any(MemberIsUnforgeable(m, self) for m in @@ -383,8 +386,12 @@ class Descriptor(DescriptorProvider): return attrs def getParentName(self): - assert self.interface.parent is not None - return self.interface.parent.identifier.name + parent = self.interface.parent + while parent: + if not parent.getExtendedAttribute("Inline"): + return parent.identifier.name + parent = parent.parent + return None def hasDescendants(self): return (self.interface.getUserData("hasConcreteDescendant", False) or diff --git a/components/script/dom/bindings/codegen/parser/WebIDL.py b/components/script/dom/bindings/codegen/parser/WebIDL.py index 2894bbeb82e..dc9fa036141 100644 --- a/components/script/dom/bindings/codegen/parser/WebIDL.py +++ b/components/script/dom/bindings/codegen/parser/WebIDL.py @@ -1695,7 +1695,8 @@ class IDLInterface(IDLInterfaceOrNamespace): identifier == "ProbablyShortLivingObject" or identifier == "LegacyUnenumerableNamedProperties" or identifier == "NonOrdinaryGetPrototypeOf" or - identifier == "Abstract"): + identifier == "Abstract" or + identifier == "Inline"): # Known extended attributes that do not take values if not attr.noArguments(): raise WebIDLError("[%s] must take no arguments" % identifier, diff --git a/components/script/dom/bindings/codegen/parser/inline.patch b/components/script/dom/bindings/codegen/parser/inline.patch new file mode 100644 index 00000000000..5d1056d2b58 --- /dev/null +++ b/components/script/dom/bindings/codegen/parser/inline.patch @@ -0,0 +1,12 @@ +--- WebIDL.py ++++ WebIDL.py +@@ -1695,7 +1695,8 @@ class IDLInterface(IDLInterfaceOrNamespace): + identifier == "ProbablyShortLivingObject" or + identifier == "LegacyUnenumerableNamedProperties" or + identifier == "NonOrdinaryGetPrototypeOf" or +- identifier == "Abstract"): ++ identifier == "Abstract" or ++ identifier == "Inline"): + # Known extended attributes that do not take values + if not attr.noArguments(): + raise WebIDLError("[%s] must take no arguments" % identifier, \ No newline at end of file diff --git a/components/script/dom/bindings/codegen/parser/update.sh b/components/script/dom/bindings/codegen/parser/update.sh index 6bf56cead30..213aba6df89 100755 --- a/components/script/dom/bindings/codegen/parser/update.sh +++ b/components/script/dom/bindings/codegen/parser/update.sh @@ -4,6 +4,7 @@ patch < debug.patch patch < pref-main-thread.patch patch < callback-location.patch patch < union-typedef.patch +patch < inline.patch wget https://hg.mozilla.org/mozilla-central/archive/tip.tar.gz/dom/bindings/parser/tests/ -O tests.tar.gz rm -r tests diff --git a/components/script/dom/globalscope.rs b/components/script/dom/globalscope.rs new file mode 100644 index 00000000000..7c284987958 --- /dev/null +++ b/components/script/dom/globalscope.rs @@ -0,0 +1,18 @@ +/* This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ + +use dom::eventtarget::EventTarget; + +#[dom_struct] +pub struct GlobalScope { + eventtarget: EventTarget, +} + +impl GlobalScope { + pub fn new_inherited() -> GlobalScope { + GlobalScope { + eventtarget: EventTarget::new_inherited(), + } + } +} diff --git a/components/script/dom/mod.rs b/components/script/dom/mod.rs index 0081efba21c..2335f8a0a25 100644 --- a/components/script/dom/mod.rs +++ b/components/script/dom/mod.rs @@ -276,6 +276,7 @@ pub mod filereadersync; pub mod focusevent; pub mod forcetouchevent; pub mod formdata; +pub mod globalscope; pub mod hashchangeevent; pub mod headers; pub mod history; diff --git a/components/script/dom/webidls/GlobalScope.webidl b/components/script/dom/webidls/GlobalScope.webidl new file mode 100644 index 00000000000..7dab4f3afa7 --- /dev/null +++ b/components/script/dom/webidls/GlobalScope.webidl @@ -0,0 +1,10 @@ +/* This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ + +// This interface is entirely internal to Servo, and should not be accessible to +// web pages. + +[Exposed=(Window,Worker), + Inline] +interface GlobalScope : EventTarget {}; diff --git a/components/script/dom/webidls/Window.webidl b/components/script/dom/webidls/Window.webidl index 84fb4d754de..8fdc636a732 100644 --- a/components/script/dom/webidls/Window.webidl +++ b/components/script/dom/webidls/Window.webidl @@ -4,7 +4,7 @@ // https://html.spec.whatwg.org/multipage/#window [PrimaryGlobal, Exposed=(Window,Worker)] -/*sealed*/ interface Window : EventTarget { +/*sealed*/ interface Window : GlobalScope { // the current browsing context [Unforgeable] readonly attribute WindowProxy window; [BinaryName="Self_", Replaceable] readonly attribute WindowProxy self; diff --git a/components/script/dom/webidls/WorkerGlobalScope.webidl b/components/script/dom/webidls/WorkerGlobalScope.webidl index 186e5cd7fee..dcdd2957d43 100644 --- a/components/script/dom/webidls/WorkerGlobalScope.webidl +++ b/components/script/dom/webidls/WorkerGlobalScope.webidl @@ -4,7 +4,7 @@ // https://html.spec.whatwg.org/multipage/#workerglobalscope [Abstract, Exposed=Worker] -interface WorkerGlobalScope : EventTarget { +interface WorkerGlobalScope : GlobalScope { [BinaryName="Self_"] readonly attribute WorkerGlobalScope self; readonly attribute WorkerLocation location; diff --git a/components/script/dom/window.rs b/components/script/dom/window.rs index 3ac5c4e37f9..85c8f46fc63 100644 --- a/components/script/dom/window.rs +++ b/components/script/dom/window.rs @@ -35,6 +35,7 @@ use dom::element::Element; use dom::errorevent::ErrorEvent; use dom::event::{Event, EventBubbles, EventCancelable}; use dom::eventtarget::EventTarget; +use dom::globalscope::GlobalScope; use dom::history::History; use dom::htmliframeelement::build_mozbrowser_custom_event; use dom::location::Location; @@ -143,7 +144,7 @@ pub type ScrollPoint = Point2D; #[dom_struct] pub struct Window { - eventtarget: EventTarget, + globalscope: GlobalScope, #[ignore_heap_size_of = "trait objects are hard"] script_chan: MainThreadScriptChan, #[ignore_heap_size_of = "task sources are hard"] @@ -1629,7 +1630,7 @@ impl Window { }; let current_time = time::get_time(); let win = box Window { - eventtarget: EventTarget::new_inherited(), + globalscope: GlobalScope::new_inherited(), script_chan: script_chan, dom_manipulation_task_source: dom_task_source, user_interaction_task_source: user_task_source, diff --git a/components/script/dom/workerglobalscope.rs b/components/script/dom/workerglobalscope.rs index 9b976c5a31d..e05043b31c4 100644 --- a/components/script/dom/workerglobalscope.rs +++ b/components/script/dom/workerglobalscope.rs @@ -22,6 +22,7 @@ use dom::errorevent::ErrorEvent; use dom::event::{Event, EventBubbles, EventCancelable}; use dom::eventdispatcher::EventStatus; use dom::eventtarget::EventTarget; +use dom::globalscope::GlobalScope; use dom::promise::Promise; use dom::serviceworkerglobalscope::ServiceWorkerGlobalScope; use dom::window::{base64_atob, base64_btoa}; @@ -79,7 +80,8 @@ pub fn prepare_workerscope_init(global: GlobalRef, // https://html.spec.whatwg.org/multipage/#the-workerglobalscope-common-interface #[dom_struct] pub struct WorkerGlobalScope { - eventtarget: EventTarget, + globalscope: GlobalScope, + worker_id: WorkerId, pipeline_id: PipelineId, worker_url: Url, @@ -140,7 +142,7 @@ impl WorkerGlobalScope { closing: Option>) -> WorkerGlobalScope { WorkerGlobalScope { - eventtarget: EventTarget::new_inherited(), + globalscope: GlobalScope::new_inherited(), next_worker_id: Cell::new(WorkerId(0)), worker_id: init.worker_id, pipeline_id: init.pipeline_id, From 093b189b4800909b17295b88aed762601f4b8482 Mon Sep 17 00:00:00 2001 From: Anthony Ramine Date: Mon, 26 Sep 2016 16:20:37 +0200 Subject: [PATCH 03/66] Remove workerglobalscope::WorkerGlobalScopeTypeId --- components/script/dom/workerglobalscope.rs | 5 ----- 1 file changed, 5 deletions(-) diff --git a/components/script/dom/workerglobalscope.rs b/components/script/dom/workerglobalscope.rs index e05043b31c4..95e8b425c25 100644 --- a/components/script/dom/workerglobalscope.rs +++ b/components/script/dom/workerglobalscope.rs @@ -54,11 +54,6 @@ use task_source::file_reading::FileReadingTaskSource; use timers::{IsInterval, OneshotTimerCallback, OneshotTimerHandle, OneshotTimers, TimerCallback}; use url::Url; -#[derive(Copy, Clone, PartialEq)] -pub enum WorkerGlobalScopeTypeId { - DedicatedWorkerGlobalScope, -} - pub fn prepare_workerscope_init(global: GlobalRef, devtools_sender: Option>) -> WorkerGlobalScopeInit { let worker_id = global.get_next_worker_id(); From fcb59d305742a18daa083352a9b6e9a45896c9f6 Mon Sep 17 00:00:00 2001 From: Anthony Ramine Date: Tue, 27 Sep 2016 13:16:41 +0200 Subject: [PATCH 04/66] Make reflect_dom_object take a &GlobalScope --- components/script/body.rs | 10 ++--- components/script/dom/attr.rs | 3 +- components/script/dom/beforeunloadevent.rs | 6 +-- .../dom/bindings/codegen/CodegenRust.py | 10 +++-- components/script/dom/bindings/error.rs | 2 +- components/script/dom/bindings/global.rs | 10 +++++ components/script/dom/bindings/iterable.rs | 6 +-- components/script/dom/bindings/reflector.rs | 18 +++++--- components/script/dom/blob.rs | 10 +++-- components/script/dom/bluetooth.rs | 10 +++-- .../script/dom/bluetoothadvertisingdata.rs | 4 +- .../dom/bluetoothcharacteristicproperties.rs | 4 +- components/script/dom/bluetoothdevice.rs | 8 ++-- .../dom/bluetoothremotegattcharacteristic.rs | 8 ++-- .../dom/bluetoothremotegattdescriptor.rs | 4 +- .../script/dom/bluetoothremotegattserver.rs | 12 +++--- .../script/dom/bluetoothremotegattservice.rs | 22 ++++++---- components/script/dom/canvasgradient.rs | 4 +- components/script/dom/canvaspattern.rs | 4 +- .../script/dom/canvasrenderingcontext2d.rs | 14 +++---- components/script/dom/client.rs | 5 ++- components/script/dom/closeevent.rs | 7 ++-- components/script/dom/crypto.rs | 4 +- components/script/dom/cssstyledeclaration.rs | 3 +- components/script/dom/customevent.rs | 7 ++-- components/script/dom/document.rs | 26 ++++++------ components/script/dom/domexception.rs | 4 +- components/script/dom/domimplementation.rs | 3 +- components/script/dom/dommatrix.rs | 9 ++-- components/script/dom/dommatrixreadonly.rs | 42 +++++++++++-------- components/script/dom/domparser.rs | 2 +- components/script/dom/dompoint.rs | 7 ++-- components/script/dom/dompointreadonly.rs | 5 ++- components/script/dom/domquad.rs | 8 +++- components/script/dom/domrect.rs | 5 ++- components/script/dom/domrectlist.rs | 3 +- components/script/dom/domrectreadonly.rs | 5 ++- components/script/dom/domstringmap.rs | 3 +- components/script/dom/domtokenlist.rs | 3 +- components/script/dom/element.rs | 5 +-- components/script/dom/errorevent.rs | 20 +++++---- components/script/dom/event.rs | 7 ++-- components/script/dom/eventsource.rs | 9 ++-- components/script/dom/eventtarget.rs | 4 +- components/script/dom/extendableevent.rs | 5 ++- .../script/dom/extendablemessageevent.rs | 8 ++-- components/script/dom/file.rs | 14 ++++--- components/script/dom/filelist.rs | 3 +- components/script/dom/filereader.rs | 13 +++--- components/script/dom/filereadersync.rs | 7 ++-- components/script/dom/focusevent.rs | 6 +-- components/script/dom/forcetouchevent.rs | 3 +- components/script/dom/formdata.rs | 7 ++-- components/script/dom/globalscope.rs | 14 +++++++ components/script/dom/hashchangeevent.rs | 8 ++-- components/script/dom/headers.rs | 9 ++-- components/script/dom/history.rs | 3 +- components/script/dom/htmlcollection.rs | 3 +- .../script/dom/htmlformcontrolscollection.rs | 3 +- components/script/dom/htmliframeelement.rs | 3 +- components/script/dom/htmlmediaelement.rs | 2 +- .../script/dom/htmloptionscollection.rs | 3 +- components/script/dom/htmlscriptelement.rs | 2 +- components/script/dom/imagedata.rs | 4 +- components/script/dom/keyboardevent.rs | 2 +- components/script/dom/location.rs | 3 +- components/script/dom/mediaerror.rs | 3 +- components/script/dom/messageevent.rs | 24 +++++++---- components/script/dom/mimetypearray.rs | 4 +- components/script/dom/mouseevent.rs | 2 +- components/script/dom/namednodemap.rs | 3 +- components/script/dom/navigator.rs | 13 +++--- components/script/dom/node.rs | 16 +++---- components/script/dom/nodeiterator.rs | 3 +- components/script/dom/nodelist.rs | 4 +- components/script/dom/pagetransitionevent.rs | 7 ++-- components/script/dom/performance.rs | 3 +- components/script/dom/performancetiming.rs | 4 +- components/script/dom/pluginarray.rs | 4 +- components/script/dom/popstateevent.rs | 7 ++-- components/script/dom/progressevent.rs | 10 ++--- components/script/dom/promisenativehandler.rs | 4 +- components/script/dom/radionodelist.rs | 3 +- components/script/dom/range.rs | 2 +- components/script/dom/request.rs | 12 ++---- components/script/dom/response.rs | 13 +++--- components/script/dom/screen.rs | 3 +- components/script/dom/serviceworker.rs | 4 +- .../script/dom/serviceworkercontainer.rs | 6 +-- .../script/dom/serviceworkerglobalscope.rs | 3 +- .../script/dom/serviceworkerregistration.rs | 3 +- components/script/dom/servohtmlparser.rs | 7 +--- components/script/dom/servoxmlparser.rs | 4 +- components/script/dom/storage.rs | 8 ++-- components/script/dom/storageevent.rs | 7 ++-- components/script/dom/stylesheet.rs | 3 +- components/script/dom/stylesheetlist.rs | 3 +- components/script/dom/testbinding.rs | 21 +++++----- components/script/dom/testbindingiterable.rs | 5 ++- .../script/dom/testbindingpairiterable.rs | 5 ++- components/script/dom/textdecoder.rs | 5 ++- components/script/dom/textencoder.rs | 5 ++- components/script/dom/touch.rs | 4 +- components/script/dom/touchevent.rs | 3 +- components/script/dom/touchlist.rs | 3 +- components/script/dom/treewalker.rs | 3 +- components/script/dom/uievent.rs | 2 +- components/script/dom/url.rs | 9 ++-- components/script/dom/urlsearchparams.rs | 5 ++- components/script/dom/validitystate.rs | 3 +- components/script/dom/webglactiveinfo.rs | 4 +- components/script/dom/webglbuffer.rs | 6 +-- components/script/dom/webglcontextevent.rs | 8 ++-- components/script/dom/webglframebuffer.rs | 6 +-- components/script/dom/webglobject.rs | 4 +- components/script/dom/webglprogram.rs | 10 ++--- components/script/dom/webglrenderbuffer.rs | 6 +-- .../script/dom/webglrenderingcontext.rs | 18 ++++---- components/script/dom/webglshader.rs | 6 +-- .../script/dom/webglshaderprecisionformat.rs | 4 +- components/script/dom/webgltexture.rs | 6 +-- components/script/dom/webgluniformlocation.rs | 4 +- components/script/dom/websocket.rs | 12 ++++-- components/script/dom/window.rs | 8 ++-- components/script/dom/worker.rs | 7 ++-- components/script/dom/workerglobalscope.rs | 4 +- components/script/dom/workerlocation.rs | 3 +- components/script/dom/workernavigator.rs | 3 +- components/script/dom/xmldocument.rs | 3 +- components/script/dom/xmlhttprequest.rs | 12 +++--- components/script/dom/xmlhttprequestupload.rs | 4 +- components/script/fetch.rs | 2 +- 132 files changed, 488 insertions(+), 407 deletions(-) diff --git a/components/script/body.rs b/components/script/body.rs index 276d6425d2f..466523f394f 100644 --- a/components/script/body.rs +++ b/components/script/body.rs @@ -4,12 +4,12 @@ use dom::bindings::codegen::Bindings::FormDataBinding::FormDataMethods; use dom::bindings::error::{Error, Fallible}; -use dom::bindings::global::GlobalRef; use dom::bindings::js::Root; use dom::bindings::reflector::Reflectable; use dom::bindings::str::USVString; use dom::blob::{Blob, BlobImpl}; use dom::formdata::FormData; +use dom::globalscope::GlobalScope; use dom::promise::Promise; use encoding::all::UTF_8; use encoding::types::{DecoderTrap, Encoding}; @@ -103,8 +103,8 @@ fn run_package_data_algorithm(object: &T, match body_type { BodyType::Text => run_text_data_algorithm(bytes), BodyType::Json => run_json_data_algorithm(cx, bytes), - BodyType::Blob => run_blob_data_algorithm(object.global().r(), bytes, mime), - BodyType::FormData => run_form_data_algorithm(object.global().r(), bytes, mime), + BodyType::Blob => run_blob_data_algorithm(object.global().r().as_global_scope(), bytes, mime), + BodyType::FormData => run_form_data_algorithm(object.global().r().as_global_scope(), bytes, mime), } } @@ -132,7 +132,7 @@ fn run_json_data_algorithm(cx: *mut JSContext, } } -fn run_blob_data_algorithm(root: GlobalRef, +fn run_blob_data_algorithm(root: &GlobalScope, bytes: Vec, mime: &[u8]) -> Fallible { let mime_string = if let Ok(s) = String::from_utf8(mime.to_vec()) { @@ -144,7 +144,7 @@ fn run_blob_data_algorithm(root: GlobalRef, Ok(FetchedData::BlobData(blob)) } -fn run_form_data_algorithm(root: GlobalRef, bytes: Vec, mime: &[u8]) -> Fallible { +fn run_form_data_algorithm(root: &GlobalScope, bytes: Vec, mime: &[u8]) -> Fallible { let mime_str = if let Ok(s) = str::from_utf8(mime) { s } else { diff --git a/components/script/dom/attr.rs b/components/script/dom/attr.rs index d5a00e6c1fa..f322204fc4b 100644 --- a/components/script/dom/attr.rs +++ b/components/script/dom/attr.rs @@ -5,7 +5,6 @@ use devtools_traits::AttrInfo; use dom::bindings::cell::DOMRefCell; use dom::bindings::codegen::Bindings::AttrBinding::{self, AttrMethods}; -use dom::bindings::global::GlobalRef; use dom::bindings::inheritance::Castable; use dom::bindings::js::{JS, MutNullableHeap}; use dom::bindings::js::{LayoutJS, Root, RootedReference}; @@ -66,7 +65,7 @@ impl Attr { namespace, prefix, owner), - GlobalRef::Window(window), + window, AttrBinding::Wrap) } diff --git a/components/script/dom/beforeunloadevent.rs b/components/script/dom/beforeunloadevent.rs index b66df9429dc..413a26a8de8 100644 --- a/components/script/dom/beforeunloadevent.rs +++ b/components/script/dom/beforeunloadevent.rs @@ -6,12 +6,12 @@ use dom::bindings::cell::DOMRefCell; use dom::bindings::codegen::Bindings::BeforeUnloadEventBinding; use dom::bindings::codegen::Bindings::BeforeUnloadEventBinding::BeforeUnloadEventMethods; use dom::bindings::codegen::Bindings::EventBinding::EventMethods; -use dom::bindings::global::GlobalRef; use dom::bindings::inheritance::Castable; use dom::bindings::js::Root; use dom::bindings::reflector::reflect_dom_object; use dom::bindings::str::DOMString; use dom::event::{Event, EventBubbles, EventCancelable}; +use dom::globalscope::GlobalScope; use string_cache::Atom; // https://html.spec.whatwg.org/multipage/#beforeunloadevent @@ -29,13 +29,13 @@ impl BeforeUnloadEvent { } } - pub fn new_uninitialized(global: GlobalRef) -> Root { + pub fn new_uninitialized(global: &GlobalScope) -> Root { reflect_dom_object(box BeforeUnloadEvent::new_inherited(), global, BeforeUnloadEventBinding::Wrap) } - pub fn new(global: GlobalRef, + pub fn new(global: &GlobalScope, type_: Atom, bubbles: EventBubbles, cancelable: EventCancelable) -> Root { diff --git a/components/script/dom/bindings/codegen/CodegenRust.py b/components/script/dom/bindings/codegen/CodegenRust.py index d30cee0ca93..7e7cb4144db 100644 --- a/components/script/dom/bindings/codegen/CodegenRust.py +++ b/components/script/dom/bindings/codegen/CodegenRust.py @@ -1927,8 +1927,10 @@ class CGImports(CGWrapper): if t in dictionaries or t in enums: continue if t.isInterface() or t.isNamespace(): - descriptor = descriptorProvider.getDescriptor(getIdentifier(t).name) - extras += [descriptor.path] + name = getIdentifier(t).name + descriptor = descriptorProvider.getDescriptor(name) + if name != 'GlobalScope': + extras += [descriptor.path] parentName = descriptor.getParentName() if parentName: descriptor = descriptorProvider.getDescriptor(parentName) @@ -2523,7 +2525,8 @@ class CGWrapMethod(CGAbstractMethod): def __init__(self, descriptor): assert not descriptor.interface.isCallback() assert not descriptor.isGlobal() - args = [Argument('*mut JSContext', 'cx'), Argument('GlobalRef', 'scope'), + args = [Argument('*mut JSContext', 'cx'), + Argument('&GlobalScope', 'scope'), Argument("Box<%s>" % descriptor.concreteType, 'object')] retval = 'Root<%s>' % descriptor.concreteType CGAbstractMethod.__init__(self, descriptor, 'Wrap', retval, args, @@ -5594,6 +5597,7 @@ def generate_imports(config, cgthings, descriptors, callbacks=None, dictionaries 'dom::bindings::weakref::WeakBox', 'dom::bindings::weakref::WeakReferenceable', 'dom::browsingcontext::BrowsingContext', + 'dom::globalscope::GlobalScope', 'mem::heap_size_of_raw_self_and_children', 'libc', 'util::prefs::PREFS', diff --git a/components/script/dom/bindings/error.rs b/components/script/dom/bindings/error.rs index 1c0d49c4976..14725b33303 100644 --- a/components/script/dom/bindings/error.rs +++ b/components/script/dom/bindings/error.rs @@ -127,7 +127,7 @@ pub unsafe fn throw_dom_exception(cx: *mut JSContext, global: GlobalRef, result: }; assert!(!JS_IsExceptionPending(cx)); - let exception = DOMException::new(global, code); + let exception = DOMException::new(global.as_global_scope(), code); rooted!(in(cx) let mut thrown = UndefinedValue()); exception.to_jsval(cx, thrown.handle_mut()); JS_SetPendingException(cx, thrown.handle()); diff --git a/components/script/dom/bindings/global.rs b/components/script/dom/bindings/global.rs index e0341ceeb68..db90f1fbcdf 100644 --- a/components/script/dom/bindings/global.rs +++ b/components/script/dom/bindings/global.rs @@ -11,9 +11,11 @@ use devtools_traits::{ScriptToDevtoolsControlMsg, WorkerId}; use dom::bindings::codegen::Bindings::WindowBinding::WindowMethods; use dom::bindings::conversions::root_from_object; use dom::bindings::error::{ErrorInfo, report_pending_exception}; +use dom::bindings::inheritance::Castable; use dom::bindings::js::Root; use dom::bindings::reflector::{Reflectable, Reflector}; use dom::console::TimerSet; +use dom::globalscope::GlobalScope; use dom::window; use dom::workerglobalscope::WorkerGlobalScope; use ipc_channel::ipc::IpcSender; @@ -55,6 +57,14 @@ pub enum GlobalRoot { } impl<'a> GlobalRef<'a> { + /// Returns that `GlobalRef` as a `GlobalScope` referengce. + pub fn as_global_scope(&self) -> &GlobalScope { + match *self { + GlobalRef::Window(window) => window.upcast(), + GlobalRef::Worker(worker) => worker.upcast(), + } + } + /// Get the `JSContext` for the `JSRuntime` associated with the thread /// this global object is on. pub fn get_cx(&self) -> *mut JSContext { diff --git a/components/script/dom/bindings/iterable.rs b/components/script/dom/bindings/iterable.rs index 84381b52655..5a86dcf64d8 100644 --- a/components/script/dom/bindings/iterable.rs +++ b/components/script/dom/bindings/iterable.rs @@ -10,10 +10,10 @@ use core::nonzero::NonZero; use dom::bindings::codegen::Bindings::IterableIteratorBinding::IterableKeyAndValueResult; use dom::bindings::codegen::Bindings::IterableIteratorBinding::IterableKeyOrValueResult; use dom::bindings::error::Fallible; -use dom::bindings::global::GlobalRef; use dom::bindings::js::{JS, Root}; use dom::bindings::reflector::{Reflector, Reflectable, MutReflectable, reflect_dom_object}; use dom::bindings::trace::JSTraceable; +use dom::globalscope::GlobalScope; use js::conversions::ToJSValConvertible; use js::jsapi::{JSContext, JSObject, MutableHandleValue, MutableHandleObject, HandleValue}; use js::jsval::UndefinedValue; @@ -85,7 +85,7 @@ impl IterableIterator { /// Create a new iterator instance for the provided iterable DOM interface. pub fn new(iterable: &T, type_: IteratorType, - wrap: fn(*mut JSContext, GlobalRef, Box>) + wrap: fn(*mut JSContext, &GlobalScope, Box>) -> Root) -> Root { let iterator = box IterableIterator { reflector: Reflector::new(), @@ -94,7 +94,7 @@ impl IterableIterator { index: Cell::new(0), }; let global = iterable.global(); - reflect_dom_object(iterator, global.r(), wrap) + reflect_dom_object(iterator, global.r().as_global_scope(), wrap) } /// Return the next value from the iterable object. diff --git a/components/script/dom/bindings/reflector.rs b/components/script/dom/bindings/reflector.rs index d5280712a03..74c039688f7 100644 --- a/components/script/dom/bindings/reflector.rs +++ b/components/script/dom/bindings/reflector.rs @@ -4,19 +4,25 @@ //! The `Reflector` struct. -use dom::bindings::global::{GlobalRef, GlobalRoot, global_root_from_reflector}; +use dom::bindings::conversions::DerivedFrom; +use dom::bindings::global::{GlobalRoot, global_root_from_reflector}; use dom::bindings::js::Root; +use dom::globalscope::GlobalScope; use js::jsapi::{HandleObject, JSContext, JSObject}; use std::cell::UnsafeCell; use std::ptr; /// Create the reflector for a new DOM object and yield ownership to the /// reflector. -pub fn reflect_dom_object(obj: Box, - global: GlobalRef, - wrap_fn: fn(*mut JSContext, GlobalRef, Box) -> Root) - -> Root { - wrap_fn(global.get_cx(), global, obj) +pub fn reflect_dom_object( + obj: Box, + global: &U, + wrap_fn: fn(*mut JSContext, &GlobalScope, Box) -> Root) + -> Root + where T: Reflectable, U: DerivedFrom +{ + let global_scope = global.upcast(); + wrap_fn(global_scope.get_cx(), global_scope, obj) } /// A struct to store a reference to the reflector of a DOM object. diff --git a/components/script/dom/blob.rs b/components/script/dom/blob.rs index aef31efd687..011f547c96a 100644 --- a/components/script/dom/blob.rs +++ b/components/script/dom/blob.rs @@ -11,6 +11,7 @@ use dom::bindings::global::GlobalRef; use dom::bindings::js::{JS, Root}; use dom::bindings::reflector::{Reflectable, Reflector, reflect_dom_object}; use dom::bindings::str::DOMString; +use dom::globalscope::GlobalScope; use encoding::all::UTF_8; use encoding::types::{EncoderTrap, Encoding}; use ipc_channel::ipc; @@ -79,7 +80,9 @@ pub struct Blob { impl Blob { #[allow(unrooted_must_root)] - pub fn new(global: GlobalRef, blob_impl: BlobImpl, typeString: String) -> Root { + pub fn new( + global: &GlobalScope, blob_impl: BlobImpl, typeString: String) + -> Root { let boxed_blob = box Blob::new_inherited(blob_impl, typeString); reflect_dom_object(boxed_blob, global, BlobBinding::Wrap) } @@ -99,7 +102,6 @@ impl Blob { #[allow(unrooted_must_root)] fn new_sliced(parent: &Blob, rel_pos: RelativePos, relative_content_type: DOMString) -> Root { - let global = parent.global(); let blob_impl = match *parent.blob_impl.borrow() { BlobImpl::File(_) => { // Create new parent node @@ -115,7 +117,7 @@ impl Blob { } }; - Blob::new(global.r(), blob_impl, relative_content_type.into()) + Blob::new(parent.global().r().as_global_scope(), blob_impl, relative_content_type.into()) } // https://w3c.github.io/FileAPI/#constructorBlob @@ -132,7 +134,7 @@ impl Blob { } }; - Ok(Blob::new(global, BlobImpl::new_from_bytes(bytes), blobPropertyBag.type_.to_string())) + Ok(Blob::new(global.as_global_scope(), BlobImpl::new_from_bytes(bytes), blobPropertyBag.type_.to_string())) } /// Get a slice to inner data, this might incur synchronous read and caching diff --git a/components/script/dom/bluetooth.rs b/components/script/dom/bluetooth.rs index 42ad4c2730a..dd5d05d4f2a 100644 --- a/components/script/dom/bluetooth.rs +++ b/components/script/dom/bluetooth.rs @@ -15,6 +15,7 @@ use dom::bindings::str::DOMString; use dom::bluetoothadvertisingdata::BluetoothAdvertisingData; use dom::bluetoothdevice::BluetoothDevice; use dom::bluetoothuuid::{BluetoothServiceUUID, BluetoothUUID}; +use dom::globalscope::GlobalScope; use dom::promise::Promise; use ipc_channel::ipc::{self, IpcSender}; use js::conversions::ToJSValConvertible; @@ -52,7 +53,7 @@ impl Bluetooth { } } - pub fn new(global: GlobalRef) -> Root { + pub fn new(global: &GlobalScope) -> Root { reflect_dom_object(box Bluetooth::new_inherited(), global, BluetoothBinding::Wrap) @@ -105,11 +106,14 @@ impl Bluetooth { // Step 12-13. match device { Ok(device) => { - let ad_data = BluetoothAdvertisingData::new(self.global().r(), + let global = self.global(); + let global = global.r(); + let global = global.as_global_scope(); + let ad_data = BluetoothAdvertisingData::new(global, device.appearance, device.tx_power, device.rssi); - Ok(BluetoothDevice::new(self.global().r(), + Ok(BluetoothDevice::new(global, DOMString::from(device.id), device.name.map(DOMString::from), &ad_data)) diff --git a/components/script/dom/bluetoothadvertisingdata.rs b/components/script/dom/bluetoothadvertisingdata.rs index 6cd77385a26..878f4fe82ec 100644 --- a/components/script/dom/bluetoothadvertisingdata.rs +++ b/components/script/dom/bluetoothadvertisingdata.rs @@ -4,9 +4,9 @@ use dom::bindings::codegen::Bindings::BluetoothAdvertisingDataBinding; use dom::bindings::codegen::Bindings::BluetoothAdvertisingDataBinding::BluetoothAdvertisingDataMethods; -use dom::bindings::global::GlobalRef; use dom::bindings::js::Root; use dom::bindings::reflector::{Reflector, reflect_dom_object}; +use dom::globalscope::GlobalScope; // https://webbluetoothcg.github.io/web-bluetooth/#bluetoothadvertisingdata #[dom_struct] @@ -30,7 +30,7 @@ impl BluetoothAdvertisingData { } } - pub fn new(global: GlobalRef, + pub fn new(global: &GlobalScope, appearance: Option, txPower: Option, rssi: Option) diff --git a/components/script/dom/bluetoothcharacteristicproperties.rs b/components/script/dom/bluetoothcharacteristicproperties.rs index fd716d72bb5..ccb5a37a6a8 100644 --- a/components/script/dom/bluetoothcharacteristicproperties.rs +++ b/components/script/dom/bluetoothcharacteristicproperties.rs @@ -5,9 +5,9 @@ use dom::bindings::codegen::Bindings::BluetoothCharacteristicPropertiesBinding; use dom::bindings::codegen::Bindings::BluetoothCharacteristicPropertiesBinding:: BluetoothCharacteristicPropertiesMethods; -use dom::bindings::global::GlobalRef; use dom::bindings::js::Root; use dom::bindings::reflector::{Reflector, reflect_dom_object}; +use dom::globalscope::GlobalScope; // https://webbluetoothcg.github.io/web-bluetooth/#characteristicproperties #[dom_struct] @@ -49,7 +49,7 @@ impl BluetoothCharacteristicProperties { } } - pub fn new(global: GlobalRef, + pub fn new(global: &GlobalScope, broadcast: bool, read: bool, writeWithoutResponse: bool, diff --git a/components/script/dom/bluetoothdevice.rs b/components/script/dom/bluetoothdevice.rs index 1508c0382c8..04327080cd4 100644 --- a/components/script/dom/bluetoothdevice.rs +++ b/components/script/dom/bluetoothdevice.rs @@ -4,12 +4,12 @@ use dom::bindings::codegen::Bindings::BluetoothDeviceBinding; use dom::bindings::codegen::Bindings::BluetoothDeviceBinding::BluetoothDeviceMethods; -use dom::bindings::global::GlobalRef; use dom::bindings::js::{JS, Root, MutHeap, MutNullableHeap}; use dom::bindings::reflector::{Reflectable, Reflector, reflect_dom_object}; use dom::bindings::str::DOMString; use dom::bluetoothadvertisingdata::BluetoothAdvertisingData; use dom::bluetoothremotegattserver::BluetoothRemoteGATTServer; +use dom::globalscope::GlobalScope; // https://webbluetoothcg.github.io/web-bluetooth/#bluetoothdevice #[dom_struct] @@ -35,7 +35,7 @@ impl BluetoothDevice { } } - pub fn new(global: GlobalRef, + pub fn new(global: &GlobalScope, id: DOMString, name: Option, adData: &BluetoothAdvertisingData) @@ -66,6 +66,8 @@ impl BluetoothDeviceMethods for BluetoothDevice { // https://webbluetoothcg.github.io/web-bluetooth/#dom-bluetoothdevice-gatt fn Gatt(&self) -> Root { - self.gatt.or_init(|| BluetoothRemoteGATTServer::new(self.global().r(), self)) + self.gatt.or_init(|| { + BluetoothRemoteGATTServer::new(self.global().r().as_global_scope(), self) + }) } } diff --git a/components/script/dom/bluetoothremotegattcharacteristic.rs b/components/script/dom/bluetoothremotegattcharacteristic.rs index 6b7ba1dcfad..701a6ddd2a2 100644 --- a/components/script/dom/bluetoothremotegattcharacteristic.rs +++ b/components/script/dom/bluetoothremotegattcharacteristic.rs @@ -14,7 +14,6 @@ use dom::bindings::codegen::Bindings::BluetoothRemoteGATTServerBinding::Bluetoot use dom::bindings::codegen::Bindings::BluetoothRemoteGATTServiceBinding::BluetoothRemoteGATTServiceMethods; use dom::bindings::error::{ErrorResult, Fallible}; use dom::bindings::error::Error::{self, InvalidModification, Network, NotSupported, Security}; -use dom::bindings::global::GlobalRef; use dom::bindings::js::{JS, MutHeap, Root}; use dom::bindings::reflector::{Reflectable, Reflector, reflect_dom_object}; use dom::bindings::str::{ByteString, DOMString}; @@ -23,6 +22,7 @@ use dom::bluetoothcharacteristicproperties::BluetoothCharacteristicProperties; use dom::bluetoothremotegattdescriptor::BluetoothRemoteGATTDescriptor; use dom::bluetoothremotegattservice::BluetoothRemoteGATTService; use dom::bluetoothuuid::{BluetoothDescriptorUUID, BluetoothUUID}; +use dom::globalscope::GlobalScope; use dom::promise::Promise; use ipc_channel::ipc::{self, IpcSender}; use net_traits::bluetooth_thread::BluetoothMethodMsg; @@ -59,7 +59,7 @@ impl BluetoothRemoteGATTCharacteristic { } } - pub fn new(global: GlobalRef, + pub fn new(global: &GlobalScope, service: &BluetoothRemoteGATTService, uuid: DOMString, properties: &BluetoothCharacteristicProperties, @@ -95,7 +95,7 @@ impl BluetoothRemoteGATTCharacteristic { let descriptor = receiver.recv().unwrap(); match descriptor { Ok(descriptor) => { - Ok(BluetoothRemoteGATTDescriptor::new(self.global().r(), + Ok(BluetoothRemoteGATTDescriptor::new(self.global().r().as_global_scope(), self, DOMString::from(descriptor.uuid), descriptor.instance_id)) @@ -126,7 +126,7 @@ impl BluetoothRemoteGATTCharacteristic { match descriptors_vec { Ok(descriptor_vec) => { Ok(descriptor_vec.into_iter() - .map(|desc| BluetoothRemoteGATTDescriptor::new(self.global().r(), + .map(|desc| BluetoothRemoteGATTDescriptor::new(self.global().r().as_global_scope(), self, DOMString::from(desc.uuid), desc.instance_id)) diff --git a/components/script/dom/bluetoothremotegattdescriptor.rs b/components/script/dom/bluetoothremotegattdescriptor.rs index d036f8bd9ea..ee4c6ce1af5 100644 --- a/components/script/dom/bluetoothremotegattdescriptor.rs +++ b/components/script/dom/bluetoothremotegattdescriptor.rs @@ -13,12 +13,12 @@ use dom::bindings::codegen::Bindings::BluetoothRemoteGATTServerBinding::Bluetoot use dom::bindings::codegen::Bindings::BluetoothRemoteGATTServiceBinding::BluetoothRemoteGATTServiceMethods; use dom::bindings::error::{ErrorResult, Fallible}; use dom::bindings::error::Error::{self, InvalidModification, Network, Security}; -use dom::bindings::global::GlobalRef; use dom::bindings::js::{JS, MutHeap, Root}; use dom::bindings::reflector::{Reflectable, Reflector, reflect_dom_object}; use dom::bindings::str::{ByteString, DOMString}; use dom::bluetooth::result_to_promise; use dom::bluetoothremotegattcharacteristic::{BluetoothRemoteGATTCharacteristic, MAXIMUM_ATTRIBUTE_LENGTH}; +use dom::globalscope::GlobalScope; use dom::promise::Promise; use ipc_channel::ipc::{self, IpcSender}; use net_traits::bluetooth_thread::BluetoothMethodMsg; @@ -48,7 +48,7 @@ impl BluetoothRemoteGATTDescriptor { } } - pub fn new(global: GlobalRef, + pub fn new(global: &GlobalScope, characteristic: &BluetoothRemoteGATTCharacteristic, uuid: DOMString, instanceID: String) diff --git a/components/script/dom/bluetoothremotegattserver.rs b/components/script/dom/bluetoothremotegattserver.rs index 3439ba53350..3a939614d36 100644 --- a/components/script/dom/bluetoothremotegattserver.rs +++ b/components/script/dom/bluetoothremotegattserver.rs @@ -8,7 +8,6 @@ use dom::bindings::codegen::Bindings::BluetoothRemoteGATTServerBinding; use dom::bindings::codegen::Bindings::BluetoothRemoteGATTServerBinding::BluetoothRemoteGATTServerMethods; use dom::bindings::error::{ErrorResult, Fallible}; use dom::bindings::error::Error::{self, Security}; -use dom::bindings::global::GlobalRef; use dom::bindings::js::{JS, MutHeap, Root}; use dom::bindings::reflector::{Reflectable, Reflector, reflect_dom_object}; use dom::bindings::str::DOMString; @@ -16,6 +15,7 @@ use dom::bluetooth::result_to_promise; use dom::bluetoothdevice::BluetoothDevice; use dom::bluetoothremotegattservice::BluetoothRemoteGATTService; use dom::bluetoothuuid::{BluetoothServiceUUID, BluetoothUUID}; +use dom::globalscope::GlobalScope; use dom::promise::Promise; use ipc_channel::ipc::{self, IpcSender}; use net_traits::bluetooth_thread::BluetoothMethodMsg; @@ -39,10 +39,10 @@ impl BluetoothRemoteGATTServer { } } - pub fn new(global: GlobalRef, device: &BluetoothDevice) -> Root { + pub fn new(global: &GlobalScope, device: &BluetoothDevice) -> Root { reflect_dom_object(box BluetoothRemoteGATTServer::new_inherited(device), - global, - BluetoothRemoteGATTServerBinding::Wrap) + global, + BluetoothRemoteGATTServerBinding::Wrap) } fn get_bluetooth_thread(&self) -> IpcSender { @@ -80,7 +80,7 @@ impl BluetoothRemoteGATTServer { let service = receiver.recv().unwrap(); match service { Ok(service) => { - Ok(BluetoothRemoteGATTService::new(self.global().r(), + Ok(BluetoothRemoteGATTService::new(self.global().r().as_global_scope(), &self.device.get(), DOMString::from(service.uuid), service.is_primary, @@ -112,7 +112,7 @@ impl BluetoothRemoteGATTServer { match services_vec { Ok(service_vec) => { Ok(service_vec.into_iter() - .map(|service| BluetoothRemoteGATTService::new(self.global().r(), + .map(|service| BluetoothRemoteGATTService::new(self.global().r().as_global_scope(), &self.device.get(), DOMString::from(service.uuid), service.is_primary, diff --git a/components/script/dom/bluetoothremotegattservice.rs b/components/script/dom/bluetoothremotegattservice.rs index 3ece2507cd3..3a590b4738a 100644 --- a/components/script/dom/bluetoothremotegattservice.rs +++ b/components/script/dom/bluetoothremotegattservice.rs @@ -7,7 +7,6 @@ use dom::bindings::codegen::Bindings::BluetoothRemoteGATTServiceBinding; use dom::bindings::codegen::Bindings::BluetoothRemoteGATTServiceBinding::BluetoothRemoteGATTServiceMethods; use dom::bindings::error::Error::{self, Security}; use dom::bindings::error::Fallible; -use dom::bindings::global::GlobalRef; use dom::bindings::js::{JS, MutHeap, Root}; use dom::bindings::reflector::{Reflectable, Reflector, reflect_dom_object}; use dom::bindings::str::DOMString; @@ -16,6 +15,7 @@ use dom::bluetoothcharacteristicproperties::BluetoothCharacteristicProperties; use dom::bluetoothdevice::BluetoothDevice; use dom::bluetoothremotegattcharacteristic::BluetoothRemoteGATTCharacteristic; use dom::bluetoothuuid::{BluetoothCharacteristicUUID, BluetoothServiceUUID, BluetoothUUID}; +use dom::globalscope::GlobalScope; use dom::promise::Promise; use ipc_channel::ipc::{self, IpcSender}; use net_traits::bluetooth_thread::BluetoothMethodMsg; @@ -46,7 +46,7 @@ impl BluetoothRemoteGATTService { } } - pub fn new(global: GlobalRef, + pub fn new(global: &GlobalScope, device: &BluetoothDevice, uuid: DOMString, isPrimary: bool, @@ -84,7 +84,10 @@ impl BluetoothRemoteGATTService { let characteristic = receiver.recv().unwrap(); match characteristic { Ok(characteristic) => { - let properties = BluetoothCharacteristicProperties::new(self.global().r(), + let global = self.global(); + let global = global.r(); + let global = global.as_global_scope(); + let properties = BluetoothCharacteristicProperties::new(global, characteristic.broadcast, characteristic.read, characteristic.write_without_response, @@ -94,7 +97,7 @@ impl BluetoothRemoteGATTService { characteristic.authenticated_signed_writes, characteristic.reliable_write, characteristic.writable_auxiliaries); - Ok(BluetoothRemoteGATTCharacteristic::new(self.global().r(), + Ok(BluetoothRemoteGATTCharacteristic::new(global, self, DOMString::from(characteristic.uuid), &properties, @@ -127,7 +130,10 @@ impl BluetoothRemoteGATTService { match characteristics_vec { Ok(characteristic_vec) => { for characteristic in characteristic_vec { - let properties = BluetoothCharacteristicProperties::new(self.global().r(), + let global = self.global(); + let global = global.r(); + let global = global.as_global_scope(); + let properties = BluetoothCharacteristicProperties::new(global, characteristic.broadcast, characteristic.read, characteristic.write_without_response, @@ -137,7 +143,7 @@ impl BluetoothRemoteGATTService { characteristic.authenticated_signed_writes, characteristic.reliable_write, characteristic.writable_auxiliaries); - characteristics.push(BluetoothRemoteGATTCharacteristic::new(self.global().r(), + characteristics.push(BluetoothRemoteGATTCharacteristic::new(global, self, DOMString::from(characteristic.uuid), &properties, @@ -167,7 +173,7 @@ impl BluetoothRemoteGATTService { let service = receiver.recv().unwrap(); match service { Ok(service) => { - Ok(BluetoothRemoteGATTService::new(self.global().r(), + Ok(BluetoothRemoteGATTService::new(self.global().r().as_global_scope(), &self.device.get(), DOMString::from(service.uuid), service.is_primary, @@ -201,7 +207,7 @@ impl BluetoothRemoteGATTService { match services_vec { Ok(service_vec) => { Ok(service_vec.into_iter() - .map(|service| BluetoothRemoteGATTService::new(self.global().r(), + .map(|service| BluetoothRemoteGATTService::new(self.global().r().as_global_scope(), &self.device.get(), DOMString::from(service.uuid), service.is_primary, diff --git a/components/script/dom/canvasgradient.rs b/components/script/dom/canvasgradient.rs index a805b485796..0fafc1c6f0f 100644 --- a/components/script/dom/canvasgradient.rs +++ b/components/script/dom/canvasgradient.rs @@ -9,11 +9,11 @@ use dom::bindings::cell::DOMRefCell; use dom::bindings::codegen::Bindings::CanvasGradientBinding; use dom::bindings::codegen::Bindings::CanvasGradientBinding::CanvasGradientMethods; use dom::bindings::error::{Error, ErrorResult}; -use dom::bindings::global::GlobalRef; use dom::bindings::js::Root; use dom::bindings::num::Finite; use dom::bindings::reflector::{Reflector, reflect_dom_object}; use dom::bindings::str::DOMString; +use dom::globalscope::GlobalScope; // https://html.spec.whatwg.org/multipage/#canvasgradient #[dom_struct] @@ -38,7 +38,7 @@ impl CanvasGradient { } } - pub fn new(global: GlobalRef, style: CanvasGradientStyle) -> Root { + pub fn new(global: &GlobalScope, style: CanvasGradientStyle) -> Root { reflect_dom_object(box CanvasGradient::new_inherited(style), global, CanvasGradientBinding::Wrap) diff --git a/components/script/dom/canvaspattern.rs b/components/script/dom/canvaspattern.rs index 059710a296b..5fdb911c73a 100644 --- a/components/script/dom/canvaspattern.rs +++ b/components/script/dom/canvaspattern.rs @@ -4,10 +4,10 @@ use canvas_traits::{FillOrStrokeStyle, RepetitionStyle, SurfaceStyle}; use dom::bindings::codegen::Bindings::CanvasPatternBinding; -use dom::bindings::global::GlobalRef; use dom::bindings::js::Root; use dom::bindings::reflector::{Reflector, reflect_dom_object}; use dom::canvasgradient::ToFillOrStrokeStyle; +use dom::globalscope::GlobalScope; use euclid::size::Size2D; // https://html.spec.whatwg.org/multipage/#canvaspattern @@ -43,7 +43,7 @@ impl CanvasPattern { origin_clean: origin_clean, } } - pub fn new(global: GlobalRef, + pub fn new(global: &GlobalScope, surface_data: Vec, surface_size: Size2D, repeat: RepetitionStyle, diff --git a/components/script/dom/canvasrenderingcontext2d.rs b/components/script/dom/canvasrenderingcontext2d.rs index 4b598407829..e4815e5f472 100644 --- a/components/script/dom/canvasrenderingcontext2d.rs +++ b/components/script/dom/canvasrenderingcontext2d.rs @@ -140,7 +140,7 @@ impl CanvasRenderingContext2D { size: Size2D) -> Root { reflect_dom_object(box CanvasRenderingContext2D::new_inherited(global, canvas, size), - global, + global.as_global_scope(), CanvasRenderingContext2DBinding::Wrap) } @@ -1016,12 +1016,12 @@ impl CanvasRenderingContext2DMethods for CanvasRenderingContext2D { let sw = cmp::max(1, sw.abs().to_u32().unwrap()); let sh = cmp::max(1, sh.abs().to_u32().unwrap()); - Ok(ImageData::new(self.global().r(), sw, sh, None)) + Ok(ImageData::new(self.global().r().as_global_scope(), sw, sh, None)) } // https://html.spec.whatwg.org/multipage/#dom-context-2d-createimagedata fn CreateImageData_(&self, imagedata: &ImageData) -> Fallible> { - Ok(ImageData::new(self.global().r(), + Ok(ImageData::new(self.global().r().as_global_scope(), imagedata.Width(), imagedata.Height(), None)) @@ -1077,7 +1077,7 @@ impl CanvasRenderingContext2DMethods for CanvasRenderingContext2D { chunk[2] = UNPREMULTIPLY_TABLE[256 * alpha + chunk[2] as usize]; } - Ok(ImageData::new(self.global().r(), sw, sh, Some(data))) + Ok(ImageData::new(self.global().r().as_global_scope(), sw, sh, Some(data))) } // https://html.spec.whatwg.org/multipage/#dom-context-2d-putimagedata @@ -1121,7 +1121,7 @@ impl CanvasRenderingContext2DMethods for CanvasRenderingContext2D { x1: Finite, y1: Finite) -> Root { - CanvasGradient::new(self.global().r(), + CanvasGradient::new(self.global().r().as_global_scope(), CanvasGradientStyle::Linear(LinearGradientStyle::new(*x0, *y0, *x1, @@ -1142,7 +1142,7 @@ impl CanvasRenderingContext2DMethods for CanvasRenderingContext2D { return Err(Error::IndexSize); } - Ok(CanvasGradient::new(self.global().r(), + Ok(CanvasGradient::new(self.global().r().as_global_scope(), CanvasGradientStyle::Radial(RadialGradientStyle::new(*x0, *y0, *r0, @@ -1182,7 +1182,7 @@ impl CanvasRenderingContext2DMethods for CanvasRenderingContext2D { } if let Ok(rep) = RepetitionStyle::from_str(&repetition) { - Ok(CanvasPattern::new(self.global().r(), + Ok(CanvasPattern::new(self.global().r().as_global_scope(), image_data, image_size, rep, diff --git a/components/script/dom/client.rs b/components/script/dom/client.rs index 74ed61a52a7..7f51b251627 100644 --- a/components/script/dom/client.rs +++ b/components/script/dom/client.rs @@ -4,7 +4,6 @@ use dom::bindings::codegen::Bindings::ClientBinding::{ClientMethods, Wrap}; use dom::bindings::codegen::Bindings::ClientBinding::FrameType; -use dom::bindings::global::GlobalRef; use dom::bindings::js::JS; use dom::bindings::js::Root; use dom::bindings::reflector::{Reflector, reflect_dom_object}; @@ -36,7 +35,9 @@ impl Client { } pub fn new(window: &Window) -> Root { - reflect_dom_object(box Client::new_inherited(window.get_url()), GlobalRef::Window(window), Wrap) + reflect_dom_object(box Client::new_inherited(window.get_url()), + window, + Wrap) } } diff --git a/components/script/dom/closeevent.rs b/components/script/dom/closeevent.rs index 07e2fbaa943..7a076df8362 100644 --- a/components/script/dom/closeevent.rs +++ b/components/script/dom/closeevent.rs @@ -12,6 +12,7 @@ use dom::bindings::js::Root; use dom::bindings::reflector::reflect_dom_object; use dom::bindings::str::DOMString; use dom::event::{Event, EventBubbles, EventCancelable}; +use dom::globalscope::GlobalScope; use string_cache::Atom; #[dom_struct] @@ -32,13 +33,13 @@ impl CloseEvent { } } - pub fn new_uninitialized(global: GlobalRef) -> Root { + pub fn new_uninitialized(global: &GlobalScope) -> Root { reflect_dom_object(box CloseEvent::new_inherited(false, 0, DOMString::new()), global, CloseEventBinding::Wrap) } - pub fn new(global: GlobalRef, + pub fn new(global: &GlobalScope, type_: Atom, bubbles: EventBubbles, cancelable: EventCancelable, @@ -63,7 +64,7 @@ impl CloseEvent { -> Fallible> { let bubbles = EventBubbles::from(init.parent.bubbles); let cancelable = EventCancelable::from(init.parent.cancelable); - Ok(CloseEvent::new(global, + Ok(CloseEvent::new(global.as_global_scope(), Atom::from(type_), bubbles, cancelable, diff --git a/components/script/dom/crypto.rs b/components/script/dom/crypto.rs index 165a3834227..45c1c4639d5 100644 --- a/components/script/dom/crypto.rs +++ b/components/script/dom/crypto.rs @@ -8,9 +8,9 @@ use dom::bindings::codegen::Bindings::CryptoBinding; use dom::bindings::codegen::Bindings::CryptoBinding::CryptoMethods; use dom::bindings::conversions::array_buffer_view_data; use dom::bindings::error::{Error, Fallible}; -use dom::bindings::global::GlobalRef; use dom::bindings::js::Root; use dom::bindings::reflector::{Reflector, reflect_dom_object}; +use dom::globalscope::GlobalScope; use js::jsapi::{JSContext, JSObject}; use js::jsapi::{JS_GetArrayBufferViewType, Type}; use rand::{OsRng, Rng}; @@ -33,7 +33,7 @@ impl Crypto { } } - pub fn new(global: GlobalRef) -> Root { + pub fn new(global: &GlobalScope) -> Root { reflect_dom_object(box Crypto::new_inherited(), global, CryptoBinding::Wrap) } } diff --git a/components/script/dom/cssstyledeclaration.rs b/components/script/dom/cssstyledeclaration.rs index 0b8c9d8a062..77aee91ce48 100644 --- a/components/script/dom/cssstyledeclaration.rs +++ b/components/script/dom/cssstyledeclaration.rs @@ -5,7 +5,6 @@ use cssparser::ToCss; use dom::bindings::codegen::Bindings::CSSStyleDeclarationBinding::{self, CSSStyleDeclarationMethods}; use dom::bindings::error::{Error, ErrorResult, Fallible}; -use dom::bindings::global::GlobalRef; use dom::bindings::inheritance::Castable; use dom::bindings::js::{JS, Root}; use dom::bindings::reflector::{Reflector, reflect_dom_object}; @@ -71,7 +70,7 @@ impl CSSStyleDeclaration { reflect_dom_object(box CSSStyleDeclaration::new_inherited(owner, pseudo, modification_access), - GlobalRef::Window(global), + global, CSSStyleDeclarationBinding::Wrap) } diff --git a/components/script/dom/customevent.rs b/components/script/dom/customevent.rs index 301c3b6f816..043fd98193c 100644 --- a/components/script/dom/customevent.rs +++ b/components/script/dom/customevent.rs @@ -12,6 +12,7 @@ use dom::bindings::js::{MutHeapJSVal, Root}; use dom::bindings::reflector::reflect_dom_object; use dom::bindings::str::DOMString; use dom::event::Event; +use dom::globalscope::GlobalScope; use js::jsapi::{HandleValue, JSContext}; use js::jsval::JSVal; use string_cache::Atom; @@ -32,12 +33,12 @@ impl CustomEvent { } } - pub fn new_uninitialized(global: GlobalRef) -> Root { + pub fn new_uninitialized(global: &GlobalScope) -> Root { reflect_dom_object(box CustomEvent::new_inherited(), global, CustomEventBinding::Wrap) } - pub fn new(global: GlobalRef, + pub fn new(global: &GlobalScope, type_: Atom, bubbles: bool, cancelable: bool, @@ -52,7 +53,7 @@ impl CustomEvent { type_: DOMString, init: &CustomEventBinding::CustomEventInit) -> Fallible> { - Ok(CustomEvent::new(global, + Ok(CustomEvent::new(global.as_global_scope(), Atom::from(type_), init.parent.bubbles, init.parent.cancelable, diff --git a/components/script/dom/document.rs b/components/script/dom/document.rs index 5e834ef52cd..7857e46ecfe 100644 --- a/components/script/dom/document.rs +++ b/components/script/dom/document.rs @@ -1848,7 +1848,7 @@ impl Document { doc_loader, referrer, referrer_policy), - GlobalRef::Window(window), + window, DocumentBinding::Wrap); { let node = document.upcast::(); @@ -2325,13 +2325,13 @@ impl DocumentMethods for Document { "mouseevents" | "mouseevent" => Ok(Root::upcast(MouseEvent::new_uninitialized(&self.window))), "customevent" => - Ok(Root::upcast(CustomEvent::new_uninitialized(GlobalRef::Window(&self.window)))), + Ok(Root::upcast(CustomEvent::new_uninitialized(self.window.upcast()))), "htmlevents" | "events" | "event" | "svgevents" => - Ok(Event::new_uninitialized(GlobalRef::Window(&self.window))), + Ok(Event::new_uninitialized(&self.window.upcast())), "keyboardevent" => Ok(Root::upcast(KeyboardEvent::new_uninitialized(&self.window))), "messageevent" => - Ok(Root::upcast(MessageEvent::new_uninitialized(GlobalRef::Window(&self.window)))), + Ok(Root::upcast(MessageEvent::new_uninitialized(self.window.upcast()))), "touchevent" => Ok(Root::upcast( TouchEvent::new_uninitialized(&self.window, @@ -2341,25 +2341,25 @@ impl DocumentMethods for Document { ) )), "webglcontextevent" => - Ok(Root::upcast(WebGLContextEvent::new_uninitialized(GlobalRef::Window(&self.window)))), + Ok(Root::upcast(WebGLContextEvent::new_uninitialized(self.window.upcast()))), "storageevent" => { let USVString(url) = self.URL(); Ok(Root::upcast(StorageEvent::new_uninitialized(&self.window, DOMString::from(url)))) }, "progressevent" => - Ok(Root::upcast(ProgressEvent::new_uninitialized(&self.window))), + Ok(Root::upcast(ProgressEvent::new_uninitialized(self.window.upcast()))), "focusevent" => - Ok(Root::upcast(FocusEvent::new_uninitialized(GlobalRef::Window(&self.window)))), + Ok(Root::upcast(FocusEvent::new_uninitialized(self.window.upcast()))), "errorevent" => - Ok(Root::upcast(ErrorEvent::new_uninitialized(GlobalRef::Window(&self.window)))), + Ok(Root::upcast(ErrorEvent::new_uninitialized(self.window.upcast()))), "closeevent" => - Ok(Root::upcast(CloseEvent::new_uninitialized(GlobalRef::Window(&self.window)))), + Ok(Root::upcast(CloseEvent::new_uninitialized(self.window.upcast()))), "popstateevent" => - Ok(Root::upcast(PopStateEvent::new_uninitialized(GlobalRef::Window(&self.window)))), + Ok(Root::upcast(PopStateEvent::new_uninitialized(self.window.upcast()))), "hashchangeevent" => - Ok(Root::upcast(HashChangeEvent::new_uninitialized(GlobalRef::Window(&self.window)))), + Ok(Root::upcast(HashChangeEvent::new_uninitialized(&self.window.upcast()))), "pagetransitionevent" => - Ok(Root::upcast(PageTransitionEvent::new_uninitialized(GlobalRef::Window(&self.window)))), + Ok(Root::upcast(PageTransitionEvent::new_uninitialized(self.window.upcast()))), _ => Err(Error::NotSupported), } @@ -2993,7 +2993,7 @@ impl DocumentProgressHandler { fn dispatch_load(&self) { let document = self.addr.root(); let window = document.window(); - let event = Event::new(GlobalRef::Window(window), + let event = Event::new(window.upcast(), atom!("load"), EventBubbles::DoesNotBubble, EventCancelable::NotCancelable); diff --git a/components/script/dom/domexception.rs b/components/script/dom/domexception.rs index e32d5dc40ac..2a5946193b6 100644 --- a/components/script/dom/domexception.rs +++ b/components/script/dom/domexception.rs @@ -5,10 +5,10 @@ use dom::bindings::codegen::Bindings::DOMExceptionBinding; use dom::bindings::codegen::Bindings::DOMExceptionBinding::DOMExceptionConstants; use dom::bindings::codegen::Bindings::DOMExceptionBinding::DOMExceptionMethods; -use dom::bindings::global::GlobalRef; use dom::bindings::js::Root; use dom::bindings::reflector::{Reflector, reflect_dom_object}; use dom::bindings::str::DOMString; +use dom::globalscope::GlobalScope; #[repr(u16)] #[derive(JSTraceable, Copy, Clone, Debug, HeapSizeOf)] @@ -52,7 +52,7 @@ impl DOMException { } } - pub fn new(global: GlobalRef, code: DOMErrorName) -> Root { + pub fn new(global: &GlobalScope, code: DOMErrorName) -> Root { reflect_dom_object(box DOMException::new_inherited(code), global, DOMExceptionBinding::Wrap) diff --git a/components/script/dom/domimplementation.rs b/components/script/dom/domimplementation.rs index dd55630204c..42d744bd6a5 100644 --- a/components/script/dom/domimplementation.rs +++ b/components/script/dom/domimplementation.rs @@ -8,7 +8,6 @@ use dom::bindings::codegen::Bindings::DOMImplementationBinding::DOMImplementatio use dom::bindings::codegen::Bindings::DocumentBinding::DocumentMethods; use dom::bindings::codegen::Bindings::NodeBinding::NodeMethods; use dom::bindings::error::Fallible; -use dom::bindings::global::GlobalRef; use dom::bindings::inheritance::Castable; use dom::bindings::js::{JS, Root}; use dom::bindings::reflector::{Reflector, reflect_dom_object}; @@ -43,7 +42,7 @@ impl DOMImplementation { pub fn new(document: &Document) -> Root { let window = document.window(); reflect_dom_object(box DOMImplementation::new_inherited(document), - GlobalRef::Window(window), + window, DOMImplementationBinding::Wrap) } } diff --git a/components/script/dom/dommatrix.rs b/components/script/dom/dommatrix.rs index c63290c9326..2ccf4b126fb 100644 --- a/components/script/dom/dommatrix.rs +++ b/components/script/dom/dommatrix.rs @@ -10,6 +10,7 @@ use dom::bindings::inheritance::Castable; use dom::bindings::js::Root; use dom::bindings::reflector::reflect_dom_object; use dom::dommatrixreadonly::{dommatrixinit_to_matrix, DOMMatrixReadOnly, entries_to_matrix}; +use dom::globalscope::GlobalScope; use euclid::Matrix4D; @@ -20,7 +21,7 @@ pub struct DOMMatrix { impl DOMMatrix { #[allow(unrooted_must_root)] - pub fn new(global: GlobalRef, is2D: bool, matrix: Matrix4D) -> Root { + pub fn new(global: &GlobalScope, is2D: bool, matrix: Matrix4D) -> Root { let dommatrix = Self::new_inherited(is2D, matrix); reflect_dom_object(box dommatrix, global, Wrap) } @@ -40,7 +41,7 @@ impl DOMMatrix { pub fn Constructor_(global: GlobalRef, entries: Vec) -> Fallible> { entries_to_matrix(&entries[..]) .map(|(is2D, matrix)| { - Self::new(global, is2D, matrix) + Self::new(global.as_global_scope(), is2D, matrix) }) } @@ -48,11 +49,11 @@ impl DOMMatrix { pub fn FromMatrix(global: GlobalRef, other: &DOMMatrixInit) -> Fallible> { dommatrixinit_to_matrix(&other) .map(|(is2D, matrix)| { - Self::new(global, is2D, matrix) + Self::new(global.as_global_scope(), is2D, matrix) }) } - pub fn from_readonly(global: GlobalRef, ro: &DOMMatrixReadOnly) -> Root { + pub fn from_readonly(global: &GlobalScope, ro: &DOMMatrixReadOnly) -> Root { Self::new(global, ro.is_2d(), ro.matrix().clone()) } } diff --git a/components/script/dom/dommatrixreadonly.rs b/components/script/dom/dommatrixreadonly.rs index 5c6d66c9a1a..b643ef3131a 100644 --- a/components/script/dom/dommatrixreadonly.rs +++ b/components/script/dom/dommatrixreadonly.rs @@ -13,6 +13,7 @@ use dom::bindings::js::Root; use dom::bindings::reflector::{reflect_dom_object, Reflectable, Reflector}; use dom::dommatrix::DOMMatrix; use dom::dompoint::DOMPoint; +use dom::globalscope::GlobalScope; use euclid::{Matrix4D, Point4D, Radians}; use std::cell::{Cell, Ref}; use std::f64; @@ -26,7 +27,7 @@ pub struct DOMMatrixReadOnly { impl DOMMatrixReadOnly { #[allow(unrooted_must_root)] - pub fn new(global: GlobalRef, is2D: bool, matrix: Matrix4D) -> Root { + pub fn new(global: &GlobalScope, is2D: bool, matrix: Matrix4D) -> Root { let dommatrix = Self::new_inherited(is2D, matrix); reflect_dom_object(box dommatrix, global, Wrap) } @@ -41,14 +42,14 @@ impl DOMMatrixReadOnly { // https://drafts.fxtf.org/geometry-1/#dom-dommatrixreadonly-dommatrixreadonly pub fn Constructor(global: GlobalRef) -> Fallible> { - Ok(Self::new(global, true, Matrix4D::identity())) + Ok(Self::new(global.as_global_scope(), true, Matrix4D::identity())) } // https://drafts.fxtf.org/geometry-1/#dom-dommatrixreadonly-dommatrixreadonly-numbersequence pub fn Constructor_(global: GlobalRef, entries: Vec) -> Fallible> { entries_to_matrix(&entries[..]) .map(|(is2D, matrix)| { - Self::new(global, is2D, matrix) + Self::new(global.as_global_scope(), is2D, matrix) }) } @@ -56,7 +57,7 @@ impl DOMMatrixReadOnly { pub fn FromMatrix(global: GlobalRef, other: &DOMMatrixInit) -> Fallible> { dommatrixinit_to_matrix(&other) .map(|(is2D, matrix)| { - Self::new(global, is2D, matrix) + Self::new(global.as_global_scope(), is2D, matrix) }) } @@ -463,48 +464,50 @@ impl DOMMatrixReadOnlyMethods for DOMMatrixReadOnly { // https://drafts.fxtf.org/geometry-1/#dom-dommatrixreadonly-translate fn Translate(&self, tx: f64, ty: f64, tz: f64) -> Root { - DOMMatrix::from_readonly(self.global().r(), self).TranslateSelf(tx, ty, tz) + DOMMatrix::from_readonly(self.global().r().as_global_scope(), self).TranslateSelf(tx, ty, tz) } // https://drafts.fxtf.org/geometry-1/#dom-dommatrixreadonly-scale fn Scale(&self, scaleX: f64, scaleY: Option, scaleZ: f64, originX: f64, originY: f64, originZ: f64) -> Root { - DOMMatrix::from_readonly(self.global().r(), self).ScaleSelf(scaleX, scaleY, scaleZ, originX, originY, originZ) + DOMMatrix::from_readonly(self.global().r().as_global_scope(), self) + .ScaleSelf(scaleX, scaleY, scaleZ, originX, originY, originZ) } // https://drafts.fxtf.org/geometry-1/#dom-dommatrixreadonly-scale3d fn Scale3d(&self, scale: f64, originX: f64, originY: f64, originZ: f64) -> Root { - DOMMatrix::from_readonly(self.global().r(), self).Scale3dSelf(scale, originX, originY, originZ) + DOMMatrix::from_readonly(self.global().r().as_global_scope(), self) + .Scale3dSelf(scale, originX, originY, originZ) } // https://drafts.fxtf.org/geometry-1/#dom-dommatrixreadonly-rotate fn Rotate(&self, rotX: f64, rotY: Option, rotZ: Option) -> Root { - DOMMatrix::from_readonly(self.global().r(), self).RotateSelf(rotX, rotY, rotZ) + DOMMatrix::from_readonly(self.global().r().as_global_scope(), self).RotateSelf(rotX, rotY, rotZ) } // https://drafts.fxtf.org/geometry-1/#dom-dommatrixreadonly-rotatefromvector fn RotateFromVector(&self, x: f64, y: f64) -> Root { - DOMMatrix::from_readonly(self.global().r(), self).RotateFromVectorSelf(x, y) + DOMMatrix::from_readonly(self.global().r().as_global_scope(), self).RotateFromVectorSelf(x, y) } // https://drafts.fxtf.org/geometry-1/#dom-dommatrixreadonly-rotateaxisangle fn RotateAxisAngle(&self, x: f64, y: f64, z: f64, angle: f64) -> Root { - DOMMatrix::from_readonly(self.global().r(), self).RotateAxisAngleSelf(x, y, z, angle) + DOMMatrix::from_readonly(self.global().r().as_global_scope(), self).RotateAxisAngleSelf(x, y, z, angle) } // https://drafts.fxtf.org/geometry-1/#dom-dommatrixreadonly-skewx fn SkewX(&self, sx: f64) -> Root { - DOMMatrix::from_readonly(self.global().r(), self).SkewXSelf(sx) + DOMMatrix::from_readonly(self.global().r().as_global_scope(), self).SkewXSelf(sx) } // https://drafts.fxtf.org/geometry-1/#dom-dommatrixreadonly-skewy fn SkewY(&self, sy: f64) -> Root { - DOMMatrix::from_readonly(self.global().r(), self).SkewYSelf(sy) + DOMMatrix::from_readonly(self.global().r().as_global_scope(), self).SkewYSelf(sy) } // https://drafts.fxtf.org/geometry-1/#dom-dommatrixreadonly-multiply fn Multiply(&self, other: &DOMMatrixInit) -> Fallible> { - DOMMatrix::from_readonly(self.global().r(), self).MultiplySelf(&other) + DOMMatrix::from_readonly(self.global().r().as_global_scope(), self).MultiplySelf(&other) } // https://drafts.fxtf.org/geometry-1/#dom-dommatrixreadonly-flipx @@ -515,7 +518,7 @@ impl DOMMatrixReadOnlyMethods for DOMMatrixReadOnly { 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0); let matrix = flip.post_mul(&self.matrix.borrow()); - DOMMatrix::new(self.global().r(), is2D, matrix) + DOMMatrix::new(self.global().r().as_global_scope(), is2D, matrix) } // https://drafts.fxtf.org/geometry-1/#dom-dommatrixreadonly-flipy @@ -526,19 +529,24 @@ impl DOMMatrixReadOnlyMethods for DOMMatrixReadOnly { 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0); let matrix = flip.post_mul(&self.matrix.borrow()); - DOMMatrix::new(self.global().r(), is2D, matrix) + DOMMatrix::new(self.global().r().as_global_scope(), is2D, matrix) } // https://drafts.fxtf.org/geometry-1/#dom-dommatrixreadonly-inverse fn Inverse(&self) -> Root { - DOMMatrix::from_readonly(self.global().r(), self).InvertSelf() + DOMMatrix::from_readonly(self.global().r().as_global_scope(), self).InvertSelf() } // https://drafts.fxtf.org/geometry-1/#dom-dommatrixreadonly-transformpoint fn TransformPoint(&self, point: &DOMPointInit) -> Root { let matrix = self.matrix.borrow(); let result = matrix.transform_point4d(&Point4D::new(point.x, point.y, point.z, point.w)); - DOMPoint::new(self.global().r(), result.x as f64, result.y as f64, result.z as f64, result.w as f64) + DOMPoint::new( + self.global().r().as_global_scope(), + result.x as f64, + result.y as f64, + result.z as f64, + result.w as f64) } } diff --git a/components/script/dom/domparser.rs b/components/script/dom/domparser.rs index a52f0b8b82f..cf82cad01ca 100644 --- a/components/script/dom/domparser.rs +++ b/components/script/dom/domparser.rs @@ -38,7 +38,7 @@ impl DOMParser { pub fn new(window: &Window) -> Root { reflect_dom_object(box DOMParser::new_inherited(window), - GlobalRef::Window(window), + window, DOMParserBinding::Wrap) } diff --git a/components/script/dom/dompoint.rs b/components/script/dom/dompoint.rs index 906a30ea617..49a873a25fc 100644 --- a/components/script/dom/dompoint.rs +++ b/components/script/dom/dompoint.rs @@ -9,6 +9,7 @@ use dom::bindings::global::GlobalRef; use dom::bindings::js::Root; use dom::bindings::reflector::reflect_dom_object; use dom::dompointreadonly::{DOMPointReadOnly, DOMPointWriteMethods}; +use dom::globalscope::GlobalScope; // http://dev.w3.org/fxtf/geometry/Overview.html#dompoint #[dom_struct] @@ -23,7 +24,7 @@ impl DOMPoint { } } - pub fn new(global: GlobalRef, x: f64, y: f64, z: f64, w: f64) -> Root { + pub fn new(global: &GlobalScope, x: f64, y: f64, z: f64, w: f64) -> Root { reflect_dom_object(box DOMPoint::new_inherited(x, y, z, w), global, Wrap) } @@ -33,10 +34,10 @@ impl DOMPoint { z: f64, w: f64) -> Fallible> { - Ok(DOMPoint::new(global, x, y, z, w)) + Ok(DOMPoint::new(global.as_global_scope(), x, y, z, w)) } - pub fn new_from_init(global: GlobalRef, p: &DOMPointInit) -> Root { + pub fn new_from_init(global: &GlobalScope, p: &DOMPointInit) -> Root { DOMPoint::new(global, p.x, p.y, p.z, p.w) } } diff --git a/components/script/dom/dompointreadonly.rs b/components/script/dom/dompointreadonly.rs index aa7efa76267..f905db356ca 100644 --- a/components/script/dom/dompointreadonly.rs +++ b/components/script/dom/dompointreadonly.rs @@ -7,6 +7,7 @@ use dom::bindings::error::Fallible; use dom::bindings::global::GlobalRef; use dom::bindings::js::Root; use dom::bindings::reflector::{Reflector, reflect_dom_object}; +use dom::globalscope::GlobalScope; use std::cell::Cell; // http://dev.w3.org/fxtf/geometry/Overview.html#dompointreadonly @@ -30,7 +31,7 @@ impl DOMPointReadOnly { } } - pub fn new(global: GlobalRef, x: f64, y: f64, z: f64, w: f64) -> Root { + pub fn new(global: &GlobalScope, x: f64, y: f64, z: f64, w: f64) -> Root { reflect_dom_object(box DOMPointReadOnly::new_inherited(x, y, z, w), global, Wrap) @@ -42,7 +43,7 @@ impl DOMPointReadOnly { z: f64, w: f64) -> Fallible> { - Ok(DOMPointReadOnly::new(global, x, y, z, w)) + Ok(DOMPointReadOnly::new(global.as_global_scope(), x, y, z, w)) } } diff --git a/components/script/dom/domquad.rs b/components/script/dom/domquad.rs index a9af14d3d69..238258889a8 100644 --- a/components/script/dom/domquad.rs +++ b/components/script/dom/domquad.rs @@ -11,6 +11,7 @@ use dom::bindings::js::{Root, JS}; use dom::bindings::reflector::{Reflectable, Reflector, reflect_dom_object}; use dom::dompoint::DOMPoint; use dom::domrect::DOMRect; +use dom::globalscope::GlobalScope; // https://drafts.fxtf.org/geometry/#DOMQuad #[dom_struct] @@ -37,7 +38,7 @@ impl DOMQuad { } } - pub fn new(global: GlobalRef, + pub fn new(global: &GlobalScope, p1: &DOMPoint, p2: &DOMPoint, p3: &DOMPoint, @@ -53,6 +54,7 @@ impl DOMQuad { p3: &DOMPointInit, p4: &DOMPointInit) -> Fallible> { + let global = global.as_global_scope(); Ok(DOMQuad::new(global, &*DOMPoint::new_from_init(global, p1), &*DOMPoint::new_from_init(global, p2), @@ -62,6 +64,7 @@ impl DOMQuad { // https://drafts.fxtf.org/geometry/#dom-domquad-fromrect pub fn FromRect(global: GlobalRef, other: &DOMRectInit) -> Root { + let global = global.as_global_scope(); DOMQuad::new(global, &*DOMPoint::new(global, other.x, other.y, 0f64, 1f64), &*DOMPoint::new(global, other.x + other.width, other.y, 0f64, 1f64), @@ -71,6 +74,7 @@ impl DOMQuad { // https://drafts.fxtf.org/geometry/#dom-domquad-fromquad pub fn FromQuad(global: GlobalRef, other: &DOMQuadInit) -> Root { + let global = global.as_global_scope(); DOMQuad::new(global, &DOMPoint::new_from_init(global, &other.p1), &DOMPoint::new_from_init(global, &other.p2), @@ -107,7 +111,7 @@ impl DOMQuadMethods for DOMQuad { let right = self.p1.X().max(self.p2.X()).max(self.p3.X()).max(self.p4.X()); let bottom = self.p1.Y().max(self.p2.Y()).max(self.p3.Y()).max(self.p4.Y()); - DOMRect::new(self.global().r(), + DOMRect::new(self.global().r().as_global_scope(), left, top, right - left, diff --git a/components/script/dom/domrect.rs b/components/script/dom/domrect.rs index 086e21882c6..f70eda2ead1 100644 --- a/components/script/dom/domrect.rs +++ b/components/script/dom/domrect.rs @@ -10,6 +10,7 @@ use dom::bindings::global::GlobalRef; use dom::bindings::js::Root; use dom::bindings::reflector::reflect_dom_object; use dom::domrectreadonly::DOMRectReadOnly; +use dom::globalscope::GlobalScope; #[dom_struct] pub struct DOMRect { @@ -23,7 +24,7 @@ impl DOMRect { } } - pub fn new(global: GlobalRef, x: f64, y: f64, width: f64, height: f64) -> Root { + pub fn new(global: &GlobalScope, x: f64, y: f64, width: f64, height: f64) -> Root { reflect_dom_object(box DOMRect::new_inherited(x, y, width, height), global, DOMRectBinding::Wrap) @@ -35,7 +36,7 @@ impl DOMRect { width: f64, height: f64) -> Fallible> { - Ok(DOMRect::new(global, x, y, width, height)) + Ok(DOMRect::new(global.as_global_scope(), x, y, width, height)) } } diff --git a/components/script/dom/domrectlist.rs b/components/script/dom/domrectlist.rs index 86774a49ff3..392aa18997e 100644 --- a/components/script/dom/domrectlist.rs +++ b/components/script/dom/domrectlist.rs @@ -4,7 +4,6 @@ use dom::bindings::codegen::Bindings::DOMRectListBinding; use dom::bindings::codegen::Bindings::DOMRectListBinding::DOMRectListMethods; -use dom::bindings::global::GlobalRef; use dom::bindings::js::{JS, Root}; use dom::bindings::reflector::{Reflector, reflect_dom_object}; use dom::domrect::DOMRect; @@ -30,7 +29,7 @@ impl DOMRectList { where T: Iterator> { reflect_dom_object(box DOMRectList::new_inherited(rects), - GlobalRef::Window(window), + window, DOMRectListBinding::Wrap) } } diff --git a/components/script/dom/domrectreadonly.rs b/components/script/dom/domrectreadonly.rs index 8e72dae6942..a9d87ec3947 100644 --- a/components/script/dom/domrectreadonly.rs +++ b/components/script/dom/domrectreadonly.rs @@ -7,6 +7,7 @@ use dom::bindings::error::Fallible; use dom::bindings::global::GlobalRef; use dom::bindings::js::Root; use dom::bindings::reflector::{Reflector, reflect_dom_object}; +use dom::globalscope::GlobalScope; use std::cell::Cell; #[dom_struct] @@ -29,7 +30,7 @@ impl DOMRectReadOnly { } } - pub fn new(global: GlobalRef, + pub fn new(global: &GlobalScope, x: f64, y: f64, width: f64, @@ -46,7 +47,7 @@ impl DOMRectReadOnly { width: f64, height: f64) -> Fallible> { - Ok(DOMRectReadOnly::new(global, x, y, width, height)) + Ok(DOMRectReadOnly::new(global.as_global_scope(), x, y, width, height)) } pub fn set_x(&self, value: f64) { diff --git a/components/script/dom/domstringmap.rs b/components/script/dom/domstringmap.rs index 11479d6b5df..687c10ec898 100644 --- a/components/script/dom/domstringmap.rs +++ b/components/script/dom/domstringmap.rs @@ -5,7 +5,6 @@ use dom::bindings::codegen::Bindings::DOMStringMapBinding; use dom::bindings::codegen::Bindings::DOMStringMapBinding::DOMStringMapMethods; use dom::bindings::error::ErrorResult; -use dom::bindings::global::GlobalRef; use dom::bindings::js::{JS, Root}; use dom::bindings::reflector::{Reflector, reflect_dom_object}; use dom::bindings::str::DOMString; @@ -29,7 +28,7 @@ impl DOMStringMap { pub fn new(element: &HTMLElement) -> Root { let window = window_from_node(element); reflect_dom_object(box DOMStringMap::new_inherited(element), - GlobalRef::Window(window.r()), + window.r(), DOMStringMapBinding::Wrap) } } diff --git a/components/script/dom/domtokenlist.rs b/components/script/dom/domtokenlist.rs index c1c09de94c2..00f6ba1abb1 100644 --- a/components/script/dom/domtokenlist.rs +++ b/components/script/dom/domtokenlist.rs @@ -6,7 +6,6 @@ use dom::attr::Attr; use dom::bindings::codegen::Bindings::DOMTokenListBinding; use dom::bindings::codegen::Bindings::DOMTokenListBinding::DOMTokenListMethods; use dom::bindings::error::{Error, ErrorResult, Fallible}; -use dom::bindings::global::GlobalRef; use dom::bindings::js::{JS, Root}; use dom::bindings::reflector::{Reflector, reflect_dom_object}; use dom::bindings::str::DOMString; @@ -34,7 +33,7 @@ impl DOMTokenList { pub fn new(element: &Element, local_name: &Atom) -> Root { let window = window_from_node(element); reflect_dom_object(box DOMTokenList::new_inherited(element, local_name.clone()), - GlobalRef::Window(window.r()), + window.r(), DOMTokenListBinding::Wrap) } diff --git a/components/script/dom/element.rs b/components/script/dom/element.rs index 5e00cb71c75..13937bf904c 100644 --- a/components/script/dom/element.rs +++ b/components/script/dom/element.rs @@ -21,7 +21,6 @@ use dom::bindings::codegen::Bindings::WindowBinding::{ScrollBehavior, ScrollToOp use dom::bindings::codegen::Bindings::WindowBinding::WindowMethods; use dom::bindings::codegen::UnionTypes::NodeOrString; use dom::bindings::error::{Error, ErrorResult, Fallible}; -use dom::bindings::global::GlobalRef; use dom::bindings::inheritance::{Castable, ElementTypeId, HTMLElementTypeId, NodeTypeId}; use dom::bindings::js::{JS, LayoutJS, MutNullableHeap}; use dom::bindings::js::{Root, RootedReference}; @@ -1589,7 +1588,7 @@ impl ElementMethods for Element { let win = window_from_node(self); let raw_rects = self.upcast::().content_boxes(); let rects = raw_rects.iter().map(|rect| { - DOMRect::new(GlobalRef::Window(win.r()), + DOMRect::new(win.upcast(), rect.origin.x.to_f64_px(), rect.origin.y.to_f64_px(), rect.size.width.to_f64_px(), @@ -1602,7 +1601,7 @@ impl ElementMethods for Element { fn GetBoundingClientRect(&self) -> Root { let win = window_from_node(self); let rect = self.upcast::().bounding_content_box(); - DOMRect::new(GlobalRef::Window(win.r()), + DOMRect::new(win.upcast(), rect.origin.x.to_f64_px(), rect.origin.y.to_f64_px(), rect.size.width.to_f64_px(), diff --git a/components/script/dom/errorevent.rs b/components/script/dom/errorevent.rs index 61db675f551..394ce749cdb 100644 --- a/components/script/dom/errorevent.rs +++ b/components/script/dom/errorevent.rs @@ -13,6 +13,7 @@ use dom::bindings::js::{MutHeapJSVal, Root}; use dom::bindings::reflector::reflect_dom_object; use dom::bindings::str::DOMString; use dom::event::{Event, EventBubbles, EventCancelable}; +use dom::globalscope::GlobalScope; use js::jsapi::{HandleValue, JSContext}; use js::jsval::JSVal; use std::cell::Cell; @@ -41,13 +42,13 @@ impl ErrorEvent { } } - pub fn new_uninitialized(global: GlobalRef) -> Root { + pub fn new_uninitialized(global: &GlobalScope) -> Root { reflect_dom_object(box ErrorEvent::new_inherited(), global, ErrorEventBinding::Wrap) } - pub fn new(global: GlobalRef, + pub fn new(global: &GlobalScope, type_: Atom, bubbles: EventBubbles, cancelable: EventCancelable, @@ -94,11 +95,16 @@ impl ErrorEvent { // Dictionaries need to be rooted // https://github.com/servo/servo/issues/6381 rooted!(in(global.get_cx()) let error = init.error); - let event = ErrorEvent::new(global, Atom::from(type_), - bubbles, cancelable, - msg, file_name, - line_num, col_num, - error.handle()); + let event = ErrorEvent::new( + global.as_global_scope(), + Atom::from(type_), + bubbles, + cancelable, + msg, + file_name, + line_num, + col_num, + error.handle()); Ok(event) } diff --git a/components/script/dom/event.rs b/components/script/dom/event.rs index a6dfe7c9ac4..3f5a7c24c8a 100644 --- a/components/script/dom/event.rs +++ b/components/script/dom/event.rs @@ -13,6 +13,7 @@ use dom::bindings::reflector::{Reflector, reflect_dom_object}; use dom::bindings::str::DOMString; use dom::eventdispatcher::EventStatus; use dom::eventtarget::EventTarget; +use dom::globalscope::GlobalScope; use script_thread::Runnable; use std::cell::Cell; use std::default::Default; @@ -115,13 +116,13 @@ impl Event { } } - pub fn new_uninitialized(global: GlobalRef) -> Root { + pub fn new_uninitialized(global: &GlobalScope) -> Root { reflect_dom_object(box Event::new_inherited(), global, EventBinding::Wrap) } - pub fn new(global: GlobalRef, + pub fn new(global: &GlobalScope, type_: Atom, bubbles: EventBubbles, cancelable: EventCancelable) -> Root { @@ -135,7 +136,7 @@ impl Event { init: &EventBinding::EventInit) -> Fallible> { let bubbles = EventBubbles::from(init.bubbles); let cancelable = EventCancelable::from(init.cancelable); - Ok(Event::new(global, Atom::from(type_), bubbles, cancelable)) + Ok(Event::new(global.as_global_scope(), Atom::from(type_), bubbles, cancelable)) } pub fn init_event(&self, type_: Atom, bubbles: bool, cancelable: bool) { diff --git a/components/script/dom/eventsource.rs b/components/script/dom/eventsource.rs index 4007e391852..667627e1e83 100644 --- a/components/script/dom/eventsource.rs +++ b/components/script/dom/eventsource.rs @@ -11,6 +11,7 @@ use dom::bindings::js::Root; use dom::bindings::reflector::reflect_dom_object; use dom::bindings::str::DOMString; use dom::eventtarget::EventTarget; +use dom::globalscope::GlobalScope; use std::cell::Cell; use url::Url; @@ -42,8 +43,10 @@ impl EventSource { } } - fn new(global: GlobalRef, url: Url, with_credentials: bool) -> Root { - reflect_dom_object(box EventSource::new_inherited(url, with_credentials), global, Wrap) + fn new(global: &GlobalScope, url: Url, with_credentials: bool) -> Root { + reflect_dom_object(box EventSource::new_inherited(url, with_credentials), + global, + Wrap) } pub fn Constructor(global: GlobalRef, @@ -56,7 +59,7 @@ impl EventSource { Err(_) => return Err(Error::Syntax) }; // Step 3 - let event_source = EventSource::new(global, url, event_source_init.withCredentials); + let event_source = EventSource::new(global.as_global_scope(), url, event_source_init.withCredentials); // Step 4 // Step 5 // Step 6 diff --git a/components/script/dom/eventtarget.rs b/components/script/dom/eventtarget.rs index 9bdaac20288..fb647d3d590 100644 --- a/components/script/dom/eventtarget.rs +++ b/components/script/dom/eventtarget.rs @@ -500,8 +500,8 @@ impl EventTarget { bubbles: EventBubbles, cancelable: EventCancelable) -> Root { - let global = self.global(); - let event = Event::new(global.r(), Atom::from(name), bubbles, cancelable); + let event = Event::new( + self.global().r().as_global_scope(), Atom::from(name), bubbles, cancelable); event.fire(self); diff --git a/components/script/dom/extendableevent.rs b/components/script/dom/extendableevent.rs index ffb6c3baad2..1888888e841 100644 --- a/components/script/dom/extendableevent.rs +++ b/components/script/dom/extendableevent.rs @@ -11,6 +11,7 @@ use dom::bindings::js::Root; use dom::bindings::reflector::reflect_dom_object; use dom::bindings::str::DOMString; use dom::event::Event; +use dom::globalscope::GlobalScope; use js::jsapi::{HandleValue, JSContext}; use string_cache::Atom; @@ -28,7 +29,7 @@ impl ExtendableEvent { extensions_allowed: true } } - pub fn new(global: GlobalRef, + pub fn new(global: &GlobalScope, type_: Atom, bubbles: bool, cancelable: bool) @@ -44,7 +45,7 @@ impl ExtendableEvent { pub fn Constructor(global: GlobalRef, type_: DOMString, init: &ExtendableEventBinding::ExtendableEventInit) -> Fallible> { - Ok(ExtendableEvent::new(global, + Ok(ExtendableEvent::new(global.as_global_scope(), Atom::from(type_), init.parent.bubbles, init.parent.cancelable)) diff --git a/components/script/dom/extendablemessageevent.rs b/components/script/dom/extendablemessageevent.rs index 202c81c0416..a0d8b3cf76b 100644 --- a/components/script/dom/extendablemessageevent.rs +++ b/components/script/dom/extendablemessageevent.rs @@ -13,6 +13,7 @@ use dom::bindings::str::DOMString; use dom::event::Event; use dom::eventtarget::EventTarget; use dom::extendableevent::ExtendableEvent; +use dom::globalscope::GlobalScope; use js::jsapi::{HandleValue, Heap, JSContext}; use js::jsval::JSVal; use std::default::Default; @@ -27,7 +28,7 @@ pub struct ExtendableMessageEvent { } impl ExtendableMessageEvent { - pub fn new(global: GlobalRef, type_: Atom, + pub fn new(global: &GlobalScope, type_: Atom, bubbles: bool, cancelable: bool, data: HandleValue, origin: DOMString, lastEventId: DOMString) -> Root { @@ -51,7 +52,8 @@ impl ExtendableMessageEvent { init: &ExtendableMessageEventBinding::ExtendableMessageEventInit) -> Fallible> { rooted!(in(global.get_cx()) let data = init.data); - let ev = ExtendableMessageEvent::new(global, Atom::from(type_), + let ev = ExtendableMessageEvent::new(global.as_global_scope(), + Atom::from(type_), init.parent.parent.bubbles, init.parent.parent.cancelable, data.handle(), @@ -66,7 +68,7 @@ impl ExtendableMessageEvent { scope: GlobalRef, message: HandleValue) { let Extendablemessageevent = ExtendableMessageEvent::new( - scope, atom!("message"), false, false, message, + scope.as_global_scope(), atom!("message"), false, false, message, DOMString::new(), DOMString::new()); Extendablemessageevent.upcast::().fire(target); } diff --git a/components/script/dom/file.rs b/components/script/dom/file.rs index 8b4abaaed80..6ee2f0c3771 100644 --- a/components/script/dom/file.rs +++ b/components/script/dom/file.rs @@ -7,10 +7,12 @@ use dom::bindings::codegen::Bindings::FileBinding::FileMethods; use dom::bindings::codegen::UnionTypes::BlobOrString; use dom::bindings::error::{Error, Fallible}; use dom::bindings::global::GlobalRef; +use dom::bindings::inheritance::Castable; use dom::bindings::js::Root; use dom::bindings::reflector::reflect_dom_object; use dom::bindings::str::DOMString; use dom::blob::{Blob, BlobImpl, blob_parts_to_bytes}; +use dom::globalscope::GlobalScope; use dom::window::Window; use net_traits::filemanager_thread::SelectedFile; use time; @@ -41,7 +43,7 @@ impl File { } #[allow(unrooted_must_root)] - pub fn new(global: GlobalRef, blob_impl: BlobImpl, + pub fn new(global: &GlobalScope, blob_impl: BlobImpl, name: DOMString, modified: Option, typeString: &str) -> Root { reflect_dom_object(box File::new_inherited(blob_impl, name, modified, typeString), global, @@ -52,9 +54,7 @@ impl File { pub fn new_from_selected(window: &Window, selected: SelectedFile) -> Root { let name = DOMString::from(selected.filename.to_str().expect("File name encoding error")); - let global = GlobalRef::Window(window); - - File::new(global, BlobImpl::new_from_file(selected.id, selected.filename, selected.size), + File::new(window.upcast(), BlobImpl::new_from_file(selected.id, selected.filename, selected.size), name, Some(selected.modified as i64), &selected.type_string) } @@ -76,7 +76,11 @@ impl File { // NOTE: Following behaviour might be removed in future, // see https://github.com/w3c/FileAPI/issues/41 let replaced_filename = DOMString::from_string(filename.replace("/", ":")); - Ok(File::new(global, BlobImpl::new_from_bytes(bytes), replaced_filename, modified, typeString)) + Ok(File::new(global.as_global_scope(), + BlobImpl::new_from_bytes(bytes), + replaced_filename, + modified, + typeString)) } pub fn name(&self) -> &DOMString { diff --git a/components/script/dom/filelist.rs b/components/script/dom/filelist.rs index 8adbe1ed467..e3654b752dc 100644 --- a/components/script/dom/filelist.rs +++ b/components/script/dom/filelist.rs @@ -4,7 +4,6 @@ use dom::bindings::codegen::Bindings::FileListBinding; use dom::bindings::codegen::Bindings::FileListBinding::FileListMethods; -use dom::bindings::global::GlobalRef; use dom::bindings::js::{JS, Root}; use dom::bindings::reflector::{Reflector, reflect_dom_object}; use dom::file::File; @@ -30,7 +29,7 @@ impl FileList { #[allow(unrooted_must_root)] pub fn new(window: &Window, files: Vec>) -> Root { reflect_dom_object(box FileList::new_inherited(files.iter().map(|r| JS::from_ref(&**r)).collect()), - GlobalRef::Window(window), + window, FileListBinding::Wrap) } diff --git a/components/script/dom/filereader.rs b/components/script/dom/filereader.rs index a82e4dc47bc..ac2aa37ee56 100644 --- a/components/script/dom/filereader.rs +++ b/components/script/dom/filereader.rs @@ -17,6 +17,7 @@ use dom::blob::Blob; use dom::domexception::{DOMErrorName, DOMException}; use dom::event::{Event, EventBubbles, EventCancelable}; use dom::eventtarget::EventTarget; +use dom::globalscope::GlobalScope; use dom::progressevent::ProgressEvent; use encoding::all::UTF_8; use encoding::label::encoding_from_whatwg_label; @@ -88,13 +89,13 @@ impl FileReader { } } - pub fn new(global: GlobalRef) -> Root { + pub fn new(global: &GlobalScope) -> Root { reflect_dom_object(box FileReader::new_inherited(), global, FileReaderBinding::Wrap) } pub fn Constructor(global: GlobalRef) -> Fallible> { - Ok(FileReader::new(global)) + Ok(FileReader::new(global.as_global_scope())) } //https://w3c.github.io/FileAPI/#dfn-error-steps @@ -115,7 +116,7 @@ impl FileReader { *fr.result.borrow_mut() = None; let global = fr.r().global(); - let exception = DOMException::new(global.r(), error); + let exception = DOMException::new(global.r().as_global_scope(), error); fr.error.set(Some(&exception)); fr.dispatch_progress_event(atom!("error"), 0, None); @@ -290,7 +291,7 @@ impl FileReaderMethods for FileReader { *self.result.borrow_mut() = None; let global = self.global(); - let exception = DOMException::new(global.r(), DOMErrorName::AbortError); + let exception = DOMException::new(global.r().as_global_scope(), DOMErrorName::AbortError); self.error.set(Some(&exception)); self.terminate_ongoing_reading(); @@ -319,7 +320,7 @@ impl FileReaderMethods for FileReader { impl FileReader { fn dispatch_progress_event(&self, type_: Atom, loaded: u64, total: Option) { let global = self.global(); - let progressevent = ProgressEvent::new(global.r(), + let progressevent = ProgressEvent::new(global.r().as_global_scope(), type_, EventBubbles::DoesNotBubble, EventCancelable::NotCancelable, total.is_some(), loaded, total.unwrap_or(0)); progressevent.upcast::().fire(self.upcast()); @@ -338,7 +339,7 @@ impl FileReader { // Step 2 if blob.IsClosed() { let global = self.global(); - let exception = DOMException::new(global.r(), DOMErrorName::InvalidStateError); + let exception = DOMException::new(global.r().as_global_scope(), DOMErrorName::InvalidStateError); self.error.set(Some(&exception)); self.dispatch_progress_event(atom!("error"), 0, None); diff --git a/components/script/dom/filereadersync.rs b/components/script/dom/filereadersync.rs index b248848edad..3e8800a65bf 100644 --- a/components/script/dom/filereadersync.rs +++ b/components/script/dom/filereadersync.rs @@ -8,8 +8,7 @@ use dom::bindings::global::GlobalRef; use dom::bindings::js::Root; use dom::bindings::reflector::reflect_dom_object; use dom::eventtarget::EventTarget; - - +use dom::globalscope::GlobalScope; #[dom_struct] pub struct FileReaderSync { @@ -23,12 +22,12 @@ impl FileReaderSync { } } - pub fn new(global: GlobalRef) -> Root { + pub fn new(global: &GlobalScope) -> Root { reflect_dom_object(box FileReaderSync::new_inherited(), global, FileReaderSyncBinding::Wrap) } pub fn Constructor(global: GlobalRef) -> Fallible> { - Ok(FileReaderSync::new(global)) + Ok(FileReaderSync::new(global.as_global_scope())) } } diff --git a/components/script/dom/focusevent.rs b/components/script/dom/focusevent.rs index dd5e41e8426..cb65d40088f 100644 --- a/components/script/dom/focusevent.rs +++ b/components/script/dom/focusevent.rs @@ -13,6 +13,7 @@ use dom::bindings::reflector::reflect_dom_object; use dom::bindings::str::DOMString; use dom::event::{EventBubbles, EventCancelable}; use dom::eventtarget::EventTarget; +use dom::globalscope::GlobalScope; use dom::uievent::UIEvent; use dom::window::Window; use std::default::Default; @@ -31,7 +32,7 @@ impl FocusEvent { } } - pub fn new_uninitialized(global: GlobalRef) -> Root { + pub fn new_uninitialized(global: &GlobalScope) -> Root { reflect_dom_object(box FocusEvent::new_inherited(), global, FocusEventBinding::Wrap) @@ -44,8 +45,7 @@ impl FocusEvent { view: Option<&Window>, detail: i32, related_target: Option<&EventTarget>) -> Root { - let event = box FocusEvent::new_inherited(); - let ev = reflect_dom_object(event, GlobalRef::Window(window), FocusEventBinding::Wrap); + let ev = FocusEvent::new_uninitialized(window.upcast()); ev.upcast::().InitUIEvent(type_, bool::from(can_bubble), bool::from(cancelable), diff --git a/components/script/dom/forcetouchevent.rs b/components/script/dom/forcetouchevent.rs index e982cfdf86e..9e1c5cfcd91 100644 --- a/components/script/dom/forcetouchevent.rs +++ b/components/script/dom/forcetouchevent.rs @@ -5,7 +5,6 @@ use dom::bindings::codegen::Bindings::ForceTouchEventBinding; use dom::bindings::codegen::Bindings::ForceTouchEventBinding::ForceTouchEventMethods; use dom::bindings::codegen::Bindings::UIEventBinding::UIEventMethods; -use dom::bindings::global::GlobalRef; use dom::bindings::inheritance::Castable; use dom::bindings::js::Root; use dom::bindings::num::Finite; @@ -32,7 +31,7 @@ impl ForceTouchEvent { type_: DOMString, force: f32) -> Root { let event = box ForceTouchEvent::new_inherited(force); - let ev = reflect_dom_object(event, GlobalRef::Window(window), ForceTouchEventBinding::Wrap); + let ev = reflect_dom_object(event, window, ForceTouchEventBinding::Wrap); ev.upcast::().InitUIEvent(type_, true, true, Some(window), 0); ev } diff --git a/components/script/dom/formdata.rs b/components/script/dom/formdata.rs index 542b44e804e..e5bdc6ca1d5 100644 --- a/components/script/dom/formdata.rs +++ b/components/script/dom/formdata.rs @@ -14,6 +14,7 @@ use dom::bindings::reflector::{Reflectable, Reflector, reflect_dom_object}; use dom::bindings::str::{DOMString, USVString}; use dom::blob::{Blob, BlobImpl}; use dom::file::File; +use dom::globalscope::GlobalScope; use dom::htmlformelement::{HTMLFormElement, FormDatumValue, FormDatum}; use std::collections::HashMap; use std::collections::hash_map::Entry::{Occupied, Vacant}; @@ -45,14 +46,14 @@ impl FormData { } } - pub fn new(form: Option<&HTMLFormElement>, global: GlobalRef) -> Root { + pub fn new(form: Option<&HTMLFormElement>, global: &GlobalScope) -> Root { reflect_dom_object(box FormData::new_inherited(form), global, FormDataWrap) } pub fn Constructor(global: GlobalRef, form: Option<&HTMLFormElement>) -> Fallible> { // TODO: Construct form data set for form if it is supplied - Ok(FormData::new(form, global)) + Ok(FormData::new(form, global.as_global_scope())) } } @@ -154,7 +155,7 @@ impl FormData { let bytes = blob.get_bytes().unwrap_or(vec![]); - File::new(global.r(), BlobImpl::new_from_bytes(bytes), name, None, "") + File::new(global.r().as_global_scope(), BlobImpl::new_from_bytes(bytes), name, None, "") } pub fn datums(&self) -> Vec { diff --git a/components/script/dom/globalscope.rs b/components/script/dom/globalscope.rs index 7c284987958..de9ee3773d2 100644 --- a/components/script/dom/globalscope.rs +++ b/components/script/dom/globalscope.rs @@ -2,7 +2,9 @@ * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ +use dom::bindings::reflector::Reflectable; use dom::eventtarget::EventTarget; +use js::jsapi::{JS_GetContext, JS_GetObjectRuntime, JSContext}; #[dom_struct] pub struct GlobalScope { @@ -15,4 +17,16 @@ impl GlobalScope { eventtarget: EventTarget::new_inherited(), } } + + #[allow(unsafe_code)] + pub fn get_cx(&self) -> *mut JSContext { + unsafe { + let runtime = JS_GetObjectRuntime( + self.reflector().get_jsobject().get()); + assert!(!runtime.is_null()); + let context = JS_GetContext(runtime); + assert!(!context.is_null()); + context + } + } } diff --git a/components/script/dom/hashchangeevent.rs b/components/script/dom/hashchangeevent.rs index 33562123ac6..c97599b25a3 100644 --- a/components/script/dom/hashchangeevent.rs +++ b/components/script/dom/hashchangeevent.rs @@ -12,6 +12,7 @@ use dom::bindings::js::Root; use dom::bindings::reflector::reflect_dom_object; use dom::bindings::str::{DOMString, USVString}; use dom::event::Event; +use dom::globalscope::GlobalScope; use string_cache::Atom; // https://html.spec.whatwg.org/multipage/#hashchangeevent @@ -31,14 +32,13 @@ impl HashChangeEvent { } } - pub fn new_uninitialized(global: GlobalRef) - -> Root { + pub fn new_uninitialized(global: &GlobalScope) -> Root { reflect_dom_object(box HashChangeEvent::new_inherited(String::new(), String::new()), global, HashChangeEventBinding::Wrap) } - pub fn new(global: GlobalRef, + pub fn new(global: &GlobalScope, type_: Atom, bubbles: bool, cancelable: bool, @@ -59,7 +59,7 @@ impl HashChangeEvent { type_: DOMString, init: &HashChangeEventBinding::HashChangeEventInit) -> Fallible> { - Ok(HashChangeEvent::new(global, + Ok(HashChangeEvent::new(global.as_global_scope(), Atom::from(type_), init.parent.bubbles, init.parent.cancelable, diff --git a/components/script/dom/headers.rs b/components/script/dom/headers.rs index 7f43dd6b07a..68c3d92c0ad 100644 --- a/components/script/dom/headers.rs +++ b/components/script/dom/headers.rs @@ -10,6 +10,7 @@ use dom::bindings::iterable::Iterable; use dom::bindings::js::Root; use dom::bindings::reflector::{Reflector, reflect_dom_object}; use dom::bindings::str::{ByteString, is_token}; +use dom::globalscope::GlobalScope; use hyper::header::Headers as HyperHeaders; use mime::{Mime, TopLevel, SubLevel}; use std::cell::Cell; @@ -43,14 +44,14 @@ impl Headers { } } - pub fn new(global: GlobalRef) -> Root { + pub fn new(global: &GlobalScope) -> Root { reflect_dom_object(box Headers::new_inherited(), global, HeadersWrap) } // https://fetch.spec.whatwg.org/#dom-headers pub fn Constructor(global: GlobalRef, init: Option) -> Fallible> { - let dom_headers_new = Headers::new(global); + let dom_headers_new = Headers::new(global.as_global_scope()); try!(dom_headers_new.fill(init)); Ok(dom_headers_new) } @@ -205,13 +206,13 @@ impl Headers { } } - pub fn for_request(global: GlobalRef) -> Root { + pub fn for_request(global: &GlobalScope) -> Root { let headers_for_request = Headers::new(global); headers_for_request.guard.set(Guard::Request); headers_for_request } - pub fn for_response(global: GlobalRef) -> Root { + pub fn for_response(global: &GlobalScope) -> Root { let headers_for_response = Headers::new(global); headers_for_response.guard.set(Guard::Response); headers_for_response diff --git a/components/script/dom/history.rs b/components/script/dom/history.rs index 5ced543d728..9fe5789524c 100644 --- a/components/script/dom/history.rs +++ b/components/script/dom/history.rs @@ -6,7 +6,6 @@ use dom::bindings::codegen::Bindings::HistoryBinding; use dom::bindings::codegen::Bindings::HistoryBinding::HistoryMethods; use dom::bindings::codegen::Bindings::LocationBinding::LocationMethods; use dom::bindings::codegen::Bindings::WindowBinding::WindowMethods; -use dom::bindings::global::GlobalRef; use dom::bindings::js::{JS, Root}; use dom::bindings::reflector::{Reflector, reflect_dom_object}; use dom::window::Window; @@ -31,7 +30,7 @@ impl History { pub fn new(window: &Window) -> Root { reflect_dom_object(box History::new_inherited(window), - GlobalRef::Window(window), + window, HistoryBinding::Wrap) } } diff --git a/components/script/dom/htmlcollection.rs b/components/script/dom/htmlcollection.rs index 66a810eff9f..4274c04a21b 100644 --- a/components/script/dom/htmlcollection.rs +++ b/components/script/dom/htmlcollection.rs @@ -4,7 +4,6 @@ use dom::bindings::codegen::Bindings::HTMLCollectionBinding; use dom::bindings::codegen::Bindings::HTMLCollectionBinding::HTMLCollectionMethods; -use dom::bindings::global::GlobalRef; use dom::bindings::inheritance::Castable; use dom::bindings::js::{JS, Root, MutNullableHeap}; use dom::bindings::reflector::{Reflector, reflect_dom_object}; @@ -83,7 +82,7 @@ impl HTMLCollection { #[allow(unrooted_must_root)] pub fn new(window: &Window, root: &Node, filter: Box) -> Root { reflect_dom_object(box HTMLCollection::new_inherited(root, filter), - GlobalRef::Window(window), HTMLCollectionBinding::Wrap) + window, HTMLCollectionBinding::Wrap) } pub fn create(window: &Window, root: &Node, diff --git a/components/script/dom/htmlformcontrolscollection.rs b/components/script/dom/htmlformcontrolscollection.rs index e52a541225f..2450b26c179 100644 --- a/components/script/dom/htmlformcontrolscollection.rs +++ b/components/script/dom/htmlformcontrolscollection.rs @@ -6,7 +6,6 @@ use dom::bindings::codegen::Bindings::HTMLCollectionBinding::HTMLCollectionMetho use dom::bindings::codegen::Bindings::HTMLFormControlsCollectionBinding; use dom::bindings::codegen::Bindings::HTMLFormControlsCollectionBinding::HTMLFormControlsCollectionMethods; use dom::bindings::codegen::UnionTypes::RadioNodeListOrElement; -use dom::bindings::global::GlobalRef; use dom::bindings::js::Root; use dom::bindings::reflector::{Reflectable, reflect_dom_object}; use dom::bindings::str::DOMString; @@ -33,7 +32,7 @@ impl HTMLFormControlsCollection { -> Root { reflect_dom_object(box HTMLFormControlsCollection::new_inherited(root, filter), - GlobalRef::Window(window), + window, HTMLFormControlsCollectionBinding::Wrap) } diff --git a/components/script/dom/htmliframeelement.rs b/components/script/dom/htmliframeelement.rs index 1503ff28e06..2b7781dae1e 100644 --- a/components/script/dom/htmliframeelement.rs +++ b/components/script/dom/htmliframeelement.rs @@ -18,7 +18,6 @@ use dom::bindings::codegen::Bindings::HTMLIFrameElementBinding::HTMLIFrameElemen use dom::bindings::codegen::Bindings::WindowBinding::WindowMethods; use dom::bindings::conversions::ToJSValConvertible; use dom::bindings::error::{Error, ErrorResult, Fallible}; -use dom::bindings::global::GlobalRef; use dom::bindings::inheritance::Castable; use dom::bindings::js::{JS, LayoutJS, MutNullableHeap, Root}; use dom::bindings::reflector::Reflectable; @@ -316,7 +315,7 @@ pub fn build_mozbrowser_custom_event(window: &Window, event: MozBrowserEvent) -> rooted!(in(cx) let mut detail = UndefinedValue()); let event_name = Atom::from(event.name()); unsafe { build_mozbrowser_event_detail(event, cx, detail.handle_mut()); } - CustomEvent::new(GlobalRef::Window(window), + CustomEvent::new(window.upcast(), event_name, true, true, diff --git a/components/script/dom/htmlmediaelement.rs b/components/script/dom/htmlmediaelement.rs index 5bbdd738079..24ae7542880 100644 --- a/components/script/dom/htmlmediaelement.rs +++ b/components/script/dom/htmlmediaelement.rs @@ -311,7 +311,7 @@ impl HTMLMediaElement { fn fire_simple_event(&self, type_: &str) { let window = window_from_node(self); - let event = Event::new(GlobalRef::Window(&*window), + let event = Event::new(window.upcast(), Atom::from(type_), EventBubbles::DoesNotBubble, EventCancelable::NotCancelable); diff --git a/components/script/dom/htmloptionscollection.rs b/components/script/dom/htmloptionscollection.rs index dd6d4531974..473d698d35b 100644 --- a/components/script/dom/htmloptionscollection.rs +++ b/components/script/dom/htmloptionscollection.rs @@ -9,7 +9,6 @@ use dom::bindings::codegen::Bindings::HTMLOptionsCollectionBinding::HTMLOptionsC use dom::bindings::codegen::Bindings::NodeBinding::NodeBinding::NodeMethods; use dom::bindings::codegen::UnionTypes::{HTMLOptionElementOrHTMLOptGroupElement, HTMLElementOrLong}; use dom::bindings::error::{Error, ErrorResult}; -use dom::bindings::global::GlobalRef; use dom::bindings::inheritance::Castable; use dom::bindings::js::{Root, RootedReference}; use dom::bindings::reflector::reflect_dom_object; @@ -36,7 +35,7 @@ impl HTMLOptionsCollection { -> Root { reflect_dom_object(box HTMLOptionsCollection::new_inherited(root, filter), - GlobalRef::Window(window), + window, HTMLOptionsCollectionBinding::Wrap) } diff --git a/components/script/dom/htmlscriptelement.rs b/components/script/dom/htmlscriptelement.rs index e96ceb6d834..7f5266b9e84 100644 --- a/components/script/dom/htmlscriptelement.rs +++ b/components/script/dom/htmlscriptelement.rs @@ -604,7 +604,7 @@ impl HTMLScriptElement { cancelable: EventCancelable) -> EventStatus { let window = window_from_node(self); let window = window.r(); - let event = Event::new(GlobalRef::Window(window), type_, bubbles, cancelable); + let event = Event::new(window.upcast(), type_, bubbles, cancelable); event.fire(self.upcast()) } } diff --git a/components/script/dom/imagedata.rs b/components/script/dom/imagedata.rs index 0959a52eb32..5f99fb9db57 100644 --- a/components/script/dom/imagedata.rs +++ b/components/script/dom/imagedata.rs @@ -5,9 +5,9 @@ use core::nonzero::NonZero; use dom::bindings::codegen::Bindings::ImageDataBinding; use dom::bindings::codegen::Bindings::ImageDataBinding::ImageDataMethods; -use dom::bindings::global::GlobalRef; use dom::bindings::js::Root; use dom::bindings::reflector::{Reflector, reflect_dom_object}; +use dom::globalscope::GlobalScope; use euclid::size::Size2D; use js::jsapi::{Heap, JSContext, JSObject}; use js::jsapi::{JS_GetUint8ClampedArrayData, JS_NewUint8ClampedArray}; @@ -27,7 +27,7 @@ pub struct ImageData { impl ImageData { #[allow(unsafe_code)] - pub fn new(global: GlobalRef, width: u32, height: u32, data: Option>) -> Root { + pub fn new(global: &GlobalScope, width: u32, height: u32, data: Option>) -> Root { let mut imagedata = box ImageData { reflector_: Reflector::new(), width: width, diff --git a/components/script/dom/keyboardevent.rs b/components/script/dom/keyboardevent.rs index d21f53eb609..06987f55b12 100644 --- a/components/script/dom/keyboardevent.rs +++ b/components/script/dom/keyboardevent.rs @@ -62,7 +62,7 @@ impl KeyboardEvent { pub fn new_uninitialized(window: &Window) -> Root { reflect_dom_object(box KeyboardEvent::new_inherited(), - GlobalRef::Window(window), + window, KeyboardEventBinding::Wrap) } diff --git a/components/script/dom/location.rs b/components/script/dom/location.rs index ba835ada146..cf91c683f2f 100644 --- a/components/script/dom/location.rs +++ b/components/script/dom/location.rs @@ -5,7 +5,6 @@ use dom::bindings::codegen::Bindings::LocationBinding; use dom::bindings::codegen::Bindings::LocationBinding::LocationMethods; use dom::bindings::error::{Error, ErrorResult}; -use dom::bindings::global::GlobalRef; use dom::bindings::js::{JS, Root}; use dom::bindings::reflector::{Reflector, reflect_dom_object}; use dom::bindings::str::{DOMString, USVString}; @@ -29,7 +28,7 @@ impl Location { pub fn new(window: &Window) -> Root { reflect_dom_object(box Location::new_inherited(window), - GlobalRef::Window(window), + window, LocationBinding::Wrap) } diff --git a/components/script/dom/mediaerror.rs b/components/script/dom/mediaerror.rs index 17d92947f72..b7b7a800989 100644 --- a/components/script/dom/mediaerror.rs +++ b/components/script/dom/mediaerror.rs @@ -3,7 +3,6 @@ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use dom::bindings::codegen::Bindings::MediaErrorBinding::{self, MediaErrorMethods}; -use dom::bindings::global::GlobalRef; use dom::bindings::js::Root; use dom::bindings::reflector::{Reflector, reflect_dom_object}; use dom::window::Window; @@ -24,7 +23,7 @@ impl MediaError { pub fn new(window: &Window, code: u16) -> Root { reflect_dom_object(box MediaError::new_inherited(code), - GlobalRef::Window(window), + window, MediaErrorBinding::Wrap) } } diff --git a/components/script/dom/messageevent.rs b/components/script/dom/messageevent.rs index b5b46fba5d8..62c8c4c5ed4 100644 --- a/components/script/dom/messageevent.rs +++ b/components/script/dom/messageevent.rs @@ -13,6 +13,7 @@ use dom::bindings::reflector::reflect_dom_object; use dom::bindings::str::DOMString; use dom::event::Event; use dom::eventtarget::EventTarget; +use dom::globalscope::GlobalScope; use js::jsapi::{HandleValue, Heap, JSContext}; use js::jsval::JSVal; use std::default::Default; @@ -27,14 +28,14 @@ pub struct MessageEvent { } impl MessageEvent { - pub fn new_uninitialized(global: GlobalRef) -> Root { + pub fn new_uninitialized(global: &GlobalScope) -> Root { MessageEvent::new_initialized(global, HandleValue::undefined(), DOMString::new(), DOMString::new()) } - pub fn new_initialized(global: GlobalRef, + pub fn new_initialized(global: &GlobalScope, data: HandleValue, origin: DOMString, lastEventId: DOMString) -> Root { @@ -48,7 +49,7 @@ impl MessageEvent { reflect_dom_object(ev, global, MessageEventBinding::Wrap) } - pub fn new(global: GlobalRef, type_: Atom, + pub fn new(global: &GlobalScope, type_: Atom, bubbles: bool, cancelable: bool, data: HandleValue, origin: DOMString, lastEventId: DOMString) -> Root { @@ -67,9 +68,13 @@ impl MessageEvent { // Dictionaries need to be rooted // https://github.com/servo/servo/issues/6381 rooted!(in(global.get_cx()) let data = init.data); - let ev = MessageEvent::new(global, Atom::from(type_), init.parent.bubbles, init.parent.cancelable, + let ev = MessageEvent::new(global.as_global_scope(), + Atom::from(type_), + init.parent.bubbles, + init.parent.cancelable, data.handle(), - init.origin.clone(), init.lastEventId.clone()); + init.origin.clone(), + init.lastEventId.clone()); Ok(ev) } } @@ -79,8 +84,13 @@ impl MessageEvent { scope: GlobalRef, message: HandleValue) { let messageevent = MessageEvent::new( - scope, atom!("message"), false, false, message, - DOMString::new(), DOMString::new()); + scope.as_global_scope(), + atom!("message"), + false, + false, + message, + DOMString::new(), + DOMString::new()); messageevent.upcast::().fire(target); } } diff --git a/components/script/dom/mimetypearray.rs b/components/script/dom/mimetypearray.rs index de820f6d06a..e0dd8090f8f 100644 --- a/components/script/dom/mimetypearray.rs +++ b/components/script/dom/mimetypearray.rs @@ -4,10 +4,10 @@ use dom::bindings::codegen::Bindings::MimeTypeArrayBinding; use dom::bindings::codegen::Bindings::MimeTypeArrayBinding::MimeTypeArrayMethods; -use dom::bindings::global::GlobalRef; use dom::bindings::js::Root; use dom::bindings::reflector::{Reflector, reflect_dom_object}; use dom::bindings::str::DOMString; +use dom::globalscope::GlobalScope; use dom::mimetype::MimeType; #[dom_struct] @@ -22,7 +22,7 @@ impl MimeTypeArray { } } - pub fn new(global: GlobalRef) -> Root { + pub fn new(global: &GlobalScope) -> Root { reflect_dom_object(box MimeTypeArray::new_inherited(), global, MimeTypeArrayBinding::Wrap) diff --git a/components/script/dom/mouseevent.rs b/components/script/dom/mouseevent.rs index 659a28226b7..096b119641f 100644 --- a/components/script/dom/mouseevent.rs +++ b/components/script/dom/mouseevent.rs @@ -53,7 +53,7 @@ impl MouseEvent { pub fn new_uninitialized(window: &Window) -> Root { reflect_dom_object(box MouseEvent::new_inherited(), - GlobalRef::Window(window), + window, MouseEventBinding::Wrap) } diff --git a/components/script/dom/namednodemap.rs b/components/script/dom/namednodemap.rs index 9edc1b1e93b..1145ff60562 100644 --- a/components/script/dom/namednodemap.rs +++ b/components/script/dom/namednodemap.rs @@ -7,7 +7,6 @@ use dom::bindings::codegen::Bindings::ElementBinding::ElementMethods; use dom::bindings::codegen::Bindings::NamedNodeMapBinding; use dom::bindings::codegen::Bindings::NamedNodeMapBinding::NamedNodeMapMethods; use dom::bindings::error::{Error, Fallible}; -use dom::bindings::global::GlobalRef; use dom::bindings::js::{JS, Root}; use dom::bindings::reflector::{Reflector, reflect_dom_object}; use dom::bindings::str::DOMString; @@ -33,7 +32,7 @@ impl NamedNodeMap { pub fn new(window: &Window, elem: &Element) -> Root { reflect_dom_object(box NamedNodeMap::new_inherited(elem), - GlobalRef::Window(window), NamedNodeMapBinding::Wrap) + window, NamedNodeMapBinding::Wrap) } } diff --git a/components/script/dom/navigator.rs b/components/script/dom/navigator.rs index ce97c30ae60..d4e4629e486 100644 --- a/components/script/dom/navigator.rs +++ b/components/script/dom/navigator.rs @@ -4,7 +4,6 @@ use dom::bindings::codegen::Bindings::NavigatorBinding; use dom::bindings::codegen::Bindings::NavigatorBinding::NavigatorMethods; -use dom::bindings::global::GlobalRef; use dom::bindings::js::{JS, MutNullableHeap, Root}; use dom::bindings::reflector::{Reflector, Reflectable, reflect_dom_object}; use dom::bindings::str::DOMString; @@ -37,7 +36,7 @@ impl Navigator { pub fn new(window: &Window) -> Root { reflect_dom_object(box Navigator::new_inherited(), - GlobalRef::Window(window), + window, NavigatorBinding::Wrap) } } @@ -80,7 +79,7 @@ impl NavigatorMethods for Navigator { // https://webbluetoothcg.github.io/web-bluetooth/#dom-navigator-bluetooth fn Bluetooth(&self) -> Root { - self.bluetooth.or_init(|| Bluetooth::new(self.global().r())) + self.bluetooth.or_init(|| Bluetooth::new(self.global().r().as_global_scope())) } // https://html.spec.whatwg.org/multipage/#navigatorlanguage @@ -90,12 +89,12 @@ impl NavigatorMethods for Navigator { // https://html.spec.whatwg.org/multipage/#dom-navigator-plugins fn Plugins(&self) -> Root { - self.plugins.or_init(|| PluginArray::new(self.global().r())) + self.plugins.or_init(|| PluginArray::new(self.global().r().as_global_scope())) } // https://html.spec.whatwg.org/multipage/#dom-navigator-mimetypes fn MimeTypes(&self) -> Root { - self.mime_types.or_init(|| MimeTypeArray::new(self.global().r())) + self.mime_types.or_init(|| MimeTypeArray::new(self.global().r().as_global_scope())) } // https://html.spec.whatwg.org/multipage/#dom-navigator-javaenabled @@ -105,7 +104,9 @@ impl NavigatorMethods for Navigator { // https://w3c.github.io/ServiceWorker/#navigator-service-worker-attribute fn ServiceWorker(&self) -> Root { - self.service_worker.or_init(|| ServiceWorkerContainer::new(self.global().r())) + self.service_worker.or_init(|| { + ServiceWorkerContainer::new(self.global().r().as_global_scope()) + }) } // https://html.spec.whatwg.org/multipage/#dom-navigator-cookieenabled diff --git a/components/script/dom/node.rs b/components/script/dom/node.rs index 041d6407418..c18613ac6a2 100644 --- a/components/script/dom/node.rs +++ b/components/script/dom/node.rs @@ -20,7 +20,6 @@ use dom::bindings::codegen::Bindings::WindowBinding::WindowMethods; use dom::bindings::codegen::UnionTypes::NodeOrString; use dom::bindings::conversions::{self, DerivedFrom}; use dom::bindings::error::{Error, ErrorResult, Fallible}; -use dom::bindings::global::GlobalRef; use dom::bindings::inheritance::{Castable, CharacterDataTypeId, ElementTypeId}; use dom::bindings::inheritance::{EventTargetTypeId, HTMLElementTypeId, NodeTypeId}; use dom::bindings::js::{JS, LayoutJS, MutNullableHeap}; @@ -35,6 +34,7 @@ use dom::documentfragment::DocumentFragment; use dom::documenttype::DocumentType; use dom::element::{Element, ElementCreator}; use dom::eventtarget::EventTarget; +use dom::globalscope::GlobalScope; use dom::htmlbodyelement::HTMLBodyElement; use dom::htmlcanvaselement::LayoutHTMLCanvasElementHelpers; use dom::htmlcollection::HTMLCollection; @@ -1339,13 +1339,15 @@ pub enum CloneChildrenFlag { fn as_uintptr(t: &T) -> uintptr_t { t as *const T as uintptr_t } impl Node { - pub fn reflect_node + Reflectable> - (node: Box, - document: &Document, - wrap_fn: extern "Rust" fn(*mut JSContext, GlobalRef, Box) -> Root) - -> Root { + pub fn reflect_node( + node: Box, + document: &Document, + wrap_fn: extern "Rust" fn(*mut JSContext, &GlobalScope, Box) -> Root) + -> Root + where N: DerivedFrom + Reflectable + { let window = document.window(); - reflect_dom_object(node, GlobalRef::Window(window), wrap_fn) + reflect_dom_object(node, window, wrap_fn) } pub fn new_inherited(doc: &Document) -> Node { diff --git a/components/script/dom/nodeiterator.rs b/components/script/dom/nodeiterator.rs index 14b8f240fbb..4315dd28113 100644 --- a/components/script/dom/nodeiterator.rs +++ b/components/script/dom/nodeiterator.rs @@ -9,7 +9,6 @@ use dom::bindings::codegen::Bindings::NodeFilterBinding::NodeFilterConstants; use dom::bindings::codegen::Bindings::NodeIteratorBinding; use dom::bindings::codegen::Bindings::NodeIteratorBinding::NodeIteratorMethods; use dom::bindings::error::Fallible; -use dom::bindings::global::GlobalRef; use dom::bindings::js::{JS, MutHeap, Root}; use dom::bindings::reflector::{Reflector, reflect_dom_object}; use dom::document::Document; @@ -48,7 +47,7 @@ impl NodeIterator { what_to_show: u32, filter: Filter) -> Root { reflect_dom_object(box NodeIterator::new_inherited(root_node, what_to_show, filter), - GlobalRef::Window(document.window()), + document.window(), NodeIteratorBinding::Wrap) } diff --git a/components/script/dom/nodelist.rs b/components/script/dom/nodelist.rs index 8f8a5515592..ffd44d277a5 100644 --- a/components/script/dom/nodelist.rs +++ b/components/script/dom/nodelist.rs @@ -5,7 +5,6 @@ use dom::bindings::codegen::Bindings::NodeBinding::NodeMethods; use dom::bindings::codegen::Bindings::NodeListBinding; use dom::bindings::codegen::Bindings::NodeListBinding::NodeListMethods; -use dom::bindings::global::GlobalRef; use dom::bindings::js::{JS, MutNullableHeap, Root, RootedReference}; use dom::bindings::reflector::{Reflector, reflect_dom_object}; use dom::node::{ChildrenMutation, Node}; @@ -38,7 +37,8 @@ impl NodeList { #[allow(unrooted_must_root)] pub fn new(window: &Window, list_type: NodeListType) -> Root { reflect_dom_object(box NodeList::new_inherited(list_type), - GlobalRef::Window(window), NodeListBinding::Wrap) + window, + NodeListBinding::Wrap) } pub fn new_simple_list(window: &Window, iter: T) -> Root diff --git a/components/script/dom/pagetransitionevent.rs b/components/script/dom/pagetransitionevent.rs index 7c6b7b6f555..c25281dcc31 100644 --- a/components/script/dom/pagetransitionevent.rs +++ b/components/script/dom/pagetransitionevent.rs @@ -12,6 +12,7 @@ use dom::bindings::js::Root; use dom::bindings::reflector::reflect_dom_object; use dom::bindings::str::DOMString; use dom::event::Event; +use dom::globalscope::GlobalScope; use std::cell::Cell; use string_cache::Atom; @@ -30,13 +31,13 @@ impl PageTransitionEvent { } } - pub fn new_uninitialized(global: GlobalRef) -> Root { + pub fn new_uninitialized(global: &GlobalScope) -> Root { reflect_dom_object(box PageTransitionEvent::new_inherited(), global, PageTransitionEventBinding::Wrap) } - pub fn new(global: GlobalRef, + pub fn new(global: &GlobalScope, type_: Atom, bubbles: bool, cancelable: bool, @@ -55,7 +56,7 @@ impl PageTransitionEvent { type_: DOMString, init: &PageTransitionEventBinding::PageTransitionEventInit) -> Fallible> { - Ok(PageTransitionEvent::new(global, + Ok(PageTransitionEvent::new(global.as_global_scope(), Atom::from(type_), init.parent.bubbles, init.parent.cancelable, diff --git a/components/script/dom/performance.rs b/components/script/dom/performance.rs index f6bc8d288f8..3852a49b28c 100644 --- a/components/script/dom/performance.rs +++ b/components/script/dom/performance.rs @@ -4,7 +4,6 @@ use dom::bindings::codegen::Bindings::PerformanceBinding; use dom::bindings::codegen::Bindings::PerformanceBinding::PerformanceMethods; -use dom::bindings::global::GlobalRef; use dom::bindings::js::{JS, Root}; use dom::bindings::num::Finite; use dom::bindings::reflector::{Reflector, reflect_dom_object}; @@ -38,7 +37,7 @@ impl Performance { reflect_dom_object(box Performance::new_inherited(window, navigation_start, navigation_start_precise), - GlobalRef::Window(window), + window, PerformanceBinding::Wrap) } } diff --git a/components/script/dom/performancetiming.rs b/components/script/dom/performancetiming.rs index 6faa8246242..16dc7650649 100644 --- a/components/script/dom/performancetiming.rs +++ b/components/script/dom/performancetiming.rs @@ -5,7 +5,6 @@ use dom::bindings::codegen::Bindings::PerformanceTimingBinding; use dom::bindings::codegen::Bindings::PerformanceTimingBinding::PerformanceTimingMethods; use dom::bindings::codegen::Bindings::WindowBinding::WindowMethods; -use dom::bindings::global::GlobalRef; use dom::bindings::js::{JS, Root}; use dom::bindings::reflector::{Reflector, reflect_dom_object}; use dom::document::Document; @@ -40,7 +39,8 @@ impl PerformanceTiming { let timing = PerformanceTiming::new_inherited(navigation_start, navigation_start_precise, window.Document().r()); - reflect_dom_object(box timing, GlobalRef::Window(window), + reflect_dom_object(box timing, + window, PerformanceTimingBinding::Wrap) } } diff --git a/components/script/dom/pluginarray.rs b/components/script/dom/pluginarray.rs index aa6b779280d..fde760d793c 100644 --- a/components/script/dom/pluginarray.rs +++ b/components/script/dom/pluginarray.rs @@ -4,10 +4,10 @@ use dom::bindings::codegen::Bindings::PluginArrayBinding; use dom::bindings::codegen::Bindings::PluginArrayBinding::PluginArrayMethods; -use dom::bindings::global::GlobalRef; use dom::bindings::js::Root; use dom::bindings::reflector::{Reflector, reflect_dom_object}; use dom::bindings::str::DOMString; +use dom::globalscope::GlobalScope; use dom::plugin::Plugin; #[dom_struct] @@ -22,7 +22,7 @@ impl PluginArray { } } - pub fn new(global: GlobalRef) -> Root { + pub fn new(global: &GlobalScope) -> Root { reflect_dom_object(box PluginArray::new_inherited(), global, PluginArrayBinding::Wrap) diff --git a/components/script/dom/popstateevent.rs b/components/script/dom/popstateevent.rs index a9487f48299..621c9d4199f 100644 --- a/components/script/dom/popstateevent.rs +++ b/components/script/dom/popstateevent.rs @@ -12,6 +12,7 @@ use dom::bindings::js::{MutHeapJSVal, Root}; use dom::bindings::reflector::reflect_dom_object; use dom::bindings::str::DOMString; use dom::event::Event; +use dom::globalscope::GlobalScope; use js::jsapi::{HandleValue, JSContext}; use js::jsval::JSVal; use string_cache::Atom; @@ -32,13 +33,13 @@ impl PopStateEvent { } } - pub fn new_uninitialized(global: GlobalRef) -> Root { + pub fn new_uninitialized(global: &GlobalScope) -> Root { reflect_dom_object(box PopStateEvent::new_inherited(), global, PopStateEventBinding::Wrap) } - pub fn new(global: GlobalRef, + pub fn new(global: &GlobalScope, type_: Atom, bubbles: bool, cancelable: bool, @@ -58,7 +59,7 @@ impl PopStateEvent { type_: DOMString, init: &PopStateEventBinding::PopStateEventInit) -> Fallible> { - Ok(PopStateEvent::new(global, + Ok(PopStateEvent::new(global.as_global_scope(), Atom::from(type_), init.parent.bubbles, init.parent.cancelable, diff --git a/components/script/dom/progressevent.rs b/components/script/dom/progressevent.rs index f0d2b5c400a..2f25df109fa 100644 --- a/components/script/dom/progressevent.rs +++ b/components/script/dom/progressevent.rs @@ -12,7 +12,7 @@ use dom::bindings::js::Root; use dom::bindings::reflector::reflect_dom_object; use dom::bindings::str::DOMString; use dom::event::{Event, EventBubbles, EventCancelable}; -use dom::window::Window; +use dom::globalscope::GlobalScope; use string_cache::Atom; #[dom_struct] @@ -32,12 +32,12 @@ impl ProgressEvent { total: total } } - pub fn new_uninitialized(window: &Window) -> Root { + pub fn new_uninitialized(global: &GlobalScope) -> Root { reflect_dom_object(box ProgressEvent::new_inherited(false, 0, 0), - GlobalRef::Window(window), + global, ProgressEventBinding::Wrap) } - pub fn new(global: GlobalRef, type_: Atom, + pub fn new(global: &GlobalScope, type_: Atom, can_bubble: EventBubbles, cancelable: EventCancelable, length_computable: bool, loaded: u64, total: u64) -> Root { let ev = reflect_dom_object(box ProgressEvent::new_inherited(length_computable, loaded, total), @@ -55,7 +55,7 @@ impl ProgressEvent { -> Fallible> { let bubbles = EventBubbles::from(init.parent.bubbles); let cancelable = EventCancelable::from(init.parent.cancelable); - let ev = ProgressEvent::new(global, Atom::from(type_), bubbles, cancelable, + let ev = ProgressEvent::new(global.as_global_scope(), Atom::from(type_), bubbles, cancelable, init.lengthComputable, init.loaded, init.total); Ok(ev) } diff --git a/components/script/dom/promisenativehandler.rs b/components/script/dom/promisenativehandler.rs index 603122556ef..b1c0ff3504c 100644 --- a/components/script/dom/promisenativehandler.rs +++ b/components/script/dom/promisenativehandler.rs @@ -3,10 +3,10 @@ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use dom::bindings::codegen::Bindings::PromiseNativeHandlerBinding; -use dom::bindings::global::GlobalRef; use dom::bindings::js::Root; use dom::bindings::reflector::{Reflector, reflect_dom_object}; use dom::bindings::trace::JSTraceable; +use dom::globalscope::GlobalScope; use heapsize::HeapSizeOf; use js::jsapi::{JSContext, HandleValue}; @@ -22,7 +22,7 @@ pub struct PromiseNativeHandler { } impl PromiseNativeHandler { - pub fn new(global: GlobalRef, + pub fn new(global: &GlobalScope, resolve: Option>, reject: Option>) -> Root { diff --git a/components/script/dom/radionodelist.rs b/components/script/dom/radionodelist.rs index 9bbdae00c85..5cf05cb872a 100644 --- a/components/script/dom/radionodelist.rs +++ b/components/script/dom/radionodelist.rs @@ -6,7 +6,6 @@ use dom::bindings::codegen::Bindings::HTMLInputElementBinding::HTMLInputElementM use dom::bindings::codegen::Bindings::NodeListBinding::NodeListMethods; use dom::bindings::codegen::Bindings::RadioNodeListBinding; use dom::bindings::codegen::Bindings::RadioNodeListBinding::RadioNodeListMethods; -use dom::bindings::global::GlobalRef; use dom::bindings::inheritance::Castable; use dom::bindings::js::{JS, Root}; use dom::bindings::reflector::reflect_dom_object; @@ -32,7 +31,7 @@ impl RadioNodeList { #[allow(unrooted_must_root)] pub fn new(window: &Window, list_type: NodeListType) -> Root { reflect_dom_object(box RadioNodeList::new_inherited(list_type), - GlobalRef::Window(window), + window, RadioNodeListBinding::Wrap) } diff --git a/components/script/dom/range.rs b/components/script/dom/range.rs index bab6bdcc3a2..80018b661f3 100644 --- a/components/script/dom/range.rs +++ b/components/script/dom/range.rs @@ -60,7 +60,7 @@ impl Range { -> Root { let range = reflect_dom_object(box Range::new_inherited(start_container, start_offset, end_container, end_offset), - GlobalRef::Window(document.window()), + document.window(), RangeBinding::Wrap); start_container.ranges().push(WeakRef::new(&range)); if start_container != end_container { diff --git a/components/script/dom/request.rs b/components/script/dom/request.rs index fa665679c0d..1496f16d353 100644 --- a/components/script/dom/request.rs +++ b/components/script/dom/request.rs @@ -73,7 +73,7 @@ impl Request { reflect_dom_object(box Request::new_inherited(global, url, is_service_worker_global_scope), - global, RequestBinding::Wrap) + global.as_global_scope(), RequestBinding::Wrap) } // https://fetch.spec.whatwg.org/#dom-request @@ -305,7 +305,7 @@ impl Request { let r = Request::from_net_request(global, false, request); - r.headers.or_init(|| Headers::for_request(r.global().r())); + r.headers.or_init(|| Headers::for_request(r.global().r().as_global_scope())); // Step 27 let mut headers_copy = r.Headers(); @@ -429,11 +429,7 @@ impl Request { let body_used = r.body_used.get(); let mime_type = r.mime_type.borrow().clone(); let headers_guard = r.Headers().get_guard(); - let r_clone = reflect_dom_object( - box Request::new_inherited(r.global().r(), - url, - is_service_worker_global_scope), - r.global().r(), RequestBinding::Wrap); + let r_clone = Request::new(r.global().r(), url, is_service_worker_global_scope); r_clone.request.borrow_mut().pipeline_id.set(req.pipeline_id.get()); { let mut borrowed_r_request = r_clone.request.borrow_mut(); @@ -553,7 +549,7 @@ impl RequestMethods for Request { // https://fetch.spec.whatwg.org/#dom-request-headers fn Headers(&self) -> Root { - self.headers.or_init(|| Headers::new(self.global().r())) + self.headers.or_init(|| Headers::new(self.global().r().as_global_scope())) } // https://fetch.spec.whatwg.org/#dom-request-type diff --git a/components/script/dom/response.rs b/components/script/dom/response.rs index 2287bb181b4..a90a551b20a 100644 --- a/components/script/dom/response.rs +++ b/components/script/dom/response.rs @@ -14,6 +14,7 @@ use dom::bindings::global::GlobalRef; use dom::bindings::js::{JS, MutNullableHeap, Root}; use dom::bindings::reflector::{Reflectable, Reflector, reflect_dom_object}; use dom::bindings::str::{ByteString, USVString}; +use dom::globalscope::GlobalScope; use dom::headers::{Headers, Guard}; use dom::headers::{is_vchar, is_obs_text}; use dom::promise::Promise; @@ -66,7 +67,7 @@ impl Response { } // https://fetch.spec.whatwg.org/#dom-response - pub fn new(global: GlobalRef) -> Root { + pub fn new(global: &GlobalScope) -> Root { reflect_dom_object(box Response::new_inherited(), global, ResponseBinding::Wrap) } @@ -86,7 +87,7 @@ impl Response { } // Step 3 - let r = Response::new(global); + let r = Response::new(global.as_global_scope()); // Step 4 *r.status.borrow_mut() = Some(StatusCode::from_u16(init.status)); @@ -139,7 +140,7 @@ impl Response { // https://fetch.spec.whatwg.org/#dom-response-error pub fn Error(global: GlobalRef) -> Root { - let r = Response::new(global); + let r = Response::new(global.as_global_scope()); *r.response_type.borrow_mut() = DOMResponseType::Error; r.Headers().set_guard(Guard::Immutable); *r.raw_status.borrow_mut() = Some((0, b"".to_vec())); @@ -166,7 +167,7 @@ impl Response { // Step 4 // see Step 4 continued - let r = Response::new(global); + let r = Response::new(global.as_global_scope()); // Step 5 *r.status.borrow_mut() = Some(StatusCode::from_u16(status)); @@ -292,7 +293,7 @@ impl ResponseMethods for Response { // https://fetch.spec.whatwg.org/#dom-response-headers fn Headers(&self) -> Root { - self.headers_reflector.or_init(|| Headers::for_response(self.global().r())) + self.headers_reflector.or_init(|| Headers::for_response(self.global().r().as_global_scope())) } // https://fetch.spec.whatwg.org/#dom-response-clone @@ -301,7 +302,7 @@ impl ResponseMethods for Response { // TODO: This step relies on body and stream, which are still unimplemented. // Step 2 - let new_response = Response::new(self.global().r()); + let new_response = Response::new(self.global().r().as_global_scope()); new_response.Headers().set_guard(self.Headers().get_guard()); // https://fetch.spec.whatwg.org/#concept-response-clone diff --git a/components/script/dom/screen.rs b/components/script/dom/screen.rs index 158615e84dc..2c9fe185de1 100644 --- a/components/script/dom/screen.rs +++ b/components/script/dom/screen.rs @@ -4,7 +4,6 @@ use dom::bindings::codegen::Bindings::ScreenBinding; use dom::bindings::codegen::Bindings::ScreenBinding::ScreenMethods; -use dom::bindings::global::GlobalRef; use dom::bindings::js::Root; use dom::bindings::reflector::{Reflector, reflect_dom_object}; use dom::window::Window; @@ -23,7 +22,7 @@ impl Screen { pub fn new(window: &Window) -> Root { reflect_dom_object(box Screen::new_inherited(), - GlobalRef::Window(window), + window, ScreenBinding::Wrap) } } diff --git a/components/script/dom/serviceworker.rs b/components/script/dom/serviceworker.rs index 8abcec513ce..cce149b5368 100644 --- a/components/script/dom/serviceworker.rs +++ b/components/script/dom/serviceworker.rs @@ -7,7 +7,6 @@ use dom::bindings::cell::DOMRefCell; use dom::bindings::codegen::Bindings::EventHandlerBinding::EventHandlerNonNull; use dom::bindings::codegen::Bindings::ServiceWorkerBinding::{ServiceWorkerMethods, ServiceWorkerState, Wrap}; use dom::bindings::error::{ErrorResult, Error}; -use dom::bindings::global::GlobalRef; use dom::bindings::inheritance::Castable; use dom::bindings::js::Root; use dom::bindings::refcounted::Trusted; @@ -15,6 +14,7 @@ use dom::bindings::reflector::{Reflectable, reflect_dom_object}; use dom::bindings::str::USVString; use dom::bindings::structuredclone::StructuredCloneData; use dom::eventtarget::EventTarget; +use dom::globalscope::GlobalScope; use js::jsapi::{HandleValue, JSContext}; use script_thread::Runnable; use script_traits::{ScriptMsg, DOMMessage}; @@ -45,7 +45,7 @@ impl ServiceWorker { } } - pub fn install_serviceworker(global: GlobalRef, + pub fn install_serviceworker(global: &GlobalScope, script_url: Url, scope_url: Url, skip_waiting: bool) -> Root { diff --git a/components/script/dom/serviceworkercontainer.rs b/components/script/dom/serviceworkercontainer.rs index abeb69f2ea3..3d9202accf4 100644 --- a/components/script/dom/serviceworkercontainer.rs +++ b/components/script/dom/serviceworkercontainer.rs @@ -5,12 +5,12 @@ use dom::bindings::codegen::Bindings::ServiceWorkerContainerBinding::{ServiceWorkerContainerMethods, Wrap}; use dom::bindings::codegen::Bindings::ServiceWorkerContainerBinding::RegistrationOptions; use dom::bindings::error::{Error, Fallible}; -use dom::bindings::global::GlobalRef; use dom::bindings::inheritance::Castable; use dom::bindings::js::{JS, MutNullableHeap, Root}; use dom::bindings::reflector::{Reflectable, reflect_dom_object}; use dom::bindings::str::USVString; use dom::eventtarget::EventTarget; +use dom::globalscope::GlobalScope; use dom::serviceworker::ServiceWorker; use dom::serviceworkerregistration::ServiceWorkerRegistration; use script_thread::ScriptThread; @@ -31,7 +31,7 @@ impl ServiceWorkerContainer { } } - pub fn new(global: GlobalRef) -> Root { + pub fn new(global: &GlobalScope) -> Root { reflect_dom_object(box ServiceWorkerContainer::new_inherited(), global, Wrap) } } @@ -95,7 +95,7 @@ impl ServiceWorkerContainerMethods for ServiceWorkerContainer { return Err(Error::Type("Scope URL contains forbidden characters".to_owned())); } - let worker_registration = ServiceWorkerRegistration::new(self.global().r(), + let worker_registration = ServiceWorkerRegistration::new(self.global().r().as_global_scope(), script_url, scope.clone(), self); diff --git a/components/script/dom/serviceworkerglobalscope.rs b/components/script/dom/serviceworkerglobalscope.rs index 6efd555c909..d635f1cd41f 100644 --- a/components/script/dom/serviceworkerglobalscope.rs +++ b/components/script/dom/serviceworkerglobalscope.rs @@ -302,8 +302,7 @@ impl ServiceWorkerGlobalScope { } fn dispatch_activate(&self) { - let global = GlobalRef::Worker(self.upcast::()); - let event = ExtendableEvent::new(global, atom!("activate"), false, false); + let event = ExtendableEvent::new(self.upcast(), atom!("activate"), false, false); let event = (&*event).upcast::(); self.upcast::().dispatch_event(event); } diff --git a/components/script/dom/serviceworkerregistration.rs b/components/script/dom/serviceworkerregistration.rs index f7c47b8ecec..b0580457f1c 100644 --- a/components/script/dom/serviceworkerregistration.rs +++ b/components/script/dom/serviceworkerregistration.rs @@ -9,6 +9,7 @@ use dom::bindings::js::{JS, Root}; use dom::bindings::reflector::reflect_dom_object; use dom::bindings::str::USVString; use dom::eventtarget::EventTarget; +use dom::globalscope::GlobalScope; use dom::serviceworker::ServiceWorker; use dom::serviceworkercontainer::Controllable; use dom::workerglobalscope::prepare_workerscope_init; @@ -35,7 +36,7 @@ impl ServiceWorkerRegistration { } } #[allow(unrooted_must_root)] - pub fn new(global: GlobalRef, + pub fn new(global: &GlobalScope, script_url: Url, scope: Url, container: &Controllable) -> Root { diff --git a/components/script/dom/servohtmlparser.rs b/components/script/dom/servohtmlparser.rs index 24a22be75dd..0f0976d0f78 100644 --- a/components/script/dom/servohtmlparser.rs +++ b/components/script/dom/servohtmlparser.rs @@ -11,7 +11,6 @@ use dom::bindings::codegen::Bindings::DocumentBinding::DocumentMethods; use dom::bindings::codegen::Bindings::HTMLImageElementBinding::HTMLImageElementMethods; use dom::bindings::codegen::Bindings::NodeBinding::NodeMethods; use dom::bindings::codegen::Bindings::ServoHTMLParserBinding; -use dom::bindings::global::GlobalRef; use dom::bindings::js::{JS, Root}; use dom::bindings::refcounted::Trusted; use dom::bindings::reflector::{Reflector, reflect_dom_object}; @@ -277,8 +276,7 @@ impl ServoHTMLParser { pipeline: pipeline, }; - reflect_dom_object(box parser, GlobalRef::Window(document.window()), - ServoHTMLParserBinding::Wrap) + reflect_dom_object(box parser, document.window(), ServoHTMLParserBinding::Wrap) } #[allow(unrooted_must_root)] @@ -314,8 +312,7 @@ impl ServoHTMLParser { pipeline: None, }; - reflect_dom_object(box parser, GlobalRef::Window(document.window()), - ServoHTMLParserBinding::Wrap) + reflect_dom_object(box parser, document.window(), ServoHTMLParserBinding::Wrap) } #[inline] diff --git a/components/script/dom/servoxmlparser.rs b/components/script/dom/servoxmlparser.rs index 892477ffd0f..2b79a5cf117 100644 --- a/components/script/dom/servoxmlparser.rs +++ b/components/script/dom/servoxmlparser.rs @@ -4,7 +4,6 @@ use dom::bindings::cell::DOMRefCell; use dom::bindings::codegen::Bindings::ServoXMLParserBinding; -use dom::bindings::global::GlobalRef; use dom::bindings::js::{JS, Root}; use dom::bindings::reflector::{Reflector, reflect_dom_object}; use dom::bindings::trace::JSTraceable; @@ -95,8 +94,7 @@ impl ServoXMLParser { pipeline: pipeline, }; - reflect_dom_object(box parser, GlobalRef::Window(document.window()), - ServoXMLParserBinding::Wrap) + reflect_dom_object(box parser, document.window(), ServoXMLParserBinding::Wrap) } pub fn window(&self) -> &Window { diff --git a/components/script/dom/storage.rs b/components/script/dom/storage.rs index 411e304b2f5..986cd8edcbe 100644 --- a/components/script/dom/storage.rs +++ b/components/script/dom/storage.rs @@ -5,13 +5,13 @@ use dom::bindings::codegen::Bindings::StorageBinding; use dom::bindings::codegen::Bindings::StorageBinding::StorageMethods; use dom::bindings::error::{Error, ErrorResult}; -use dom::bindings::global::GlobalRef; use dom::bindings::inheritance::Castable; use dom::bindings::js::Root; use dom::bindings::refcounted::Trusted; use dom::bindings::reflector::{Reflectable, Reflector, reflect_dom_object}; use dom::bindings::str::DOMString; use dom::event::{Event, EventBubbles, EventCancelable}; +use dom::globalscope::GlobalScope; use dom::storageevent::StorageEvent; use dom::urlhelper::UrlHelper; use ipc_channel::ipc::{self, IpcSender}; @@ -35,8 +35,8 @@ impl Storage { } } - pub fn new(global: &GlobalRef, storage_type: StorageType) -> Root { - reflect_dom_object(box Storage::new_inherited(storage_type), *global, StorageBinding::Wrap) + pub fn new(global: &GlobalScope, storage_type: StorageType) -> Root { + reflect_dom_object(box Storage::new_inherited(storage_type), global, StorageBinding::Wrap) } fn get_url(&self) -> Url { @@ -191,7 +191,7 @@ impl Runnable for StorageEventRunnable { let ev_url = storage.get_url(); let storage_event = StorageEvent::new( - global_ref, + global_ref.as_global_scope(), atom!("storage"), EventBubbles::DoesNotBubble, EventCancelable::NotCancelable, this.key.map(DOMString::from), this.old_value.map(DOMString::from), this.new_value.map(DOMString::from), diff --git a/components/script/dom/storageevent.rs b/components/script/dom/storageevent.rs index 69fe7c257d5..0b4a484ebc0 100644 --- a/components/script/dom/storageevent.rs +++ b/components/script/dom/storageevent.rs @@ -12,6 +12,7 @@ use dom::bindings::js::{JS, MutNullableHeap, Root, RootedReference}; use dom::bindings::reflector::reflect_dom_object; use dom::bindings::str::DOMString; use dom::event::{Event, EventBubbles, EventCancelable}; +use dom::globalscope::GlobalScope; use dom::storage::Storage; use dom::window::Window; use string_cache::Atom; @@ -46,11 +47,11 @@ impl StorageEvent { pub fn new_uninitialized(window: &Window, url: DOMString) -> Root { reflect_dom_object(box StorageEvent::new_inherited(None, None, None, url, None), - GlobalRef::Window(window), + window, StorageEventBinding::Wrap) } - pub fn new(global: GlobalRef, + pub fn new(global: &GlobalScope, type_: Atom, bubbles: EventBubbles, cancelable: EventCancelable, @@ -80,7 +81,7 @@ impl StorageEvent { let storageArea = init.storageArea.r(); let bubbles = EventBubbles::from(init.parent.bubbles); let cancelable = EventCancelable::from(init.parent.cancelable); - let event = StorageEvent::new(global, Atom::from(type_), + let event = StorageEvent::new(global.as_global_scope(), Atom::from(type_), bubbles, cancelable, key, oldValue, newValue, url, storageArea); diff --git a/components/script/dom/stylesheet.rs b/components/script/dom/stylesheet.rs index 15b8693c537..02c96623800 100644 --- a/components/script/dom/stylesheet.rs +++ b/components/script/dom/stylesheet.rs @@ -4,7 +4,6 @@ use dom::bindings::codegen::Bindings::StyleSheetBinding; use dom::bindings::codegen::Bindings::StyleSheetBinding::StyleSheetMethods; -use dom::bindings::global::GlobalRef; use dom::bindings::js::Root; use dom::bindings::reflector::{Reflector, reflect_dom_object}; use dom::bindings::str::DOMString; @@ -35,7 +34,7 @@ impl StyleSheet { href: Option, title: Option) -> Root { reflect_dom_object(box StyleSheet::new_inherited(type_, href, title), - GlobalRef::Window(window), + window, StyleSheetBinding::Wrap) } } diff --git a/components/script/dom/stylesheetlist.rs b/components/script/dom/stylesheetlist.rs index 721ac06525c..a4541fc9bb4 100644 --- a/components/script/dom/stylesheetlist.rs +++ b/components/script/dom/stylesheetlist.rs @@ -4,7 +4,6 @@ use dom::bindings::codegen::Bindings::StyleSheetListBinding; use dom::bindings::codegen::Bindings::StyleSheetListBinding::StyleSheetListMethods; -use dom::bindings::global::GlobalRef; use dom::bindings::js::{JS, Root}; use dom::bindings::reflector::{Reflector, reflect_dom_object}; use dom::document::Document; @@ -29,7 +28,7 @@ impl StyleSheetList { #[allow(unrooted_must_root)] pub fn new(window: &Window, document: JS) -> Root { reflect_dom_object(box StyleSheetList::new_inherited(document), - GlobalRef::Window(window), StyleSheetListBinding::Wrap) + window, StyleSheetListBinding::Wrap) } } diff --git a/components/script/dom/testbinding.rs b/components/script/dom/testbinding.rs index 6f7d7baf770..62714dfc220 100644 --- a/components/script/dom/testbinding.rs +++ b/components/script/dom/testbinding.rs @@ -30,6 +30,7 @@ use dom::bindings::reflector::{Reflectable, Reflector, reflect_dom_object}; use dom::bindings::str::{ByteString, DOMString, USVString}; use dom::bindings::weakref::MutableWeakRef; use dom::blob::{Blob, BlobImpl}; +use dom::globalscope::GlobalScope; use dom::promise::Promise; use dom::promisenativehandler::{PromiseNativeHandler, Callback}; use dom::url::URL; @@ -57,23 +58,23 @@ impl TestBinding { } } - pub fn new(global: GlobalRef) -> Root { + pub fn new(global: &GlobalScope) -> Root { reflect_dom_object(box TestBinding::new_inherited(), global, TestBindingBinding::Wrap) } pub fn Constructor(global: GlobalRef) -> Fallible> { - Ok(TestBinding::new(global)) + Ok(TestBinding::new(global.as_global_scope())) } #[allow(unused_variables)] pub fn Constructor_(global: GlobalRef, nums: Vec) -> Fallible> { - Ok(TestBinding::new(global)) + Ok(TestBinding::new(global.as_global_scope())) } #[allow(unused_variables)] pub fn Constructor__(global: GlobalRef, num: f64) -> Fallible> { - Ok(TestBinding::new(global)) + Ok(TestBinding::new(global.as_global_scope())) } } @@ -113,7 +114,7 @@ impl TestBindingMethods for TestBinding { fn EnumAttribute(&self) -> TestEnum { TestEnum::_empty } fn SetEnumAttribute(&self, _: TestEnum) {} fn InterfaceAttribute(&self) -> Root { - Blob::new(self.global().r(), BlobImpl::new_from_bytes(vec![]), "".to_owned()) + Blob::new(self.global().r().as_global_scope(), BlobImpl::new_from_bytes(vec![]), "".to_owned()) } fn SetInterfaceAttribute(&self, _: &Blob) {} fn UnionAttribute(&self) -> HTMLElementOrLong { HTMLElementOrLong::Long(0) } @@ -209,7 +210,7 @@ impl TestBindingMethods for TestBinding { fn SetAttr_to_automatically_rename(&self, _: DOMString) {} fn GetEnumAttributeNullable(&self) -> Option { Some(TestEnum::_empty) } fn GetInterfaceAttributeNullable(&self) -> Option> { - Some(Blob::new(self.global().r(), BlobImpl::new_from_bytes(vec![]), "".to_owned())) + Some(Blob::new(self.global().r().as_global_scope(), BlobImpl::new_from_bytes(vec![]), "".to_owned())) } fn SetInterfaceAttributeNullable(&self, _: Option<&Blob>) {} fn GetInterfaceAttributeWeak(&self) -> Option> { @@ -264,7 +265,7 @@ impl TestBindingMethods for TestBinding { fn ReceiveByteString(&self) -> ByteString { ByteString::new(vec!()) } fn ReceiveEnum(&self) -> TestEnum { TestEnum::_empty } fn ReceiveInterface(&self) -> Root { - Blob::new(self.global().r(), BlobImpl::new_from_bytes(vec![]), "".to_owned()) + Blob::new(self.global().r().as_global_scope(), BlobImpl::new_from_bytes(vec![]), "".to_owned()) } fn ReceiveAny(&self, _: *mut JSContext) -> JSVal { NullValue() } fn ReceiveObject(&self, cx: *mut JSContext) -> NonZero<*mut JSObject> { @@ -287,7 +288,7 @@ impl TestBindingMethods for TestBinding { } fn ReceiveSequence(&self) -> Vec { vec![1] } fn ReceiveInterfaceSequence(&self) -> Vec> { - vec![Blob::new(self.global().r(), BlobImpl::new_from_bytes(vec![]), "".to_owned())] + vec![Blob::new(self.global().r().as_global_scope(), BlobImpl::new_from_bytes(vec![]), "".to_owned())] } fn ReceiveNullableBoolean(&self) -> Option { Some(false) } @@ -308,7 +309,7 @@ impl TestBindingMethods for TestBinding { fn ReceiveNullableByteString(&self) -> Option { Some(ByteString::new(vec!())) } fn ReceiveNullableEnum(&self) -> Option { Some(TestEnum::_empty) } fn ReceiveNullableInterface(&self) -> Option> { - Some(Blob::new(self.global().r(), BlobImpl::new_from_bytes(vec![]), "".to_owned())) + Some(Blob::new(self.global().r().as_global_scope(), BlobImpl::new_from_bytes(vec![]), "".to_owned())) } fn ReceiveNullableObject(&self, cx: *mut JSContext) -> Option> { self.GetObjectAttributeNullable(cx) @@ -691,7 +692,7 @@ impl TestBindingMethods for TestBinding { resolve: Option>, reject: Option>) -> Rc { let global = self.global(); - let handler = PromiseNativeHandler::new(global.r(), + let handler = PromiseNativeHandler::new(global.r().as_global_scope(), resolve.map(SimpleHandler::new), reject.map(SimpleHandler::new)); let p = Promise::new(global.r()); diff --git a/components/script/dom/testbindingiterable.rs b/components/script/dom/testbindingiterable.rs index 2ad0df6dbb6..6023051d8f6 100644 --- a/components/script/dom/testbindingiterable.rs +++ b/components/script/dom/testbindingiterable.rs @@ -11,6 +11,7 @@ use dom::bindings::global::GlobalRef; use dom::bindings::js::Root; use dom::bindings::reflector::{Reflector, reflect_dom_object}; use dom::bindings::str::DOMString; +use dom::globalscope::GlobalScope; #[dom_struct] pub struct TestBindingIterable { @@ -19,7 +20,7 @@ pub struct TestBindingIterable { } impl TestBindingIterable { - fn new(global: GlobalRef) -> Root { + fn new(global: &GlobalScope) -> Root { reflect_dom_object(box TestBindingIterable { reflector: Reflector::new(), vals: DOMRefCell::new(vec![]), @@ -27,7 +28,7 @@ impl TestBindingIterable { } pub fn Constructor(global: GlobalRef) -> Fallible> { - Ok(TestBindingIterable::new(global)) + Ok(TestBindingIterable::new(global.as_global_scope())) } } diff --git a/components/script/dom/testbindingpairiterable.rs b/components/script/dom/testbindingpairiterable.rs index 9bceedd4980..7e3ad537aa5 100644 --- a/components/script/dom/testbindingpairiterable.rs +++ b/components/script/dom/testbindingpairiterable.rs @@ -13,6 +13,7 @@ use dom::bindings::iterable::Iterable; use dom::bindings::js::Root; use dom::bindings::reflector::{Reflector, reflect_dom_object}; use dom::bindings::str::DOMString; +use dom::globalscope::GlobalScope; #[dom_struct] pub struct TestBindingPairIterable { @@ -35,7 +36,7 @@ impl Iterable for TestBindingPairIterable { } impl TestBindingPairIterable { - fn new(global: GlobalRef) -> Root { + fn new(global: &GlobalScope) -> Root { reflect_dom_object(box TestBindingPairIterable { reflector: Reflector::new(), map: DOMRefCell::new(vec![]), @@ -43,7 +44,7 @@ impl TestBindingPairIterable { } pub fn Constructor(global: GlobalRef) -> Fallible> { - Ok(TestBindingPairIterable::new(global)) + Ok(TestBindingPairIterable::new(global.as_global_scope())) } } diff --git a/components/script/dom/textdecoder.rs b/components/script/dom/textdecoder.rs index fae78342a73..4d0e18e87f6 100644 --- a/components/script/dom/textdecoder.rs +++ b/components/script/dom/textdecoder.rs @@ -10,6 +10,7 @@ use dom::bindings::global::GlobalRef; use dom::bindings::js::Root; use dom::bindings::reflector::{Reflector, reflect_dom_object}; use dom::bindings::str::{DOMString, USVString}; +use dom::globalscope::GlobalScope; use encoding::label::encoding_from_whatwg_label; use encoding::types::{DecoderTrap, EncodingRef}; use js::jsapi::{JSContext, JSObject}; @@ -36,7 +37,7 @@ impl TextDecoder { Err(Error::Range("The given encoding is not supported.".to_owned())) } - pub fn new(global: GlobalRef, encoding: EncodingRef, fatal: bool) -> Root { + pub fn new(global: &GlobalScope, encoding: EncodingRef, fatal: bool) -> Root { reflect_dom_object(box TextDecoder::new_inherited(encoding, fatal), global, TextDecoderBinding::Wrap) @@ -60,7 +61,7 @@ impl TextDecoder { Some("replacement") => return TextDecoder::make_range_error(), _ => () }; - Ok(TextDecoder::new(global, encoding, options.fatal)) + Ok(TextDecoder::new(global.as_global_scope(), encoding, options.fatal)) } } diff --git a/components/script/dom/textencoder.rs b/components/script/dom/textencoder.rs index 996e5d28e98..5076c82190d 100644 --- a/components/script/dom/textencoder.rs +++ b/components/script/dom/textencoder.rs @@ -10,6 +10,7 @@ use dom::bindings::global::GlobalRef; use dom::bindings::js::Root; use dom::bindings::reflector::{Reflector, reflect_dom_object}; use dom::bindings::str::{DOMString, USVString}; +use dom::globalscope::GlobalScope; use encoding::EncoderTrap; use encoding::Encoding; use encoding::all::UTF_8; @@ -30,7 +31,7 @@ impl TextEncoder { } } - pub fn new(global: GlobalRef) -> Root { + pub fn new(global: &GlobalScope) -> Root { reflect_dom_object(box TextEncoder::new_inherited(), global, TextEncoderBinding::Wrap) @@ -38,7 +39,7 @@ impl TextEncoder { // https://encoding.spec.whatwg.org/#dom-textencoder pub fn Constructor(global: GlobalRef) -> Fallible> { - Ok(TextEncoder::new(global)) + Ok(TextEncoder::new(global.as_global_scope())) } } diff --git a/components/script/dom/touch.rs b/components/script/dom/touch.rs index 29bfac34152..32eeb24b6e1 100644 --- a/components/script/dom/touch.rs +++ b/components/script/dom/touch.rs @@ -4,7 +4,6 @@ use dom::bindings::codegen::Bindings::TouchBinding; use dom::bindings::codegen::Bindings::TouchBinding::TouchMethods; -use dom::bindings::global::GlobalRef; use dom::bindings::js::{JS, MutHeap, Root}; use dom::bindings::num::Finite; use dom::bindings::reflector::{Reflector, reflect_dom_object}; @@ -50,7 +49,8 @@ impl Touch { screen_x, screen_y, client_x, client_y, page_x, page_y), - GlobalRef::Window(window), TouchBinding::Wrap) + window, + TouchBinding::Wrap) } } diff --git a/components/script/dom/touchevent.rs b/components/script/dom/touchevent.rs index 1a2f7334cdf..9b4b3a250d5 100644 --- a/components/script/dom/touchevent.rs +++ b/components/script/dom/touchevent.rs @@ -5,7 +5,6 @@ use dom::bindings::codegen::Bindings::TouchEventBinding; use dom::bindings::codegen::Bindings::TouchEventBinding::TouchEventMethods; use dom::bindings::codegen::Bindings::UIEventBinding::UIEventMethods; -use dom::bindings::global::GlobalRef; use dom::bindings::inheritance::Castable; use dom::bindings::js::{JS, MutHeap, Root}; use dom::bindings::reflector::reflect_dom_object; @@ -49,7 +48,7 @@ impl TouchEvent { changed_touches: &TouchList, target_touches: &TouchList) -> Root { reflect_dom_object(box TouchEvent::new_inherited(touches, changed_touches, target_touches), - GlobalRef::Window(window), + window, TouchEventBinding::Wrap) } diff --git a/components/script/dom/touchlist.rs b/components/script/dom/touchlist.rs index 14bb8a68766..a4ff7f8443e 100644 --- a/components/script/dom/touchlist.rs +++ b/components/script/dom/touchlist.rs @@ -4,7 +4,6 @@ use dom::bindings::codegen::Bindings::TouchListBinding; use dom::bindings::codegen::Bindings::TouchListBinding::TouchListMethods; -use dom::bindings::global::GlobalRef; use dom::bindings::js::{JS, Root}; use dom::bindings::reflector::{Reflector, reflect_dom_object}; use dom::touch::Touch; @@ -26,7 +25,7 @@ impl TouchList { pub fn new(window: &Window, touches: &[&Touch]) -> Root { reflect_dom_object(box TouchList::new_inherited(touches), - GlobalRef::Window(window), TouchListBinding::Wrap) + window, TouchListBinding::Wrap) } } diff --git a/components/script/dom/treewalker.rs b/components/script/dom/treewalker.rs index c4097fc761a..7c749a5c502 100644 --- a/components/script/dom/treewalker.rs +++ b/components/script/dom/treewalker.rs @@ -9,7 +9,6 @@ use dom::bindings::codegen::Bindings::NodeFilterBinding::NodeFilterConstants; use dom::bindings::codegen::Bindings::TreeWalkerBinding; use dom::bindings::codegen::Bindings::TreeWalkerBinding::TreeWalkerMethods; use dom::bindings::error::Fallible; -use dom::bindings::global::GlobalRef; use dom::bindings::js::{JS, MutHeap}; use dom::bindings::js::Root; use dom::bindings::reflector::{Reflector, reflect_dom_object}; @@ -46,7 +45,7 @@ impl TreeWalker { what_to_show: u32, filter: Filter) -> Root { reflect_dom_object(box TreeWalker::new_inherited(root_node, what_to_show, filter), - GlobalRef::Window(document.window()), + document.window(), TreeWalkerBinding::Wrap) } diff --git a/components/script/dom/uievent.rs b/components/script/dom/uievent.rs index a0f35868662..0b64e36c62f 100644 --- a/components/script/dom/uievent.rs +++ b/components/script/dom/uievent.rs @@ -37,7 +37,7 @@ impl UIEvent { pub fn new_uninitialized(window: &Window) -> Root { reflect_dom_object(box UIEvent::new_inherited(), - GlobalRef::Window(window), + window, UIEventBinding::Wrap) } diff --git a/components/script/dom/url.rs b/components/script/dom/url.rs index bc686d23cc4..5fd4a9b005f 100644 --- a/components/script/dom/url.rs +++ b/components/script/dom/url.rs @@ -11,6 +11,7 @@ use dom::bindings::js::{JS, MutNullableHeap, Root}; use dom::bindings::reflector::{Reflectable, Reflector, reflect_dom_object}; use dom::bindings::str::{DOMString, USVString}; use dom::blob::Blob; +use dom::globalscope::GlobalScope; use dom::urlhelper::UrlHelper; use dom::urlsearchparams::URLSearchParams; use ipc_channel::ipc; @@ -44,7 +45,7 @@ impl URL { } } - pub fn new(global: GlobalRef, url: Url) -> Root { + pub fn new(global: &GlobalScope, url: Url) -> Root { reflect_dom_object(box URL::new_inherited(url), global, URLBinding::Wrap) } @@ -89,7 +90,7 @@ impl URL { }; // Step 5: Skip (see step 8 below). // Steps 6-7. - let result = URL::new(global, parsed_url); + let result = URL::new(global.as_global_scope(), parsed_url); // Step 8: Instead of construcing a new `URLSearchParams` object here, construct it // on-demand inside `URL::SearchParams`. // Step 9. @@ -283,7 +284,9 @@ impl URLMethods for URL { // https://url.spec.whatwg.org/#dom-url-searchparams fn SearchParams(&self) -> Root { - self.search_params.or_init(|| URLSearchParams::new(self.global().r(), Some(self))) + self.search_params.or_init(|| { + URLSearchParams::new(self.global().r().as_global_scope(), Some(self)) + }) } // https://url.spec.whatwg.org/#dom-url-href diff --git a/components/script/dom/urlsearchparams.rs b/components/script/dom/urlsearchparams.rs index 44eadea0932..a7b1672852f 100644 --- a/components/script/dom/urlsearchparams.rs +++ b/components/script/dom/urlsearchparams.rs @@ -12,6 +12,7 @@ use dom::bindings::js::Root; use dom::bindings::reflector::{Reflector, reflect_dom_object}; use dom::bindings::str::{DOMString, USVString}; use dom::bindings::weakref::MutableWeakRef; +use dom::globalscope::GlobalScope; use dom::url::URL; use encoding::types::EncodingRef; use url::form_urlencoded; @@ -35,7 +36,7 @@ impl URLSearchParams { } } - pub fn new(global: GlobalRef, url: Option<&URL>) -> Root { + pub fn new(global: &GlobalScope, url: Option<&URL>) -> Root { reflect_dom_object(box URLSearchParams::new_inherited(url), global, URLSearchParamsBinding::Wrap) } @@ -44,7 +45,7 @@ impl URLSearchParams { pub fn Constructor(global: GlobalRef, init: Option) -> Fallible> { // Step 1. - let query = URLSearchParams::new(global, None); + let query = URLSearchParams::new(global.as_global_scope(), None); match init { Some(USVStringOrURLSearchParams::USVString(init)) => { // Step 2. diff --git a/components/script/dom/validitystate.rs b/components/script/dom/validitystate.rs index 7595566f275..938320b7254 100644 --- a/components/script/dom/validitystate.rs +++ b/components/script/dom/validitystate.rs @@ -4,7 +4,6 @@ use dom::bindings::codegen::Bindings::ValidityStateBinding; use dom::bindings::codegen::Bindings::ValidityStateBinding::ValidityStateMethods; -use dom::bindings::global::GlobalRef; use dom::bindings::js::{JS, Root}; use dom::bindings::reflector::{Reflector, reflect_dom_object}; use dom::element::Element; @@ -47,7 +46,7 @@ impl ValidityState { pub fn new(window: &Window, element: &Element) -> Root { reflect_dom_object(box ValidityState::new_inherited(element), - GlobalRef::Window(window), + window, ValidityStateBinding::Wrap) } } diff --git a/components/script/dom/webglactiveinfo.rs b/components/script/dom/webglactiveinfo.rs index 00f70b682b7..ff82ce3b05f 100644 --- a/components/script/dom/webglactiveinfo.rs +++ b/components/script/dom/webglactiveinfo.rs @@ -5,10 +5,10 @@ // https://www.khronos.org/registry/webgl/specs/latest/1.0/webgl.idl use dom::bindings::codegen::Bindings::WebGLActiveInfoBinding; use dom::bindings::codegen::Bindings::WebGLActiveInfoBinding::WebGLActiveInfoMethods; -use dom::bindings::global::GlobalRef; use dom::bindings::js::Root; use dom::bindings::reflector::{Reflector, reflect_dom_object}; use dom::bindings::str::DOMString; +use dom::globalscope::GlobalScope; #[dom_struct] pub struct WebGLActiveInfo { @@ -29,7 +29,7 @@ impl WebGLActiveInfo { } } - pub fn new(global: GlobalRef, size: i32, ty: u32, name: DOMString) -> Root { + pub fn new(global: &GlobalScope, size: i32, ty: u32, name: DOMString) -> Root { reflect_dom_object(box WebGLActiveInfo::new_inherited(size, ty, name), global, WebGLActiveInfoBinding::Wrap) } } diff --git a/components/script/dom/webglbuffer.rs b/components/script/dom/webglbuffer.rs index 3899d417b38..af8f83d256d 100644 --- a/components/script/dom/webglbuffer.rs +++ b/components/script/dom/webglbuffer.rs @@ -5,9 +5,9 @@ // https://www.khronos.org/registry/webgl/specs/latest/1.0/webgl.idl use canvas_traits::CanvasMsg; use dom::bindings::codegen::Bindings::WebGLBufferBinding; -use dom::bindings::global::GlobalRef; use dom::bindings::js::Root; use dom::bindings::reflector::reflect_dom_object; +use dom::globalscope::GlobalScope; use dom::webglobject::WebGLObject; use ipc_channel::ipc::{self, IpcSender}; use std::cell::Cell; @@ -39,7 +39,7 @@ impl WebGLBuffer { } } - pub fn maybe_new(global: GlobalRef, renderer: IpcSender) + pub fn maybe_new(global: &GlobalScope, renderer: IpcSender) -> Option> { let (sender, receiver) = ipc::channel().unwrap(); renderer.send(CanvasMsg::WebGL(WebGLCommand::CreateBuffer(sender))).unwrap(); @@ -48,7 +48,7 @@ impl WebGLBuffer { result.map(|buffer_id| WebGLBuffer::new(global, renderer, buffer_id)) } - pub fn new(global: GlobalRef, + pub fn new(global: &GlobalScope, renderer: IpcSender, id: WebGLBufferId) -> Root { diff --git a/components/script/dom/webglcontextevent.rs b/components/script/dom/webglcontextevent.rs index 9c73a9f6b65..01ab7e0eec1 100644 --- a/components/script/dom/webglcontextevent.rs +++ b/components/script/dom/webglcontextevent.rs @@ -13,6 +13,7 @@ use dom::bindings::js::Root; use dom::bindings::reflector::reflect_dom_object; use dom::bindings::str::DOMString; use dom::event::{Event, EventBubbles, EventCancelable}; +use dom::globalscope::GlobalScope; use string_cache::Atom; #[dom_struct] @@ -41,7 +42,7 @@ impl WebGLContextEvent { } } - pub fn new_uninitialized(global_ref: GlobalRef) -> Root { + pub fn new_uninitialized(global_ref: &GlobalScope) -> Root { // according to https://www.khronos.org/registry/webgl/specs/1.0/#5.15 this is // additional information or the empty string if no additional information is // available. @@ -52,7 +53,7 @@ impl WebGLContextEvent { WebGLContextEventBinding::Wrap) } - pub fn new(global: GlobalRef, + pub fn new(global: &GlobalScope, type_: Atom, bubbles: EventBubbles, cancelable: EventCancelable, @@ -82,7 +83,8 @@ impl WebGLContextEvent { let cancelable = EventCancelable::from(init.parent.cancelable); - Ok(WebGLContextEvent::new(global, Atom::from(type_), + Ok(WebGLContextEvent::new(global.as_global_scope(), + Atom::from(type_), bubbles, cancelable, status_message)) diff --git a/components/script/dom/webglframebuffer.rs b/components/script/dom/webglframebuffer.rs index cd212d644bf..22749832389 100644 --- a/components/script/dom/webglframebuffer.rs +++ b/components/script/dom/webglframebuffer.rs @@ -6,9 +6,9 @@ use canvas_traits::CanvasMsg; use dom::bindings::codegen::Bindings::WebGLFramebufferBinding; use dom::bindings::codegen::Bindings::WebGLRenderingContextBinding::WebGLRenderingContextConstants as constants; -use dom::bindings::global::GlobalRef; use dom::bindings::js::Root; use dom::bindings::reflector::reflect_dom_object; +use dom::globalscope::GlobalScope; use dom::webglobject::WebGLObject; use ipc_channel::ipc::{self, IpcSender}; use std::cell::Cell; @@ -38,7 +38,7 @@ impl WebGLFramebuffer { } } - pub fn maybe_new(global: GlobalRef, renderer: IpcSender) + pub fn maybe_new(global: &GlobalScope, renderer: IpcSender) -> Option> { let (sender, receiver) = ipc::channel().unwrap(); renderer.send(CanvasMsg::WebGL(WebGLCommand::CreateFramebuffer(sender))).unwrap(); @@ -47,7 +47,7 @@ impl WebGLFramebuffer { result.map(|fb_id| WebGLFramebuffer::new(global, renderer, fb_id)) } - pub fn new(global: GlobalRef, + pub fn new(global: &GlobalScope, renderer: IpcSender, id: WebGLFramebufferId) -> Root { diff --git a/components/script/dom/webglobject.rs b/components/script/dom/webglobject.rs index c6bc733de62..0964fc5d0cf 100644 --- a/components/script/dom/webglobject.rs +++ b/components/script/dom/webglobject.rs @@ -4,9 +4,9 @@ // https://www.khronos.org/registry/webgl/specs/latest/1.0/webgl.idl use dom::bindings::codegen::Bindings::WebGLObjectBinding; -use dom::bindings::global::GlobalRef; use dom::bindings::js::Root; use dom::bindings::reflector::{Reflector, reflect_dom_object}; +use dom::globalscope::GlobalScope; #[dom_struct] pub struct WebGLObject { @@ -20,7 +20,7 @@ impl WebGLObject { } } - pub fn new(global: GlobalRef) -> Root { + pub fn new(global: &GlobalScope) -> Root { reflect_dom_object(box WebGLObject::new_inherited(), global, WebGLObjectBinding::Wrap) } } diff --git a/components/script/dom/webglprogram.rs b/components/script/dom/webglprogram.rs index 6382897efb3..4b3b39b05cc 100644 --- a/components/script/dom/webglprogram.rs +++ b/components/script/dom/webglprogram.rs @@ -6,10 +6,10 @@ use canvas_traits::CanvasMsg; use dom::bindings::codegen::Bindings::WebGLProgramBinding; use dom::bindings::codegen::Bindings::WebGLRenderingContextBinding::WebGLRenderingContextConstants as constants; -use dom::bindings::global::GlobalRef; use dom::bindings::js::{JS, MutNullableHeap, Root}; use dom::bindings::reflector::{Reflectable, reflect_dom_object}; use dom::bindings::str::DOMString; +use dom::globalscope::GlobalScope; use dom::webglactiveinfo::WebGLActiveInfo; use dom::webglobject::WebGLObject; use dom::webglrenderingcontext::MAX_UNIFORM_AND_ATTRIBUTE_LEN; @@ -48,7 +48,7 @@ impl WebGLProgram { } } - pub fn maybe_new(global: GlobalRef, renderer: IpcSender) + pub fn maybe_new(global: &GlobalScope, renderer: IpcSender) -> Option> { let (sender, receiver) = ipc::channel().unwrap(); renderer.send(CanvasMsg::WebGL(WebGLCommand::CreateProgram(sender))).unwrap(); @@ -57,7 +57,7 @@ impl WebGLProgram { result.map(|program_id| WebGLProgram::new(global, renderer, program_id)) } - pub fn new(global: GlobalRef, + pub fn new(global: &GlobalScope, renderer: IpcSender, id: WebGLProgramId) -> Root { @@ -230,7 +230,7 @@ impl WebGLProgram { .unwrap(); receiver.recv().unwrap().map(|(size, ty, name)| - WebGLActiveInfo::new(self.global().r(), size, ty, DOMString::from(name))) + WebGLActiveInfo::new(self.global().r().as_global_scope(), size, ty, DOMString::from(name))) } /// glGetActiveAttrib @@ -244,7 +244,7 @@ impl WebGLProgram { .unwrap(); receiver.recv().unwrap().map(|(size, ty, name)| - WebGLActiveInfo::new(self.global().r(), size, ty, DOMString::from(name))) + WebGLActiveInfo::new(self.global().r().as_global_scope(), size, ty, DOMString::from(name))) } /// glGetAttribLocation diff --git a/components/script/dom/webglrenderbuffer.rs b/components/script/dom/webglrenderbuffer.rs index b7e89f2eb22..de4eaa2d2c8 100644 --- a/components/script/dom/webglrenderbuffer.rs +++ b/components/script/dom/webglrenderbuffer.rs @@ -5,9 +5,9 @@ // https://www.khronos.org/registry/webgl/specs/latest/1.0/webgl.idl use canvas_traits::CanvasMsg; use dom::bindings::codegen::Bindings::WebGLRenderbufferBinding; -use dom::bindings::global::GlobalRef; use dom::bindings::js::Root; use dom::bindings::reflector::reflect_dom_object; +use dom::globalscope::GlobalScope; use dom::webglobject::WebGLObject; use ipc_channel::ipc::{self, IpcSender}; use std::cell::Cell; @@ -36,7 +36,7 @@ impl WebGLRenderbuffer { } } - pub fn maybe_new(global: GlobalRef, renderer: IpcSender) + pub fn maybe_new(global: &GlobalScope, renderer: IpcSender) -> Option> { let (sender, receiver) = ipc::channel().unwrap(); renderer.send(CanvasMsg::WebGL(WebGLCommand::CreateRenderbuffer(sender))).unwrap(); @@ -45,7 +45,7 @@ impl WebGLRenderbuffer { result.map(|renderbuffer_id| WebGLRenderbuffer::new(global, renderer, renderbuffer_id)) } - pub fn new(global: GlobalRef, + pub fn new(global: &GlobalScope, renderer: IpcSender, id: WebGLRenderbufferId) -> Root { diff --git a/components/script/dom/webglrenderingcontext.rs b/components/script/dom/webglrenderingcontext.rs index b69f11146fd..4b6e8b2cefd 100644 --- a/components/script/dom/webglrenderingcontext.rs +++ b/components/script/dom/webglrenderingcontext.rs @@ -162,11 +162,11 @@ impl WebGLRenderingContext { pub fn new(global: GlobalRef, canvas: &HTMLCanvasElement, size: Size2D, attrs: GLContextAttributes) -> Option> { match WebGLRenderingContext::new_inherited(global, canvas, size, attrs) { - Ok(ctx) => Some(reflect_dom_object(box ctx, global, + Ok(ctx) => Some(reflect_dom_object(box ctx, global.as_global_scope(), WebGLRenderingContextBinding::Wrap)), Err(msg) => { error!("Couldn't create WebGLRenderingContext: {}", msg); - let event = WebGLContextEvent::new(global, + let event = WebGLContextEvent::new(global.as_global_scope(), atom!("webglcontextcreationerror"), EventBubbles::DoesNotBubble, EventCancelable::Cancelable, @@ -1154,27 +1154,27 @@ impl WebGLRenderingContextMethods for WebGLRenderingContext { // generated objects, either here or in the webgl thread // https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.5 fn CreateBuffer(&self) -> Option> { - WebGLBuffer::maybe_new(self.global().r(), self.ipc_renderer.clone()) + WebGLBuffer::maybe_new(self.global().r().as_global_scope(), self.ipc_renderer.clone()) } // https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.6 fn CreateFramebuffer(&self) -> Option> { - WebGLFramebuffer::maybe_new(self.global().r(), self.ipc_renderer.clone()) + WebGLFramebuffer::maybe_new(self.global().r().as_global_scope(), self.ipc_renderer.clone()) } // https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.7 fn CreateRenderbuffer(&self) -> Option> { - WebGLRenderbuffer::maybe_new(self.global().r(), self.ipc_renderer.clone()) + WebGLRenderbuffer::maybe_new(self.global().r().as_global_scope(), self.ipc_renderer.clone()) } // https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.8 fn CreateTexture(&self) -> Option> { - WebGLTexture::maybe_new(self.global().r(), self.ipc_renderer.clone()) + WebGLTexture::maybe_new(self.global().r().as_global_scope(), self.ipc_renderer.clone()) } // https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.9 fn CreateProgram(&self) -> Option> { - WebGLProgram::maybe_new(self.global().r(), self.ipc_renderer.clone()) + WebGLProgram::maybe_new(self.global().r().as_global_scope(), self.ipc_renderer.clone()) } // https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.9 @@ -1186,7 +1186,7 @@ impl WebGLRenderingContextMethods for WebGLRenderingContext { return None; } } - WebGLShader::maybe_new(self.global().r(), self.ipc_renderer.clone(), shader_type) + WebGLShader::maybe_new(self.global().r().as_global_scope(), self.ipc_renderer.clone(), shader_type) } // https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.5 @@ -1480,7 +1480,7 @@ impl WebGLRenderingContextMethods for WebGLRenderingContext { name: DOMString) -> Option> { program.and_then(|p| { handle_potential_webgl_error!(self, p.get_uniform_location(name), None) - .map(|location| WebGLUniformLocation::new(self.global().r(), location, p.id())) + .map(|location| WebGLUniformLocation::new(self.global().r().as_global_scope(), location, p.id())) }) } diff --git a/components/script/dom/webglshader.rs b/components/script/dom/webglshader.rs index ca2555faa8e..82d1b88a7da 100644 --- a/components/script/dom/webglshader.rs +++ b/components/script/dom/webglshader.rs @@ -7,10 +7,10 @@ use angle::hl::{BuiltInResources, Output, ShaderValidator}; use canvas_traits::CanvasMsg; use dom::bindings::cell::DOMRefCell; use dom::bindings::codegen::Bindings::WebGLShaderBinding; -use dom::bindings::global::GlobalRef; use dom::bindings::js::Root; use dom::bindings::reflector::reflect_dom_object; use dom::bindings::str::DOMString; +use dom::globalscope::GlobalScope; use dom::webglobject::WebGLObject; use ipc_channel::ipc::{self, IpcSender}; use std::cell::Cell; @@ -65,7 +65,7 @@ impl WebGLShader { } } - pub fn maybe_new(global: GlobalRef, + pub fn maybe_new(global: &GlobalScope, renderer: IpcSender, shader_type: u32) -> Option> { let (sender, receiver) = ipc::channel().unwrap(); @@ -75,7 +75,7 @@ impl WebGLShader { result.map(|shader_id| WebGLShader::new(global, renderer, shader_id, shader_type)) } - pub fn new(global: GlobalRef, + pub fn new(global: &GlobalScope, renderer: IpcSender, id: WebGLShaderId, shader_type: u32) diff --git a/components/script/dom/webglshaderprecisionformat.rs b/components/script/dom/webglshaderprecisionformat.rs index 6cd78b8d51a..18ba8c189a5 100644 --- a/components/script/dom/webglshaderprecisionformat.rs +++ b/components/script/dom/webglshaderprecisionformat.rs @@ -5,9 +5,9 @@ // https://www.khronos.org/registry/webgl/specs/latest/1.0/webgl.idl use dom::bindings::codegen::Bindings::WebGLShaderPrecisionFormatBinding; use dom::bindings::codegen::Bindings::WebGLShaderPrecisionFormatBinding::WebGLShaderPrecisionFormatMethods; -use dom::bindings::global::GlobalRef; use dom::bindings::js::Root; use dom::bindings::reflector::{Reflector, reflect_dom_object}; +use dom::globalscope::GlobalScope; #[dom_struct] pub struct WebGLShaderPrecisionFormat { @@ -27,7 +27,7 @@ impl WebGLShaderPrecisionFormat { } } - pub fn new(global: GlobalRef, + pub fn new(global: &GlobalScope, range_min: i32, range_max: i32, precision: i32) -> Root { diff --git a/components/script/dom/webgltexture.rs b/components/script/dom/webgltexture.rs index e189835ee9d..31fdaafcffd 100644 --- a/components/script/dom/webgltexture.rs +++ b/components/script/dom/webgltexture.rs @@ -7,9 +7,9 @@ use canvas_traits::CanvasMsg; use dom::bindings::cell::DOMRefCell; use dom::bindings::codegen::Bindings::WebGLRenderingContextBinding::WebGLRenderingContextConstants as constants; use dom::bindings::codegen::Bindings::WebGLTextureBinding; -use dom::bindings::global::GlobalRef; use dom::bindings::js::Root; use dom::bindings::reflector::reflect_dom_object; +use dom::globalscope::GlobalScope; use dom::webgl_validations::types::{TexImageTarget, TexFormat, TexDataType}; use dom::webglobject::WebGLObject; use ipc_channel::ipc::{self, IpcSender}; @@ -60,7 +60,7 @@ impl WebGLTexture { } } - pub fn maybe_new(global: GlobalRef, renderer: IpcSender) + pub fn maybe_new(global: &GlobalScope, renderer: IpcSender) -> Option> { let (sender, receiver) = ipc::channel().unwrap(); renderer.send(CanvasMsg::WebGL(WebGLCommand::CreateTexture(sender))).unwrap(); @@ -69,7 +69,7 @@ impl WebGLTexture { result.map(|texture_id| WebGLTexture::new(global, renderer, texture_id)) } - pub fn new(global: GlobalRef, + pub fn new(global: &GlobalScope, renderer: IpcSender, id: WebGLTextureId) -> Root { diff --git a/components/script/dom/webgluniformlocation.rs b/components/script/dom/webgluniformlocation.rs index f52cb899eb8..6e0683ec833 100644 --- a/components/script/dom/webgluniformlocation.rs +++ b/components/script/dom/webgluniformlocation.rs @@ -4,9 +4,9 @@ // https://www.khronos.org/registry/webgl/specs/latest/1.0/webgl.idl use dom::bindings::codegen::Bindings::WebGLUniformLocationBinding; -use dom::bindings::global::GlobalRef; use dom::bindings::js::Root; use dom::bindings::reflector::{Reflector, reflect_dom_object}; +use dom::globalscope::GlobalScope; use webrender_traits::WebGLProgramId; #[dom_struct] @@ -27,7 +27,7 @@ impl WebGLUniformLocation { } } - pub fn new(global: GlobalRef, + pub fn new(global: &GlobalScope, id: i32, program_id: WebGLProgramId) -> Root { diff --git a/components/script/dom/websocket.rs b/components/script/dom/websocket.rs index df9c2e5ed34..4e86241f36a 100644 --- a/components/script/dom/websocket.rs +++ b/components/script/dom/websocket.rs @@ -20,6 +20,7 @@ use dom::blob::{Blob, BlobImpl}; use dom::closeevent::CloseEvent; use dom::event::{Event, EventBubbles, EventCancelable}; use dom::eventtarget::EventTarget; +use dom::globalscope::GlobalScope; use dom::messageevent::MessageEvent; use dom::urlhelper::UrlHelper; use ipc_channel::ipc::{self, IpcReceiver, IpcSender}; @@ -190,7 +191,7 @@ impl WebSocket { } } - fn new(global: GlobalRef, url: Url) -> Root { + fn new(global: &GlobalScope, url: Url) -> Root { reflect_dom_object(box WebSocket::new_inherited(url), global, WebSocketBinding::Wrap) } @@ -241,7 +242,7 @@ impl WebSocket { let origin = UrlHelper::Origin(&global.get_url()).0; // Step 7. - let ws = WebSocket::new(global, resource_url.clone()); + let ws = WebSocket::new(global.as_global_scope(), resource_url.clone()); let address = Trusted::new(ws.r()); let connect_data = WebSocketConnectData { @@ -557,7 +558,7 @@ impl Runnable for CloseTask { let clean_close = !self.failed; let code = self.code.unwrap_or(close_code::NO_STATUS); let reason = DOMString::from(self.reason.unwrap_or("".to_owned())); - let close_event = CloseEvent::new(global.r(), + let close_event = CloseEvent::new(global.r().as_global_scope(), atom!("close"), EventBubbles::DoesNotBubble, EventCancelable::NotCancelable, @@ -599,7 +600,10 @@ impl Runnable for MessageReceivedTask { MessageData::Binary(data) => { match ws.binary_type.get() { BinaryType::Blob => { - let blob = Blob::new(global.r(), BlobImpl::new_from_bytes(data), "".to_owned()); + let blob = Blob::new( + global.r().as_global_scope(), + BlobImpl::new_from_bytes(data), + "".to_owned()); blob.to_jsval(cx, message.handle_mut()); } BinaryType::Arraybuffer => { diff --git a/components/script/dom/window.rs b/components/script/dom/window.rs index 85c8f46fc63..0b764f6fa05 100644 --- a/components/script/dom/window.rs +++ b/components/script/dom/window.rs @@ -495,17 +495,17 @@ impl WindowMethods for Window { // https://html.spec.whatwg.org/multipage/#dom-sessionstorage fn SessionStorage(&self) -> Root { - self.session_storage.or_init(|| Storage::new(&GlobalRef::Window(self), StorageType::Session)) + self.session_storage.or_init(|| Storage::new(self.upcast(), StorageType::Session)) } // https://html.spec.whatwg.org/multipage/#dom-localstorage fn LocalStorage(&self) -> Root { - self.local_storage.or_init(|| Storage::new(&GlobalRef::Window(self), StorageType::Local)) + self.local_storage.or_init(|| Storage::new(self.upcast(), StorageType::Local)) } // https://dvcs.w3.org/hg/webcrypto-api/raw-file/tip/spec/Overview.html#dfn-GlobalCrypto fn Crypto(&self) -> Root { - self.crypto.or_init(|| Crypto::new(GlobalRef::Window(self))) + self.crypto.or_init(|| Crypto::new(self.upcast())) } // https://html.spec.whatwg.org/multipage/#dom-frameelement @@ -1708,7 +1708,7 @@ impl Window { // Steps 3-12. // FIXME(#13195): muted errors. - let event = ErrorEvent::new(GlobalRef::Window(self), + let event = ErrorEvent::new(self.upcast(), atom!("error"), EventBubbles::DoesNotBubble, EventCancelable::Cancelable, diff --git a/components/script/dom/worker.rs b/components/script/dom/worker.rs index fb6b170ab1d..9c43f1c148d 100644 --- a/components/script/dom/worker.rs +++ b/components/script/dom/worker.rs @@ -21,6 +21,7 @@ use dom::errorevent::ErrorEvent; use dom::event::{Event, EventBubbles, EventCancelable}; use dom::eventdispatcher::EventStatus; use dom::eventtarget::EventTarget; +use dom::globalscope::GlobalScope; use dom::messageevent::MessageEvent; use dom::workerglobalscope::prepare_workerscope_init; use ipc_channel::ipc; @@ -61,7 +62,7 @@ impl Worker { } } - pub fn new(global: GlobalRef, + pub fn new(global: &GlobalScope, sender: Sender<(TrustedWorkerAddress, WorkerScriptMsg)>, closing: Arc) -> Root { reflect_dom_object(box Worker::new_inherited(sender, closing), @@ -80,7 +81,7 @@ impl Worker { let (sender, receiver) = channel(); let closing = Arc::new(AtomicBool::new(false)); - let worker = Worker::new(global, sender.clone(), closing.clone()); + let worker = Worker::new(global.as_global_scope(), sender.clone(), closing.clone()); let worker_ref = Trusted::new(worker.r()); let worker_load_origin = WorkerScriptLoadOrigin { @@ -144,7 +145,7 @@ impl Worker { #[allow(unsafe_code)] fn dispatch_error(&self, error_info: ErrorInfo) { let global = self.global(); - let event = ErrorEvent::new(global.r(), + let event = ErrorEvent::new(global.r().as_global_scope(), atom!("error"), EventBubbles::DoesNotBubble, EventCancelable::Cancelable, diff --git a/components/script/dom/workerglobalscope.rs b/components/script/dom/workerglobalscope.rs index 95e8b425c25..83cef1d994f 100644 --- a/components/script/dom/workerglobalscope.rs +++ b/components/script/dom/workerglobalscope.rs @@ -343,7 +343,7 @@ impl WorkerGlobalScopeMethods for WorkerGlobalScope { // https://html.spec.whatwg.org/multipage/#dfn-Crypto fn Crypto(&self) -> Root { - self.crypto.or_init(|| Crypto::new(GlobalRef::Worker(self))) + self.crypto.or_init(|| Crypto::new(self.upcast())) } // https://html.spec.whatwg.org/multipage/#dom-windowbase64-btoa @@ -505,7 +505,7 @@ impl WorkerGlobalScope { // Steps 3-12. // FIXME(#13195): muted errors. - let event = ErrorEvent::new(GlobalRef::Worker(self), + let event = ErrorEvent::new(self.upcast(), atom!("error"), EventBubbles::DoesNotBubble, EventCancelable::Cancelable, diff --git a/components/script/dom/workerlocation.rs b/components/script/dom/workerlocation.rs index a037f7737a8..287a803a612 100644 --- a/components/script/dom/workerlocation.rs +++ b/components/script/dom/workerlocation.rs @@ -4,7 +4,6 @@ use dom::bindings::codegen::Bindings::WorkerLocationBinding; use dom::bindings::codegen::Bindings::WorkerLocationBinding::WorkerLocationMethods; -use dom::bindings::global::GlobalRef; use dom::bindings::js::Root; use dom::bindings::reflector::{Reflector, reflect_dom_object}; use dom::bindings::str::{DOMString, USVString}; @@ -29,7 +28,7 @@ impl WorkerLocation { pub fn new(global: &WorkerGlobalScope, url: Url) -> Root { reflect_dom_object(box WorkerLocation::new_inherited(url), - GlobalRef::Worker(global), + global, WorkerLocationBinding::Wrap) } } diff --git a/components/script/dom/workernavigator.rs b/components/script/dom/workernavigator.rs index 1114a91a169..f6cd521634d 100644 --- a/components/script/dom/workernavigator.rs +++ b/components/script/dom/workernavigator.rs @@ -4,7 +4,6 @@ use dom::bindings::codegen::Bindings::WorkerNavigatorBinding; use dom::bindings::codegen::Bindings::WorkerNavigatorBinding::WorkerNavigatorMethods; -use dom::bindings::global::GlobalRef; use dom::bindings::js::Root; use dom::bindings::reflector::{Reflector, reflect_dom_object}; use dom::bindings::str::DOMString; @@ -26,7 +25,7 @@ impl WorkerNavigator { pub fn new(global: &WorkerGlobalScope) -> Root { reflect_dom_object(box WorkerNavigator::new_inherited(), - GlobalRef::Worker(global), + global, WorkerNavigatorBinding::Wrap) } } diff --git a/components/script/dom/xmldocument.rs b/components/script/dom/xmldocument.rs index 1a00f67b80c..6fb57ea52fd 100644 --- a/components/script/dom/xmldocument.rs +++ b/components/script/dom/xmldocument.rs @@ -6,7 +6,6 @@ use core::nonzero::NonZero; use document_loader::DocumentLoader; use dom::bindings::codegen::Bindings::DocumentBinding::DocumentMethods; use dom::bindings::codegen::Bindings::XMLDocumentBinding::{self, XMLDocumentMethods}; -use dom::bindings::global::GlobalRef; use dom::bindings::inheritance::Castable; use dom::bindings::js::Root; use dom::bindings::reflector::reflect_dom_object; @@ -66,7 +65,7 @@ impl XMLDocument { last_modified, source, doc_loader), - GlobalRef::Window(window), + window, XMLDocumentBinding::Wrap); { let node = doc.upcast::(); diff --git a/components/script/dom/xmlhttprequest.rs b/components/script/dom/xmlhttprequest.rs index caebbddd09e..4c9397db566 100644 --- a/components/script/dom/xmlhttprequest.rs +++ b/components/script/dom/xmlhttprequest.rs @@ -167,7 +167,7 @@ impl XMLHttpRequest { ready_state: Cell::new(XMLHttpRequestState::Unsent), timeout: Cell::new(0u32), with_credentials: Cell::new(false), - upload: JS::from_ref(&*XMLHttpRequestUpload::new(global)), + upload: JS::from_ref(&*XMLHttpRequestUpload::new(global.as_global_scope())), response_url: DOMRefCell::new(String::from("")), status: Cell::new(0), status_text: DOMRefCell::new(ByteString::new(vec!())), @@ -198,7 +198,7 @@ impl XMLHttpRequest { } pub fn new(global: GlobalRef) -> Root { reflect_dom_object(box XMLHttpRequest::new_inherited(global), - global, + global.as_global_scope(), XMLHttpRequestBinding::Wrap) } @@ -860,7 +860,7 @@ impl XMLHttpRequest { assert!(self.ready_state.get() != rs); self.ready_state.set(rs); let global = self.global(); - let event = Event::new(global.r(), + let event = Event::new(global.r().as_global_scope(), atom!("readystatechange"), EventBubbles::DoesNotBubble, EventCancelable::Cancelable); @@ -977,7 +977,7 @@ impl XMLHttpRequest { } let global = self.global(); let event = Event::new( - global.r(), + global.r().as_global_scope(), atom!("readystatechange"), EventBubbles::DoesNotBubble, EventCancelable::Cancelable); @@ -1050,7 +1050,7 @@ impl XMLHttpRequest { fn dispatch_progress_event(&self, upload: bool, type_: Atom, loaded: u64, total: Option) { let global = self.global(); - let progressevent = ProgressEvent::new(global.r(), + let progressevent = ProgressEvent::new(global.r().as_global_scope(), type_, EventBubbles::DoesNotBubble, EventCancelable::NotCancelable, @@ -1118,7 +1118,7 @@ impl XMLHttpRequest { // Step 3, 4 let bytes = self.response.borrow().to_vec(); - let blob = Blob::new(self.global().r(), BlobImpl::new_from_bytes(bytes), mime); + let blob = Blob::new(self.global().r().as_global_scope(), BlobImpl::new_from_bytes(bytes), mime); self.response_blob.set(Some(blob.r())); blob } diff --git a/components/script/dom/xmlhttprequestupload.rs b/components/script/dom/xmlhttprequestupload.rs index 900548f2e05..6c53fe15eca 100644 --- a/components/script/dom/xmlhttprequestupload.rs +++ b/components/script/dom/xmlhttprequestupload.rs @@ -3,9 +3,9 @@ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use dom::bindings::codegen::Bindings::XMLHttpRequestUploadBinding; -use dom::bindings::global::GlobalRef; use dom::bindings::js::Root; use dom::bindings::reflector::reflect_dom_object; +use dom::globalscope::GlobalScope; use dom::xmlhttprequesteventtarget::XMLHttpRequestEventTarget; #[dom_struct] @@ -19,7 +19,7 @@ impl XMLHttpRequestUpload { eventtarget: XMLHttpRequestEventTarget::new_inherited(), } } - pub fn new(global: GlobalRef) -> Root { + pub fn new(global: &GlobalScope) -> Root { reflect_dom_object(box XMLHttpRequestUpload::new_inherited(), global, XMLHttpRequestUploadBinding::Wrap) diff --git a/components/script/fetch.rs b/components/script/fetch.rs index 634439c7c7d..75d6e3b0848 100644 --- a/components/script/fetch.rs +++ b/components/script/fetch.rs @@ -71,7 +71,7 @@ pub fn Fetch(global: GlobalRef, input: RequestOrUSVString, init: &RequestInit) - // Step 1 let promise = Promise::new(global); - let response = Response::new(global); + let response = Response::new(global.as_global_scope()); // Step 2 let request = match Request::Constructor(global, input, init) { From 38273fe7a83313649384a6f265ee9ab816287b18 Mon Sep 17 00:00:00 2001 From: Anthony Ramine Date: Tue, 27 Sep 2016 13:26:21 +0200 Subject: [PATCH 05/66] Introduce GlobalScope::crypto --- components/script/dom/globalscope.rs | 8 ++++++++ components/script/dom/window.rs | 4 +--- components/script/dom/workerglobalscope.rs | 4 +--- 3 files changed, 10 insertions(+), 6 deletions(-) diff --git a/components/script/dom/globalscope.rs b/components/script/dom/globalscope.rs index de9ee3773d2..0eaf631f0e1 100644 --- a/components/script/dom/globalscope.rs +++ b/components/script/dom/globalscope.rs @@ -2,19 +2,23 @@ * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ +use dom::bindings::js::{JS, MutNullableHeap, Root}; use dom::bindings::reflector::Reflectable; +use dom::crypto::Crypto; use dom::eventtarget::EventTarget; use js::jsapi::{JS_GetContext, JS_GetObjectRuntime, JSContext}; #[dom_struct] pub struct GlobalScope { eventtarget: EventTarget, + crypto: MutNullableHeap>, } impl GlobalScope { pub fn new_inherited() -> GlobalScope { GlobalScope { eventtarget: EventTarget::new_inherited(), + crypto: Default::default(), } } @@ -29,4 +33,8 @@ impl GlobalScope { context } } + + pub fn crypto(&self) -> Root { + self.crypto.or_init(|| Crypto::new(self)) + } } diff --git a/components/script/dom/window.rs b/components/script/dom/window.rs index 0b764f6fa05..148ee2f5eed 100644 --- a/components/script/dom/window.rs +++ b/components/script/dom/window.rs @@ -157,7 +157,6 @@ pub struct Window { history_traversal_task_source: HistoryTraversalTaskSource, #[ignore_heap_size_of = "task sources are hard"] file_reading_task_source: FileReadingTaskSource, - crypto: MutNullableHeap>, navigator: MutNullableHeap>, #[ignore_heap_size_of = "channels are hard"] image_cache_thread: ImageCacheThread, @@ -505,7 +504,7 @@ impl WindowMethods for Window { // https://dvcs.w3.org/hg/webcrypto-api/raw-file/tip/spec/Overview.html#dfn-GlobalCrypto fn Crypto(&self) -> Root { - self.crypto.or_init(|| Crypto::new(self.upcast())) + self.upcast::().crypto() } // https://html.spec.whatwg.org/multipage/#dom-frameelement @@ -1638,7 +1637,6 @@ impl Window { history_traversal_task_source: history_task_source, file_reading_task_source: file_task_source, image_cache_chan: image_cache_chan, - crypto: Default::default(), navigator: Default::default(), image_cache_thread: image_cache_thread, mem_profiler_chan: mem_profiler_chan, diff --git a/components/script/dom/workerglobalscope.rs b/components/script/dom/workerglobalscope.rs index 83cef1d994f..739e81c87ac 100644 --- a/components/script/dom/workerglobalscope.rs +++ b/components/script/dom/workerglobalscope.rs @@ -89,7 +89,6 @@ pub struct WorkerGlobalScope { resource_threads: ResourceThreads, location: MutNullableHeap>, navigator: MutNullableHeap>, - crypto: MutNullableHeap>, timers: OneshotTimers, #[ignore_heap_size_of = "Defined in std"] @@ -147,7 +146,6 @@ impl WorkerGlobalScope { resource_threads: init.resource_threads, location: Default::default(), navigator: Default::default(), - crypto: Default::default(), timers: OneshotTimers::new(timer_event_chan, init.scheduler_chan.clone()), mem_profiler_chan: init.mem_profiler_chan, time_profiler_chan: init.time_profiler_chan, @@ -343,7 +341,7 @@ impl WorkerGlobalScopeMethods for WorkerGlobalScope { // https://html.spec.whatwg.org/multipage/#dfn-Crypto fn Crypto(&self) -> Root { - self.crypto.or_init(|| Crypto::new(self.upcast())) + self.upcast::().crypto() } // https://html.spec.whatwg.org/multipage/#dom-windowbase64-btoa From 3e5c0c386c425e51067038228561e78d10c80a53 Mon Sep 17 00:00:00 2001 From: Anthony Ramine Date: Tue, 27 Sep 2016 14:07:45 +0200 Subject: [PATCH 06/66] Introduce GlobalScope::get_next_worker_id --- components/script/dom/bindings/global.rs | 10 +--------- components/script/dom/globalscope.rs | 12 ++++++++++++ components/script/dom/serviceworkerregistration.rs | 2 +- components/script/dom/window.rs | 12 +----------- components/script/dom/worker.rs | 2 +- components/script/dom/workerglobalscope.rs | 11 +---------- 6 files changed, 17 insertions(+), 32 deletions(-) diff --git a/components/script/dom/bindings/global.rs b/components/script/dom/bindings/global.rs index db90f1fbcdf..b49a3b51ba3 100644 --- a/components/script/dom/bindings/global.rs +++ b/components/script/dom/bindings/global.rs @@ -7,7 +7,7 @@ //! This module contains smart pointers to global scopes, to simplify writing //! code that works in workers as well as window scopes. -use devtools_traits::{ScriptToDevtoolsControlMsg, WorkerId}; +use devtools_traits::ScriptToDevtoolsControlMsg; use dom::bindings::codegen::Bindings::WindowBinding::WindowMethods; use dom::bindings::conversions::root_from_object; use dom::bindings::error::{ErrorInfo, report_pending_exception}; @@ -145,14 +145,6 @@ impl<'a> GlobalRef<'a> { self.resource_threads().sender() } - /// Get next worker id. - pub fn get_next_worker_id(&self) -> WorkerId { - match *self { - GlobalRef::Window(ref window) => window.get_next_worker_id(), - GlobalRef::Worker(ref worker) => worker.get_next_worker_id(), - } - } - /// Get the URL for this global scope. pub fn get_url(&self) -> Url { match *self { diff --git a/components/script/dom/globalscope.rs b/components/script/dom/globalscope.rs index 0eaf631f0e1..a09e727f772 100644 --- a/components/script/dom/globalscope.rs +++ b/components/script/dom/globalscope.rs @@ -2,16 +2,19 @@ * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ +use devtools_traits::WorkerId; use dom::bindings::js::{JS, MutNullableHeap, Root}; use dom::bindings::reflector::Reflectable; use dom::crypto::Crypto; use dom::eventtarget::EventTarget; use js::jsapi::{JS_GetContext, JS_GetObjectRuntime, JSContext}; +use std::cell::Cell; #[dom_struct] pub struct GlobalScope { eventtarget: EventTarget, crypto: MutNullableHeap>, + next_worker_id: Cell, } impl GlobalScope { @@ -19,6 +22,7 @@ impl GlobalScope { GlobalScope { eventtarget: EventTarget::new_inherited(), crypto: Default::default(), + next_worker_id: Cell::new(WorkerId(0)), } } @@ -37,4 +41,12 @@ impl GlobalScope { pub fn crypto(&self) -> Root { self.crypto.or_init(|| Crypto::new(self)) } + + /// Get next worker id. + pub fn get_next_worker_id(&self) -> WorkerId { + let worker_id = self.next_worker_id.get(); + let WorkerId(id_num) = worker_id; + self.next_worker_id.set(WorkerId(id_num + 1)); + worker_id + } } diff --git a/components/script/dom/serviceworkerregistration.rs b/components/script/dom/serviceworkerregistration.rs index b0580457f1c..bc089c18dac 100644 --- a/components/script/dom/serviceworkerregistration.rs +++ b/components/script/dom/serviceworkerregistration.rs @@ -57,7 +57,7 @@ impl ServiceWorkerRegistration { pipeline_id: Some(global.pipeline_id()) }; - let worker_id = global.get_next_worker_id(); + let worker_id = global.as_global_scope().get_next_worker_id(); let init = prepare_workerscope_init(global, None); ScopeThings { script_url: script_url, diff --git a/components/script/dom/window.rs b/components/script/dom/window.rs index 148ee2f5eed..406371261d0 100644 --- a/components/script/dom/window.rs +++ b/components/script/dom/window.rs @@ -3,7 +3,7 @@ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use app_units::Au; -use devtools_traits::{ScriptToDevtoolsControlMsg, TimelineMarker, TimelineMarkerType, WorkerId}; +use devtools_traits::{ScriptToDevtoolsControlMsg, TimelineMarker, TimelineMarkerType}; use dom::bindings::callback::ExceptionHandling; use dom::bindings::cell::DOMRefCell; use dom::bindings::codegen::Bindings::DocumentBinding::{DocumentMethods, DocumentReadyState}; @@ -175,8 +175,6 @@ pub struct Window { scheduler_chan: IpcSender, timers: OneshotTimers, - next_worker_id: Cell, - /// For sending messages to the memory profiler. #[ignore_heap_size_of = "channels are hard"] mem_profiler_chan: mem::ProfilerChan, @@ -320,13 +318,6 @@ impl Window { self.image_cache_chan.clone() } - pub fn get_next_worker_id(&self) -> WorkerId { - let worker_id = self.next_worker_id.get(); - let WorkerId(id_num) = worker_id; - self.next_worker_id.set(WorkerId(id_num + 1)); - worker_id - } - pub fn pipeline_id(&self) -> PipelineId { self.id } @@ -1653,7 +1644,6 @@ impl Window { status: DOMRefCell::new(DOMString::new()), scheduler_chan: scheduler_chan.clone(), timers: OneshotTimers::new(timer_event_chan, scheduler_chan), - next_worker_id: Cell::new(WorkerId(0)), id: id, parent_info: parent_info, dom_static: GlobalStaticData::new(), diff --git a/components/script/dom/worker.rs b/components/script/dom/worker.rs index 9c43f1c148d..1e32b4375f1 100644 --- a/components/script/dom/worker.rs +++ b/components/script/dom/worker.rs @@ -91,7 +91,7 @@ impl Worker { }; let (devtools_sender, devtools_receiver) = ipc::channel().unwrap(); - let worker_id = global.get_next_worker_id(); + let worker_id = global.as_global_scope().get_next_worker_id(); if let Some(ref chan) = global.devtools_chan() { let pipeline_id = global.pipeline_id(); let title = format!("Worker for {}", worker_url); diff --git a/components/script/dom/workerglobalscope.rs b/components/script/dom/workerglobalscope.rs index 739e81c87ac..b72ae48251c 100644 --- a/components/script/dom/workerglobalscope.rs +++ b/components/script/dom/workerglobalscope.rs @@ -56,7 +56,7 @@ use url::Url; pub fn prepare_workerscope_init(global: GlobalRef, devtools_sender: Option>) -> WorkerGlobalScopeInit { - let worker_id = global.get_next_worker_id(); + let worker_id = global.as_global_scope().get_next_worker_id(); let init = WorkerGlobalScopeInit { resource_threads: global.resource_threads(), mem_profiler_chan: global.mem_profiler_chan().clone(), @@ -84,7 +84,6 @@ pub struct WorkerGlobalScope { closing: Option>, #[ignore_heap_size_of = "Defined in js"] runtime: Runtime, - next_worker_id: Cell, #[ignore_heap_size_of = "Defined in std"] resource_threads: ResourceThreads, location: MutNullableHeap>, @@ -137,7 +136,6 @@ impl WorkerGlobalScope { -> WorkerGlobalScope { WorkerGlobalScope { globalscope: GlobalScope::new_inherited(), - next_worker_id: Cell::new(WorkerId(0)), worker_id: init.worker_id, pipeline_id: init.pipeline_id, worker_url: worker_url, @@ -231,13 +229,6 @@ impl WorkerGlobalScope { self.worker_id.clone() } - pub fn get_next_worker_id(&self) -> WorkerId { - let worker_id = self.next_worker_id.get(); - let WorkerId(id_num) = worker_id; - self.next_worker_id.set(WorkerId(id_num + 1)); - worker_id - } - pub fn get_runnable_wrapper(&self) -> RunnableWrapper { RunnableWrapper { cancelled: self.closing.clone().unwrap(), From d7c2da450bb7a4e1b393c1260cd13ec658d408f0 Mon Sep 17 00:00:00 2001 From: Anthony Ramine Date: Tue, 27 Sep 2016 14:39:44 +0200 Subject: [PATCH 07/66] Introduce GlobalScope::live_devtools_updates --- components/script/devtools.rs | 3 ++- components/script/dom/bindings/global.rs | 9 --------- components/script/dom/dedicatedworkerglobalscope.rs | 2 +- components/script/dom/globalscope.rs | 13 +++++++++++++ components/script/dom/serviceworkerglobalscope.rs | 2 +- components/script/dom/window.rs | 13 ------------- components/script/dom/workerglobalscope.rs | 9 --------- components/script/script_thread.rs | 6 +++--- 8 files changed, 20 insertions(+), 37 deletions(-) diff --git a/components/script/devtools.rs b/components/script/devtools.rs index d515d1fb99a..9da8093f287 100644 --- a/components/script/devtools.rs +++ b/components/script/devtools.rs @@ -20,6 +20,7 @@ use dom::bindings::reflector::Reflectable; use dom::bindings::str::DOMString; use dom::browsingcontext::BrowsingContext; use dom::element::Element; +use dom::globalscope::GlobalScope; use dom::node::Node; use dom::window::Window; use ipc_channel::ipc::IpcSender; @@ -245,7 +246,7 @@ pub fn handle_modify_attribute(context: &BrowsingContext, } } -pub fn handle_wants_live_notifications(global: &GlobalRef, send_notifications: bool) { +pub fn handle_wants_live_notifications(global: &GlobalScope, send_notifications: bool) { global.set_devtools_wants_updates(send_notifications); } diff --git a/components/script/dom/bindings/global.rs b/components/script/dom/bindings/global.rs index b49a3b51ba3..fdfd5edd82a 100644 --- a/components/script/dom/bindings/global.rs +++ b/components/script/dom/bindings/global.rs @@ -258,15 +258,6 @@ impl<'a> GlobalRef<'a> { ) } - /// Set the `bool` value to indicate whether developer tools has requested - /// updates from the global - pub fn set_devtools_wants_updates(&self, send_updates: bool) { - match *self { - GlobalRef::Window(window) => window.set_devtools_wants_updates(send_updates), - GlobalRef::Worker(worker) => worker.set_devtools_wants_updates(send_updates), - } - } - /// Schedule the given `callback` to be invoked after at least `duration` milliseconds have /// passed. pub fn schedule_callback(&self, diff --git a/components/script/dom/dedicatedworkerglobalscope.rs b/components/script/dom/dedicatedworkerglobalscope.rs index 49a46b88575..f68d27a6871 100644 --- a/components/script/dom/dedicatedworkerglobalscope.rs +++ b/components/script/dom/dedicatedworkerglobalscope.rs @@ -307,7 +307,7 @@ impl DedicatedWorkerGlobalScope { DevtoolScriptControlMsg::GetCachedMessages(pipe_id, message_types, sender) => devtools::handle_get_cached_messages(pipe_id, message_types, sender), DevtoolScriptControlMsg::WantsLiveNotifications(_pipe_id, bool_val) => - devtools::handle_wants_live_notifications(&global_ref, bool_val), + devtools::handle_wants_live_notifications(self.upcast(), bool_val), _ => debug!("got an unusable devtools control message inside the worker!"), } }, diff --git a/components/script/dom/globalscope.rs b/components/script/dom/globalscope.rs index a09e727f772..e5f42c3f9ed 100644 --- a/components/script/dom/globalscope.rs +++ b/components/script/dom/globalscope.rs @@ -15,6 +15,10 @@ pub struct GlobalScope { eventtarget: EventTarget, crypto: MutNullableHeap>, next_worker_id: Cell, + + /// A flag to indicate whether the developer tools has requested + /// live updates from the worker. + devtools_wants_updates: Cell, } impl GlobalScope { @@ -23,6 +27,7 @@ impl GlobalScope { eventtarget: EventTarget::new_inherited(), crypto: Default::default(), next_worker_id: Cell::new(WorkerId(0)), + devtools_wants_updates: Default::default(), } } @@ -49,4 +54,12 @@ impl GlobalScope { self.next_worker_id.set(WorkerId(id_num + 1)); worker_id } + + pub fn live_devtools_updates(&self) -> bool { + self.devtools_wants_updates.get() + } + + pub fn set_devtools_wants_updates(&self, value: bool) { + self.devtools_wants_updates.set(value); + } } diff --git a/components/script/dom/serviceworkerglobalscope.rs b/components/script/dom/serviceworkerglobalscope.rs index d635f1cd41f..a65eb325138 100644 --- a/components/script/dom/serviceworkerglobalscope.rs +++ b/components/script/dom/serviceworkerglobalscope.rs @@ -212,7 +212,7 @@ impl ServiceWorkerGlobalScope { DevtoolScriptControlMsg::GetCachedMessages(pipe_id, message_types, sender) => devtools::handle_get_cached_messages(pipe_id, message_types, sender), DevtoolScriptControlMsg::WantsLiveNotifications(_pipe_id, bool_val) => - devtools::handle_wants_live_notifications(&global_ref, bool_val), + devtools::handle_wants_live_notifications(self.upcast(), bool_val), _ => debug!("got an unusable devtools control message inside the worker!"), } true diff --git a/components/script/dom/window.rs b/components/script/dom/window.rs index 406371261d0..046246191a1 100644 --- a/components/script/dom/window.rs +++ b/components/script/dom/window.rs @@ -192,10 +192,6 @@ pub struct Window { #[ignore_heap_size_of = "channels are hard"] devtools_marker_sender: DOMRefCell>>, - /// A flag to indicate whether the developer tools have requested live updates of - /// page changes. - devtools_wants_updates: Cell, - /// Pending resize event, if any. resize_event: Cell>, @@ -1474,10 +1470,6 @@ impl Window { had_clip_rect } - pub fn set_devtools_wants_updates(&self, value: bool) { - self.devtools_wants_updates.set(value); - } - // https://html.spec.whatwg.org/multipage/#accessing-other-browsing-contexts pub fn IndexedGetter(&self, _index: u32, _found: &mut bool) -> Option> { None @@ -1664,7 +1656,6 @@ impl Window { devtools_marker_sender: DOMRefCell::new(None), devtools_markers: DOMRefCell::new(HashSet::new()), - devtools_wants_updates: Cell::new(false), webdriver_script_chan: DOMRefCell::new(None), ignore_further_async_events: Arc::new(AtomicBool::new(false)), error_reporter: error_reporter, @@ -1680,10 +1671,6 @@ impl Window { &self.console_timers } - pub fn live_devtools_updates(&self) -> bool { - return self.devtools_wants_updates.get(); - } - /// https://html.spec.whatwg.org/multipage/#report-the-error pub fn report_an_error(&self, error_info: ErrorInfo, value: HandleValue) { // Step 1. diff --git a/components/script/dom/workerglobalscope.rs b/components/script/dom/workerglobalscope.rs index b72ae48251c..cc0a9dfcbf7 100644 --- a/components/script/dom/workerglobalscope.rs +++ b/components/script/dom/workerglobalscope.rs @@ -107,10 +107,6 @@ pub struct WorkerGlobalScope { /// `IpcSender` doesn't exist from_devtools_receiver: Receiver, - /// A flag to indicate whether the developer tools has requested live updates - /// from the worker - devtools_wants_updates: Cell, - #[ignore_heap_size_of = "Defined in std"] constellation_chan: IpcSender, @@ -150,7 +146,6 @@ impl WorkerGlobalScope { to_devtools_sender: init.to_devtools_sender, from_devtools_sender: init.from_devtools_sender, from_devtools_receiver: from_devtools_receiver, - devtools_wants_updates: Cell::new(false), constellation_chan: init.constellation_chan, scheduler_chan: init.scheduler_chan, console_timers: TimerSet::new(), @@ -472,10 +467,6 @@ impl WorkerGlobalScope { self.timers.fire_timer(timer_id, self); } - pub fn set_devtools_wants_updates(&self, value: bool) { - self.devtools_wants_updates.set(value); - } - pub fn close(&self) { if let Some(ref closing) = self.closing { closing.store(true, Ordering::SeqCst); diff --git a/components/script/script_thread.rs b/components/script/script_thread.rs index 61ecacda815..0b26647f3e8 100644 --- a/components/script/script_thread.rs +++ b/components/script/script_thread.rs @@ -40,6 +40,7 @@ use dom::browsingcontext::BrowsingContext; use dom::document::{Document, DocumentProgressHandler, DocumentSource, FocusType, IsHTMLDocument}; use dom::element::Element; use dom::event::{Event, EventBubbles, EventCancelable}; +use dom::globalscope::GlobalScope; use dom::htmlanchorelement::HTMLAnchorElement; use dom::node::{Node, NodeDamage, window_from_node}; use dom::serviceworker::TrustedServiceWorkerAddress; @@ -1004,8 +1005,7 @@ impl ScriptThread { Some(browsing_context) => browsing_context.active_window(), None => return warn!("Message sent to closed pipeline {}.", id), }; - let global_ref = GlobalRef::Window(window.r()); - devtools::handle_wants_live_notifications(&global_ref, to_send) + devtools::handle_wants_live_notifications(window.upcast(), to_send) }, DevtoolScriptControlMsg::SetTimelineMarkers(_pipeline_id, marker_types, reply) => devtools::handle_set_timeline_markers(&context, marker_types, reply), @@ -2153,7 +2153,7 @@ impl ScriptThread { }; let window = context.active_window(); - if window.live_devtools_updates() { + if window.upcast::().live_devtools_updates() { let css_error = CSSError { filename: filename, line: line, From 14a0b8d88c7def8a247603cb8548e50087acdbc9 Mon Sep 17 00:00:00 2001 From: Anthony Ramine Date: Sat, 1 Oct 2016 03:01:54 +0200 Subject: [PATCH 08/66] Move console timers to GlobalScope --- components/script/dom/bindings/global.rs | 9 ----- components/script/dom/console.rs | 41 ++-------------------- components/script/dom/globalscope.rs | 33 +++++++++++++++++ components/script/dom/window.rs | 9 ----- components/script/dom/workerglobalscope.rs | 9 ----- 5 files changed, 35 insertions(+), 66 deletions(-) diff --git a/components/script/dom/bindings/global.rs b/components/script/dom/bindings/global.rs index fdfd5edd82a..23925b314a5 100644 --- a/components/script/dom/bindings/global.rs +++ b/components/script/dom/bindings/global.rs @@ -14,7 +14,6 @@ use dom::bindings::error::{ErrorInfo, report_pending_exception}; use dom::bindings::inheritance::Castable; use dom::bindings::js::Root; use dom::bindings::reflector::{Reflectable, Reflector}; -use dom::console::TimerSet; use dom::globalscope::GlobalScope; use dom::window; use dom::workerglobalscope::WorkerGlobalScope; @@ -278,14 +277,6 @@ impl<'a> GlobalRef<'a> { } } - /// Returns the global's timers for the Console API. - pub fn console_timers(&self) -> &TimerSet { - match *self { - GlobalRef::Window(ref window) => window.console_timers(), - GlobalRef::Worker(ref worker) => worker.console_timers(), - } - } - /// Returns a wrapper for runnables to ensure they are cancelled if the global /// is being destroyed. pub fn get_runnable_wrapper(&self) -> RunnableWrapper { diff --git a/components/script/dom/console.rs b/components/script/dom/console.rs index ad28c585248..09180ced2c2 100644 --- a/components/script/dom/console.rs +++ b/components/script/dom/console.rs @@ -3,12 +3,8 @@ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use devtools_traits::{ConsoleMessage, LogLevel, ScriptToDevtoolsControlMsg}; -use dom::bindings::cell::DOMRefCell; use dom::bindings::global::GlobalRef; use dom::bindings::str::DOMString; -use std::collections::HashMap; -use std::collections::hash_map::Entry; -use time::{Timespec, get_time}; // https://developer.mozilla.org/en-US/docs/Web/API/Console pub struct Console(()); @@ -83,7 +79,7 @@ impl Console { // https://developer.mozilla.org/en-US/docs/Web/API/Console/time pub fn Time(global: GlobalRef, label: DOMString) { - if let Ok(()) = global.console_timers().time(label.clone()) { + if let Ok(()) = global.as_global_scope().time(label.clone()) { let message = DOMString::from(format!("{}: timer started", label)); println!("{}", message); Self::send_to_devtools(global, LogLevel::Log, message); @@ -92,7 +88,7 @@ impl Console { // https://developer.mozilla.org/en-US/docs/Web/API/Console/timeEnd pub fn TimeEnd(global: GlobalRef, label: DOMString) { - if let Ok(delta) = global.console_timers().time_end(&label) { + if let Ok(delta) = global.as_global_scope().time_end(&label) { let message = DOMString::from( format!("{}: {}ms", label, delta) ); @@ -102,10 +98,6 @@ impl Console { } } -fn timestamp_in_ms(time: Timespec) -> u64 { - (time.sec * 1000 + (time.nsec / 1000000) as i64) as u64 -} - fn prepare_message(log_level: LogLevel, message: DOMString) -> ConsoleMessage { // TODO: Sending fake values for filename, lineNumber and columnNumber in LogMessage; adjust later ConsoleMessage { @@ -116,32 +108,3 @@ fn prepare_message(log_level: LogLevel, message: DOMString) -> ConsoleMessage { columnNumber: 1, } } - -#[derive(HeapSizeOf, JSTraceable)] -pub struct TimerSet(DOMRefCell>); - -impl TimerSet { - pub fn new() -> Self { - TimerSet(DOMRefCell::new(Default::default())) - } - - fn time(&self, label: DOMString) -> Result<(), ()> { - let mut timers = self.0.borrow_mut(); - if timers.len() >= 10000 { - return Err(()); - } - match timers.entry(label) { - Entry::Vacant(entry) => { - entry.insert(timestamp_in_ms(get_time())); - Ok(()) - }, - Entry::Occupied(_) => Err(()), - } - } - - fn time_end(&self, label: &str) -> Result { - self.0.borrow_mut().remove(label).ok_or(()).map(|start| { - timestamp_in_ms(get_time()) - start - }) - } -} diff --git a/components/script/dom/globalscope.rs b/components/script/dom/globalscope.rs index e5f42c3f9ed..3fd485835e2 100644 --- a/components/script/dom/globalscope.rs +++ b/components/script/dom/globalscope.rs @@ -3,12 +3,17 @@ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use devtools_traits::WorkerId; +use dom::bindings::cell::DOMRefCell; use dom::bindings::js::{JS, MutNullableHeap, Root}; use dom::bindings::reflector::Reflectable; +use dom::bindings::str::DOMString; use dom::crypto::Crypto; use dom::eventtarget::EventTarget; use js::jsapi::{JS_GetContext, JS_GetObjectRuntime, JSContext}; use std::cell::Cell; +use std::collections::HashMap; +use std::collections::hash_map::Entry; +use time::{Timespec, get_time}; #[dom_struct] pub struct GlobalScope { @@ -19,6 +24,9 @@ pub struct GlobalScope { /// A flag to indicate whether the developer tools has requested /// live updates from the worker. devtools_wants_updates: Cell, + + /// Timers used by the Console API. + console_timers: DOMRefCell>, } impl GlobalScope { @@ -28,6 +36,7 @@ impl GlobalScope { crypto: Default::default(), next_worker_id: Cell::new(WorkerId(0)), devtools_wants_updates: Default::default(), + console_timers: DOMRefCell::new(Default::default()), } } @@ -62,4 +71,28 @@ impl GlobalScope { pub fn set_devtools_wants_updates(&self, value: bool) { self.devtools_wants_updates.set(value); } + + pub fn time(&self, label: DOMString) -> Result<(), ()> { + let mut timers = self.console_timers.borrow_mut(); + if timers.len() >= 10000 { + return Err(()); + } + match timers.entry(label) { + Entry::Vacant(entry) => { + entry.insert(timestamp_in_ms(get_time())); + Ok(()) + }, + Entry::Occupied(_) => Err(()), + } + } + + pub fn time_end(&self, label: &str) -> Result { + self.console_timers.borrow_mut().remove(label).ok_or(()).map(|start| { + timestamp_in_ms(get_time()) - start + }) + } +} + +fn timestamp_in_ms(time: Timespec) -> u64 { + (time.sec * 1000 + (time.nsec / 1000000) as i64) as u64 } diff --git a/components/script/dom/window.rs b/components/script/dom/window.rs index 046246191a1..92f99ec273d 100644 --- a/components/script/dom/window.rs +++ b/components/script/dom/window.rs @@ -27,7 +27,6 @@ use dom::bindings::str::DOMString; use dom::bindings::structuredclone::StructuredCloneData; use dom::bindings::utils::{GlobalStaticData, WindowProxyHandler}; use dom::browsingcontext::BrowsingContext; -use dom::console::TimerSet; use dom::crypto::Crypto; use dom::cssstyledeclaration::{CSSModificationAccess, CSSStyleDeclaration}; use dom::document::Document; @@ -266,9 +265,6 @@ pub struct Window { /// https://html.spec.whatwg.org/multipage/#in-error-reporting-mode in_error_reporting_mode: Cell, - - /// Timers used by the Console API. - console_timers: TimerSet, } impl Window { @@ -1661,16 +1657,11 @@ impl Window { error_reporter: error_reporter, scroll_offsets: DOMRefCell::new(HashMap::new()), in_error_reporting_mode: Cell::new(false), - console_timers: TimerSet::new(), }; WindowBinding::Wrap(runtime.cx(), win) } - pub fn console_timers(&self) -> &TimerSet { - &self.console_timers - } - /// https://html.spec.whatwg.org/multipage/#report-the-error pub fn report_an_error(&self, error_info: ErrorInfo, value: HandleValue) { // Step 1. diff --git a/components/script/dom/workerglobalscope.rs b/components/script/dom/workerglobalscope.rs index cc0a9dfcbf7..c3656daf8cf 100644 --- a/components/script/dom/workerglobalscope.rs +++ b/components/script/dom/workerglobalscope.rs @@ -15,7 +15,6 @@ use dom::bindings::js::{JS, MutNullableHeap, Root}; use dom::bindings::refcounted::Trusted; use dom::bindings::reflector::Reflectable; use dom::bindings::str::DOMString; -use dom::console::TimerSet; use dom::crypto::Crypto; use dom::dedicatedworkerglobalscope::DedicatedWorkerGlobalScope; use dom::errorevent::ErrorEvent; @@ -113,9 +112,6 @@ pub struct WorkerGlobalScope { #[ignore_heap_size_of = "Defined in std"] scheduler_chan: IpcSender, - /// Timers used by the Console API. - console_timers: TimerSet, - promise_job_queue: PromiseJobQueue, /// https://html.spec.whatwg.org/multipage/#in-error-reporting-mode @@ -148,16 +144,11 @@ impl WorkerGlobalScope { from_devtools_receiver: from_devtools_receiver, constellation_chan: init.constellation_chan, scheduler_chan: init.scheduler_chan, - console_timers: TimerSet::new(), promise_job_queue: PromiseJobQueue::new(), in_error_reporting_mode: Default::default(), } } - pub fn console_timers(&self) -> &TimerSet { - &self.console_timers - } - pub fn mem_profiler_chan(&self) -> &mem::ProfilerChan { &self.mem_profiler_chan } From fe6fca9e1fe94fcefb61a1cde1812d575f164ace Mon Sep 17 00:00:00 2001 From: Anthony Ramine Date: Sat, 1 Oct 2016 03:44:05 +0200 Subject: [PATCH 09/66] Introduce GlobalScope::devtools_chan --- components/script/devtools.rs | 3 ++- components/script/dom/bindings/global.rs | 10 ---------- components/script/dom/console.rs | 2 +- components/script/dom/globalscope.rs | 18 ++++++++++++++++-- .../script/dom/serviceworkerregistration.rs | 6 ++++-- components/script/dom/window.rs | 10 +--------- components/script/dom/worker.rs | 5 +++-- components/script/dom/workerglobalscope.rs | 17 ++++++----------- 8 files changed, 33 insertions(+), 38 deletions(-) diff --git a/components/script/devtools.rs b/components/script/devtools.rs index 9da8093f287..eb4a31d794c 100644 --- a/components/script/devtools.rs +++ b/components/script/devtools.rs @@ -272,7 +272,8 @@ pub fn handle_request_animation_frame(context: &BrowsingContext, }; let doc = context.active_document(); - let devtools_sender = context.active_window().devtools_chan().unwrap(); + let devtools_sender = + context.active_window().upcast::().devtools_chan().unwrap().clone(); doc.request_animation_frame(box move |time| { let msg = ScriptToDevtoolsControlMsg::FramerateTick(actor_name, time); devtools_sender.send(msg).unwrap(); diff --git a/components/script/dom/bindings/global.rs b/components/script/dom/bindings/global.rs index 23925b314a5..b0a8f9cca75 100644 --- a/components/script/dom/bindings/global.rs +++ b/components/script/dom/bindings/global.rs @@ -7,7 +7,6 @@ //! This module contains smart pointers to global scopes, to simplify writing //! code that works in workers as well as window scopes. -use devtools_traits::ScriptToDevtoolsControlMsg; use dom::bindings::codegen::Bindings::WindowBinding::WindowMethods; use dom::bindings::conversions::root_from_object; use dom::bindings::error::{ErrorInfo, report_pending_exception}; @@ -122,15 +121,6 @@ impl<'a> GlobalRef<'a> { } } - /// Get an `IpcSender` to send messages to Devtools - /// thread when available. - pub fn devtools_chan(&self) -> Option> { - match *self { - GlobalRef::Window(window) => window.devtools_chan(), - GlobalRef::Worker(worker) => worker.devtools_chan(), - } - } - /// Get the `ResourceThreads` for this global scope. pub fn resource_threads(&self) -> ResourceThreads { match *self { diff --git a/components/script/dom/console.rs b/components/script/dom/console.rs index 09180ced2c2..d9660296e05 100644 --- a/components/script/dom/console.rs +++ b/components/script/dom/console.rs @@ -11,7 +11,7 @@ pub struct Console(()); impl Console { fn send_to_devtools(global: GlobalRef, level: LogLevel, message: DOMString) { - if let Some(chan) = global.devtools_chan() { + if let Some(chan) = global.as_global_scope().devtools_chan() { let console_message = prepare_message(level, message); let worker_id = if let GlobalRef::Worker(worker) = global { Some(worker.get_worker_id()) diff --git a/components/script/dom/globalscope.rs b/components/script/dom/globalscope.rs index 3fd485835e2..6b5c3810da6 100644 --- a/components/script/dom/globalscope.rs +++ b/components/script/dom/globalscope.rs @@ -2,13 +2,14 @@ * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ -use devtools_traits::WorkerId; +use devtools_traits::{ScriptToDevtoolsControlMsg, WorkerId}; use dom::bindings::cell::DOMRefCell; use dom::bindings::js::{JS, MutNullableHeap, Root}; use dom::bindings::reflector::Reflectable; use dom::bindings::str::DOMString; use dom::crypto::Crypto; use dom::eventtarget::EventTarget; +use ipc_channel::ipc::IpcSender; use js::jsapi::{JS_GetContext, JS_GetObjectRuntime, JSContext}; use std::cell::Cell; use std::collections::HashMap; @@ -27,16 +28,23 @@ pub struct GlobalScope { /// Timers used by the Console API. console_timers: DOMRefCell>, + + /// For providing instructions to an optional devtools server. + #[ignore_heap_size_of = "channels are hard"] + devtools_chan: Option>, } impl GlobalScope { - pub fn new_inherited() -> GlobalScope { + pub fn new_inherited( + devtools_chan: Option>) + -> Self { GlobalScope { eventtarget: EventTarget::new_inherited(), crypto: Default::default(), next_worker_id: Cell::new(WorkerId(0)), devtools_wants_updates: Default::default(), console_timers: DOMRefCell::new(Default::default()), + devtools_chan: devtools_chan, } } @@ -91,6 +99,12 @@ impl GlobalScope { timestamp_in_ms(get_time()) - start }) } + + /// Get an `&IpcSender` to send messages + /// to the devtools thread when available. + pub fn devtools_chan(&self) -> Option<&IpcSender> { + self.devtools_chan.as_ref() + } } fn timestamp_in_ms(time: Timespec) -> u64 { diff --git a/components/script/dom/serviceworkerregistration.rs b/components/script/dom/serviceworkerregistration.rs index bc089c18dac..09c23570243 100644 --- a/components/script/dom/serviceworkerregistration.rs +++ b/components/script/dom/serviceworkerregistration.rs @@ -57,13 +57,15 @@ impl ServiceWorkerRegistration { pipeline_id: Some(global.pipeline_id()) }; - let worker_id = global.as_global_scope().get_next_worker_id(); + let global_scope = global.as_global_scope(); + let worker_id = global_scope.get_next_worker_id(); + let devtools_chan = global_scope.devtools_chan().cloned(); let init = prepare_workerscope_init(global, None); ScopeThings { script_url: script_url, init: init, worker_load_origin: worker_load_origin, - devtools_chan: global.devtools_chan(), + devtools_chan: devtools_chan, worker_id: worker_id } } diff --git a/components/script/dom/window.rs b/components/script/dom/window.rs index 92f99ec273d..f07e395a709 100644 --- a/components/script/dom/window.rs +++ b/components/script/dom/window.rs @@ -182,9 +182,6 @@ pub struct Window { #[ignore_heap_size_of = "channels are hard"] time_profiler_chan: ProfilerChan, - /// For providing instructions to an optional devtools server. - #[ignore_heap_size_of = "channels are hard"] - devtools_chan: Option>, /// For sending timeline markers. Will be ignored if /// no devtools server devtools_markers: DOMRefCell>, @@ -1391,10 +1388,6 @@ impl Window { &self.time_profiler_chan } - pub fn devtools_chan(&self) -> Option> { - self.devtools_chan.clone() - } - pub fn layout_chan(&self) -> &Sender { &self.layout_chan } @@ -1608,7 +1601,7 @@ impl Window { }; let current_time = time::get_time(); let win = box Window { - globalscope: GlobalScope::new_inherited(), + globalscope: GlobalScope::new_inherited(devtools_chan), script_chan: script_chan, dom_manipulation_task_source: dom_task_source, user_interaction_task_source: user_task_source, @@ -1620,7 +1613,6 @@ impl Window { image_cache_thread: image_cache_thread, mem_profiler_chan: mem_profiler_chan, time_profiler_chan: time_profiler_chan, - devtools_chan: devtools_chan, history: Default::default(), browsing_context: Default::default(), performance: Default::default(), diff --git a/components/script/dom/worker.rs b/components/script/dom/worker.rs index 1e32b4375f1..067b564d595 100644 --- a/components/script/dom/worker.rs +++ b/components/script/dom/worker.rs @@ -91,8 +91,9 @@ impl Worker { }; let (devtools_sender, devtools_receiver) = ipc::channel().unwrap(); - let worker_id = global.as_global_scope().get_next_worker_id(); - if let Some(ref chan) = global.devtools_chan() { + let global_scope = global.as_global_scope(); + let worker_id = global_scope.get_next_worker_id(); + if let Some(ref chan) = global_scope.devtools_chan() { let pipeline_id = global.pipeline_id(); let title = format!("Worker for {}", worker_url); let page_info = DevtoolsPageInfo { diff --git a/components/script/dom/workerglobalscope.rs b/components/script/dom/workerglobalscope.rs index c3656daf8cf..af707508abf 100644 --- a/components/script/dom/workerglobalscope.rs +++ b/components/script/dom/workerglobalscope.rs @@ -2,7 +2,7 @@ * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ -use devtools_traits::{DevtoolScriptControlMsg, ScriptToDevtoolsControlMsg, WorkerId}; +use devtools_traits::{DevtoolScriptControlMsg, WorkerId}; use dom::bindings::codegen::Bindings::EventHandlerBinding::OnErrorEventHandlerNonNull; use dom::bindings::codegen::Bindings::FunctionBinding::Function; use dom::bindings::codegen::Bindings::RequestBinding::RequestInit; @@ -55,11 +55,13 @@ use url::Url; pub fn prepare_workerscope_init(global: GlobalRef, devtools_sender: Option>) -> WorkerGlobalScopeInit { - let worker_id = global.as_global_scope().get_next_worker_id(); + let global_scope = global.as_global_scope(); + let worker_id = global_scope.get_next_worker_id(); + let to_devtools_sender = global_scope.devtools_chan().cloned(); let init = WorkerGlobalScopeInit { resource_threads: global.resource_threads(), mem_profiler_chan: global.mem_profiler_chan().clone(), - to_devtools_sender: global.devtools_chan(), + to_devtools_sender: to_devtools_sender, time_profiler_chan: global.time_profiler_chan().clone(), from_devtools_sender: devtools_sender, constellation_chan: global.constellation_chan().clone(), @@ -93,8 +95,6 @@ pub struct WorkerGlobalScope { mem_profiler_chan: mem::ProfilerChan, #[ignore_heap_size_of = "Defined in std"] time_profiler_chan: time::ProfilerChan, - #[ignore_heap_size_of = "Defined in ipc-channel"] - to_devtools_sender: Option>, #[ignore_heap_size_of = "Defined in ipc-channel"] /// Optional `IpcSender` for sending the `DevtoolScriptControlMsg` @@ -127,7 +127,7 @@ impl WorkerGlobalScope { closing: Option>) -> WorkerGlobalScope { WorkerGlobalScope { - globalscope: GlobalScope::new_inherited(), + globalscope: GlobalScope::new_inherited(init.to_devtools_sender), worker_id: init.worker_id, pipeline_id: init.pipeline_id, worker_url: worker_url, @@ -139,7 +139,6 @@ impl WorkerGlobalScope { timers: OneshotTimers::new(timer_event_chan, init.scheduler_chan.clone()), mem_profiler_chan: init.mem_profiler_chan, time_profiler_chan: init.time_profiler_chan, - to_devtools_sender: init.to_devtools_sender, from_devtools_sender: init.from_devtools_sender, from_devtools_receiver: from_devtools_receiver, constellation_chan: init.constellation_chan, @@ -157,10 +156,6 @@ impl WorkerGlobalScope { &self.time_profiler_chan } - pub fn devtools_chan(&self) -> Option> { - self.to_devtools_sender.clone() - } - pub fn from_devtools_sender(&self) -> Option> { self.from_devtools_sender.clone() } From bfa7d045d0c83bf44acedd425262e39d29c0bffa Mon Sep 17 00:00:00 2001 From: Anthony Ramine Date: Sat, 1 Oct 2016 03:53:20 +0200 Subject: [PATCH 10/66] Introduce GlobalScope::mem_profiler_chan --- components/script/dom/bindings/global.rs | 10 +--------- .../script/dom/dedicatedworkerglobalscope.rs | 3 ++- components/script/dom/globalscope.rs | 14 +++++++++++++- components/script/dom/serviceworkerglobalscope.rs | 3 ++- components/script/dom/window.rs | 11 +---------- components/script/dom/workerglobalscope.rs | 15 +++++---------- 6 files changed, 24 insertions(+), 32 deletions(-) diff --git a/components/script/dom/bindings/global.rs b/components/script/dom/bindings/global.rs index b0a8f9cca75..adb0df51c61 100644 --- a/components/script/dom/bindings/global.rs +++ b/components/script/dom/bindings/global.rs @@ -26,7 +26,7 @@ use js::rust::CompileOptionsWrapper; use libc; use msg::constellation_msg::PipelineId; use net_traits::{CoreResourceThread, IpcSend, ResourceThreads}; -use profile_traits::{mem, time}; +use profile_traits::time; use script_runtime::{CommonScriptMsg, EnqueuedPromiseCallback, ScriptChan}; use script_runtime::{ScriptPort, maybe_take_panic_result}; use script_thread::{MainThreadScriptChan, RunnableWrapper, ScriptThread}; @@ -89,14 +89,6 @@ impl<'a> GlobalRef<'a> { } } - /// Get a `mem::ProfilerChan` to send messages to the memory profiler thread. - pub fn mem_profiler_chan(&self) -> &mem::ProfilerChan { - match *self { - GlobalRef::Window(window) => window.mem_profiler_chan(), - GlobalRef::Worker(worker) => worker.mem_profiler_chan(), - } - } - /// Get a `time::ProfilerChan` to send messages to the time profiler thread. pub fn time_profiler_chan(&self) -> &time::ProfilerChan { match *self { diff --git a/components/script/dom/dedicatedworkerglobalscope.rs b/components/script/dom/dedicatedworkerglobalscope.rs index f68d27a6871..6a07a303fcb 100644 --- a/components/script/dom/dedicatedworkerglobalscope.rs +++ b/components/script/dom/dedicatedworkerglobalscope.rs @@ -17,6 +17,7 @@ use dom::bindings::js::{Root, RootCollection}; use dom::bindings::reflector::Reflectable; use dom::bindings::str::DOMString; use dom::bindings::structuredclone::StructuredCloneData; +use dom::globalscope::GlobalScope; use dom::messageevent::MessageEvent; use dom::worker::{TrustedWorkerAddress, WorkerErrorHandler, WorkerMessageHandler}; use dom::workerglobalscope::WorkerGlobalScope; @@ -212,7 +213,7 @@ impl DedicatedWorkerGlobalScope { } let reporter_name = format!("dedicated-worker-reporter-{}", random::()); - scope.mem_profiler_chan().run_with_memory_reporting(|| { + scope.upcast::().mem_profiler_chan().run_with_memory_reporting(|| { while let Ok(event) = global.receive_event() { if scope.is_closing() { break; diff --git a/components/script/dom/globalscope.rs b/components/script/dom/globalscope.rs index 6b5c3810da6..02409edc080 100644 --- a/components/script/dom/globalscope.rs +++ b/components/script/dom/globalscope.rs @@ -11,6 +11,7 @@ use dom::crypto::Crypto; use dom::eventtarget::EventTarget; use ipc_channel::ipc::IpcSender; use js::jsapi::{JS_GetContext, JS_GetObjectRuntime, JSContext}; +use profile_traits::mem; use std::cell::Cell; use std::collections::HashMap; use std::collections::hash_map::Entry; @@ -32,11 +33,16 @@ pub struct GlobalScope { /// For providing instructions to an optional devtools server. #[ignore_heap_size_of = "channels are hard"] devtools_chan: Option>, + + /// For sending messages to the memory profiler. + #[ignore_heap_size_of = "channels are hard"] + mem_profiler_chan: mem::ProfilerChan, } impl GlobalScope { pub fn new_inherited( - devtools_chan: Option>) + devtools_chan: Option>, + mem_profiler_chan: mem::ProfilerChan) -> Self { GlobalScope { eventtarget: EventTarget::new_inherited(), @@ -45,6 +51,7 @@ impl GlobalScope { devtools_wants_updates: Default::default(), console_timers: DOMRefCell::new(Default::default()), devtools_chan: devtools_chan, + mem_profiler_chan: mem_profiler_chan, } } @@ -105,6 +112,11 @@ impl GlobalScope { pub fn devtools_chan(&self) -> Option<&IpcSender> { self.devtools_chan.as_ref() } + + /// Get a sender to the memory profiler thread. + pub fn mem_profiler_chan(&self) -> &mem::ProfilerChan { + &self.mem_profiler_chan + } } fn timestamp_in_ms(time: Timespec) -> u64 { diff --git a/components/script/dom/serviceworkerglobalscope.rs b/components/script/dom/serviceworkerglobalscope.rs index a65eb325138..87f9741a205 100644 --- a/components/script/dom/serviceworkerglobalscope.rs +++ b/components/script/dom/serviceworkerglobalscope.rs @@ -17,6 +17,7 @@ use dom::event::Event; use dom::eventtarget::EventTarget; use dom::extendableevent::ExtendableEvent; use dom::extendablemessageevent::ExtendableMessageEvent; +use dom::globalscope::GlobalScope; use dom::workerglobalscope::WorkerGlobalScope; use ipc_channel::ipc::{self, IpcSender, IpcReceiver}; use ipc_channel::router::ROUTER; @@ -192,7 +193,7 @@ impl ServiceWorkerGlobalScope { global.dispatch_activate(); let reporter_name = format!("service-worker-reporter-{}", random::()); - scope.mem_profiler_chan().run_with_memory_reporting(|| { + scope.upcast::().mem_profiler_chan().run_with_memory_reporting(|| { while let Ok(event) = global.receive_event() { if !global.handle_event(event) { break; diff --git a/components/script/dom/window.rs b/components/script/dom/window.rs index f07e395a709..848f6b0d72f 100644 --- a/components/script/dom/window.rs +++ b/components/script/dom/window.rs @@ -174,10 +174,6 @@ pub struct Window { scheduler_chan: IpcSender, timers: OneshotTimers, - /// For sending messages to the memory profiler. - #[ignore_heap_size_of = "channels are hard"] - mem_profiler_chan: mem::ProfilerChan, - /// For sending messages to the memory profiler. #[ignore_heap_size_of = "channels are hard"] time_profiler_chan: ProfilerChan, @@ -1380,10 +1376,6 @@ impl Window { &self.resource_threads } - pub fn mem_profiler_chan(&self) -> &mem::ProfilerChan { - &self.mem_profiler_chan - } - pub fn time_profiler_chan(&self) -> &ProfilerChan { &self.time_profiler_chan } @@ -1601,7 +1593,7 @@ impl Window { }; let current_time = time::get_time(); let win = box Window { - globalscope: GlobalScope::new_inherited(devtools_chan), + globalscope: GlobalScope::new_inherited(devtools_chan, mem_profiler_chan), script_chan: script_chan, dom_manipulation_task_source: dom_task_source, user_interaction_task_source: user_task_source, @@ -1611,7 +1603,6 @@ impl Window { image_cache_chan: image_cache_chan, navigator: Default::default(), image_cache_thread: image_cache_thread, - mem_profiler_chan: mem_profiler_chan, time_profiler_chan: time_profiler_chan, history: Default::default(), browsing_context: Default::default(), diff --git a/components/script/dom/workerglobalscope.rs b/components/script/dom/workerglobalscope.rs index af707508abf..071b68fa274 100644 --- a/components/script/dom/workerglobalscope.rs +++ b/components/script/dom/workerglobalscope.rs @@ -35,7 +35,7 @@ use js::rust::Runtime; use msg::constellation_msg::{PipelineId, ReferrerPolicy}; use net_traits::{IpcSend, LoadOrigin}; use net_traits::{LoadContext, ResourceThreads, load_whole_resource}; -use profile_traits::{mem, time}; +use profile_traits::time; use script_runtime::{CommonScriptMsg, ScriptChan, ScriptPort, maybe_take_panic_result}; use script_runtime::{ScriptThreadEventCategory, PromiseJobQueue, EnqueuedPromiseCallback}; use script_thread::{Runnable, RunnableWrapper}; @@ -58,9 +58,10 @@ pub fn prepare_workerscope_init(global: GlobalRef, let global_scope = global.as_global_scope(); let worker_id = global_scope.get_next_worker_id(); let to_devtools_sender = global_scope.devtools_chan().cloned(); + let mem_profiler_chan = global_scope.mem_profiler_chan().clone(); let init = WorkerGlobalScopeInit { resource_threads: global.resource_threads(), - mem_profiler_chan: global.mem_profiler_chan().clone(), + mem_profiler_chan: mem_profiler_chan, to_devtools_sender: to_devtools_sender, time_profiler_chan: global.time_profiler_chan().clone(), from_devtools_sender: devtools_sender, @@ -91,8 +92,6 @@ pub struct WorkerGlobalScope { navigator: MutNullableHeap>, timers: OneshotTimers, - #[ignore_heap_size_of = "Defined in std"] - mem_profiler_chan: mem::ProfilerChan, #[ignore_heap_size_of = "Defined in std"] time_profiler_chan: time::ProfilerChan, @@ -127,7 +126,8 @@ impl WorkerGlobalScope { closing: Option>) -> WorkerGlobalScope { WorkerGlobalScope { - globalscope: GlobalScope::new_inherited(init.to_devtools_sender), + globalscope: + GlobalScope::new_inherited(init.to_devtools_sender, init.mem_profiler_chan), worker_id: init.worker_id, pipeline_id: init.pipeline_id, worker_url: worker_url, @@ -137,7 +137,6 @@ impl WorkerGlobalScope { location: Default::default(), navigator: Default::default(), timers: OneshotTimers::new(timer_event_chan, init.scheduler_chan.clone()), - mem_profiler_chan: init.mem_profiler_chan, time_profiler_chan: init.time_profiler_chan, from_devtools_sender: init.from_devtools_sender, from_devtools_receiver: from_devtools_receiver, @@ -148,10 +147,6 @@ impl WorkerGlobalScope { } } - pub fn mem_profiler_chan(&self) -> &mem::ProfilerChan { - &self.mem_profiler_chan - } - pub fn time_profiler_chan(&self) -> &time::ProfilerChan { &self.time_profiler_chan } From ae3763e7b35fd4836d28b396ef4fa8abda0912d1 Mon Sep 17 00:00:00 2001 From: Anthony Ramine Date: Sat, 1 Oct 2016 04:00:23 +0200 Subject: [PATCH 11/66] Introduce GlobalScope::time_profiler_chan --- components/script/dom/bindings/global.rs | 10 +--------- components/script/dom/globalscope.rs | 15 +++++++++++++-- components/script/dom/servohtmlparser.rs | 4 +++- components/script/dom/window.rs | 12 ++---------- components/script/dom/workerglobalscope.rs | 15 ++++----------- 5 files changed, 23 insertions(+), 33 deletions(-) diff --git a/components/script/dom/bindings/global.rs b/components/script/dom/bindings/global.rs index adb0df51c61..4e433477a39 100644 --- a/components/script/dom/bindings/global.rs +++ b/components/script/dom/bindings/global.rs @@ -89,14 +89,6 @@ impl<'a> GlobalRef<'a> { } } - /// Get a `time::ProfilerChan` to send messages to the time profiler thread. - pub fn time_profiler_chan(&self) -> &time::ProfilerChan { - match *self { - GlobalRef::Window(window) => window.time_profiler_chan(), - GlobalRef::Worker(worker) => worker.time_profiler_chan(), - } - } - /// Get a `IpcSender` to send messages to the constellation when available. pub fn constellation_chan(&self) -> &IpcSender { match *self { @@ -214,7 +206,7 @@ impl<'a> GlobalRef<'a> { time::profile( time::ProfilerCategory::ScriptEvaluate, Some(metadata), - self.time_profiler_chan().clone(), + self.as_global_scope().time_profiler_chan().clone(), || { let cx = self.get_cx(); let globalhandle = self.reflector().get_jsobject(); diff --git a/components/script/dom/globalscope.rs b/components/script/dom/globalscope.rs index 02409edc080..ac8cef37c43 100644 --- a/components/script/dom/globalscope.rs +++ b/components/script/dom/globalscope.rs @@ -11,7 +11,7 @@ use dom::crypto::Crypto; use dom::eventtarget::EventTarget; use ipc_channel::ipc::IpcSender; use js::jsapi::{JS_GetContext, JS_GetObjectRuntime, JSContext}; -use profile_traits::mem; +use profile_traits::{mem, time}; use std::cell::Cell; use std::collections::HashMap; use std::collections::hash_map::Entry; @@ -37,12 +37,17 @@ pub struct GlobalScope { /// For sending messages to the memory profiler. #[ignore_heap_size_of = "channels are hard"] mem_profiler_chan: mem::ProfilerChan, + + /// For sending messages to the time profiler. + #[ignore_heap_size_of = "channels are hard"] + time_profiler_chan: time::ProfilerChan, } impl GlobalScope { pub fn new_inherited( devtools_chan: Option>, - mem_profiler_chan: mem::ProfilerChan) + mem_profiler_chan: mem::ProfilerChan, + time_profiler_chan: time::ProfilerChan) -> Self { GlobalScope { eventtarget: EventTarget::new_inherited(), @@ -52,6 +57,7 @@ impl GlobalScope { console_timers: DOMRefCell::new(Default::default()), devtools_chan: devtools_chan, mem_profiler_chan: mem_profiler_chan, + time_profiler_chan: time_profiler_chan, } } @@ -117,6 +123,11 @@ impl GlobalScope { pub fn mem_profiler_chan(&self) -> &mem::ProfilerChan { &self.mem_profiler_chan } + + /// Get a sender to the time profiler thread. + pub fn time_profiler_chan(&self) -> &time::ProfilerChan { + &self.time_profiler_chan + } } fn timestamp_in_ms(time: Timespec) -> u64 { diff --git a/components/script/dom/servohtmlparser.rs b/components/script/dom/servohtmlparser.rs index 0f0976d0f78..a65d9e84a6d 100644 --- a/components/script/dom/servohtmlparser.rs +++ b/components/script/dom/servohtmlparser.rs @@ -11,12 +11,14 @@ use dom::bindings::codegen::Bindings::DocumentBinding::DocumentMethods; use dom::bindings::codegen::Bindings::HTMLImageElementBinding::HTMLImageElementMethods; use dom::bindings::codegen::Bindings::NodeBinding::NodeMethods; use dom::bindings::codegen::Bindings::ServoHTMLParserBinding; +use dom::bindings::inheritance::Castable; use dom::bindings::js::{JS, Root}; use dom::bindings::refcounted::Trusted; use dom::bindings::reflector::{Reflector, reflect_dom_object}; use dom::bindings::str::DOMString; use dom::bindings::trace::JSTraceable; use dom::document::Document; +use dom::globalscope::GlobalScope; use dom::htmlimageelement::HTMLImageElement; use dom::node::Node; use dom::window::Window; @@ -343,7 +345,7 @@ impl ServoHTMLParser { }; profile(ProfilerCategory::ScriptParseHTML, Some(metadata), - self.document.window().time_profiler_chan().clone(), + self.document.window().upcast::().time_profiler_chan().clone(), || self.do_parse_sync()) } diff --git a/components/script/dom/window.rs b/components/script/dom/window.rs index 848f6b0d72f..57aeada88a5 100644 --- a/components/script/dom/window.rs +++ b/components/script/dom/window.rs @@ -174,10 +174,6 @@ pub struct Window { scheduler_chan: IpcSender, timers: OneshotTimers, - /// For sending messages to the memory profiler. - #[ignore_heap_size_of = "channels are hard"] - time_profiler_chan: ProfilerChan, - /// For sending timeline markers. Will be ignored if /// no devtools server devtools_markers: DOMRefCell>, @@ -1376,10 +1372,6 @@ impl Window { &self.resource_threads } - pub fn time_profiler_chan(&self) -> &ProfilerChan { - &self.time_profiler_chan - } - pub fn layout_chan(&self) -> &Sender { &self.layout_chan } @@ -1593,7 +1585,8 @@ impl Window { }; let current_time = time::get_time(); let win = box Window { - globalscope: GlobalScope::new_inherited(devtools_chan, mem_profiler_chan), + globalscope: + GlobalScope::new_inherited(devtools_chan, mem_profiler_chan, time_profiler_chan), script_chan: script_chan, dom_manipulation_task_source: dom_task_source, user_interaction_task_source: user_task_source, @@ -1603,7 +1596,6 @@ impl Window { image_cache_chan: image_cache_chan, navigator: Default::default(), image_cache_thread: image_cache_thread, - time_profiler_chan: time_profiler_chan, history: Default::default(), browsing_context: Default::default(), performance: Default::default(), diff --git a/components/script/dom/workerglobalscope.rs b/components/script/dom/workerglobalscope.rs index 071b68fa274..f9757a976ef 100644 --- a/components/script/dom/workerglobalscope.rs +++ b/components/script/dom/workerglobalscope.rs @@ -35,7 +35,6 @@ use js::rust::Runtime; use msg::constellation_msg::{PipelineId, ReferrerPolicy}; use net_traits::{IpcSend, LoadOrigin}; use net_traits::{LoadContext, ResourceThreads, load_whole_resource}; -use profile_traits::time; use script_runtime::{CommonScriptMsg, ScriptChan, ScriptPort, maybe_take_panic_result}; use script_runtime::{ScriptThreadEventCategory, PromiseJobQueue, EnqueuedPromiseCallback}; use script_thread::{Runnable, RunnableWrapper}; @@ -59,11 +58,12 @@ pub fn prepare_workerscope_init(global: GlobalRef, let worker_id = global_scope.get_next_worker_id(); let to_devtools_sender = global_scope.devtools_chan().cloned(); let mem_profiler_chan = global_scope.mem_profiler_chan().clone(); + let time_profiler_chan = global_scope.time_profiler_chan().clone(); let init = WorkerGlobalScopeInit { resource_threads: global.resource_threads(), mem_profiler_chan: mem_profiler_chan, to_devtools_sender: to_devtools_sender, - time_profiler_chan: global.time_profiler_chan().clone(), + time_profiler_chan: time_profiler_chan, from_devtools_sender: devtools_sender, constellation_chan: global.constellation_chan().clone(), scheduler_chan: global.scheduler_chan().clone(), @@ -92,9 +92,6 @@ pub struct WorkerGlobalScope { navigator: MutNullableHeap>, timers: OneshotTimers, - #[ignore_heap_size_of = "Defined in std"] - time_profiler_chan: time::ProfilerChan, - #[ignore_heap_size_of = "Defined in ipc-channel"] /// Optional `IpcSender` for sending the `DevtoolScriptControlMsg` /// to the server from within the worker @@ -127,7 +124,8 @@ impl WorkerGlobalScope { -> WorkerGlobalScope { WorkerGlobalScope { globalscope: - GlobalScope::new_inherited(init.to_devtools_sender, init.mem_profiler_chan), + GlobalScope::new_inherited( + init.to_devtools_sender, init.mem_profiler_chan, init.time_profiler_chan), worker_id: init.worker_id, pipeline_id: init.pipeline_id, worker_url: worker_url, @@ -137,7 +135,6 @@ impl WorkerGlobalScope { location: Default::default(), navigator: Default::default(), timers: OneshotTimers::new(timer_event_chan, init.scheduler_chan.clone()), - time_profiler_chan: init.time_profiler_chan, from_devtools_sender: init.from_devtools_sender, from_devtools_receiver: from_devtools_receiver, constellation_chan: init.constellation_chan, @@ -147,10 +144,6 @@ impl WorkerGlobalScope { } } - pub fn time_profiler_chan(&self) -> &time::ProfilerChan { - &self.time_profiler_chan - } - pub fn from_devtools_sender(&self) -> Option> { self.from_devtools_sender.clone() } From f789e73fd2cf3d88d4447978a82ac6d629a1edf4 Mon Sep 17 00:00:00 2001 From: Anthony Ramine Date: Sat, 1 Oct 2016 04:15:47 +0200 Subject: [PATCH 12/66] Introduce GlobalScope::constellation_chan --- components/script/dom/bindings/global.rs | 10 +---- .../script/dom/canvasrenderingcontext2d.rs | 2 +- components/script/dom/document.rs | 18 ++++---- components/script/dom/globalscope.rs | 14 ++++++- components/script/dom/history.rs | 6 ++- components/script/dom/htmlbodyelement.rs | 3 +- components/script/dom/htmliframeelement.rs | 10 +++-- components/script/dom/htmlinputelement.rs | 3 +- components/script/dom/htmllinkelement.rs | 3 +- components/script/dom/htmltextareaelement.rs | 3 +- components/script/dom/serviceworker.rs | 7 +++- .../script/dom/webglrenderingcontext.rs | 2 +- components/script/dom/window.rs | 41 +++++++++++-------- components/script/dom/workerglobalscope.rs | 17 +++----- 14 files changed, 79 insertions(+), 60 deletions(-) diff --git a/components/script/dom/bindings/global.rs b/components/script/dom/bindings/global.rs index 4e433477a39..43eafcc2d2e 100644 --- a/components/script/dom/bindings/global.rs +++ b/components/script/dom/bindings/global.rs @@ -30,7 +30,7 @@ use profile_traits::time; use script_runtime::{CommonScriptMsg, EnqueuedPromiseCallback, ScriptChan}; use script_runtime::{ScriptPort, maybe_take_panic_result}; use script_thread::{MainThreadScriptChan, RunnableWrapper, ScriptThread}; -use script_traits::{MsDuration, ScriptMsg as ConstellationMsg, TimerEventRequest}; +use script_traits::{MsDuration, TimerEventRequest}; use std::ffi::CString; use std::panic; use task_source::file_reading::FileReadingTaskSource; @@ -89,14 +89,6 @@ impl<'a> GlobalRef<'a> { } } - /// Get a `IpcSender` to send messages to the constellation when available. - pub fn constellation_chan(&self) -> &IpcSender { - match *self { - GlobalRef::Window(window) => window.constellation_chan(), - GlobalRef::Worker(worker) => worker.constellation_chan(), - } - } - /// Get the scheduler channel to request timer events. pub fn scheduler_chan(&self) -> &IpcSender { match *self { diff --git a/components/script/dom/canvasrenderingcontext2d.rs b/components/script/dom/canvasrenderingcontext2d.rs index e4815e5f472..3872eb31272 100644 --- a/components/script/dom/canvasrenderingcontext2d.rs +++ b/components/script/dom/canvasrenderingcontext2d.rs @@ -122,7 +122,7 @@ impl CanvasRenderingContext2D { size: Size2D) -> CanvasRenderingContext2D { let (sender, receiver) = ipc::channel().unwrap(); - let constellation_chan = global.constellation_chan(); + let constellation_chan = global.as_global_scope().constellation_chan(); constellation_chan.send(ConstellationMsg::CreateCanvasPaintThread(size, sender)).unwrap(); let ipc_renderer = receiver.recv().unwrap(); CanvasRenderingContext2D { diff --git a/components/script/dom/document.rs b/components/script/dom/document.rs index 7857e46ecfe..ec109e82240 100644 --- a/components/script/dom/document.rs +++ b/components/script/dom/document.rs @@ -45,6 +45,7 @@ use dom::eventdispatcher::EventStatus; use dom::eventtarget::EventTarget; use dom::focusevent::FocusEvent; use dom::forcetouchevent::ForceTouchEvent; +use dom::globalscope::GlobalScope; use dom::hashchangeevent::HashChangeEvent; use dom::htmlanchorelement::HTMLAnchorElement; use dom::htmlappletelement::HTMLAppletElement; @@ -651,7 +652,7 @@ impl Document { // https://html.spec.whatwg.org/multipage/#focus-chain if focus_type == FocusType::Element { let event = ConstellationMsg::Focus(self.window.pipeline_id()); - self.window.constellation_chan().send(event).unwrap(); + self.window.upcast::().constellation_chan().send(event).unwrap(); } } } @@ -669,7 +670,8 @@ impl Document { /// Sends this document's title to the compositor. pub fn send_title_to_compositor(&self) { let window = self.window(); - window.constellation_chan() + window.upcast::() + .constellation_chan() .send(ConstellationMsg::SetTitle(window.pipeline_id(), Some(String::from(self.Title())))) .unwrap(); @@ -723,7 +725,7 @@ impl Document { let event = ConstellationMsg::ForwardMouseButtonEvent(pipeline_id, mouse_event_type, button, child_point); - self.window.constellation_chan().send(event).unwrap(); + self.window.upcast::().constellation_chan().send(event).unwrap(); } return; } @@ -961,7 +963,7 @@ impl Document { let child_point = client_point - child_origin; let event = ConstellationMsg::ForwardMouseMoveEvent(pipeline_id, child_point); - self.window.constellation_chan().send(event).unwrap(); + self.window.upcast::().constellation_chan().send(event).unwrap(); } return; } @@ -1359,7 +1361,7 @@ impl Document { let event = ConstellationMsg::MozBrowserEvent(parent_pipeline_id, Some(self.window.pipeline_id()), event); - self.window.constellation_chan().send(event).unwrap(); + self.window.upcast::().constellation_chan().send(event).unwrap(); } } } @@ -1382,7 +1384,7 @@ impl Document { let event = ConstellationMsg::ChangeRunningAnimationsState( self.window.pipeline_id(), AnimationState::AnimationCallbacksPresent); - self.window.constellation_chan().send(event).unwrap(); + self.window.upcast::().constellation_chan().send(event).unwrap(); } ident @@ -1420,7 +1422,7 @@ impl Document { &mut animation_frame_list); let event = ConstellationMsg::ChangeRunningAnimationsState(self.window.pipeline_id(), AnimationState::NoAnimationCallbacksPresent); - self.window.constellation_chan().send(event).unwrap(); + self.window.upcast::().constellation_chan().send(event).unwrap(); } self.running_animation_callbacks.set(false); @@ -1578,7 +1580,7 @@ impl Document { pub fn notify_constellation_load(&self) { let pipeline_id = self.window.pipeline_id(); let load_event = ConstellationMsg::LoadComplete(pipeline_id); - self.window.constellation_chan().send(load_event).unwrap(); + self.window.upcast::().constellation_chan().send(load_event).unwrap(); } pub fn set_current_parser(&self, script: Option) { diff --git a/components/script/dom/globalscope.rs b/components/script/dom/globalscope.rs index ac8cef37c43..9f2443b85bc 100644 --- a/components/script/dom/globalscope.rs +++ b/components/script/dom/globalscope.rs @@ -12,6 +12,7 @@ use dom::eventtarget::EventTarget; use ipc_channel::ipc::IpcSender; use js::jsapi::{JS_GetContext, JS_GetObjectRuntime, JSContext}; use profile_traits::{mem, time}; +use script_traits::ScriptMsg as ConstellationMsg; use std::cell::Cell; use std::collections::HashMap; use std::collections::hash_map::Entry; @@ -41,13 +42,18 @@ pub struct GlobalScope { /// For sending messages to the time profiler. #[ignore_heap_size_of = "channels are hard"] time_profiler_chan: time::ProfilerChan, + + /// A handle for communicating messages to the constellation thread. + #[ignore_heap_size_of = "channels are hard"] + constellation_chan: IpcSender, } impl GlobalScope { pub fn new_inherited( devtools_chan: Option>, mem_profiler_chan: mem::ProfilerChan, - time_profiler_chan: time::ProfilerChan) + time_profiler_chan: time::ProfilerChan, + constellation_chan: IpcSender) -> Self { GlobalScope { eventtarget: EventTarget::new_inherited(), @@ -58,6 +64,7 @@ impl GlobalScope { devtools_chan: devtools_chan, mem_profiler_chan: mem_profiler_chan, time_profiler_chan: time_profiler_chan, + constellation_chan: constellation_chan, } } @@ -128,6 +135,11 @@ impl GlobalScope { pub fn time_profiler_chan(&self) -> &time::ProfilerChan { &self.time_profiler_chan } + + /// Get a sender to the constellation thread. + pub fn constellation_chan(&self) -> &IpcSender { + &self.constellation_chan + } } fn timestamp_in_ms(time: Timespec) -> u64 { diff --git a/components/script/dom/history.rs b/components/script/dom/history.rs index 9fe5789524c..23dc3951e42 100644 --- a/components/script/dom/history.rs +++ b/components/script/dom/history.rs @@ -6,8 +6,10 @@ use dom::bindings::codegen::Bindings::HistoryBinding; use dom::bindings::codegen::Bindings::HistoryBinding::HistoryMethods; use dom::bindings::codegen::Bindings::LocationBinding::LocationMethods; use dom::bindings::codegen::Bindings::WindowBinding::WindowMethods; +use dom::bindings::inheritance::Castable; use dom::bindings::js::{JS, Root}; use dom::bindings::reflector::{Reflector, reflect_dom_object}; +use dom::globalscope::GlobalScope; use dom::window::Window; use ipc_channel::ipc; use msg::constellation_msg::TraversalDirection; @@ -39,7 +41,7 @@ impl History { fn traverse_history(&self, direction: TraversalDirection) { let pipeline = self.window.pipeline_id(); let msg = ConstellationMsg::TraverseHistory(Some(pipeline), direction); - let _ = self.window.constellation_chan().send(msg); + let _ = self.window.upcast::().constellation_chan().send(msg); } } @@ -49,7 +51,7 @@ impl HistoryMethods for History { let pipeline = self.window.pipeline_id(); let (sender, recv) = ipc::channel().expect("Failed to create channel to send jsh length."); let msg = ConstellationMsg::JointSessionHistoryLength(pipeline, sender); - let _ = self.window.constellation_chan().send(msg); + let _ = self.window.upcast::().constellation_chan().send(msg); recv.recv().unwrap() } diff --git a/components/script/dom/htmlbodyelement.rs b/components/script/dom/htmlbodyelement.rs index 993d50a2a76..1cab444e871 100644 --- a/components/script/dom/htmlbodyelement.rs +++ b/components/script/dom/htmlbodyelement.rs @@ -13,6 +13,7 @@ use dom::bindings::str::DOMString; use dom::document::Document; use dom::element::{AttributeMutation, Element, RawLayoutElementHelpers}; use dom::eventtarget::EventTarget; +use dom::globalscope::GlobalScope; use dom::htmlelement::HTMLElement; use dom::node::{Node, document_from_node, window_from_node}; use dom::virtualmethods::VirtualMethods; @@ -137,7 +138,7 @@ impl VirtualMethods for HTMLBodyElement { let document = window.Document(); document.set_reflow_timeout(time::precise_time_ns() + INITIAL_REFLOW_DELAY); let event = ConstellationMsg::HeadParsed; - window.constellation_chan().send(event).unwrap(); + window.upcast::().constellation_chan().send(event).unwrap(); } fn parse_plain_attribute(&self, name: &Atom, value: DOMString) -> AttrValue { diff --git a/components/script/dom/htmliframeelement.rs b/components/script/dom/htmliframeelement.rs index 2b7781dae1e..355c825429d 100644 --- a/components/script/dom/htmliframeelement.rs +++ b/components/script/dom/htmliframeelement.rs @@ -29,6 +29,7 @@ use dom::domtokenlist::DOMTokenList; use dom::element::{AttributeMutation, Element, RawLayoutElementHelpers}; use dom::event::Event; use dom::eventtarget::EventTarget; +use dom::globalscope::GlobalScope; use dom::htmlelement::HTMLElement; use dom::node::{Node, NodeDamage, UnbindContext, document_from_node, window_from_node}; use dom::urlhelper::UrlHelper; @@ -135,7 +136,8 @@ impl HTMLIFrameElement { frame_type: frame_type, replace: replace, }; - window.constellation_chan() + window.upcast::() + .constellation_chan() .send(ConstellationMsg::ScriptLoadedURLInIFrame(load_info)) .unwrap(); @@ -216,7 +218,7 @@ impl HTMLIFrameElement { let window = window_from_node(self); let window = window.r(); let msg = ConstellationMsg::SetVisible(pipeline_id, visible); - window.constellation_chan().send(msg).unwrap(); + window.upcast::().constellation_chan().send(msg).unwrap(); } } @@ -407,7 +409,7 @@ pub fn Navigate(iframe: &HTMLIFrameElement, direction: TraversalDirection) -> Er if iframe.upcast::().is_in_doc() { let window = window_from_node(iframe); let msg = ConstellationMsg::TraverseHistory(iframe.pipeline_id(), direction); - window.constellation_chan().send(msg).unwrap(); + window.upcast::().constellation_chan().send(msg).unwrap(); } Ok(()) @@ -641,7 +643,7 @@ impl VirtualMethods for HTMLIFrameElement { (Some(sender), Some(receiver)) }; let msg = ConstellationMsg::RemoveIFrame(pipeline_id, sender); - window.constellation_chan().send(msg).unwrap(); + window.upcast::().constellation_chan().send(msg).unwrap(); if let Some(receiver) = receiver { receiver.recv().unwrap() } diff --git a/components/script/dom/htmlinputelement.rs b/components/script/dom/htmlinputelement.rs index d9cda98b284..4097b885d91 100644 --- a/components/script/dom/htmlinputelement.rs +++ b/components/script/dom/htmlinputelement.rs @@ -21,6 +21,7 @@ use dom::event::{Event, EventBubbles, EventCancelable}; use dom::eventtarget::EventTarget; use dom::file::File; use dom::filelist::FileList; +use dom::globalscope::GlobalScope; use dom::htmlelement::HTMLElement; use dom::htmlfieldsetelement::HTMLFieldSetElement; use dom::htmlformelement::{FormControl, FormDatum, FormDatumValue, FormSubmitter, HTMLFormElement}; @@ -128,7 +129,7 @@ static DEFAULT_MIN_LENGTH: i32 = -1; impl HTMLInputElement { fn new_inherited(local_name: Atom, prefix: Option, document: &Document) -> HTMLInputElement { - let chan = document.window().constellation_chan().clone(); + let chan = document.window().upcast::().constellation_chan().clone(); HTMLInputElement { htmlelement: HTMLElement::new_inherited_with_state(IN_ENABLED_STATE | IN_READ_WRITE_STATE, diff --git a/components/script/dom/htmllinkelement.rs b/components/script/dom/htmllinkelement.rs index b02aa0ad6a7..f3797469ea4 100644 --- a/components/script/dom/htmllinkelement.rs +++ b/components/script/dom/htmllinkelement.rs @@ -18,6 +18,7 @@ use dom::document::Document; use dom::domtokenlist::DOMTokenList; use dom::element::{AttributeMutation, Element, ElementCreator}; use dom::eventtarget::EventTarget; +use dom::globalscope::GlobalScope; use dom::htmlelement::HTMLElement; use dom::node::{Node, document_from_node, window_from_node}; use dom::virtualmethods::VirtualMethods; @@ -280,7 +281,7 @@ impl HTMLLinkElement { match document.base_url().join(href) { Ok(url) => { let event = ConstellationMsg::NewFavicon(url.clone()); - document.window().constellation_chan().send(event).unwrap(); + document.window().upcast::().constellation_chan().send(event).unwrap(); let mozbrowser_event = match *sizes { Some(ref sizes) => MozBrowserEvent::IconChange(rel.to_owned(), url.to_string(), sizes.to_owned()), diff --git a/components/script/dom/htmltextareaelement.rs b/components/script/dom/htmltextareaelement.rs index 3a4418d713d..bcdb8268c61 100644 --- a/components/script/dom/htmltextareaelement.rs +++ b/components/script/dom/htmltextareaelement.rs @@ -15,6 +15,7 @@ use dom::document::Document; use dom::element::{AttributeMutation, Element}; use dom::element::RawLayoutElementHelpers; use dom::event::{Event, EventBubbles, EventCancelable}; +use dom::globalscope::GlobalScope; use dom::htmlelement::HTMLElement; use dom::htmlfieldsetelement::HTMLFieldSetElement; use dom::htmlformelement::{FormControl, HTMLFormElement}; @@ -99,7 +100,7 @@ impl HTMLTextAreaElement { fn new_inherited(local_name: Atom, prefix: Option, document: &Document) -> HTMLTextAreaElement { - let chan = document.window().constellation_chan().clone(); + let chan = document.window().upcast::().constellation_chan().clone(); HTMLTextAreaElement { htmlelement: HTMLElement::new_inherited_with_state(IN_ENABLED_STATE | IN_READ_WRITE_STATE, diff --git a/components/script/dom/serviceworker.rs b/components/script/dom/serviceworker.rs index cce149b5368..6f2dce2f8e0 100644 --- a/components/script/dom/serviceworker.rs +++ b/components/script/dom/serviceworker.rs @@ -89,8 +89,11 @@ impl ServiceWorkerMethods for ServiceWorker { // Step 7 let data = try!(StructuredCloneData::write(cx, message)); let msg_vec = DOMMessage(data.move_to_arraybuffer()); - let _ = self.global().r().constellation_chan().send(ScriptMsg::ForwardDOMMessage(msg_vec, - self.scope_url.clone())); + let _ = + self.global().r() + .as_global_scope() + .constellation_chan() + .send(ScriptMsg::ForwardDOMMessage(msg_vec, self.scope_url.clone())); Ok(()) } diff --git a/components/script/dom/webglrenderingcontext.rs b/components/script/dom/webglrenderingcontext.rs index 4b6e8b2cefd..1b29bd47621 100644 --- a/components/script/dom/webglrenderingcontext.rs +++ b/components/script/dom/webglrenderingcontext.rs @@ -133,7 +133,7 @@ impl WebGLRenderingContext { attrs: GLContextAttributes) -> Result { let (sender, receiver) = ipc::channel().unwrap(); - let constellation_chan = global.constellation_chan(); + let constellation_chan = global.as_global_scope().constellation_chan(); constellation_chan.send(ConstellationMsg::CreateWebGLPaintThread(size, attrs, sender)) .unwrap(); let result = receiver.recv().unwrap(); diff --git a/components/script/dom/window.rs b/components/script/dom/window.rs index 57aeada88a5..7bc64f58b1c 100644 --- a/components/script/dom/window.rs +++ b/components/script/dom/window.rs @@ -215,10 +215,6 @@ pub struct Window { #[ignore_heap_size_of = "channels are hard"] bluetooth_thread: IpcSender, - /// A handle for communicating messages to the constellation thread. - #[ignore_heap_size_of = "channels are hard"] - constellation_chan: IpcSender, - /// Pending scroll to fragment event, if any fragment_name: DOMRefCell>, @@ -436,7 +432,10 @@ impl WindowMethods for Window { } let (sender, receiver) = ipc::channel().unwrap(); - self.constellation_chan().send(ConstellationMsg::Alert(self.pipeline_id(), s.to_string(), sender)).unwrap(); + self.upcast::() + .constellation_chan() + .send(ConstellationMsg::Alert(self.pipeline_id(), s.to_string(), sender)) + .unwrap(); let should_display_alert_dialog = receiver.recv().unwrap(); if should_display_alert_dialog { @@ -797,7 +796,10 @@ impl WindowMethods for Window { // Step 1 //TODO determine if this operation is allowed let size = Size2D::new(x.to_u32().unwrap_or(1), y.to_u32().unwrap_or(1)); - self.constellation_chan.send(ConstellationMsg::ResizeTo(size)).unwrap() + self.upcast::() + .constellation_chan() + .send(ConstellationMsg::ResizeTo(size)) + .unwrap() } // https://drafts.csswg.org/cssom-view/#dom-window-resizeby @@ -812,7 +814,10 @@ impl WindowMethods for Window { // Step 1 //TODO determine if this operation is allowed let point = Point2D::new(x, y); - self.constellation_chan.send(ConstellationMsg::MoveTo(point)).unwrap() + self.upcast::() + .constellation_chan() + .send(ConstellationMsg::MoveTo(point)) + .unwrap() } // https://drafts.csswg.org/cssom-view/#dom-window-moveby @@ -974,7 +979,7 @@ impl Window { self.update_viewport_for_scroll(x, y); let message = ConstellationMsg::ScrollFragmentPoint(self.pipeline_id(), layer_id, point, smooth); - self.constellation_chan.send(message).unwrap(); + self.upcast::().constellation_chan().send(message).unwrap(); } pub fn update_viewport_for_scroll(&self, x: f32, y: f32) { @@ -985,7 +990,10 @@ impl Window { pub fn client_window(&self) -> (Size2D, Point2D) { let (send, recv) = ipc::channel::<(Size2D, Point2D)>().unwrap(); - self.constellation_chan.send(ConstellationMsg::GetClientWindow(send)).unwrap(); + self.upcast::() + .constellation_chan() + .send(ConstellationMsg::GetClientWindow(send)) + .unwrap(); recv.recv().unwrap_or((Size2D::zero(), Point2D::zero())) } @@ -1149,7 +1157,7 @@ impl Window { if ready_state == DocumentReadyState::Complete && !reftest_wait { let event = ConstellationMsg::SetDocumentState(self.id, DocumentState::Idle); - self.constellation_chan().send(event).unwrap(); + self.upcast::().constellation_chan().send(event).unwrap(); } } @@ -1261,7 +1269,10 @@ impl Window { let pipeline_id = self.id; let (send, recv) = ipc::channel::>().unwrap(); - self.constellation_chan.send(ConstellationMsg::GetScrollOffset(pipeline_id, layer_id, send)).unwrap(); + self.upcast::() + .constellation_chan() + .send(ConstellationMsg::GetScrollOffset(pipeline_id, layer_id, send)) + .unwrap(); recv.recv().unwrap_or(Point2D::zero()) } @@ -1376,10 +1387,6 @@ impl Window { &self.layout_chan } - pub fn constellation_chan(&self) -> &IpcSender { - &self.constellation_chan - } - pub fn scheduler_chan(&self) -> &IpcSender { &self.scheduler_chan } @@ -1586,7 +1593,8 @@ impl Window { let current_time = time::get_time(); let win = box Window { globalscope: - GlobalScope::new_inherited(devtools_chan, mem_profiler_chan, time_profiler_chan), + GlobalScope::new_inherited( + devtools_chan, mem_profiler_chan, time_profiler_chan, constellation_chan), script_chan: script_chan, dom_manipulation_task_source: dom_task_source, user_interaction_task_source: user_task_source, @@ -1613,7 +1621,6 @@ impl Window { js_runtime: DOMRefCell::new(Some(runtime.clone())), resource_threads: resource_threads, bluetooth_thread: bluetooth_thread, - constellation_chan: constellation_chan, page_clip_rect: Cell::new(max_rect()), fragment_name: DOMRefCell::new(None), resize_event: Cell::new(None), diff --git a/components/script/dom/workerglobalscope.rs b/components/script/dom/workerglobalscope.rs index f9757a976ef..81c43c2c5fe 100644 --- a/components/script/dom/workerglobalscope.rs +++ b/components/script/dom/workerglobalscope.rs @@ -39,7 +39,6 @@ use script_runtime::{CommonScriptMsg, ScriptChan, ScriptPort, maybe_take_panic_r use script_runtime::{ScriptThreadEventCategory, PromiseJobQueue, EnqueuedPromiseCallback}; use script_thread::{Runnable, RunnableWrapper}; use script_traits::{MsDuration, TimerEvent, TimerEventId, TimerEventRequest, TimerSource}; -use script_traits::ScriptMsg as ConstellationMsg; use script_traits::WorkerGlobalScopeInit; use std::cell::Cell; use std::default::Default; @@ -59,13 +58,14 @@ pub fn prepare_workerscope_init(global: GlobalRef, let to_devtools_sender = global_scope.devtools_chan().cloned(); let mem_profiler_chan = global_scope.mem_profiler_chan().clone(); let time_profiler_chan = global_scope.time_profiler_chan().clone(); + let constellation_chan = global_scope.constellation_chan().clone(); let init = WorkerGlobalScopeInit { resource_threads: global.resource_threads(), mem_profiler_chan: mem_profiler_chan, to_devtools_sender: to_devtools_sender, time_profiler_chan: time_profiler_chan, from_devtools_sender: devtools_sender, - constellation_chan: global.constellation_chan().clone(), + constellation_chan: constellation_chan, scheduler_chan: global.scheduler_chan().clone(), worker_id: worker_id, pipeline_id: global.pipeline_id(), @@ -102,9 +102,6 @@ pub struct WorkerGlobalScope { /// `IpcSender` doesn't exist from_devtools_receiver: Receiver, - #[ignore_heap_size_of = "Defined in std"] - constellation_chan: IpcSender, - #[ignore_heap_size_of = "Defined in std"] scheduler_chan: IpcSender, @@ -125,7 +122,10 @@ impl WorkerGlobalScope { WorkerGlobalScope { globalscope: GlobalScope::new_inherited( - init.to_devtools_sender, init.mem_profiler_chan, init.time_profiler_chan), + init.to_devtools_sender, + init.mem_profiler_chan, + init.time_profiler_chan, + init.constellation_chan), worker_id: init.worker_id, pipeline_id: init.pipeline_id, worker_url: worker_url, @@ -137,7 +137,6 @@ impl WorkerGlobalScope { timers: OneshotTimers::new(timer_event_chan, init.scheduler_chan.clone()), from_devtools_sender: init.from_devtools_sender, from_devtools_receiver: from_devtools_receiver, - constellation_chan: init.constellation_chan, scheduler_chan: init.scheduler_chan, promise_job_queue: PromiseJobQueue::new(), in_error_reporting_mode: Default::default(), @@ -152,10 +151,6 @@ impl WorkerGlobalScope { &self.from_devtools_receiver } - pub fn constellation_chan(&self) -> &IpcSender { - &self.constellation_chan - } - pub fn scheduler_chan(&self) -> &IpcSender { &self.scheduler_chan } From c6ff767625fff00e7c8f41d254c074e8e1e277be Mon Sep 17 00:00:00 2001 From: Anthony Ramine Date: Sat, 1 Oct 2016 16:02:20 +0200 Subject: [PATCH 13/66] Introduce GlobalScope::scheduler_chan --- components/script/dom/bindings/global.rs | 11 +---------- components/script/dom/globalscope.rs | 13 +++++++++++-- components/script/dom/window.rs | 13 +++++-------- components/script/dom/workerglobalscope.rs | 18 ++++++------------ 4 files changed, 23 insertions(+), 32 deletions(-) diff --git a/components/script/dom/bindings/global.rs b/components/script/dom/bindings/global.rs index 43eafcc2d2e..11fb22a1684 100644 --- a/components/script/dom/bindings/global.rs +++ b/components/script/dom/bindings/global.rs @@ -16,7 +16,6 @@ use dom::bindings::reflector::{Reflectable, Reflector}; use dom::globalscope::GlobalScope; use dom::window; use dom::workerglobalscope::WorkerGlobalScope; -use ipc_channel::ipc::IpcSender; use js::{JSCLASS_IS_DOMJSCLASS, JSCLASS_IS_GLOBAL}; use js::glue::{IsWrapper, UnwrapObject}; use js::jsapi::{CurrentGlobalOrNull, Evaluate2, GetGlobalForObjectCrossCompartment}; @@ -30,7 +29,7 @@ use profile_traits::time; use script_runtime::{CommonScriptMsg, EnqueuedPromiseCallback, ScriptChan}; use script_runtime::{ScriptPort, maybe_take_panic_result}; use script_thread::{MainThreadScriptChan, RunnableWrapper, ScriptThread}; -use script_traits::{MsDuration, TimerEventRequest}; +use script_traits::MsDuration; use std::ffi::CString; use std::panic; use task_source::file_reading::FileReadingTaskSource; @@ -89,14 +88,6 @@ impl<'a> GlobalRef<'a> { } } - /// Get the scheduler channel to request timer events. - pub fn scheduler_chan(&self) -> &IpcSender { - match *self { - GlobalRef::Window(window) => window.scheduler_chan(), - GlobalRef::Worker(worker) => worker.scheduler_chan(), - } - } - /// Get the `ResourceThreads` for this global scope. pub fn resource_threads(&self) -> ResourceThreads { match *self { diff --git a/components/script/dom/globalscope.rs b/components/script/dom/globalscope.rs index 9f2443b85bc..94522928b3f 100644 --- a/components/script/dom/globalscope.rs +++ b/components/script/dom/globalscope.rs @@ -12,7 +12,7 @@ use dom::eventtarget::EventTarget; use ipc_channel::ipc::IpcSender; use js::jsapi::{JS_GetContext, JS_GetObjectRuntime, JSContext}; use profile_traits::{mem, time}; -use script_traits::ScriptMsg as ConstellationMsg; +use script_traits::{ScriptMsg as ConstellationMsg, TimerEventRequest}; use std::cell::Cell; use std::collections::HashMap; use std::collections::hash_map::Entry; @@ -46,6 +46,9 @@ pub struct GlobalScope { /// A handle for communicating messages to the constellation thread. #[ignore_heap_size_of = "channels are hard"] constellation_chan: IpcSender, + + #[ignore_heap_size_of = "channels are hard"] + scheduler_chan: IpcSender, } impl GlobalScope { @@ -53,7 +56,8 @@ impl GlobalScope { devtools_chan: Option>, mem_profiler_chan: mem::ProfilerChan, time_profiler_chan: time::ProfilerChan, - constellation_chan: IpcSender) + constellation_chan: IpcSender, + scheduler_chan: IpcSender) -> Self { GlobalScope { eventtarget: EventTarget::new_inherited(), @@ -65,6 +69,7 @@ impl GlobalScope { mem_profiler_chan: mem_profiler_chan, time_profiler_chan: time_profiler_chan, constellation_chan: constellation_chan, + scheduler_chan: scheduler_chan, } } @@ -140,6 +145,10 @@ impl GlobalScope { pub fn constellation_chan(&self) -> &IpcSender { &self.constellation_chan } + + pub fn scheduler_chan(&self) -> &IpcSender { + &self.scheduler_chan + } } fn timestamp_in_ms(time: Timespec) -> u64 { diff --git a/components/script/dom/window.rs b/components/script/dom/window.rs index 7bc64f58b1c..34c93fda495 100644 --- a/components/script/dom/window.rs +++ b/components/script/dom/window.rs @@ -170,8 +170,6 @@ pub struct Window { session_storage: MutNullableHeap>, local_storage: MutNullableHeap>, status: DOMRefCell, - #[ignore_heap_size_of = "channels are hard"] - scheduler_chan: IpcSender, timers: OneshotTimers, /// For sending timeline markers. Will be ignored if @@ -1387,10 +1385,6 @@ impl Window { &self.layout_chan } - pub fn scheduler_chan(&self) -> &IpcSender { - &self.scheduler_chan - } - pub fn schedule_callback(&self, callback: OneshotTimerCallback, duration: MsDuration) -> OneshotTimerHandle { self.timers.schedule_callback(callback, duration, @@ -1594,7 +1588,11 @@ impl Window { let win = box Window { globalscope: GlobalScope::new_inherited( - devtools_chan, mem_profiler_chan, time_profiler_chan, constellation_chan), + devtools_chan, + mem_profiler_chan, + time_profiler_chan, + constellation_chan, + scheduler_chan.clone()), script_chan: script_chan, dom_manipulation_task_source: dom_task_source, user_interaction_task_source: user_task_source, @@ -1613,7 +1611,6 @@ impl Window { session_storage: Default::default(), local_storage: Default::default(), status: DOMRefCell::new(DOMString::new()), - scheduler_chan: scheduler_chan.clone(), timers: OneshotTimers::new(timer_event_chan, scheduler_chan), id: id, parent_info: parent_info, diff --git a/components/script/dom/workerglobalscope.rs b/components/script/dom/workerglobalscope.rs index 81c43c2c5fe..9590e11409d 100644 --- a/components/script/dom/workerglobalscope.rs +++ b/components/script/dom/workerglobalscope.rs @@ -38,7 +38,7 @@ use net_traits::{LoadContext, ResourceThreads, load_whole_resource}; use script_runtime::{CommonScriptMsg, ScriptChan, ScriptPort, maybe_take_panic_result}; use script_runtime::{ScriptThreadEventCategory, PromiseJobQueue, EnqueuedPromiseCallback}; use script_thread::{Runnable, RunnableWrapper}; -use script_traits::{MsDuration, TimerEvent, TimerEventId, TimerEventRequest, TimerSource}; +use script_traits::{MsDuration, TimerEvent, TimerEventId, TimerSource}; use script_traits::WorkerGlobalScopeInit; use std::cell::Cell; use std::default::Default; @@ -59,6 +59,7 @@ pub fn prepare_workerscope_init(global: GlobalRef, let mem_profiler_chan = global_scope.mem_profiler_chan().clone(); let time_profiler_chan = global_scope.time_profiler_chan().clone(); let constellation_chan = global_scope.constellation_chan().clone(); + let scheduler_chan = global_scope.scheduler_chan().clone(); let init = WorkerGlobalScopeInit { resource_threads: global.resource_threads(), mem_profiler_chan: mem_profiler_chan, @@ -66,7 +67,7 @@ pub fn prepare_workerscope_init(global: GlobalRef, time_profiler_chan: time_profiler_chan, from_devtools_sender: devtools_sender, constellation_chan: constellation_chan, - scheduler_chan: global.scheduler_chan().clone(), + scheduler_chan: scheduler_chan, worker_id: worker_id, pipeline_id: global.pipeline_id(), }; @@ -102,9 +103,6 @@ pub struct WorkerGlobalScope { /// `IpcSender` doesn't exist from_devtools_receiver: Receiver, - #[ignore_heap_size_of = "Defined in std"] - scheduler_chan: IpcSender, - promise_job_queue: PromiseJobQueue, /// https://html.spec.whatwg.org/multipage/#in-error-reporting-mode @@ -125,7 +123,8 @@ impl WorkerGlobalScope { init.to_devtools_sender, init.mem_profiler_chan, init.time_profiler_chan, - init.constellation_chan), + init.constellation_chan, + init.scheduler_chan.clone()), worker_id: init.worker_id, pipeline_id: init.pipeline_id, worker_url: worker_url, @@ -134,10 +133,9 @@ impl WorkerGlobalScope { resource_threads: init.resource_threads, location: Default::default(), navigator: Default::default(), - timers: OneshotTimers::new(timer_event_chan, init.scheduler_chan.clone()), + timers: OneshotTimers::new(timer_event_chan, init.scheduler_chan), from_devtools_sender: init.from_devtools_sender, from_devtools_receiver: from_devtools_receiver, - scheduler_chan: init.scheduler_chan, promise_job_queue: PromiseJobQueue::new(), in_error_reporting_mode: Default::default(), } @@ -151,10 +149,6 @@ impl WorkerGlobalScope { &self.from_devtools_receiver } - pub fn scheduler_chan(&self) -> &IpcSender { - &self.scheduler_chan - } - pub fn schedule_callback(&self, callback: OneshotTimerCallback, duration: MsDuration) -> OneshotTimerHandle { self.timers.schedule_callback(callback, duration, From 27f100b1d47058b92d0e23d8c1b2e472fb0eafca Mon Sep 17 00:00:00 2001 From: Anthony Ramine Date: Sat, 1 Oct 2016 17:24:54 +0200 Subject: [PATCH 14/66] Introduce GlobalScope::pipeline_id --- components/script/dom/bindings/global.rs | 9 ---- components/script/dom/browsingcontext.rs | 4 +- components/script/dom/console.rs | 5 +- components/script/dom/document.rs | 33 +++++++----- components/script/dom/globalscope.rs | 11 ++++ components/script/dom/history.rs | 10 ++-- components/script/dom/htmlformelement.rs | 3 +- components/script/dom/htmliframeelement.rs | 5 +- components/script/dom/htmllinkelement.rs | 2 +- components/script/dom/htmlscriptelement.rs | 2 +- components/script/dom/request.rs | 2 +- .../script/dom/serviceworkercontainer.rs | 7 ++- .../script/dom/serviceworkerregistration.rs | 4 +- components/script/dom/storage.rs | 2 +- components/script/dom/window.rs | 51 +++++++++---------- components/script/dom/worker.rs | 6 +-- components/script/dom/workerglobalscope.rs | 14 ++--- components/script/dom/xmlhttprequest.rs | 9 ++-- components/script/script_runtime.rs | 2 +- components/script/script_thread.rs | 4 +- components/script/webdriver_handlers.rs | 3 +- 21 files changed, 103 insertions(+), 85 deletions(-) diff --git a/components/script/dom/bindings/global.rs b/components/script/dom/bindings/global.rs index 11fb22a1684..0dbbba2c376 100644 --- a/components/script/dom/bindings/global.rs +++ b/components/script/dom/bindings/global.rs @@ -23,7 +23,6 @@ use js::jsapi::{HandleValue, JS_GetClass, JSAutoCompartment, JSContext}; use js::jsapi::{JSObject, MutableHandleValue}; use js::rust::CompileOptionsWrapper; use libc; -use msg::constellation_msg::PipelineId; use net_traits::{CoreResourceThread, IpcSend, ResourceThreads}; use profile_traits::time; use script_runtime::{CommonScriptMsg, EnqueuedPromiseCallback, ScriptChan}; @@ -80,14 +79,6 @@ impl<'a> GlobalRef<'a> { } } - /// Get the `PipelineId` for this global scope. - pub fn pipeline_id(&self) -> PipelineId { - match *self { - GlobalRef::Window(window) => window.pipeline_id(), - GlobalRef::Worker(worker) => worker.pipeline_id(), - } - } - /// Get the `ResourceThreads` for this global scope. pub fn resource_threads(&self) -> ResourceThreads { match *self { diff --git a/components/script/dom/browsingcontext.rs b/components/script/dom/browsingcontext.rs index 9f867157fab..2ea6a1b78bd 100644 --- a/components/script/dom/browsingcontext.rs +++ b/components/script/dom/browsingcontext.rs @@ -4,6 +4,7 @@ use dom::bindings::cell::DOMRefCell; use dom::bindings::conversions::{ToJSValConvertible, root_from_handleobject}; +use dom::bindings::inheritance::Castable; use dom::bindings::js::{JS, MutNullableHeap, Root, RootedReference}; use dom::bindings::proxyhandler::{fill_property_descriptor, get_property_descriptor}; use dom::bindings::reflector::{Reflectable, MutReflectable, Reflector}; @@ -12,6 +13,7 @@ use dom::bindings::utils::WindowProxyHandler; use dom::bindings::utils::get_array_index_from_id; use dom::document::Document; use dom::element::Element; +use dom::globalscope::GlobalScope; use dom::window::Window; use js::JSCLASS_IS_GLOBAL; use js::glue::{CreateWrapperProxyHandler, ProxyTraps, NewWindowProxy}; @@ -150,7 +152,7 @@ impl BrowsingContext { pub fn find_child_by_id(&self, pipeline_id: PipelineId) -> Option> { self.children.borrow().iter().find(|context| { let window = context.active_window(); - window.pipeline_id() == pipeline_id + window.upcast::().pipeline_id() == pipeline_id }).map(|context| context.active_window()) } diff --git a/components/script/dom/console.rs b/components/script/dom/console.rs index d9660296e05..a33a40d7dfc 100644 --- a/components/script/dom/console.rs +++ b/components/script/dom/console.rs @@ -11,7 +11,8 @@ pub struct Console(()); impl Console { fn send_to_devtools(global: GlobalRef, level: LogLevel, message: DOMString) { - if let Some(chan) = global.as_global_scope().devtools_chan() { + let global_scope = global.as_global_scope(); + if let Some(chan) = global_scope.devtools_chan() { let console_message = prepare_message(level, message); let worker_id = if let GlobalRef::Worker(worker) = global { Some(worker.get_worker_id()) @@ -19,7 +20,7 @@ impl Console { None }; let devtools_message = ScriptToDevtoolsControlMsg::ConsoleAPI( - global.pipeline_id(), + global_scope.pipeline_id(), console_message, worker_id); chan.send(devtools_message).unwrap(); diff --git a/components/script/dom/document.rs b/components/script/dom/document.rs index ec109e82240..da7b895a4f3 100644 --- a/components/script/dom/document.rs +++ b/components/script/dom/document.rs @@ -651,8 +651,9 @@ impl Document { // Update the focus state for all elements in the focus chain. // https://html.spec.whatwg.org/multipage/#focus-chain if focus_type == FocusType::Element { - let event = ConstellationMsg::Focus(self.window.pipeline_id()); - self.window.upcast::().constellation_chan().send(event).unwrap(); + let global_scope = self.window.upcast::(); + let event = ConstellationMsg::Focus(global_scope.pipeline_id()); + global_scope.constellation_chan().send(event).unwrap(); } } } @@ -670,9 +671,10 @@ impl Document { /// Sends this document's title to the compositor. pub fn send_title_to_compositor(&self) { let window = self.window(); - window.upcast::() + let global_scope = window.upcast::(); + global_scope .constellation_chan() - .send(ConstellationMsg::SetTitle(window.pipeline_id(), + .send(ConstellationMsg::SetTitle(global_scope.pipeline_id(), Some(String::from(self.Title())))) .unwrap(); } @@ -1358,10 +1360,11 @@ impl Document { pub fn trigger_mozbrowser_event(&self, event: MozBrowserEvent) { if PREFS.is_mozbrowser_enabled() { if let Some((parent_pipeline_id, _)) = self.window.parent_info() { + let global_scope = self.window.upcast::(); let event = ConstellationMsg::MozBrowserEvent(parent_pipeline_id, - Some(self.window.pipeline_id()), + Some(global_scope.pipeline_id()), event); - self.window.upcast::().constellation_chan().send(event).unwrap(); + global_scope.constellation_chan().send(event).unwrap(); } } } @@ -1381,10 +1384,11 @@ impl Document { // // TODO: Should tick animation only when document is visible if !self.running_animation_callbacks.get() { + let global_scope = self.window.upcast::(); let event = ConstellationMsg::ChangeRunningAnimationsState( - self.window.pipeline_id(), + global_scope.pipeline_id(), AnimationState::AnimationCallbacksPresent); - self.window.upcast::().constellation_chan().send(event).unwrap(); + global_scope.constellation_chan().send(event).unwrap(); } ident @@ -1420,9 +1424,10 @@ impl Document { if self.animation_frame_list.borrow().is_empty() { mem::swap(&mut *self.animation_frame_list.borrow_mut(), &mut animation_frame_list); - let event = ConstellationMsg::ChangeRunningAnimationsState(self.window.pipeline_id(), + let global_scope = self.window.upcast::(); + let event = ConstellationMsg::ChangeRunningAnimationsState(global_scope.pipeline_id(), AnimationState::NoAnimationCallbacksPresent); - self.window.upcast::().constellation_chan().send(event).unwrap(); + global_scope.constellation_chan().send(event).unwrap(); } self.running_animation_callbacks.set(false); @@ -1480,7 +1485,8 @@ impl Document { let loader = self.loader.borrow(); if !loader.is_blocked() && !loader.events_inhibited() { let win = self.window(); - let msg = MainThreadScriptMsg::DocumentLoadsComplete(win.pipeline_id()); + let msg = MainThreadScriptMsg::DocumentLoadsComplete( + win.upcast::().pipeline_id()); win.main_thread_script_chan().send(msg).unwrap(); } } @@ -1578,9 +1584,10 @@ impl Document { } pub fn notify_constellation_load(&self) { - let pipeline_id = self.window.pipeline_id(); + let global_scope = self.window.upcast::(); + let pipeline_id = global_scope.pipeline_id(); let load_event = ConstellationMsg::LoadComplete(pipeline_id); - self.window.upcast::().constellation_chan().send(load_event).unwrap(); + global_scope.constellation_chan().send(load_event).unwrap(); } pub fn set_current_parser(&self, script: Option) { diff --git a/components/script/dom/globalscope.rs b/components/script/dom/globalscope.rs index 94522928b3f..b455536ed1c 100644 --- a/components/script/dom/globalscope.rs +++ b/components/script/dom/globalscope.rs @@ -11,6 +11,7 @@ use dom::crypto::Crypto; use dom::eventtarget::EventTarget; use ipc_channel::ipc::IpcSender; use js::jsapi::{JS_GetContext, JS_GetObjectRuntime, JSContext}; +use msg::constellation_msg::PipelineId; use profile_traits::{mem, time}; use script_traits::{ScriptMsg as ConstellationMsg, TimerEventRequest}; use std::cell::Cell; @@ -24,6 +25,9 @@ pub struct GlobalScope { crypto: MutNullableHeap>, next_worker_id: Cell, + /// Pipeline id associated with this global. + pipeline_id: PipelineId, + /// A flag to indicate whether the developer tools has requested /// live updates from the worker. devtools_wants_updates: Cell, @@ -53,6 +57,7 @@ pub struct GlobalScope { impl GlobalScope { pub fn new_inherited( + pipeline_id: PipelineId, devtools_chan: Option>, mem_profiler_chan: mem::ProfilerChan, time_profiler_chan: time::ProfilerChan, @@ -63,6 +68,7 @@ impl GlobalScope { eventtarget: EventTarget::new_inherited(), crypto: Default::default(), next_worker_id: Cell::new(WorkerId(0)), + pipeline_id: pipeline_id, devtools_wants_updates: Default::default(), console_timers: DOMRefCell::new(Default::default()), devtools_chan: devtools_chan, @@ -149,6 +155,11 @@ impl GlobalScope { pub fn scheduler_chan(&self) -> &IpcSender { &self.scheduler_chan } + + /// Get the `PipelineId` for this global scope. + pub fn pipeline_id(&self) -> PipelineId { + self.pipeline_id + } } fn timestamp_in_ms(time: Timespec) -> u64 { diff --git a/components/script/dom/history.rs b/components/script/dom/history.rs index 23dc3951e42..1a971eae009 100644 --- a/components/script/dom/history.rs +++ b/components/script/dom/history.rs @@ -39,19 +39,21 @@ impl History { impl History { fn traverse_history(&self, direction: TraversalDirection) { - let pipeline = self.window.pipeline_id(); + let global_scope = self.window.upcast::(); + let pipeline = global_scope.pipeline_id(); let msg = ConstellationMsg::TraverseHistory(Some(pipeline), direction); - let _ = self.window.upcast::().constellation_chan().send(msg); + let _ = global_scope.constellation_chan().send(msg); } } impl HistoryMethods for History { // https://html.spec.whatwg.org/multipage/#dom-history-length fn Length(&self) -> u32 { - let pipeline = self.window.pipeline_id(); + let global_scope = self.window.upcast::(); + let pipeline = global_scope.pipeline_id(); let (sender, recv) = ipc::channel().expect("Failed to create channel to send jsh length."); let msg = ConstellationMsg::JointSessionHistoryLength(pipeline, sender); - let _ = self.window.upcast::().constellation_chan().send(msg); + let _ = global_scope.constellation_chan().send(msg); recv.recv().unwrap() } diff --git a/components/script/dom/htmlformelement.rs b/components/script/dom/htmlformelement.rs index 8759fbafe5e..58454eed0dc 100644 --- a/components/script/dom/htmlformelement.rs +++ b/components/script/dom/htmlformelement.rs @@ -24,6 +24,7 @@ use dom::element::Element; use dom::event::{EventBubbles, EventCancelable}; use dom::eventtarget::EventTarget; use dom::file::File; +use dom::globalscope::GlobalScope; use dom::htmlbuttonelement::HTMLButtonElement; use dom::htmlcollection::CollectionFilter; use dom::htmldatalistelement::HTMLDataListElement; @@ -436,7 +437,7 @@ impl HTMLFormElement { // Step 2 let nav = box PlannedNavigation { load_data: load_data, - pipeline_id: window.pipeline_id(), + pipeline_id: window.upcast::().pipeline_id(), script_chan: window.main_thread_script_chan().clone(), generation_id: self.generation_id.get(), form: Trusted::new(self) diff --git a/components/script/dom/htmliframeelement.rs b/components/script/dom/htmliframeelement.rs index 355c825429d..75d828e73c9 100644 --- a/components/script/dom/htmliframeelement.rs +++ b/components/script/dom/htmliframeelement.rs @@ -126,9 +126,10 @@ impl HTMLIFrameElement { let private_iframe = self.privatebrowsing(); let frame_type = if self.Mozbrowser() { FrameType::MozBrowserIFrame } else { FrameType::IFrame }; + let global_scope = window.upcast::(); let load_info = IFrameLoadInfo { load_data: load_data, - parent_pipeline_id: window.pipeline_id(), + parent_pipeline_id: global_scope.pipeline_id(), old_pipeline_id: old_pipeline_id, new_pipeline_id: new_pipeline_id, sandbox: sandboxed, @@ -136,7 +137,7 @@ impl HTMLIFrameElement { frame_type: frame_type, replace: replace, }; - window.upcast::() + global_scope .constellation_chan() .send(ConstellationMsg::ScriptLoadedURLInIFrame(load_info)) .unwrap(); diff --git a/components/script/dom/htmllinkelement.rs b/components/script/dom/htmllinkelement.rs index f3797469ea4..f74946ba841 100644 --- a/components/script/dom/htmllinkelement.rs +++ b/components/script/dom/htmllinkelement.rs @@ -267,7 +267,7 @@ impl HTMLLinkElement { credentials_mode: CredentialsMode::Include, use_url_credentials: true, origin: document.url().clone(), - pipeline_id: Some(self.global().r().pipeline_id()), + pipeline_id: Some(self.global().r().as_global_scope().pipeline_id()), referrer_url: Some(document.url().clone()), referrer_policy: referrer_policy, .. RequestInit::default() diff --git a/components/script/dom/htmlscriptelement.rs b/components/script/dom/htmlscriptelement.rs index 7f5266b9e84..4cf7e2df59c 100644 --- a/components/script/dom/htmlscriptelement.rs +++ b/components/script/dom/htmlscriptelement.rs @@ -242,7 +242,7 @@ fn fetch_a_classic_script(script: &HTMLScriptElement, _ => CredentialsMode::Include, }, origin: doc.url().clone(), - pipeline_id: Some(script.global().r().pipeline_id()), + pipeline_id: Some(script.global().r().as_global_scope().pipeline_id()), referrer_url: Some(doc.url().clone()), referrer_policy: doc.get_referrer_policy(), .. RequestInit::default() diff --git a/components/script/dom/request.rs b/components/script/dom/request.rs index 1496f16d353..4a9343b76b4 100644 --- a/components/script/dom/request.rs +++ b/components/script/dom/request.rs @@ -451,7 +451,7 @@ fn net_request_from_global(global: GlobalRef, url: Url, is_service_worker_global_scope: bool) -> NetTraitsRequest { let origin = Origin::Origin(global.get_url().origin()); - let pipeline_id = global.pipeline_id(); + let pipeline_id = global.as_global_scope().pipeline_id(); NetTraitsRequest::new(url, Some(origin), is_service_worker_global_scope, diff --git a/components/script/dom/serviceworkercontainer.rs b/components/script/dom/serviceworkercontainer.rs index 3d9202accf4..993241445d5 100644 --- a/components/script/dom/serviceworkercontainer.rs +++ b/components/script/dom/serviceworkercontainer.rs @@ -95,11 +95,14 @@ impl ServiceWorkerContainerMethods for ServiceWorkerContainer { return Err(Error::Type("Scope URL contains forbidden characters".to_owned())); } - let worker_registration = ServiceWorkerRegistration::new(self.global().r().as_global_scope(), + let global = self.global(); + let global = global.r(); + let global_scope = global.as_global_scope(); + let worker_registration = ServiceWorkerRegistration::new(global_scope, script_url, scope.clone(), self); - ScriptThread::set_registration(scope, &*worker_registration, self.global().r().pipeline_id()); + ScriptThread::set_registration(scope, &*worker_registration, global_scope.pipeline_id()); Ok(worker_registration) } } diff --git a/components/script/dom/serviceworkerregistration.rs b/components/script/dom/serviceworkerregistration.rs index 09c23570243..87226207266 100644 --- a/components/script/dom/serviceworkerregistration.rs +++ b/components/script/dom/serviceworkerregistration.rs @@ -51,13 +51,13 @@ impl ServiceWorkerRegistration { } pub fn create_scope_things(global: GlobalRef, script_url: Url) -> ScopeThings { + let global_scope = global.as_global_scope(); let worker_load_origin = WorkerScriptLoadOrigin { referrer_url: None, referrer_policy: None, - pipeline_id: Some(global.pipeline_id()) + pipeline_id: Some(global_scope.pipeline_id()) }; - let global_scope = global.as_global_scope(); let worker_id = global_scope.get_next_worker_id(); let devtools_chan = global_scope.devtools_chan().cloned(); let init = prepare_workerscope_init(global, None); diff --git a/components/script/dom/storage.rs b/components/script/dom/storage.rs index 986cd8edcbe..30afd8719c4 100644 --- a/components/script/dom/storage.rs +++ b/components/script/dom/storage.rs @@ -206,7 +206,7 @@ impl Runnable for StorageEventRunnable { assert!(UrlHelper::SameOrigin(&ev_url, &it_window.get_url())); // TODO: Such a Document object is not necessarily fully active, but events fired on such // objects are ignored by the event loop until the Document becomes fully active again. - if ev_window.pipeline_id() != it_window.pipeline_id() { + if ev_window.upcast::().pipeline_id() != it_window.upcast::().pipeline_id() { storage_event.upcast::().fire(it_window.upcast()); } } diff --git a/components/script/dom/window.rs b/components/script/dom/window.rs index 34c93fda495..d560efa0746 100644 --- a/components/script/dom/window.rs +++ b/components/script/dom/window.rs @@ -181,9 +181,6 @@ pub struct Window { /// Pending resize event, if any. resize_event: Cell>, - /// Pipeline id associated with this page. - id: PipelineId, - /// Parent id associated with this page, if any. parent_info: Option<(PipelineId, FrameType)>, @@ -293,10 +290,6 @@ impl Window { self.image_cache_chan.clone() } - pub fn pipeline_id(&self) -> PipelineId { - self.id - } - pub fn parent_info(&self) -> Option<(PipelineId, FrameType)> { self.parent_info } @@ -430,9 +423,10 @@ impl WindowMethods for Window { } let (sender, receiver) = ipc::channel().unwrap(); - self.upcast::() + let global_scope = self.upcast::(); + global_scope .constellation_chan() - .send(ConstellationMsg::Alert(self.pipeline_id(), s.to_string(), sender)) + .send(ConstellationMsg::Alert(global_scope.pipeline_id(), s.to_string(), sender)) .unwrap(); let should_display_alert_dialog = receiver.recv().unwrap(); @@ -443,7 +437,9 @@ impl WindowMethods for Window { // https://html.spec.whatwg.org/multipage/#dom-window-close fn Close(&self) { - self.main_thread_script_chan().send(MainThreadScriptMsg::ExitWindow(self.id.clone())).unwrap(); + self.main_thread_script_chan() + .send(MainThreadScriptMsg::ExitWindow(self.upcast::().pipeline_id())) + .unwrap(); } // https://html.spec.whatwg.org/multipage/#dom-document-2 @@ -493,7 +489,7 @@ impl WindowMethods for Window { args, timeout, IsInterval::NonInterval, - TimerSource::FromWindow(self.id.clone())) + TimerSource::FromWindow(self.upcast::().pipeline_id())) } // https://html.spec.whatwg.org/multipage/#dom-windowtimers-settimeout @@ -503,7 +499,7 @@ impl WindowMethods for Window { args, timeout, IsInterval::NonInterval, - TimerSource::FromWindow(self.id.clone())) + TimerSource::FromWindow(self.upcast::().pipeline_id())) } // https://html.spec.whatwg.org/multipage/#dom-windowtimers-cleartimeout @@ -518,7 +514,7 @@ impl WindowMethods for Window { args, timeout, IsInterval::Interval, - TimerSource::FromWindow(self.id.clone())) + TimerSource::FromWindow(self.upcast::().pipeline_id())) } // https://html.spec.whatwg.org/multipage/#dom-windowtimers-setinterval @@ -528,7 +524,7 @@ impl WindowMethods for Window { args, timeout, IsInterval::Interval, - TimerSource::FromWindow(self.id.clone())) + TimerSource::FromWindow(self.upcast::().pipeline_id())) } // https://html.spec.whatwg.org/multipage/#dom-windowtimers-clearinterval @@ -976,8 +972,10 @@ impl Window { // TODO (farodin91): Raise an event to stop the current_viewport self.update_viewport_for_scroll(x, y); - let message = ConstellationMsg::ScrollFragmentPoint(self.pipeline_id(), layer_id, point, smooth); - self.upcast::().constellation_chan().send(message).unwrap(); + let global_scope = self.upcast::(); + let message = ConstellationMsg::ScrollFragmentPoint( + global_scope.pipeline_id(), layer_id, point, smooth); + global_scope.constellation_chan().send(message).unwrap(); } pub fn update_viewport_for_scroll(&self, x: f32, y: f32) { @@ -1032,7 +1030,7 @@ impl Window { let for_display = query_type == ReflowQueryType::NoQuery; if for_display && self.suppress_reflow.get() { debug!("Suppressing reflow pipeline {} for goal {:?} reason {:?} before FirstLoad or RefreshTick", - self.id, goal, reason); + self.upcast::().pipeline_id(), goal, reason); return false; } @@ -1049,7 +1047,7 @@ impl Window { // On debug mode, print the reflow event information. if opts::get().relayout_event { - debug_reflow_events(self.id, &goal, &query_type, &reason); + debug_reflow_events(self.upcast::().pipeline_id(), &goal, &query_type, &reason); } let document = self.Document(); @@ -1154,8 +1152,9 @@ impl Window { let ready_state = document.ReadyState(); if ready_state == DocumentReadyState::Complete && !reftest_wait { - let event = ConstellationMsg::SetDocumentState(self.id, DocumentState::Idle); - self.upcast::().constellation_chan().send(event).unwrap(); + let global_scope = self.upcast::(); + let event = ConstellationMsg::SetDocumentState(global_scope.pipeline_id(), DocumentState::Idle); + global_scope.constellation_chan().send(event).unwrap(); } } @@ -1264,12 +1263,12 @@ impl Window { } let layer_id = self.layout_rpc.node_layer_id().layer_id; - let pipeline_id = self.id; let (send, recv) = ipc::channel::>().unwrap(); - self.upcast::() + let global_scope = self.upcast::(); + global_scope .constellation_chan() - .send(ConstellationMsg::GetScrollOffset(pipeline_id, layer_id, send)) + .send(ConstellationMsg::GetScrollOffset(global_scope.pipeline_id(), layer_id, send)) .unwrap(); recv.recv().unwrap_or(Point2D::zero()) } @@ -1345,7 +1344,7 @@ impl Window { let referrer_policy = referrer_policy.or(doc.get_referrer_policy()); self.main_thread_script_chan().send( - MainThreadScriptMsg::Navigate(self.id, + MainThreadScriptMsg::Navigate(self.upcast::().pipeline_id(), LoadData::new(url, referrer_policy, Some(doc.url().clone())), replace)).unwrap(); } @@ -1388,7 +1387,7 @@ impl Window { pub fn schedule_callback(&self, callback: OneshotTimerCallback, duration: MsDuration) -> OneshotTimerHandle { self.timers.schedule_callback(callback, duration, - TimerSource::FromWindow(self.id.clone())) + TimerSource::FromWindow(self.upcast::().pipeline_id())) } pub fn unschedule_callback(&self, handle: OneshotTimerHandle) { @@ -1588,6 +1587,7 @@ impl Window { let win = box Window { globalscope: GlobalScope::new_inherited( + id, devtools_chan, mem_profiler_chan, time_profiler_chan, @@ -1612,7 +1612,6 @@ impl Window { local_storage: Default::default(), status: DOMRefCell::new(DOMString::new()), timers: OneshotTimers::new(timer_event_chan, scheduler_chan), - id: id, parent_info: parent_info, dom_static: GlobalStaticData::new(), js_runtime: DOMRefCell::new(Some(runtime.clone())), diff --git a/components/script/dom/worker.rs b/components/script/dom/worker.rs index 067b564d595..772cb5edc10 100644 --- a/components/script/dom/worker.rs +++ b/components/script/dom/worker.rs @@ -84,17 +84,17 @@ impl Worker { let worker = Worker::new(global.as_global_scope(), sender.clone(), closing.clone()); let worker_ref = Trusted::new(worker.r()); + let global_scope = global.as_global_scope(); let worker_load_origin = WorkerScriptLoadOrigin { referrer_url: None, referrer_policy: None, - pipeline_id: Some(global.pipeline_id()), + pipeline_id: Some(global_scope.pipeline_id()), }; let (devtools_sender, devtools_receiver) = ipc::channel().unwrap(); - let global_scope = global.as_global_scope(); let worker_id = global_scope.get_next_worker_id(); if let Some(ref chan) = global_scope.devtools_chan() { - let pipeline_id = global.pipeline_id(); + let pipeline_id = global_scope.pipeline_id(); let title = format!("Worker for {}", worker_url); let page_info = DevtoolsPageInfo { title: title, diff --git a/components/script/dom/workerglobalscope.rs b/components/script/dom/workerglobalscope.rs index 9590e11409d..55326f20277 100644 --- a/components/script/dom/workerglobalscope.rs +++ b/components/script/dom/workerglobalscope.rs @@ -60,6 +60,7 @@ pub fn prepare_workerscope_init(global: GlobalRef, let time_profiler_chan = global_scope.time_profiler_chan().clone(); let constellation_chan = global_scope.constellation_chan().clone(); let scheduler_chan = global_scope.scheduler_chan().clone(); + let pipeline_id = global_scope.pipeline_id(); let init = WorkerGlobalScopeInit { resource_threads: global.resource_threads(), mem_profiler_chan: mem_profiler_chan, @@ -69,7 +70,7 @@ pub fn prepare_workerscope_init(global: GlobalRef, constellation_chan: constellation_chan, scheduler_chan: scheduler_chan, worker_id: worker_id, - pipeline_id: global.pipeline_id(), + pipeline_id: pipeline_id, }; init @@ -81,7 +82,6 @@ pub struct WorkerGlobalScope { globalscope: GlobalScope, worker_id: WorkerId, - pipeline_id: PipelineId, worker_url: Url, #[ignore_heap_size_of = "Arc"] closing: Option>, @@ -120,13 +120,13 @@ impl WorkerGlobalScope { WorkerGlobalScope { globalscope: GlobalScope::new_inherited( + init.pipeline_id, init.to_devtools_sender, init.mem_profiler_chan, init.time_profiler_chan, init.constellation_chan, init.scheduler_chan.clone()), worker_id: init.worker_id, - pipeline_id: init.pipeline_id, worker_url: worker_url, closing: closing, runtime: runtime, @@ -207,7 +207,7 @@ impl WorkerGlobalScope { fn do_flush_promise_jobs(&self) { self.promise_job_queue.flush_promise_jobs(|id| { - assert_eq!(self.pipeline_id(), id); + assert_eq!(self.upcast::().pipeline_id(), id); Some(GlobalRoot::Worker(Root::from_ref(self))) }); } @@ -221,7 +221,7 @@ impl LoadOrigin for WorkerGlobalScope { None } fn pipeline_id(&self) -> Option { - Some(self.pipeline_id()) + Some(self.upcast::().pipeline_id()) } } @@ -401,10 +401,6 @@ impl WorkerGlobalScope { FileReadingTaskSource(self.script_chan()) } - pub fn pipeline_id(&self) -> PipelineId { - self.pipeline_id - } - pub fn new_script_pair(&self) -> (Box, Box) { let dedicated = self.downcast::(); if let Some(dedicated) = dedicated { diff --git a/components/script/dom/xmlhttprequest.rs b/components/script/dom/xmlhttprequest.rs index 4c9397db566..0cf5381767d 100644 --- a/components/script/dom/xmlhttprequest.rs +++ b/components/script/dom/xmlhttprequest.rs @@ -284,7 +284,7 @@ impl LoadOrigin for XMLHttpRequest { fn pipeline_id(&self) -> Option { let global = self.global(); - Some(global.r().pipeline_id()) + Some(global.r().as_global_scope().pipeline_id()) } } @@ -1208,7 +1208,10 @@ impl XMLHttpRequest { let decoded = charset.decode(&self.response.borrow(), DecoderTrap::Replace).unwrap(); let document = self.new_doc(IsHTMLDocument::HTMLDocument); // TODO: Disable scripting while parsing - parse_html(document.r(), DOMString::from(decoded), wr.get_url(), ParseContext::Owner(Some(wr.pipeline_id()))); + parse_html(document.r(), + DOMString::from(decoded), + wr.get_url(), + ParseContext::Owner(Some(wr.as_global_scope().pipeline_id()))); document } @@ -1222,7 +1225,7 @@ impl XMLHttpRequest { parse_xml(document.r(), DOMString::from(decoded), wr.get_url(), - xml::ParseContext::Owner(Some(wr.pipeline_id()))); + xml::ParseContext::Owner(Some(wr.as_global_scope().pipeline_id()))); document } diff --git a/components/script/script_runtime.rs b/components/script/script_runtime.rs index 658ace4c46a..ab7cb607985 100644 --- a/components/script/script_runtime.rs +++ b/components/script/script_runtime.rs @@ -178,7 +178,7 @@ unsafe extern "C" fn enqueue_job(_cx: *mut JSContext, _data: *mut c_void) -> bool { let result = panic::catch_unwind(AssertUnwindSafe(|| { let global = global_root_from_object(job.get()); - let pipeline = global.r().pipeline_id(); + let pipeline = global.r().as_global_scope().pipeline_id(); global.r().enqueue_promise_job(EnqueuedPromiseCallback { callback: PromiseJobCallback::new(job.get()), pipeline: pipeline, diff --git a/components/script/script_thread.rs b/components/script/script_thread.rs index 0b26647f3e8..8699a56742b 100644 --- a/components/script/script_thread.rs +++ b/components/script/script_thread.rs @@ -650,7 +650,7 @@ impl ScriptThread { let window = context.active_window(); let resize_event = window.steal_resize_event(); match resize_event { - Some(size) => resizes.push((window.pipeline_id(), size)), + Some(size) => resizes.push((window.upcast::().pipeline_id(), size)), None => () } } @@ -1501,7 +1501,7 @@ impl ScriptThread { // If root is being exited, shut down all contexts let context = self.root_browsing_context(); let window = context.active_window(); - if window.pipeline_id() == id { + if window.upcast::().pipeline_id() == id { debug!("shutting down layout for root context {:?}", id); shut_down_layout(&context); let _ = self.constellation_chan.send(ConstellationMsg::PipelineExited(id)); diff --git a/components/script/webdriver_handlers.rs b/components/script/webdriver_handlers.rs index 03281464765..870b3235d38 100644 --- a/components/script/webdriver_handlers.rs +++ b/components/script/webdriver_handlers.rs @@ -19,6 +19,7 @@ use dom::bindings::js::Root; use dom::bindings::str::DOMString; use dom::browsingcontext::BrowsingContext; use dom::element::Element; +use dom::globalscope::GlobalScope; use dom::htmlelement::HTMLElement; use dom::htmliframeelement::HTMLIFrameElement; use dom::htmlinputelement::HTMLInputElement; @@ -142,7 +143,7 @@ pub fn handle_get_frame_id(context: &BrowsingContext, } }; - let frame_id = window.map(|x| x.map(|x| x.pipeline_id())); + let frame_id = window.map(|x| x.map(|x| x.upcast::().pipeline_id())); reply.send(frame_id).unwrap() } From ae6af5172b5f09e9ba19d0beca026fd0ac39f8c8 Mon Sep 17 00:00:00 2001 From: Anthony Ramine Date: Sat, 1 Oct 2016 18:15:15 +0200 Subject: [PATCH 15/66] Introduce Reflectable::global_scope --- components/script/body.rs | 7 ++-- components/script/dom/bindings/global.rs | 36 +++++++++++++------ components/script/dom/bindings/iterable.rs | 3 +- components/script/dom/bindings/reflector.rs | 7 +++- components/script/dom/blob.rs | 2 +- components/script/dom/bluetooth.rs | 8 ++--- components/script/dom/bluetoothdevice.rs | 2 +- .../dom/bluetoothremotegattcharacteristic.rs | 4 +-- .../script/dom/bluetoothremotegattserver.rs | 4 +-- .../script/dom/bluetoothremotegattservice.rs | 20 +++++------ .../script/dom/canvasrenderingcontext2d.rs | 12 +++---- components/script/dom/dommatrixreadonly.rs | 26 +++++++------- components/script/dom/domquad.rs | 2 +- components/script/dom/eventtarget.rs | 3 +- components/script/dom/filereader.rs | 12 +++---- components/script/dom/formdata.rs | 4 +-- components/script/dom/htmllinkelement.rs | 2 +- components/script/dom/htmlscriptelement.rs | 2 +- components/script/dom/navigator.rs | 8 ++--- components/script/dom/request.rs | 4 +-- components/script/dom/response.rs | 4 +-- components/script/dom/serviceworker.rs | 3 +- .../script/dom/serviceworkercontainer.rs | 8 ++--- components/script/dom/storage.rs | 8 ++--- components/script/dom/testbinding.rs | 10 +++--- components/script/dom/url.rs | 2 +- components/script/dom/webglprogram.rs | 4 +-- .../script/dom/webglrenderingcontext.rs | 14 ++++---- components/script/dom/websocket.rs | 4 +-- components/script/dom/xmlhttprequest.rs | 11 +++--- 30 files changed, 116 insertions(+), 120 deletions(-) diff --git a/components/script/body.rs b/components/script/body.rs index 466523f394f..41886e0aee0 100644 --- a/components/script/body.rs +++ b/components/script/body.rs @@ -98,13 +98,14 @@ fn run_package_data_algorithm(object: &T, body_type: BodyType, mime_type: Ref>) -> Fallible { - let cx = object.global().r().get_cx(); + let global = object.global_scope(); + let cx = global.get_cx(); let mime = &*mime_type; match body_type { BodyType::Text => run_text_data_algorithm(bytes), BodyType::Json => run_json_data_algorithm(cx, bytes), - BodyType::Blob => run_blob_data_algorithm(object.global().r().as_global_scope(), bytes, mime), - BodyType::FormData => run_form_data_algorithm(object.global().r().as_global_scope(), bytes, mime), + BodyType::Blob => run_blob_data_algorithm(&global, bytes, mime), + BodyType::FormData => run_form_data_algorithm(&global, bytes, mime), } } diff --git a/components/script/dom/bindings/global.rs b/components/script/dom/bindings/global.rs index 0dbbba2c376..cf108e5e526 100644 --- a/components/script/dom/bindings/global.rs +++ b/components/script/dom/bindings/global.rs @@ -280,30 +280,44 @@ impl GlobalRoot { } } +/// Returns the global scope of the realm that the given DOM object's reflector was created in. +pub fn global_scope_from_reflector(reflector: &T) -> Root { + unsafe { global_scope_from_object(*reflector.reflector().get_jsobject()) } +} + /// Returns the global object of the realm that the given DOM object's reflector was created in. pub fn global_root_from_reflector(reflector: &T) -> GlobalRoot { unsafe { global_root_from_object(*reflector.reflector().get_jsobject()) } } -/// Returns the Rust global object from a JS global object. -#[allow(unrooted_must_root)] -unsafe fn global_root_from_global(global: *mut JSObject) -> GlobalRoot { +/// Returns the Rust global scope from a JS global object. +unsafe fn global_scope_from_global(global: *mut JSObject) -> Root { assert!(!global.is_null()); let clasp = JS_GetClass(global); assert!(((*clasp).flags & (JSCLASS_IS_DOMJSCLASS | JSCLASS_IS_GLOBAL)) != 0); - match root_from_object(global) { - Ok(window) => return GlobalRoot::Window(window), - Err(_) => (), - } + root_from_object(global).unwrap() +} - match root_from_object(global) { - Ok(worker) => return GlobalRoot::Worker(worker), - Err(_) => (), +/// Returns the Rust global object from a JS global object. +#[allow(unrooted_must_root)] +unsafe fn global_root_from_global(global: *mut JSObject) -> GlobalRoot { + let global_scope = global_scope_from_global(global); + if let Some(window) = global_scope.downcast::() { + return GlobalRoot::Window(Root::from_ref(window)); + } + if let Some(worker) = Root::downcast(global_scope) { + return GlobalRoot::Worker(worker); } - panic!("found DOM global that doesn't unwrap to Window or WorkerGlobalScope") } +/// Returns the global scope of the realm that the given JS object was created in. +pub unsafe fn global_scope_from_object(obj: *mut JSObject) -> Root { + assert!(!obj.is_null()); + let global = GetGlobalForObjectCrossCompartment(obj); + global_scope_from_global(global) +} + /// Returns the global object of the realm that the given JS object was created in. #[allow(unrooted_must_root)] pub unsafe fn global_root_from_object(obj: *mut JSObject) -> GlobalRoot { diff --git a/components/script/dom/bindings/iterable.rs b/components/script/dom/bindings/iterable.rs index 5a86dcf64d8..8e316336607 100644 --- a/components/script/dom/bindings/iterable.rs +++ b/components/script/dom/bindings/iterable.rs @@ -93,8 +93,7 @@ impl IterableIterator { iterable: JS::from_ref(iterable), index: Cell::new(0), }; - let global = iterable.global(); - reflect_dom_object(iterator, global.r().as_global_scope(), wrap) + reflect_dom_object(iterator, &*iterable.global_scope(), wrap) } /// Return the next value from the iterable object. diff --git a/components/script/dom/bindings/reflector.rs b/components/script/dom/bindings/reflector.rs index 74c039688f7..bb48cee0b1a 100644 --- a/components/script/dom/bindings/reflector.rs +++ b/components/script/dom/bindings/reflector.rs @@ -5,7 +5,7 @@ //! The `Reflector` struct. use dom::bindings::conversions::DerivedFrom; -use dom::bindings::global::{GlobalRoot, global_root_from_reflector}; +use dom::bindings::global::{GlobalRoot, global_root_from_reflector, global_scope_from_reflector}; use dom::bindings::js::Root; use dom::globalscope::GlobalScope; use js::jsapi::{HandleObject, JSContext, JSObject}; @@ -80,6 +80,11 @@ pub trait Reflectable { /// Returns the receiver's reflector. fn reflector(&self) -> &Reflector; + /// Returns the global scope of the realm that the Reflectable was created in. + fn global_scope(&self) -> Root where Self: Sized { + global_scope_from_reflector(self) + } + /// Returns the global object of the realm that the Reflectable was created in. fn global(&self) -> GlobalRoot where Self: Sized { global_root_from_reflector(self) diff --git a/components/script/dom/blob.rs b/components/script/dom/blob.rs index 011f547c96a..997edb52d6c 100644 --- a/components/script/dom/blob.rs +++ b/components/script/dom/blob.rs @@ -117,7 +117,7 @@ impl Blob { } }; - Blob::new(parent.global().r().as_global_scope(), blob_impl, relative_content_type.into()) + Blob::new(&parent.global_scope(), blob_impl, relative_content_type.into()) } // https://w3c.github.io/FileAPI/#constructorBlob diff --git a/components/script/dom/bluetooth.rs b/components/script/dom/bluetooth.rs index dd5d05d4f2a..db32bcd4edf 100644 --- a/components/script/dom/bluetooth.rs +++ b/components/script/dom/bluetooth.rs @@ -106,14 +106,12 @@ impl Bluetooth { // Step 12-13. match device { Ok(device) => { - let global = self.global(); - let global = global.r(); - let global = global.as_global_scope(); - let ad_data = BluetoothAdvertisingData::new(global, + let global = self.global_scope(); + let ad_data = BluetoothAdvertisingData::new(&global, device.appearance, device.tx_power, device.rssi); - Ok(BluetoothDevice::new(global, + Ok(BluetoothDevice::new(&global, DOMString::from(device.id), device.name.map(DOMString::from), &ad_data)) diff --git a/components/script/dom/bluetoothdevice.rs b/components/script/dom/bluetoothdevice.rs index 04327080cd4..c4ceaa333d0 100644 --- a/components/script/dom/bluetoothdevice.rs +++ b/components/script/dom/bluetoothdevice.rs @@ -67,7 +67,7 @@ impl BluetoothDeviceMethods for BluetoothDevice { // https://webbluetoothcg.github.io/web-bluetooth/#dom-bluetoothdevice-gatt fn Gatt(&self) -> Root { self.gatt.or_init(|| { - BluetoothRemoteGATTServer::new(self.global().r().as_global_scope(), self) + BluetoothRemoteGATTServer::new(&self.global_scope(), self) }) } } diff --git a/components/script/dom/bluetoothremotegattcharacteristic.rs b/components/script/dom/bluetoothremotegattcharacteristic.rs index 701a6ddd2a2..0dbb7c4670e 100644 --- a/components/script/dom/bluetoothremotegattcharacteristic.rs +++ b/components/script/dom/bluetoothremotegattcharacteristic.rs @@ -95,7 +95,7 @@ impl BluetoothRemoteGATTCharacteristic { let descriptor = receiver.recv().unwrap(); match descriptor { Ok(descriptor) => { - Ok(BluetoothRemoteGATTDescriptor::new(self.global().r().as_global_scope(), + Ok(BluetoothRemoteGATTDescriptor::new(&self.global_scope(), self, DOMString::from(descriptor.uuid), descriptor.instance_id)) @@ -126,7 +126,7 @@ impl BluetoothRemoteGATTCharacteristic { match descriptors_vec { Ok(descriptor_vec) => { Ok(descriptor_vec.into_iter() - .map(|desc| BluetoothRemoteGATTDescriptor::new(self.global().r().as_global_scope(), + .map(|desc| BluetoothRemoteGATTDescriptor::new(&self.global_scope(), self, DOMString::from(desc.uuid), desc.instance_id)) diff --git a/components/script/dom/bluetoothremotegattserver.rs b/components/script/dom/bluetoothremotegattserver.rs index 3a939614d36..7bb4d8fb05d 100644 --- a/components/script/dom/bluetoothremotegattserver.rs +++ b/components/script/dom/bluetoothremotegattserver.rs @@ -80,7 +80,7 @@ impl BluetoothRemoteGATTServer { let service = receiver.recv().unwrap(); match service { Ok(service) => { - Ok(BluetoothRemoteGATTService::new(self.global().r().as_global_scope(), + Ok(BluetoothRemoteGATTService::new(&self.global_scope(), &self.device.get(), DOMString::from(service.uuid), service.is_primary, @@ -112,7 +112,7 @@ impl BluetoothRemoteGATTServer { match services_vec { Ok(service_vec) => { Ok(service_vec.into_iter() - .map(|service| BluetoothRemoteGATTService::new(self.global().r().as_global_scope(), + .map(|service| BluetoothRemoteGATTService::new(&self.global_scope(), &self.device.get(), DOMString::from(service.uuid), service.is_primary, diff --git a/components/script/dom/bluetoothremotegattservice.rs b/components/script/dom/bluetoothremotegattservice.rs index 3a590b4738a..df1718ef403 100644 --- a/components/script/dom/bluetoothremotegattservice.rs +++ b/components/script/dom/bluetoothremotegattservice.rs @@ -84,10 +84,8 @@ impl BluetoothRemoteGATTService { let characteristic = receiver.recv().unwrap(); match characteristic { Ok(characteristic) => { - let global = self.global(); - let global = global.r(); - let global = global.as_global_scope(); - let properties = BluetoothCharacteristicProperties::new(global, + let global = self.global_scope(); + let properties = BluetoothCharacteristicProperties::new(&global, characteristic.broadcast, characteristic.read, characteristic.write_without_response, @@ -97,7 +95,7 @@ impl BluetoothRemoteGATTService { characteristic.authenticated_signed_writes, characteristic.reliable_write, characteristic.writable_auxiliaries); - Ok(BluetoothRemoteGATTCharacteristic::new(global, + Ok(BluetoothRemoteGATTCharacteristic::new(&global, self, DOMString::from(characteristic.uuid), &properties, @@ -130,10 +128,8 @@ impl BluetoothRemoteGATTService { match characteristics_vec { Ok(characteristic_vec) => { for characteristic in characteristic_vec { - let global = self.global(); - let global = global.r(); - let global = global.as_global_scope(); - let properties = BluetoothCharacteristicProperties::new(global, + let global = self.global_scope(); + let properties = BluetoothCharacteristicProperties::new(&global, characteristic.broadcast, characteristic.read, characteristic.write_without_response, @@ -143,7 +139,7 @@ impl BluetoothRemoteGATTService { characteristic.authenticated_signed_writes, characteristic.reliable_write, characteristic.writable_auxiliaries); - characteristics.push(BluetoothRemoteGATTCharacteristic::new(global, + characteristics.push(BluetoothRemoteGATTCharacteristic::new(&global, self, DOMString::from(characteristic.uuid), &properties, @@ -173,7 +169,7 @@ impl BluetoothRemoteGATTService { let service = receiver.recv().unwrap(); match service { Ok(service) => { - Ok(BluetoothRemoteGATTService::new(self.global().r().as_global_scope(), + Ok(BluetoothRemoteGATTService::new(&self.global_scope(), &self.device.get(), DOMString::from(service.uuid), service.is_primary, @@ -207,7 +203,7 @@ impl BluetoothRemoteGATTService { match services_vec { Ok(service_vec) => { Ok(service_vec.into_iter() - .map(|service| BluetoothRemoteGATTService::new(self.global().r().as_global_scope(), + .map(|service| BluetoothRemoteGATTService::new(&self.global_scope(), &self.device.get(), DOMString::from(service.uuid), service.is_primary, diff --git a/components/script/dom/canvasrenderingcontext2d.rs b/components/script/dom/canvasrenderingcontext2d.rs index 3872eb31272..3a965f14d6f 100644 --- a/components/script/dom/canvasrenderingcontext2d.rs +++ b/components/script/dom/canvasrenderingcontext2d.rs @@ -1016,12 +1016,12 @@ impl CanvasRenderingContext2DMethods for CanvasRenderingContext2D { let sw = cmp::max(1, sw.abs().to_u32().unwrap()); let sh = cmp::max(1, sh.abs().to_u32().unwrap()); - Ok(ImageData::new(self.global().r().as_global_scope(), sw, sh, None)) + Ok(ImageData::new(&self.global_scope(), sw, sh, None)) } // https://html.spec.whatwg.org/multipage/#dom-context-2d-createimagedata fn CreateImageData_(&self, imagedata: &ImageData) -> Fallible> { - Ok(ImageData::new(self.global().r().as_global_scope(), + Ok(ImageData::new(&self.global_scope(), imagedata.Width(), imagedata.Height(), None)) @@ -1077,7 +1077,7 @@ impl CanvasRenderingContext2DMethods for CanvasRenderingContext2D { chunk[2] = UNPREMULTIPLY_TABLE[256 * alpha + chunk[2] as usize]; } - Ok(ImageData::new(self.global().r().as_global_scope(), sw, sh, Some(data))) + Ok(ImageData::new(&self.global_scope(), sw, sh, Some(data))) } // https://html.spec.whatwg.org/multipage/#dom-context-2d-putimagedata @@ -1121,7 +1121,7 @@ impl CanvasRenderingContext2DMethods for CanvasRenderingContext2D { x1: Finite, y1: Finite) -> Root { - CanvasGradient::new(self.global().r().as_global_scope(), + CanvasGradient::new(&self.global_scope(), CanvasGradientStyle::Linear(LinearGradientStyle::new(*x0, *y0, *x1, @@ -1142,7 +1142,7 @@ impl CanvasRenderingContext2DMethods for CanvasRenderingContext2D { return Err(Error::IndexSize); } - Ok(CanvasGradient::new(self.global().r().as_global_scope(), + Ok(CanvasGradient::new(&self.global_scope(), CanvasGradientStyle::Radial(RadialGradientStyle::new(*x0, *y0, *r0, @@ -1182,7 +1182,7 @@ impl CanvasRenderingContext2DMethods for CanvasRenderingContext2D { } if let Ok(rep) = RepetitionStyle::from_str(&repetition) { - Ok(CanvasPattern::new(self.global().r().as_global_scope(), + Ok(CanvasPattern::new(&self.global_scope(), image_data, image_size, rep, diff --git a/components/script/dom/dommatrixreadonly.rs b/components/script/dom/dommatrixreadonly.rs index b643ef3131a..23feb88a348 100644 --- a/components/script/dom/dommatrixreadonly.rs +++ b/components/script/dom/dommatrixreadonly.rs @@ -464,50 +464,50 @@ impl DOMMatrixReadOnlyMethods for DOMMatrixReadOnly { // https://drafts.fxtf.org/geometry-1/#dom-dommatrixreadonly-translate fn Translate(&self, tx: f64, ty: f64, tz: f64) -> Root { - DOMMatrix::from_readonly(self.global().r().as_global_scope(), self).TranslateSelf(tx, ty, tz) + DOMMatrix::from_readonly(&self.global_scope(), self).TranslateSelf(tx, ty, tz) } // https://drafts.fxtf.org/geometry-1/#dom-dommatrixreadonly-scale fn Scale(&self, scaleX: f64, scaleY: Option, scaleZ: f64, originX: f64, originY: f64, originZ: f64) -> Root { - DOMMatrix::from_readonly(self.global().r().as_global_scope(), self) + DOMMatrix::from_readonly(&self.global_scope(), self) .ScaleSelf(scaleX, scaleY, scaleZ, originX, originY, originZ) } // https://drafts.fxtf.org/geometry-1/#dom-dommatrixreadonly-scale3d fn Scale3d(&self, scale: f64, originX: f64, originY: f64, originZ: f64) -> Root { - DOMMatrix::from_readonly(self.global().r().as_global_scope(), self) + DOMMatrix::from_readonly(&self.global_scope(), self) .Scale3dSelf(scale, originX, originY, originZ) } // https://drafts.fxtf.org/geometry-1/#dom-dommatrixreadonly-rotate fn Rotate(&self, rotX: f64, rotY: Option, rotZ: Option) -> Root { - DOMMatrix::from_readonly(self.global().r().as_global_scope(), self).RotateSelf(rotX, rotY, rotZ) + DOMMatrix::from_readonly(&self.global_scope(), self).RotateSelf(rotX, rotY, rotZ) } // https://drafts.fxtf.org/geometry-1/#dom-dommatrixreadonly-rotatefromvector fn RotateFromVector(&self, x: f64, y: f64) -> Root { - DOMMatrix::from_readonly(self.global().r().as_global_scope(), self).RotateFromVectorSelf(x, y) + DOMMatrix::from_readonly(&self.global_scope(), self).RotateFromVectorSelf(x, y) } // https://drafts.fxtf.org/geometry-1/#dom-dommatrixreadonly-rotateaxisangle fn RotateAxisAngle(&self, x: f64, y: f64, z: f64, angle: f64) -> Root { - DOMMatrix::from_readonly(self.global().r().as_global_scope(), self).RotateAxisAngleSelf(x, y, z, angle) + DOMMatrix::from_readonly(&self.global_scope(), self).RotateAxisAngleSelf(x, y, z, angle) } // https://drafts.fxtf.org/geometry-1/#dom-dommatrixreadonly-skewx fn SkewX(&self, sx: f64) -> Root { - DOMMatrix::from_readonly(self.global().r().as_global_scope(), self).SkewXSelf(sx) + DOMMatrix::from_readonly(&self.global_scope(), self).SkewXSelf(sx) } // https://drafts.fxtf.org/geometry-1/#dom-dommatrixreadonly-skewy fn SkewY(&self, sy: f64) -> Root { - DOMMatrix::from_readonly(self.global().r().as_global_scope(), self).SkewYSelf(sy) + DOMMatrix::from_readonly(&self.global_scope(), self).SkewYSelf(sy) } // https://drafts.fxtf.org/geometry-1/#dom-dommatrixreadonly-multiply fn Multiply(&self, other: &DOMMatrixInit) -> Fallible> { - DOMMatrix::from_readonly(self.global().r().as_global_scope(), self).MultiplySelf(&other) + DOMMatrix::from_readonly(&self.global_scope(), self).MultiplySelf(&other) } // https://drafts.fxtf.org/geometry-1/#dom-dommatrixreadonly-flipx @@ -518,7 +518,7 @@ impl DOMMatrixReadOnlyMethods for DOMMatrixReadOnly { 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0); let matrix = flip.post_mul(&self.matrix.borrow()); - DOMMatrix::new(self.global().r().as_global_scope(), is2D, matrix) + DOMMatrix::new(&self.global_scope(), is2D, matrix) } // https://drafts.fxtf.org/geometry-1/#dom-dommatrixreadonly-flipy @@ -529,12 +529,12 @@ impl DOMMatrixReadOnlyMethods for DOMMatrixReadOnly { 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0); let matrix = flip.post_mul(&self.matrix.borrow()); - DOMMatrix::new(self.global().r().as_global_scope(), is2D, matrix) + DOMMatrix::new(&self.global_scope(), is2D, matrix) } // https://drafts.fxtf.org/geometry-1/#dom-dommatrixreadonly-inverse fn Inverse(&self) -> Root { - DOMMatrix::from_readonly(self.global().r().as_global_scope(), self).InvertSelf() + DOMMatrix::from_readonly(&self.global_scope(), self).InvertSelf() } // https://drafts.fxtf.org/geometry-1/#dom-dommatrixreadonly-transformpoint @@ -542,7 +542,7 @@ impl DOMMatrixReadOnlyMethods for DOMMatrixReadOnly { let matrix = self.matrix.borrow(); let result = matrix.transform_point4d(&Point4D::new(point.x, point.y, point.z, point.w)); DOMPoint::new( - self.global().r().as_global_scope(), + &self.global_scope(), result.x as f64, result.y as f64, result.z as f64, diff --git a/components/script/dom/domquad.rs b/components/script/dom/domquad.rs index 238258889a8..f4a388df284 100644 --- a/components/script/dom/domquad.rs +++ b/components/script/dom/domquad.rs @@ -111,7 +111,7 @@ impl DOMQuadMethods for DOMQuad { let right = self.p1.X().max(self.p2.X()).max(self.p3.X()).max(self.p4.X()); let bottom = self.p1.Y().max(self.p2.Y()).max(self.p3.Y()).max(self.p4.Y()); - DOMRect::new(self.global().r().as_global_scope(), + DOMRect::new(&self.global_scope(), left, top, right - left, diff --git a/components/script/dom/eventtarget.rs b/components/script/dom/eventtarget.rs index fb647d3d590..af13822c456 100644 --- a/components/script/dom/eventtarget.rs +++ b/components/script/dom/eventtarget.rs @@ -500,8 +500,7 @@ impl EventTarget { bubbles: EventBubbles, cancelable: EventCancelable) -> Root { - let event = Event::new( - self.global().r().as_global_scope(), Atom::from(name), bubbles, cancelable); + let event = Event::new(&self.global_scope(), Atom::from(name), bubbles, cancelable); event.fire(self); diff --git a/components/script/dom/filereader.rs b/components/script/dom/filereader.rs index ac2aa37ee56..afd291c8f62 100644 --- a/components/script/dom/filereader.rs +++ b/components/script/dom/filereader.rs @@ -115,8 +115,7 @@ impl FileReader { fr.change_ready_state(FileReaderReadyState::Done); *fr.result.borrow_mut() = None; - let global = fr.r().global(); - let exception = DOMException::new(global.r().as_global_scope(), error); + let exception = DOMException::new(&fr.global_scope(), error); fr.error.set(Some(&exception)); fr.dispatch_progress_event(atom!("error"), 0, None); @@ -290,8 +289,7 @@ impl FileReaderMethods for FileReader { // Steps 1 & 3 *self.result.borrow_mut() = None; - let global = self.global(); - let exception = DOMException::new(global.r().as_global_scope(), DOMErrorName::AbortError); + let exception = DOMException::new(&self.global_scope(), DOMErrorName::AbortError); self.error.set(Some(&exception)); self.terminate_ongoing_reading(); @@ -319,8 +317,7 @@ impl FileReaderMethods for FileReader { impl FileReader { fn dispatch_progress_event(&self, type_: Atom, loaded: u64, total: Option) { - let global = self.global(); - let progressevent = ProgressEvent::new(global.r().as_global_scope(), + let progressevent = ProgressEvent::new(&self.global_scope(), type_, EventBubbles::DoesNotBubble, EventCancelable::NotCancelable, total.is_some(), loaded, total.unwrap_or(0)); progressevent.upcast::().fire(self.upcast()); @@ -338,8 +335,7 @@ impl FileReader { } // Step 2 if blob.IsClosed() { - let global = self.global(); - let exception = DOMException::new(global.r().as_global_scope(), DOMErrorName::InvalidStateError); + let exception = DOMException::new(&self.global_scope(), DOMErrorName::InvalidStateError); self.error.set(Some(&exception)); self.dispatch_progress_event(atom!("error"), 0, None); diff --git a/components/script/dom/formdata.rs b/components/script/dom/formdata.rs index e5bdc6ca1d5..50747245c21 100644 --- a/components/script/dom/formdata.rs +++ b/components/script/dom/formdata.rs @@ -146,8 +146,6 @@ impl FormDataMethods for FormData { impl FormData { fn get_file(&self, blob: &Blob, opt_filename: Option) -> Root { - let global = self.global(); - let name = match opt_filename { Some(filename) => DOMString::from(filename.0), None => DOMString::from(""), @@ -155,7 +153,7 @@ impl FormData { let bytes = blob.get_bytes().unwrap_or(vec![]); - File::new(global.r().as_global_scope(), BlobImpl::new_from_bytes(bytes), name, None, "") + File::new(&self.global_scope(), BlobImpl::new_from_bytes(bytes), name, None, "") } pub fn datums(&self) -> Vec { diff --git a/components/script/dom/htmllinkelement.rs b/components/script/dom/htmllinkelement.rs index f74946ba841..b387990b68e 100644 --- a/components/script/dom/htmllinkelement.rs +++ b/components/script/dom/htmllinkelement.rs @@ -267,7 +267,7 @@ impl HTMLLinkElement { credentials_mode: CredentialsMode::Include, use_url_credentials: true, origin: document.url().clone(), - pipeline_id: Some(self.global().r().as_global_scope().pipeline_id()), + pipeline_id: Some(self.global_scope().pipeline_id()), referrer_url: Some(document.url().clone()), referrer_policy: referrer_policy, .. RequestInit::default() diff --git a/components/script/dom/htmlscriptelement.rs b/components/script/dom/htmlscriptelement.rs index 4cf7e2df59c..2132d41edf7 100644 --- a/components/script/dom/htmlscriptelement.rs +++ b/components/script/dom/htmlscriptelement.rs @@ -242,7 +242,7 @@ fn fetch_a_classic_script(script: &HTMLScriptElement, _ => CredentialsMode::Include, }, origin: doc.url().clone(), - pipeline_id: Some(script.global().r().as_global_scope().pipeline_id()), + pipeline_id: Some(script.global_scope().pipeline_id()), referrer_url: Some(doc.url().clone()), referrer_policy: doc.get_referrer_policy(), .. RequestInit::default() diff --git a/components/script/dom/navigator.rs b/components/script/dom/navigator.rs index d4e4629e486..51dbf5bbfa7 100644 --- a/components/script/dom/navigator.rs +++ b/components/script/dom/navigator.rs @@ -79,7 +79,7 @@ impl NavigatorMethods for Navigator { // https://webbluetoothcg.github.io/web-bluetooth/#dom-navigator-bluetooth fn Bluetooth(&self) -> Root { - self.bluetooth.or_init(|| Bluetooth::new(self.global().r().as_global_scope())) + self.bluetooth.or_init(|| Bluetooth::new(&self.global_scope())) } // https://html.spec.whatwg.org/multipage/#navigatorlanguage @@ -89,12 +89,12 @@ impl NavigatorMethods for Navigator { // https://html.spec.whatwg.org/multipage/#dom-navigator-plugins fn Plugins(&self) -> Root { - self.plugins.or_init(|| PluginArray::new(self.global().r().as_global_scope())) + self.plugins.or_init(|| PluginArray::new(&self.global_scope())) } // https://html.spec.whatwg.org/multipage/#dom-navigator-mimetypes fn MimeTypes(&self) -> Root { - self.mime_types.or_init(|| MimeTypeArray::new(self.global().r().as_global_scope())) + self.mime_types.or_init(|| MimeTypeArray::new(&self.global_scope())) } // https://html.spec.whatwg.org/multipage/#dom-navigator-javaenabled @@ -105,7 +105,7 @@ impl NavigatorMethods for Navigator { // https://w3c.github.io/ServiceWorker/#navigator-service-worker-attribute fn ServiceWorker(&self) -> Root { self.service_worker.or_init(|| { - ServiceWorkerContainer::new(self.global().r().as_global_scope()) + ServiceWorkerContainer::new(&self.global_scope()) }) } diff --git a/components/script/dom/request.rs b/components/script/dom/request.rs index 4a9343b76b4..1060f4b963b 100644 --- a/components/script/dom/request.rs +++ b/components/script/dom/request.rs @@ -305,7 +305,7 @@ impl Request { let r = Request::from_net_request(global, false, request); - r.headers.or_init(|| Headers::for_request(r.global().r().as_global_scope())); + r.headers.or_init(|| Headers::for_request(&r.global_scope())); // Step 27 let mut headers_copy = r.Headers(); @@ -549,7 +549,7 @@ impl RequestMethods for Request { // https://fetch.spec.whatwg.org/#dom-request-headers fn Headers(&self) -> Root { - self.headers.or_init(|| Headers::new(self.global().r().as_global_scope())) + self.headers.or_init(|| Headers::new(&self.global_scope())) } // https://fetch.spec.whatwg.org/#dom-request-type diff --git a/components/script/dom/response.rs b/components/script/dom/response.rs index a90a551b20a..5306a152156 100644 --- a/components/script/dom/response.rs +++ b/components/script/dom/response.rs @@ -293,7 +293,7 @@ impl ResponseMethods for Response { // https://fetch.spec.whatwg.org/#dom-response-headers fn Headers(&self) -> Root { - self.headers_reflector.or_init(|| Headers::for_response(self.global().r().as_global_scope())) + self.headers_reflector.or_init(|| Headers::for_response(&self.global_scope())) } // https://fetch.spec.whatwg.org/#dom-response-clone @@ -302,7 +302,7 @@ impl ResponseMethods for Response { // TODO: This step relies on body and stream, which are still unimplemented. // Step 2 - let new_response = Response::new(self.global().r().as_global_scope()); + let new_response = Response::new(&self.global_scope()); new_response.Headers().set_guard(self.Headers().get_guard()); // https://fetch.spec.whatwg.org/#concept-response-clone diff --git a/components/script/dom/serviceworker.rs b/components/script/dom/serviceworker.rs index 6f2dce2f8e0..3b3cd58eee4 100644 --- a/components/script/dom/serviceworker.rs +++ b/components/script/dom/serviceworker.rs @@ -90,8 +90,7 @@ impl ServiceWorkerMethods for ServiceWorker { let data = try!(StructuredCloneData::write(cx, message)); let msg_vec = DOMMessage(data.move_to_arraybuffer()); let _ = - self.global().r() - .as_global_scope() + self.global_scope() .constellation_chan() .send(ScriptMsg::ForwardDOMMessage(msg_vec, self.scope_url.clone())); Ok(()) diff --git a/components/script/dom/serviceworkercontainer.rs b/components/script/dom/serviceworkercontainer.rs index 993241445d5..12bab94fe12 100644 --- a/components/script/dom/serviceworkercontainer.rs +++ b/components/script/dom/serviceworkercontainer.rs @@ -95,14 +95,12 @@ impl ServiceWorkerContainerMethods for ServiceWorkerContainer { return Err(Error::Type("Scope URL contains forbidden characters".to_owned())); } - let global = self.global(); - let global = global.r(); - let global_scope = global.as_global_scope(); - let worker_registration = ServiceWorkerRegistration::new(global_scope, + let global = self.global_scope(); + let worker_registration = ServiceWorkerRegistration::new(&global, script_url, scope.clone(), self); - ScriptThread::set_registration(scope, &*worker_registration, global_scope.pipeline_id()); + ScriptThread::set_registration(scope, &*worker_registration, global.pipeline_id()); Ok(worker_registration) } } diff --git a/components/script/dom/storage.rs b/components/script/dom/storage.rs index 30afd8719c4..7152e27acc7 100644 --- a/components/script/dom/storage.rs +++ b/components/script/dom/storage.rs @@ -185,13 +185,11 @@ impl Runnable for StorageEventRunnable { let this = *self; let storage_root = this.element.root(); let storage = storage_root.r(); - let global_root = storage.global(); - let global_ref = global_root.r(); - let ev_window = global_ref.as_window(); + let global = storage.global_scope(); let ev_url = storage.get_url(); let storage_event = StorageEvent::new( - global_ref.as_global_scope(), + &global, atom!("storage"), EventBubbles::DoesNotBubble, EventCancelable::NotCancelable, this.key.map(DOMString::from), this.old_value.map(DOMString::from), this.new_value.map(DOMString::from), @@ -206,7 +204,7 @@ impl Runnable for StorageEventRunnable { assert!(UrlHelper::SameOrigin(&ev_url, &it_window.get_url())); // TODO: Such a Document object is not necessarily fully active, but events fired on such // objects are ignored by the event loop until the Document becomes fully active again. - if ev_window.upcast::().pipeline_id() != it_window.upcast::().pipeline_id() { + if global.pipeline_id() != it_window.upcast::().pipeline_id() { storage_event.upcast::().fire(it_window.upcast()); } } diff --git a/components/script/dom/testbinding.rs b/components/script/dom/testbinding.rs index 62714dfc220..0ebeac1ccb1 100644 --- a/components/script/dom/testbinding.rs +++ b/components/script/dom/testbinding.rs @@ -114,7 +114,7 @@ impl TestBindingMethods for TestBinding { fn EnumAttribute(&self) -> TestEnum { TestEnum::_empty } fn SetEnumAttribute(&self, _: TestEnum) {} fn InterfaceAttribute(&self) -> Root { - Blob::new(self.global().r().as_global_scope(), BlobImpl::new_from_bytes(vec![]), "".to_owned()) + Blob::new(&self.global_scope(), BlobImpl::new_from_bytes(vec![]), "".to_owned()) } fn SetInterfaceAttribute(&self, _: &Blob) {} fn UnionAttribute(&self) -> HTMLElementOrLong { HTMLElementOrLong::Long(0) } @@ -210,7 +210,7 @@ impl TestBindingMethods for TestBinding { fn SetAttr_to_automatically_rename(&self, _: DOMString) {} fn GetEnumAttributeNullable(&self) -> Option { Some(TestEnum::_empty) } fn GetInterfaceAttributeNullable(&self) -> Option> { - Some(Blob::new(self.global().r().as_global_scope(), BlobImpl::new_from_bytes(vec![]), "".to_owned())) + Some(Blob::new(&self.global_scope(), BlobImpl::new_from_bytes(vec![]), "".to_owned())) } fn SetInterfaceAttributeNullable(&self, _: Option<&Blob>) {} fn GetInterfaceAttributeWeak(&self) -> Option> { @@ -265,7 +265,7 @@ impl TestBindingMethods for TestBinding { fn ReceiveByteString(&self) -> ByteString { ByteString::new(vec!()) } fn ReceiveEnum(&self) -> TestEnum { TestEnum::_empty } fn ReceiveInterface(&self) -> Root { - Blob::new(self.global().r().as_global_scope(), BlobImpl::new_from_bytes(vec![]), "".to_owned()) + Blob::new(&self.global_scope(), BlobImpl::new_from_bytes(vec![]), "".to_owned()) } fn ReceiveAny(&self, _: *mut JSContext) -> JSVal { NullValue() } fn ReceiveObject(&self, cx: *mut JSContext) -> NonZero<*mut JSObject> { @@ -288,7 +288,7 @@ impl TestBindingMethods for TestBinding { } fn ReceiveSequence(&self) -> Vec { vec![1] } fn ReceiveInterfaceSequence(&self) -> Vec> { - vec![Blob::new(self.global().r().as_global_scope(), BlobImpl::new_from_bytes(vec![]), "".to_owned())] + vec![Blob::new(&self.global_scope(), BlobImpl::new_from_bytes(vec![]), "".to_owned())] } fn ReceiveNullableBoolean(&self) -> Option { Some(false) } @@ -309,7 +309,7 @@ impl TestBindingMethods for TestBinding { fn ReceiveNullableByteString(&self) -> Option { Some(ByteString::new(vec!())) } fn ReceiveNullableEnum(&self) -> Option { Some(TestEnum::_empty) } fn ReceiveNullableInterface(&self) -> Option> { - Some(Blob::new(self.global().r().as_global_scope(), BlobImpl::new_from_bytes(vec![]), "".to_owned())) + Some(Blob::new(&self.global_scope(), BlobImpl::new_from_bytes(vec![]), "".to_owned())) } fn ReceiveNullableObject(&self, cx: *mut JSContext) -> Option> { self.GetObjectAttributeNullable(cx) diff --git a/components/script/dom/url.rs b/components/script/dom/url.rs index 5fd4a9b005f..2d5968e9e07 100644 --- a/components/script/dom/url.rs +++ b/components/script/dom/url.rs @@ -285,7 +285,7 @@ impl URLMethods for URL { // https://url.spec.whatwg.org/#dom-url-searchparams fn SearchParams(&self) -> Root { self.search_params.or_init(|| { - URLSearchParams::new(self.global().r().as_global_scope(), Some(self)) + URLSearchParams::new(&self.global_scope(), Some(self)) }) } diff --git a/components/script/dom/webglprogram.rs b/components/script/dom/webglprogram.rs index 4b3b39b05cc..5c2648de4b9 100644 --- a/components/script/dom/webglprogram.rs +++ b/components/script/dom/webglprogram.rs @@ -230,7 +230,7 @@ impl WebGLProgram { .unwrap(); receiver.recv().unwrap().map(|(size, ty, name)| - WebGLActiveInfo::new(self.global().r().as_global_scope(), size, ty, DOMString::from(name))) + WebGLActiveInfo::new(&self.global_scope(), size, ty, DOMString::from(name))) } /// glGetActiveAttrib @@ -244,7 +244,7 @@ impl WebGLProgram { .unwrap(); receiver.recv().unwrap().map(|(size, ty, name)| - WebGLActiveInfo::new(self.global().r().as_global_scope(), size, ty, DOMString::from(name))) + WebGLActiveInfo::new(&self.global_scope(), size, ty, DOMString::from(name))) } /// glGetAttribLocation diff --git a/components/script/dom/webglrenderingcontext.rs b/components/script/dom/webglrenderingcontext.rs index 1b29bd47621..5b1f20a6218 100644 --- a/components/script/dom/webglrenderingcontext.rs +++ b/components/script/dom/webglrenderingcontext.rs @@ -1154,27 +1154,27 @@ impl WebGLRenderingContextMethods for WebGLRenderingContext { // generated objects, either here or in the webgl thread // https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.5 fn CreateBuffer(&self) -> Option> { - WebGLBuffer::maybe_new(self.global().r().as_global_scope(), self.ipc_renderer.clone()) + WebGLBuffer::maybe_new(&self.global_scope(), self.ipc_renderer.clone()) } // https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.6 fn CreateFramebuffer(&self) -> Option> { - WebGLFramebuffer::maybe_new(self.global().r().as_global_scope(), self.ipc_renderer.clone()) + WebGLFramebuffer::maybe_new(&self.global_scope(), self.ipc_renderer.clone()) } // https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.7 fn CreateRenderbuffer(&self) -> Option> { - WebGLRenderbuffer::maybe_new(self.global().r().as_global_scope(), self.ipc_renderer.clone()) + WebGLRenderbuffer::maybe_new(&self.global_scope(), self.ipc_renderer.clone()) } // https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.8 fn CreateTexture(&self) -> Option> { - WebGLTexture::maybe_new(self.global().r().as_global_scope(), self.ipc_renderer.clone()) + WebGLTexture::maybe_new(&self.global_scope(), self.ipc_renderer.clone()) } // https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.9 fn CreateProgram(&self) -> Option> { - WebGLProgram::maybe_new(self.global().r().as_global_scope(), self.ipc_renderer.clone()) + WebGLProgram::maybe_new(&self.global_scope(), self.ipc_renderer.clone()) } // https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.9 @@ -1186,7 +1186,7 @@ impl WebGLRenderingContextMethods for WebGLRenderingContext { return None; } } - WebGLShader::maybe_new(self.global().r().as_global_scope(), self.ipc_renderer.clone(), shader_type) + WebGLShader::maybe_new(&self.global_scope(), self.ipc_renderer.clone(), shader_type) } // https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.5 @@ -1480,7 +1480,7 @@ impl WebGLRenderingContextMethods for WebGLRenderingContext { name: DOMString) -> Option> { program.and_then(|p| { handle_potential_webgl_error!(self, p.get_uniform_location(name), None) - .map(|location| WebGLUniformLocation::new(self.global().r().as_global_scope(), location, p.id())) + .map(|location| WebGLUniformLocation::new(&self.global_scope(), location, p.id())) }) } diff --git a/components/script/dom/websocket.rs b/components/script/dom/websocket.rs index 4e86241f36a..a7bf55b6757 100644 --- a/components/script/dom/websocket.rs +++ b/components/script/dom/websocket.rs @@ -535,8 +535,6 @@ impl Runnable for CloseTask { fn handler(self: Box) { let ws = self.address.root(); - let ws = ws.r(); - let global = ws.global(); if ws.ready_state.get() == WebSocketRequestState::Closed { // Do nothing if already closed. @@ -558,7 +556,7 @@ impl Runnable for CloseTask { let clean_close = !self.failed; let code = self.code.unwrap_or(close_code::NO_STATUS); let reason = DOMString::from(self.reason.unwrap_or("".to_owned())); - let close_event = CloseEvent::new(global.r().as_global_scope(), + let close_event = CloseEvent::new(&ws.global_scope(), atom!("close"), EventBubbles::DoesNotBubble, EventCancelable::NotCancelable, diff --git a/components/script/dom/xmlhttprequest.rs b/components/script/dom/xmlhttprequest.rs index 0cf5381767d..fe99410419b 100644 --- a/components/script/dom/xmlhttprequest.rs +++ b/components/script/dom/xmlhttprequest.rs @@ -283,8 +283,7 @@ impl LoadOrigin for XMLHttpRequest { } fn pipeline_id(&self) -> Option { - let global = self.global(); - Some(global.r().as_global_scope().pipeline_id()) + Some(self.global_scope().pipeline_id()) } } @@ -859,8 +858,7 @@ impl XMLHttpRequest { fn change_ready_state(&self, rs: XMLHttpRequestState) { assert!(self.ready_state.get() != rs); self.ready_state.set(rs); - let global = self.global(); - let event = Event::new(global.r().as_global_scope(), + let event = Event::new(&self.global_scope(), atom!("readystatechange"), EventBubbles::DoesNotBubble, EventCancelable::Cancelable); @@ -1049,8 +1047,7 @@ impl XMLHttpRequest { } fn dispatch_progress_event(&self, upload: bool, type_: Atom, loaded: u64, total: Option) { - let global = self.global(); - let progressevent = ProgressEvent::new(global.r().as_global_scope(), + let progressevent = ProgressEvent::new(&self.global_scope(), type_, EventBubbles::DoesNotBubble, EventCancelable::NotCancelable, @@ -1118,7 +1115,7 @@ impl XMLHttpRequest { // Step 3, 4 let bytes = self.response.borrow().to_vec(); - let blob = Blob::new(self.global().r().as_global_scope(), BlobImpl::new_from_bytes(bytes), mime); + let blob = Blob::new(&self.global_scope(), BlobImpl::new_from_bytes(bytes), mime); self.response_blob.set(Some(blob.r())); blob } From 896d8d4781ebce2a0884dd0d53412db7ac919aea Mon Sep 17 00:00:00 2001 From: Anthony Ramine Date: Sat, 1 Oct 2016 18:21:06 +0200 Subject: [PATCH 16/66] Make throw_dom_exception take a &GlobalScope --- components/script/dom/bindings/codegen/CodegenRust.py | 10 +++++----- components/script/dom/bindings/error.rs | 7 ++++--- components/script/dom/xmlhttprequest.rs | 3 +-- 3 files changed, 10 insertions(+), 10 deletions(-) diff --git a/components/script/dom/bindings/codegen/CodegenRust.py b/components/script/dom/bindings/codegen/CodegenRust.py index 7e7cb4144db..3bc6f088a23 100644 --- a/components/script/dom/bindings/codegen/CodegenRust.py +++ b/components/script/dom/bindings/codegen/CodegenRust.py @@ -826,7 +826,7 @@ def getJSToNativeConversionInfo(type, descriptorProvider, failureCode=None, match Promise::Resolve(promiseGlobal.r(), cx, valueToResolve.handle()) { Ok(value) => value, Err(error) => { - throw_dom_exception(cx, promiseGlobal.r(), error); + throw_dom_exception(cx, promiseGlobal.r().as_global_scope(), error); $*{exceptionCode} } } @@ -3168,16 +3168,15 @@ class CGCallGenerator(CGThing): if isFallible: if static: - glob = "" + glob = "global.r().as_global_scope()" else: - glob = " let global = global_root_from_reflector(this);\n" + glob = "&global_scope_from_reflector(this)" self.cgRoot.append(CGGeneric( "let result = match result {\n" " Ok(result) => result,\n" " Err(e) => {\n" - "%s" - " throw_dom_exception(cx, global.r(), e);\n" + " throw_dom_exception(cx, %s, e);\n" " return%s;\n" " },\n" "};" % (glob, errorResult))) @@ -5504,6 +5503,7 @@ def generate_imports(config, cgthings, descriptors, callbacks=None, dictionaries 'dom::bindings::global::global_root_from_object', 'dom::bindings::global::global_root_from_object_maybe_wrapped', 'dom::bindings::global::global_root_from_reflector', + 'dom::bindings::global::global_scope_from_reflector', 'dom::bindings::interface::ConstructorClassHook', 'dom::bindings::interface::InterfaceConstructorBehavior', 'dom::bindings::interface::NonCallbackInterfaceObjectClass', diff --git a/components/script/dom/bindings/error.rs b/components/script/dom/bindings/error.rs index 14725b33303..0b4249e7405 100644 --- a/components/script/dom/bindings/error.rs +++ b/components/script/dom/bindings/error.rs @@ -11,6 +11,7 @@ use dom::bindings::conversions::root_from_object; use dom::bindings::global::{GlobalRef, global_root_from_context}; use dom::bindings::str::USVString; use dom::domexception::{DOMErrorName, DOMException}; +use dom::globalscope::GlobalScope; use js::error::{throw_range_error, throw_type_error}; use js::jsapi::HandleObject; use js::jsapi::JSContext; @@ -87,7 +88,7 @@ pub type Fallible = Result; pub type ErrorResult = Fallible<()>; /// Set a pending exception for the given `result` on `cx`. -pub unsafe fn throw_dom_exception(cx: *mut JSContext, global: GlobalRef, result: Error) { +pub unsafe fn throw_dom_exception(cx: *mut JSContext, global: &GlobalScope, result: Error) { let code = match result { Error::IndexSize => DOMErrorName::IndexSizeError, Error::NotFound => DOMErrorName::NotFoundError, @@ -127,7 +128,7 @@ pub unsafe fn throw_dom_exception(cx: *mut JSContext, global: GlobalRef, result: }; assert!(!JS_IsExceptionPending(cx)); - let exception = DOMException::new(global.as_global_scope(), code); + let exception = DOMException::new(global, code); rooted!(in(cx) let mut thrown = UndefinedValue()); exception.to_jsval(cx, thrown.handle_mut()); JS_SetPendingException(cx, thrown.handle()); @@ -272,7 +273,7 @@ impl Error { /// Convert this error value to a JS value, consuming it in the process. pub unsafe fn to_jsval(self, cx: *mut JSContext, global: GlobalRef, rval: MutableHandleValue) { assert!(!JS_IsExceptionPending(cx)); - throw_dom_exception(cx, global, self); + throw_dom_exception(cx, global.as_global_scope(), self); assert!(JS_IsExceptionPending(cx)); assert!(JS_GetPendingException(cx, rval)); JS_ClearPendingException(cx); diff --git a/components/script/dom/xmlhttprequest.rs b/components/script/dom/xmlhttprequest.rs index fe99410419b..3994334ba6b 100644 --- a/components/script/dom/xmlhttprequest.rs +++ b/components/script/dom/xmlhttprequest.rs @@ -973,9 +973,8 @@ impl XMLHttpRequest { if self.ready_state.get() == XMLHttpRequestState::HeadersReceived { self.ready_state.set(XMLHttpRequestState::Loading); } - let global = self.global(); let event = Event::new( - global.r().as_global_scope(), + &self.global_scope(), atom!("readystatechange"), EventBubbles::DoesNotBubble, EventCancelable::Cancelable); From a8c05c6962849f921bc0aee2d7c3dfa600caec30 Mon Sep 17 00:00:00 2001 From: Anthony Ramine Date: Sat, 1 Oct 2016 18:28:44 +0200 Subject: [PATCH 17/66] Make CanvasRenderingContext2d::new take a &GlobalScope --- components/script/dom/canvasrenderingcontext2d.rs | 10 +++++----- components/script/dom/htmlcanvaselement.rs | 3 ++- 2 files changed, 7 insertions(+), 6 deletions(-) diff --git a/components/script/dom/canvasrenderingcontext2d.rs b/components/script/dom/canvasrenderingcontext2d.rs index 3a965f14d6f..c95ada7054d 100644 --- a/components/script/dom/canvasrenderingcontext2d.rs +++ b/components/script/dom/canvasrenderingcontext2d.rs @@ -20,7 +20,6 @@ use dom::bindings::codegen::Bindings::WindowBinding::WindowMethods; use dom::bindings::codegen::UnionTypes::HTMLImageElementOrHTMLCanvasElementOrCanvasRenderingContext2D; use dom::bindings::codegen::UnionTypes::StringOrCanvasGradientOrCanvasPattern; use dom::bindings::error::{Error, ErrorResult, Fallible}; -use dom::bindings::global::GlobalRef; use dom::bindings::inheritance::Castable; use dom::bindings::js::{JS, LayoutJS, Root}; use dom::bindings::num::Finite; @@ -28,6 +27,7 @@ use dom::bindings::reflector::{Reflectable, Reflector, reflect_dom_object}; use dom::bindings::str::DOMString; use dom::canvasgradient::{CanvasGradient, CanvasGradientStyle, ToFillOrStrokeStyle}; use dom::canvaspattern::CanvasPattern; +use dom::globalscope::GlobalScope; use dom::htmlcanvaselement::HTMLCanvasElement; use dom::htmlcanvaselement::utils as canvas_utils; use dom::htmlimageelement::HTMLImageElement; @@ -117,12 +117,12 @@ impl CanvasContextState { } impl CanvasRenderingContext2D { - fn new_inherited(global: GlobalRef, + fn new_inherited(global: &GlobalScope, canvas: &HTMLCanvasElement, size: Size2D) -> CanvasRenderingContext2D { let (sender, receiver) = ipc::channel().unwrap(); - let constellation_chan = global.as_global_scope().constellation_chan(); + let constellation_chan = global.constellation_chan(); constellation_chan.send(ConstellationMsg::CreateCanvasPaintThread(size, sender)).unwrap(); let ipc_renderer = receiver.recv().unwrap(); CanvasRenderingContext2D { @@ -135,12 +135,12 @@ impl CanvasRenderingContext2D { } } - pub fn new(global: GlobalRef, + pub fn new(global: &GlobalScope, canvas: &HTMLCanvasElement, size: Size2D) -> Root { reflect_dom_object(box CanvasRenderingContext2D::new_inherited(global, canvas, size), - global.as_global_scope(), + global, CanvasRenderingContext2DBinding::Wrap) } diff --git a/components/script/dom/htmlcanvaselement.rs b/components/script/dom/htmlcanvaselement.rs index f4a13836eb1..a7111f7866e 100644 --- a/components/script/dom/htmlcanvaselement.rs +++ b/components/script/dom/htmlcanvaselement.rs @@ -20,6 +20,7 @@ use dom::bindings::str::DOMString; use dom::canvasrenderingcontext2d::{CanvasRenderingContext2D, LayoutCanvasRenderingContext2DHelpers}; use dom::document::Document; use dom::element::{AttributeMutation, Element, RawLayoutElementHelpers}; +use dom::globalscope::GlobalScope; use dom::htmlelement::HTMLElement; use dom::node::{Node, window_from_node}; use dom::virtualmethods::VirtualMethods; @@ -142,7 +143,7 @@ impl HTMLCanvasElement { if self.context.borrow().is_none() { let window = window_from_node(self); let size = self.get_size(); - let context = CanvasRenderingContext2D::new(GlobalRef::Window(window.r()), self, size); + let context = CanvasRenderingContext2D::new(window.upcast::(), self, size); *self.context.borrow_mut() = Some(CanvasContext::Context2d(JS::from_ref(&*context))); } From ac5a4adf5fcbab26219b2a3fa31cac037ea8abd5 Mon Sep 17 00:00:00 2001 From: Anthony Ramine Date: Sat, 1 Oct 2016 21:00:17 +0200 Subject: [PATCH 18/66] Make Promise::new take a &GlobalScope --- components/script/body.rs | 2 +- components/script/dom/bluetooth.rs | 2 +- components/script/dom/promise.rs | 3 ++- components/script/dom/testbinding.rs | 8 ++++---- components/script/fetch.rs | 5 +++-- 5 files changed, 11 insertions(+), 9 deletions(-) diff --git a/components/script/body.rs b/components/script/body.rs index 41886e0aee0..ade32161549 100644 --- a/components/script/body.rs +++ b/components/script/body.rs @@ -42,7 +42,7 @@ pub enum FetchedData { // https://fetch.spec.whatwg.org/#concept-body-consume-body #[allow(unrooted_must_root)] pub fn consume_body(object: &T, body_type: BodyType) -> Rc { - let promise = Promise::new(object.global().r()); + let promise = Promise::new(&object.global_scope()); // Step 1 if object.get_body_used() || object.is_locked() { diff --git a/components/script/dom/bluetooth.rs b/components/script/dom/bluetooth.rs index db32bcd4edf..02bccb80f91 100644 --- a/components/script/dom/bluetooth.rs +++ b/components/script/dom/bluetooth.rs @@ -276,7 +276,7 @@ fn canonicalize_filter(filter: &BluetoothRequestDeviceFilter) -> Fallible(global_ref: GlobalRef, bluetooth_result: Fallible) -> Rc { - let p = Promise::new(global_ref); + let p = Promise::new(global_ref.as_global_scope()); match bluetooth_result { Ok(v) => p.resolve_native(p.global().r().get_cx(), &v), Err(e) => p.reject_error(p.global().r().get_cx(), e), diff --git a/components/script/dom/promise.rs b/components/script/dom/promise.rs index 5fd1ef6f85e..867be7809d3 100644 --- a/components/script/dom/promise.rs +++ b/components/script/dom/promise.rs @@ -18,6 +18,7 @@ use dom::bindings::error::{Error, Fallible}; use dom::bindings::global::GlobalRef; use dom::bindings::js::MutHeapJSVal; use dom::bindings::reflector::{Reflectable, MutReflectable, Reflector}; +use dom::globalscope::GlobalScope; use dom::promisenativehandler::PromiseNativeHandler; use js::conversions::ToJSValConvertible; use js::jsapi::{CallOriginalPromiseResolve, CallOriginalPromiseReject, CallOriginalPromiseThen}; @@ -70,7 +71,7 @@ impl Drop for Promise { impl Promise { #[allow(unsafe_code)] - pub fn new(global: GlobalRef) -> Rc { + pub fn new(global: &GlobalScope) -> Rc { let cx = global.get_cx(); rooted!(in(cx) let mut obj = ptr::null_mut()); unsafe { diff --git a/components/script/dom/testbinding.rs b/components/script/dom/testbinding.rs index 0ebeac1ccb1..fdb20fc5114 100644 --- a/components/script/dom/testbinding.rs +++ b/components/script/dom/testbinding.rs @@ -691,11 +691,11 @@ impl TestBindingMethods for TestBinding { fn PromiseNativeHandler(&self, resolve: Option>, reject: Option>) -> Rc { - let global = self.global(); - let handler = PromiseNativeHandler::new(global.r().as_global_scope(), + let global = self.global_scope(); + let handler = PromiseNativeHandler::new(&global, resolve.map(SimpleHandler::new), reject.map(SimpleHandler::new)); - let p = Promise::new(global.r()); + let p = Promise::new(&global); p.append_native_handler(&handler); return p; @@ -720,7 +720,7 @@ impl TestBindingMethods for TestBinding { #[allow(unrooted_must_root)] fn PromiseAttribute(&self) -> Rc { - Promise::new(self.global().r()) + Promise::new(&self.global_scope()) } fn AcceptPromise(&self, _promise: &Promise) { diff --git a/components/script/fetch.rs b/components/script/fetch.rs index 75d6e3b0848..bc04a5ecd92 100644 --- a/components/script/fetch.rs +++ b/components/script/fetch.rs @@ -70,8 +70,9 @@ pub fn Fetch(global: GlobalRef, input: RequestOrUSVString, init: &RequestInit) - let core_resource_thread = global.core_resource_thread(); // Step 1 - let promise = Promise::new(global); - let response = Response::new(global.as_global_scope()); + let global_scope = global.as_global_scope(); + let promise = Promise::new(global_scope); + let response = Response::new(global_scope); // Step 2 let request = match Request::Constructor(global, input, init) { From b3393fba18a3d5499ed1e52a0805128e33083aca Mon Sep 17 00:00:00 2001 From: Anthony Ramine Date: Sat, 1 Oct 2016 21:09:57 +0200 Subject: [PATCH 19/66] Make StructuredCloneData::read take a &GlobalScope --- components/script/dom/bindings/structuredclone.rs | 6 +++--- components/script/dom/dedicatedworkerglobalscope.rs | 2 +- components/script/dom/serviceworkerglobalscope.rs | 2 +- components/script/dom/window.rs | 2 +- components/script/dom/worker.rs | 2 +- 5 files changed, 7 insertions(+), 7 deletions(-) diff --git a/components/script/dom/bindings/structuredclone.rs b/components/script/dom/bindings/structuredclone.rs index 21963eec172..405d245c4bb 100644 --- a/components/script/dom/bindings/structuredclone.rs +++ b/components/script/dom/bindings/structuredclone.rs @@ -6,7 +6,7 @@ //! (https://html.spec.whatwg.org/multipage/#safe-passing-of-structured-data). use dom::bindings::error::{Error, Fallible}; -use dom::bindings::global::GlobalRef; +use dom::globalscope::GlobalScope; use js::jsapi::{HandleValue, MutableHandleValue}; use js::jsapi::{JSContext, JS_ReadStructuredClone, JS_STRUCTURED_CLONE_VERSION}; use js::jsapi::{JS_ClearPendingException, JS_WriteStructuredClone}; @@ -60,7 +60,7 @@ impl StructuredCloneData { /// Reads a structured clone. /// /// Panics if `JS_ReadStructuredClone` fails. - fn read_clone(global: GlobalRef, data: *mut u64, nbytes: size_t, rval: MutableHandleValue) { + fn read_clone(global: &GlobalScope, data: *mut u64, nbytes: size_t, rval: MutableHandleValue) { unsafe { assert!(JS_ReadStructuredClone(global.get_cx(), data, @@ -73,7 +73,7 @@ impl StructuredCloneData { } /// Thunk for the actual `read_clone` method. Resolves proper variant for read_clone. - pub fn read(self, global: GlobalRef, rval: MutableHandleValue) { + pub fn read(self, global: &GlobalScope, rval: MutableHandleValue) { match self { StructuredCloneData::Vector(mut vec_msg) => { let nbytes = vec_msg.len(); diff --git a/components/script/dom/dedicatedworkerglobalscope.rs b/components/script/dom/dedicatedworkerglobalscope.rs index 6a07a303fcb..9cae8b597dc 100644 --- a/components/script/dom/dedicatedworkerglobalscope.rs +++ b/components/script/dom/dedicatedworkerglobalscope.rs @@ -282,7 +282,7 @@ impl DedicatedWorkerGlobalScope { let _ac = JSAutoCompartment::new(scope.get_cx(), scope.reflector().get_jsobject().get()); rooted!(in(scope.get_cx()) let mut message = UndefinedValue()); - data.read(GlobalRef::Worker(scope), message.handle_mut()); + data.read(scope.upcast(), message.handle_mut()); MessageEvent::dispatch_jsval(target, GlobalRef::Worker(scope), message.handle()); }, WorkerScriptMsg::Common(CommonScriptMsg::RunnableMsg(_, runnable)) => { diff --git a/components/script/dom/serviceworkerglobalscope.rs b/components/script/dom/serviceworkerglobalscope.rs index 87f9741a205..98380eaa193 100644 --- a/components/script/dom/serviceworkerglobalscope.rs +++ b/components/script/dom/serviceworkerglobalscope.rs @@ -238,7 +238,7 @@ impl ServiceWorkerGlobalScope { let target = self.upcast(); let _ac = JSAutoCompartment::new(scope.get_cx(), scope.reflector().get_jsobject().get()); rooted!(in(scope.get_cx()) let mut message = UndefinedValue()); - data.read(GlobalRef::Worker(scope), message.handle_mut()); + data.read(scope.upcast(), message.handle_mut()); ExtendableMessageEvent::dispatch_jsval(target, GlobalRef::Worker(scope), message.handle()); }, CommonWorker(WorkerScriptMsg::Common(CommonScriptMsg::RunnableMsg(_, runnable))) => { diff --git a/components/script/dom/window.rs b/components/script/dom/window.rs index d560efa0746..137a46275b1 100644 --- a/components/script/dom/window.rs +++ b/components/script/dom/window.rs @@ -1771,7 +1771,7 @@ impl Runnable for PostMessageHandler { let _ac = JSAutoCompartment::new(cx, globalhandle.get()); rooted!(in(cx) let mut message = UndefinedValue()); - this.message.read(GlobalRef::Window(&*window), message.handle_mut()); + this.message.read(window.upcast(), message.handle_mut()); // Step 11-12. // TODO(#12719): set the other attributes. diff --git a/components/script/dom/worker.rs b/components/script/dom/worker.rs index 772cb5edc10..b959be94354 100644 --- a/components/script/dom/worker.rs +++ b/components/script/dom/worker.rs @@ -134,7 +134,7 @@ impl Worker { let target = worker.upcast(); let _ac = JSAutoCompartment::new(global.r().get_cx(), target.reflector().get_jsobject().get()); rooted!(in(global.r().get_cx()) let mut message = UndefinedValue()); - data.read(global.r(), message.handle_mut()); + data.read(global.r().as_global_scope(), message.handle_mut()); MessageEvent::dispatch_jsval(target, global.r(), message.handle()); } From 20bacbf42e73bef560c32372a983097b8073cb22 Mon Sep 17 00:00:00 2001 From: Anthony Ramine Date: Sat, 1 Oct 2016 21:17:46 +0200 Subject: [PATCH 20/66] Make dispatch_jsval methods take a &GlobalScope --- components/script/dom/dedicatedworkerglobalscope.rs | 2 +- components/script/dom/extendablemessageevent.rs | 4 ++-- components/script/dom/messageevent.rs | 4 ++-- components/script/dom/serviceworkerglobalscope.rs | 2 +- components/script/dom/websocket.rs | 11 ++++------- components/script/dom/window.rs | 2 +- components/script/dom/worker.rs | 10 +++++----- 7 files changed, 16 insertions(+), 19 deletions(-) diff --git a/components/script/dom/dedicatedworkerglobalscope.rs b/components/script/dom/dedicatedworkerglobalscope.rs index 9cae8b597dc..bc4a34eeb1b 100644 --- a/components/script/dom/dedicatedworkerglobalscope.rs +++ b/components/script/dom/dedicatedworkerglobalscope.rs @@ -283,7 +283,7 @@ impl DedicatedWorkerGlobalScope { scope.reflector().get_jsobject().get()); rooted!(in(scope.get_cx()) let mut message = UndefinedValue()); data.read(scope.upcast(), message.handle_mut()); - MessageEvent::dispatch_jsval(target, GlobalRef::Worker(scope), message.handle()); + MessageEvent::dispatch_jsval(target, scope.upcast(), message.handle()); }, WorkerScriptMsg::Common(CommonScriptMsg::RunnableMsg(_, runnable)) => { runnable.handler() diff --git a/components/script/dom/extendablemessageevent.rs b/components/script/dom/extendablemessageevent.rs index a0d8b3cf76b..8acddbaf7fa 100644 --- a/components/script/dom/extendablemessageevent.rs +++ b/components/script/dom/extendablemessageevent.rs @@ -65,10 +65,10 @@ impl ExtendableMessageEvent { impl ExtendableMessageEvent { pub fn dispatch_jsval(target: &EventTarget, - scope: GlobalRef, + scope: &GlobalScope, message: HandleValue) { let Extendablemessageevent = ExtendableMessageEvent::new( - scope.as_global_scope(), atom!("message"), false, false, message, + scope, atom!("message"), false, false, message, DOMString::new(), DOMString::new()); Extendablemessageevent.upcast::().fire(target); } diff --git a/components/script/dom/messageevent.rs b/components/script/dom/messageevent.rs index 62c8c4c5ed4..8192c8301cf 100644 --- a/components/script/dom/messageevent.rs +++ b/components/script/dom/messageevent.rs @@ -81,10 +81,10 @@ impl MessageEvent { impl MessageEvent { pub fn dispatch_jsval(target: &EventTarget, - scope: GlobalRef, + scope: &GlobalScope, message: HandleValue) { let messageevent = MessageEvent::new( - scope.as_global_scope(), + scope, atom!("message"), false, false, diff --git a/components/script/dom/serviceworkerglobalscope.rs b/components/script/dom/serviceworkerglobalscope.rs index 98380eaa193..52cfbff5bff 100644 --- a/components/script/dom/serviceworkerglobalscope.rs +++ b/components/script/dom/serviceworkerglobalscope.rs @@ -239,7 +239,7 @@ impl ServiceWorkerGlobalScope { let _ac = JSAutoCompartment::new(scope.get_cx(), scope.reflector().get_jsobject().get()); rooted!(in(scope.get_cx()) let mut message = UndefinedValue()); data.read(scope.upcast(), message.handle_mut()); - ExtendableMessageEvent::dispatch_jsval(target, GlobalRef::Worker(scope), message.handle()); + ExtendableMessageEvent::dispatch_jsval(target, scope.upcast(), message.handle()); }, CommonWorker(WorkerScriptMsg::Common(CommonScriptMsg::RunnableMsg(_, runnable))) => { runnable.handler() diff --git a/components/script/dom/websocket.rs b/components/script/dom/websocket.rs index a7bf55b6757..bbdc6a1c9b5 100644 --- a/components/script/dom/websocket.rs +++ b/components/script/dom/websocket.rs @@ -587,10 +587,10 @@ impl Runnable for MessageReceivedTask { } // Step 2-5. - let global = ws.r().global(); + let global = ws.global_scope(); // global.get_cx() returns a valid `JSContext` pointer, so this is safe. unsafe { - let cx = global.r().get_cx(); + let cx = global.get_cx(); let _ac = JSAutoCompartment::new(cx, ws.reflector().get_jsobject().get()); rooted!(in(cx) let mut message = UndefinedValue()); match self.message { @@ -598,10 +598,7 @@ impl Runnable for MessageReceivedTask { MessageData::Binary(data) => { match ws.binary_type.get() { BinaryType::Blob => { - let blob = Blob::new( - global.r().as_global_scope(), - BlobImpl::new_from_bytes(data), - "".to_owned()); + let blob = Blob::new(&global, BlobImpl::new_from_bytes(data), "".to_owned()); blob.to_jsval(cx, message.handle_mut()); } BinaryType::Arraybuffer => { @@ -617,7 +614,7 @@ impl Runnable for MessageReceivedTask { } }, } - MessageEvent::dispatch_jsval(ws.upcast(), global.r(), message.handle()); + MessageEvent::dispatch_jsval(ws.upcast(), &global, message.handle()); } } } diff --git a/components/script/dom/window.rs b/components/script/dom/window.rs index 137a46275b1..f5b021feea6 100644 --- a/components/script/dom/window.rs +++ b/components/script/dom/window.rs @@ -1776,7 +1776,7 @@ impl Runnable for PostMessageHandler { // Step 11-12. // TODO(#12719): set the other attributes. MessageEvent::dispatch_jsval(window.upcast(), - GlobalRef::Window(&*window), + window.upcast(), message.handle()); } } diff --git a/components/script/dom/worker.rs b/components/script/dom/worker.rs index b959be94354..9b8f3200878 100644 --- a/components/script/dom/worker.rs +++ b/components/script/dom/worker.rs @@ -130,12 +130,12 @@ impl Worker { return; } - let global = worker.r().global(); + let global = worker.global_scope(); let target = worker.upcast(); - let _ac = JSAutoCompartment::new(global.r().get_cx(), target.reflector().get_jsobject().get()); - rooted!(in(global.r().get_cx()) let mut message = UndefinedValue()); - data.read(global.r().as_global_scope(), message.handle_mut()); - MessageEvent::dispatch_jsval(target, global.r(), message.handle()); + let _ac = JSAutoCompartment::new(global.get_cx(), target.reflector().get_jsobject().get()); + rooted!(in(global.get_cx()) let mut message = UndefinedValue()); + data.read(&global, message.handle_mut()); + MessageEvent::dispatch_jsval(target, &global, message.handle()); } pub fn dispatch_simple_error(address: TrustedWorkerAddress) { From 22252605af6aa41543fb3c841355f9223f30e5b3 Mon Sep 17 00:00:00 2001 From: Anthony Ramine Date: Sat, 1 Oct 2016 21:23:41 +0200 Subject: [PATCH 21/66] Make WebGLRenderingContext::new take a &GlobalScope --- components/script/dom/htmlcanvaselement.rs | 3 +-- components/script/dom/webglrenderingcontext.rs | 13 ++++++------- 2 files changed, 7 insertions(+), 9 deletions(-) diff --git a/components/script/dom/htmlcanvaselement.rs b/components/script/dom/htmlcanvaselement.rs index a7111f7866e..c63ab1a9531 100644 --- a/components/script/dom/htmlcanvaselement.rs +++ b/components/script/dom/htmlcanvaselement.rs @@ -12,7 +12,6 @@ use dom::bindings::codegen::Bindings::WebGLRenderingContextBinding::WebGLContext use dom::bindings::codegen::UnionTypes::CanvasRenderingContext2DOrWebGLRenderingContext; use dom::bindings::conversions::ConversionResult; use dom::bindings::error::{Error, Fallible}; -use dom::bindings::global::GlobalRef; use dom::bindings::inheritance::Castable; use dom::bindings::js::{HeapGCValue, JS, LayoutJS, Root}; use dom::bindings::num::Finite; @@ -178,7 +177,7 @@ impl HTMLCanvasElement { GLContextAttributes::default() }; - let maybe_ctx = WebGLRenderingContext::new(GlobalRef::Window(window.r()), self, size, attrs); + let maybe_ctx = WebGLRenderingContext::new(window.upcast(), self, size, attrs); *self.context.borrow_mut() = maybe_ctx.map( |ctx| CanvasContext::WebGL(JS::from_ref(&*ctx))); } diff --git a/components/script/dom/webglrenderingcontext.rs b/components/script/dom/webglrenderingcontext.rs index 5b1f20a6218..0f9e6072a30 100644 --- a/components/script/dom/webglrenderingcontext.rs +++ b/components/script/dom/webglrenderingcontext.rs @@ -10,12 +10,12 @@ use dom::bindings::codegen::Bindings::WebGLRenderingContextBinding::WebGLRenderi use dom::bindings::codegen::UnionTypes::ImageDataOrHTMLImageElementOrHTMLCanvasElementOrHTMLVideoElement; use dom::bindings::conversions::{ToJSValConvertible, array_buffer_view_data, array_buffer_view_data_checked}; use dom::bindings::conversions::{array_buffer_view_to_vec, array_buffer_view_to_vec_checked}; -use dom::bindings::global::GlobalRef; use dom::bindings::inheritance::Castable; use dom::bindings::js::{JS, LayoutJS, MutNullableHeap, Root}; use dom::bindings::reflector::{Reflectable, Reflector, reflect_dom_object}; use dom::bindings::str::DOMString; use dom::event::{Event, EventBubbles, EventCancelable}; +use dom::globalscope::GlobalScope; use dom::htmlcanvaselement::HTMLCanvasElement; use dom::htmlcanvaselement::utils as canvas_utils; use dom::node::{Node, NodeDamage, window_from_node}; @@ -127,13 +127,13 @@ pub struct WebGLRenderingContext { } impl WebGLRenderingContext { - fn new_inherited(global: GlobalRef, + fn new_inherited(global: &GlobalScope, canvas: &HTMLCanvasElement, size: Size2D, attrs: GLContextAttributes) -> Result { let (sender, receiver) = ipc::channel().unwrap(); - let constellation_chan = global.as_global_scope().constellation_chan(); + let constellation_chan = global.constellation_chan(); constellation_chan.send(ConstellationMsg::CreateWebGLPaintThread(size, attrs, sender)) .unwrap(); let result = receiver.recv().unwrap(); @@ -159,14 +159,13 @@ impl WebGLRenderingContext { } #[allow(unrooted_must_root)] - pub fn new(global: GlobalRef, canvas: &HTMLCanvasElement, size: Size2D, attrs: GLContextAttributes) + pub fn new(global: &GlobalScope, canvas: &HTMLCanvasElement, size: Size2D, attrs: GLContextAttributes) -> Option> { match WebGLRenderingContext::new_inherited(global, canvas, size, attrs) { - Ok(ctx) => Some(reflect_dom_object(box ctx, global.as_global_scope(), - WebGLRenderingContextBinding::Wrap)), + Ok(ctx) => Some(reflect_dom_object(box ctx, global, WebGLRenderingContextBinding::Wrap)), Err(msg) => { error!("Couldn't create WebGLRenderingContext: {}", msg); - let event = WebGLContextEvent::new(global.as_global_scope(), + let event = WebGLContextEvent::new(global, atom!("webglcontextcreationerror"), EventBubbles::DoesNotBubble, EventCancelable::Cancelable, From e036579ea09b262b2f217f8711f26cc9aecdfef5 Mon Sep 17 00:00:00 2001 From: Anthony Ramine Date: Sat, 1 Oct 2016 21:32:13 +0200 Subject: [PATCH 22/66] Make XMLHttpRequest::new take a &GlobalScope --- components/script/dom/xmlhttprequest.rs | 14 ++++++++------ 1 file changed, 8 insertions(+), 6 deletions(-) diff --git a/components/script/dom/xmlhttprequest.rs b/components/script/dom/xmlhttprequest.rs index 3994334ba6b..e96650c5538 100644 --- a/components/script/dom/xmlhttprequest.rs +++ b/components/script/dom/xmlhttprequest.rs @@ -25,9 +25,11 @@ use dom::document::{Document, IsHTMLDocument}; use dom::document::DocumentSource; use dom::event::{Event, EventBubbles, EventCancelable}; use dom::eventtarget::EventTarget; +use dom::globalscope::GlobalScope; use dom::headers::is_forbidden_header_name; use dom::htmlformelement::{encode_multipart_form_data, generate_boundary}; use dom::progressevent::ProgressEvent; +use dom::window::Window; use dom::xmlhttprequesteventtarget::XMLHttpRequestEventTarget; use dom::xmlhttprequestupload::XMLHttpRequestUpload; use encoding::all::UTF_8; @@ -153,9 +155,9 @@ pub struct XMLHttpRequest { } impl XMLHttpRequest { - fn new_inherited(global: GlobalRef) -> XMLHttpRequest { + fn new_inherited(global: &GlobalScope) -> XMLHttpRequest { //TODO - update this when referrer policy implemented for workers - let (referrer_url, referrer_policy) = if let GlobalRef::Window(window) = global { + let (referrer_url, referrer_policy) = if let Some(window) = global.downcast::() { let document = window.Document(); (Some(document.url().clone()), document.get_referrer_policy()) } else { @@ -167,7 +169,7 @@ impl XMLHttpRequest { ready_state: Cell::new(XMLHttpRequestState::Unsent), timeout: Cell::new(0u32), with_credentials: Cell::new(false), - upload: JS::from_ref(&*XMLHttpRequestUpload::new(global.as_global_scope())), + upload: JS::from_ref(&*XMLHttpRequestUpload::new(global)), response_url: DOMRefCell::new(String::from("")), status: Cell::new(0), status_text: DOMRefCell::new(ByteString::new(vec!())), @@ -196,15 +198,15 @@ impl XMLHttpRequest { referrer_policy: referrer_policy, } } - pub fn new(global: GlobalRef) -> Root { + pub fn new(global: &GlobalScope) -> Root { reflect_dom_object(box XMLHttpRequest::new_inherited(global), - global.as_global_scope(), + global, XMLHttpRequestBinding::Wrap) } // https://xhr.spec.whatwg.org/#constructors pub fn Constructor(global: GlobalRef) -> Fallible> { - Ok(XMLHttpRequest::new(global)) + Ok(XMLHttpRequest::new(global.as_global_scope())) } fn sync_in_window(&self) -> bool { From ac5c4c2194495b1949ab4283f0c9c33c8029d5ae Mon Sep 17 00:00:00 2001 From: Anthony Ramine Date: Sat, 1 Oct 2016 21:39:09 +0200 Subject: [PATCH 23/66] Make Error::to_jsval take a &GlobalScope --- components/script/dom/bindings/error.rs | 6 +++--- components/script/dom/promise.rs | 2 +- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/components/script/dom/bindings/error.rs b/components/script/dom/bindings/error.rs index 0b4249e7405..ed274426bd3 100644 --- a/components/script/dom/bindings/error.rs +++ b/components/script/dom/bindings/error.rs @@ -8,7 +8,7 @@ use dom::bindings::codegen::Bindings::DOMExceptionBinding::DOMExceptionMethods; use dom::bindings::codegen::PrototypeList::proto_id_to_name; use dom::bindings::conversions::{ConversionResult, FromJSValConvertible, ToJSValConvertible}; use dom::bindings::conversions::root_from_object; -use dom::bindings::global::{GlobalRef, global_root_from_context}; +use dom::bindings::global::global_root_from_context; use dom::bindings::str::USVString; use dom::domexception::{DOMErrorName, DOMException}; use dom::globalscope::GlobalScope; @@ -271,9 +271,9 @@ pub unsafe fn throw_invalid_this(cx: *mut JSContext, proto_id: u16) { impl Error { /// Convert this error value to a JS value, consuming it in the process. - pub unsafe fn to_jsval(self, cx: *mut JSContext, global: GlobalRef, rval: MutableHandleValue) { + pub unsafe fn to_jsval(self, cx: *mut JSContext, global: &GlobalScope, rval: MutableHandleValue) { assert!(!JS_IsExceptionPending(cx)); - throw_dom_exception(cx, global.as_global_scope(), self); + throw_dom_exception(cx, global, self); assert!(JS_IsExceptionPending(cx)); assert!(JS_GetPendingException(cx, rval)); JS_ClearPendingException(cx); diff --git a/components/script/dom/promise.rs b/components/script/dom/promise.rs index 867be7809d3..fe63cff9b94 100644 --- a/components/script/dom/promise.rs +++ b/components/script/dom/promise.rs @@ -167,7 +167,7 @@ impl Promise { pub fn reject_error(&self, cx: *mut JSContext, error: Error) { rooted!(in(cx) let mut v = UndefinedValue()); unsafe { - error.to_jsval(cx, self.global().r(), v.handle_mut()); + error.to_jsval(cx, &self.global_scope(), v.handle_mut()); } self.reject(cx, v.handle()); } From 5bdc5a4c485a779c7af393ba6a8b0867078871c2 Mon Sep 17 00:00:00 2001 From: Anthony Ramine Date: Sat, 1 Oct 2016 22:30:24 +0200 Subject: [PATCH 24/66] Use GlobalScope in dispatch_to_listeners --- components/script/dom/eventdispatcher.rs | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/components/script/dom/eventdispatcher.rs b/components/script/dom/eventdispatcher.rs index 28ea0b42b31..5ed7c5effe1 100644 --- a/components/script/dom/eventdispatcher.rs +++ b/components/script/dom/eventdispatcher.rs @@ -5,7 +5,6 @@ use devtools_traits::{StartedTimelineMarker, TimelineMarker, TimelineMarkerType}; use dom::bindings::callback::ExceptionHandling::Report; use dom::bindings::codegen::Bindings::EventBinding::EventMethods; -use dom::bindings::global::GlobalRoot; use dom::bindings::inheritance::Castable; use dom::bindings::js::{JS, Root, RootedReference}; use dom::bindings::reflector::Reflectable; @@ -52,8 +51,8 @@ fn dispatch_to_listeners(event: &Event, target: &EventTarget, event_path: &[&Eve assert!(!event.stop_propagation()); assert!(!event.stop_immediate()); - let window = match target.global() { - GlobalRoot::Window(window) => { + let window = match Root::downcast::(target.global_scope()) { + Some(window) => { if window.need_emit_timeline_marker(TimelineMarkerType::DOMEvent) { Some(window) } else { From cb02d7911a5dd98846ddf4a0c2dd6b2fc9032a07 Mon Sep 17 00:00:00 2001 From: Anthony Ramine Date: Sat, 1 Oct 2016 22:38:50 +0200 Subject: [PATCH 25/66] Do not use GlobalRoot in dom::xmlhttprequest --- components/script/dom/xmlhttprequest.rs | 24 ++++++++++-------------- 1 file changed, 10 insertions(+), 14 deletions(-) diff --git a/components/script/dom/xmlhttprequest.rs b/components/script/dom/xmlhttprequest.rs index e96650c5538..26b6cafcf3a 100644 --- a/components/script/dom/xmlhttprequest.rs +++ b/components/script/dom/xmlhttprequest.rs @@ -13,7 +13,7 @@ use dom::bindings::codegen::Bindings::XMLHttpRequestBinding::XMLHttpRequestMetho use dom::bindings::codegen::Bindings::XMLHttpRequestBinding::XMLHttpRequestResponseType; use dom::bindings::conversions::ToJSValConvertible; use dom::bindings::error::{Error, ErrorResult, Fallible}; -use dom::bindings::global::{GlobalRef, GlobalRoot}; +use dom::bindings::global::GlobalRef; use dom::bindings::inheritance::Castable; use dom::bindings::js::{JS, MutHeapJSVal, MutNullableHeap}; use dom::bindings::js::{Root, RootedReference}; @@ -30,6 +30,7 @@ use dom::headers::is_forbidden_header_name; use dom::htmlformelement::{encode_multipart_form_data, generate_boundary}; use dom::progressevent::ProgressEvent; use dom::window::Window; +use dom::workerglobalscope::WorkerGlobalScope; use dom::xmlhttprequesteventtarget::XMLHttpRequestEventTarget; use dom::xmlhttprequestupload::XMLHttpRequestUpload; use encoding::all::UTF_8; @@ -210,10 +211,7 @@ impl XMLHttpRequest { } fn sync_in_window(&self) -> bool { - match self.global() { - GlobalRoot::Window(_) if self.sync.get() => true, - _ => false - } + self.sync.get() && self.global_scope().is::() } fn initiate_async_xhr(context: Arc>, @@ -308,11 +306,10 @@ impl XMLHttpRequestMethods for XMLHttpRequest { fn Open_(&self, method: ByteString, url: USVString, async: bool, username: Option, password: Option) -> ErrorResult { // Step 1 - match self.global() { - GlobalRoot::Window(ref window) => { - if !window.Document().r().is_fully_active() { return Err(Error::InvalidState); } + if let Some(window) = Root::downcast::(self.global_scope()) { + if !window.Document().r().is_fully_active() { + return Err(Error::InvalidState); } - _ => {} } // Step 5 @@ -575,7 +572,7 @@ impl XMLHttpRequestMethods for XMLHttpRequest { // preference is enabled, we allow bypassing the CORS check. // This is a temporary measure until we figure out Servo privilege // story. See https://github.com/servo/servo/issues/9582 - if let GlobalRoot::Window(win) = self.global() { + if let Some(win) = Root::downcast::(self.global_scope()) { let is_root_pipeline = win.parent_info().is_none(); is_root_pipeline && PREFS.is_mozbrowser_enabled() } else { @@ -744,9 +741,8 @@ impl XMLHttpRequestMethods for XMLHttpRequest { // https://xhr.spec.whatwg.org/#the-responsetype-attribute fn SetResponseType(&self, response_type: XMLHttpRequestResponseType) -> ErrorResult { // Step 1 - match self.global() { - GlobalRoot::Worker(_) if response_type == XMLHttpRequestResponseType::Document => return Ok(()), - _ => {} + if self.global_scope().is::() && response_type == XMLHttpRequestResponseType::Document { + return Ok(()); } match self.ready_state.get() { // Step 2 @@ -829,7 +825,7 @@ impl XMLHttpRequestMethods for XMLHttpRequest { fn GetResponseXML(&self) -> Fallible>> { // TODO(#2823): Until [Exposed] is implemented, this attribute needs to return null // explicitly in the worker scope. - if let GlobalRoot::Worker(_) = self.global() { + if self.global_scope().is::() { return Ok(None); } From 3302a53d38721fa18bcf0c3886f24f37cfd6bd13 Mon Sep 17 00:00:00 2001 From: Anthony Ramine Date: Sun, 2 Oct 2016 01:15:12 +0200 Subject: [PATCH 26/66] Introduce GlobalScope::api_base_url --- components/script/dom/bindings/global.rs | 12 ------------ components/script/dom/globalscope.rs | 19 +++++++++++++++++++ .../script/dom/serviceworkercontainer.rs | 5 +++-- components/script/dom/worker.rs | 6 +++--- components/script/dom/xmlhttprequest.rs | 2 +- 5 files changed, 26 insertions(+), 18 deletions(-) diff --git a/components/script/dom/bindings/global.rs b/components/script/dom/bindings/global.rs index cf108e5e526..fd3cba582f7 100644 --- a/components/script/dom/bindings/global.rs +++ b/components/script/dom/bindings/global.rs @@ -7,7 +7,6 @@ //! This module contains smart pointers to global scopes, to simplify writing //! code that works in workers as well as window scopes. -use dom::bindings::codegen::Bindings::WindowBinding::WindowMethods; use dom::bindings::conversions::root_from_object; use dom::bindings::error::{ErrorInfo, report_pending_exception}; use dom::bindings::inheritance::Castable; @@ -100,17 +99,6 @@ impl<'a> GlobalRef<'a> { } } - /// Get the [base url](https://html.spec.whatwg.org/multipage/#api-base-url) - /// for this global scope. - pub fn api_base_url(&self) -> Url { - match *self { - // https://html.spec.whatwg.org/multipage/#script-settings-for-browsing-contexts:api-base-url - GlobalRef::Window(ref window) => window.Document().base_url(), - // https://html.spec.whatwg.org/multipage/#script-settings-for-workers:api-base-url - GlobalRef::Worker(ref worker) => worker.get_url().clone(), - } - } - /// `ScriptChan` used to send messages to the event loop of this global's /// thread. pub fn script_chan(&self) -> Box { diff --git a/components/script/dom/globalscope.rs b/components/script/dom/globalscope.rs index b455536ed1c..96787adb303 100644 --- a/components/script/dom/globalscope.rs +++ b/components/script/dom/globalscope.rs @@ -4,11 +4,15 @@ use devtools_traits::{ScriptToDevtoolsControlMsg, WorkerId}; use dom::bindings::cell::DOMRefCell; +use dom::bindings::codegen::Bindings::WindowBinding::WindowMethods; +use dom::bindings::inheritance::Castable; use dom::bindings::js::{JS, MutNullableHeap, Root}; use dom::bindings::reflector::Reflectable; use dom::bindings::str::DOMString; use dom::crypto::Crypto; use dom::eventtarget::EventTarget; +use dom::window::Window; +use dom::workerglobalscope::WorkerGlobalScope; use ipc_channel::ipc::IpcSender; use js::jsapi::{JS_GetContext, JS_GetObjectRuntime, JSContext}; use msg::constellation_msg::PipelineId; @@ -18,6 +22,7 @@ use std::cell::Cell; use std::collections::HashMap; use std::collections::hash_map::Entry; use time::{Timespec, get_time}; +use url::Url; #[dom_struct] pub struct GlobalScope { @@ -160,6 +165,20 @@ impl GlobalScope { pub fn pipeline_id(&self) -> PipelineId { self.pipeline_id } + + /// Get the [base url](https://html.spec.whatwg.org/multipage/#api-base-url) + /// for this global scope. + pub fn api_base_url(&self) -> Url { + if let Some(window) = self.downcast::() { + // https://html.spec.whatwg.org/multipage/#script-settings-for-browsing-contexts:api-base-url + return window.Document().base_url(); + } + if let Some(worker) = self.downcast::() { + // https://html.spec.whatwg.org/multipage/#script-settings-for-workers:api-base-url + return worker.get_url().clone(); + } + unreachable!(); + } } fn timestamp_in_ms(time: Timespec) -> u64 { diff --git a/components/script/dom/serviceworkercontainer.rs b/components/script/dom/serviceworkercontainer.rs index 12bab94fe12..c5d27017f8e 100644 --- a/components/script/dom/serviceworkercontainer.rs +++ b/components/script/dom/serviceworkercontainer.rs @@ -58,8 +58,9 @@ impl ServiceWorkerContainerMethods for ServiceWorkerContainer { script_url: USVString, options: &RegistrationOptions) -> Fallible> { let USVString(ref script_url) = script_url; + let api_base_url = self.global_scope().api_base_url(); // Step 3-4 - let script_url = match self.global().r().api_base_url().join(script_url) { + let script_url = match api_base_url.join(script_url) { Ok(url) => url, Err(_) => return Err(Error::Type("Invalid script URL".to_owned())) }; @@ -77,7 +78,7 @@ impl ServiceWorkerContainerMethods for ServiceWorkerContainer { let scope = match options.scope { Some(ref scope) => { let &USVString(ref inner_scope) = scope; - match self.global().r().api_base_url().join(inner_scope) { + match api_base_url.join(inner_scope) { Ok(url) => url, Err(_) => return Err(Error::Type("Invalid scope URL".to_owned())) } diff --git a/components/script/dom/worker.rs b/components/script/dom/worker.rs index 9b8f3200878..833675fa1e3 100644 --- a/components/script/dom/worker.rs +++ b/components/script/dom/worker.rs @@ -73,18 +73,18 @@ impl Worker { // https://html.spec.whatwg.org/multipage/#dom-worker #[allow(unsafe_code)] pub fn Constructor(global: GlobalRef, script_url: DOMString) -> Fallible> { + let global_scope = global.as_global_scope(); // Step 2-4. - let worker_url = match global.api_base_url().join(&script_url) { + let worker_url = match global_scope.api_base_url().join(&script_url) { Ok(url) => url, Err(_) => return Err(Error::Syntax), }; let (sender, receiver) = channel(); let closing = Arc::new(AtomicBool::new(false)); - let worker = Worker::new(global.as_global_scope(), sender.clone(), closing.clone()); + let worker = Worker::new(global_scope, sender.clone(), closing.clone()); let worker_ref = Trusted::new(worker.r()); - let global_scope = global.as_global_scope(); let worker_load_origin = WorkerScriptLoadOrigin { referrer_url: None, referrer_policy: None, diff --git a/components/script/dom/xmlhttprequest.rs b/components/script/dom/xmlhttprequest.rs index 26b6cafcf3a..844d46f904e 100644 --- a/components/script/dom/xmlhttprequest.rs +++ b/components/script/dom/xmlhttprequest.rs @@ -340,7 +340,7 @@ impl XMLHttpRequestMethods for XMLHttpRequest { } // Step 2 - let base = self.global().r().api_base_url(); + let base = self.global_scope().api_base_url(); // Step 6 let mut parsed_url = match base.join(&url.0) { Ok(parsed) => parsed, From 092504b4e3c10593730e3c625f98863651b9cc91 Mon Sep 17 00:00:00 2001 From: Anthony Ramine Date: Sun, 2 Oct 2016 01:20:35 +0200 Subject: [PATCH 27/66] Make Console::send_to_devtools take a &GlobalScope --- components/script/dom/console.rs | 34 ++++++++++++++++---------------- 1 file changed, 17 insertions(+), 17 deletions(-) diff --git a/components/script/dom/console.rs b/components/script/dom/console.rs index a33a40d7dfc..8350b05b10f 100644 --- a/components/script/dom/console.rs +++ b/components/script/dom/console.rs @@ -4,23 +4,23 @@ use devtools_traits::{ConsoleMessage, LogLevel, ScriptToDevtoolsControlMsg}; use dom::bindings::global::GlobalRef; +use dom::bindings::inheritance::Castable; use dom::bindings::str::DOMString; +use dom::globalscope::GlobalScope; +use dom::workerglobalscope::WorkerGlobalScope; // https://developer.mozilla.org/en-US/docs/Web/API/Console pub struct Console(()); impl Console { - fn send_to_devtools(global: GlobalRef, level: LogLevel, message: DOMString) { - let global_scope = global.as_global_scope(); - if let Some(chan) = global_scope.devtools_chan() { + fn send_to_devtools(global: &GlobalScope, level: LogLevel, message: DOMString) { + if let Some(chan) = global.devtools_chan() { let console_message = prepare_message(level, message); - let worker_id = if let GlobalRef::Worker(worker) = global { - Some(worker.get_worker_id()) - } else { - None - }; + let worker_id = global.downcast::().map(|worker| { + worker.get_worker_id() + }); let devtools_message = ScriptToDevtoolsControlMsg::ConsoleAPI( - global_scope.pipeline_id(), + global.pipeline_id(), console_message, worker_id); chan.send(devtools_message).unwrap(); @@ -33,7 +33,7 @@ impl Console { pub fn Log(global: GlobalRef, messages: Vec) { for message in messages { println!("{}", message); - Self::send_to_devtools(global, LogLevel::Log, message); + Self::send_to_devtools(global.as_global_scope(), LogLevel::Log, message); } } @@ -41,7 +41,7 @@ impl Console { pub fn Debug(global: GlobalRef, messages: Vec) { for message in messages { println!("{}", message); - Self::send_to_devtools(global, LogLevel::Debug, message); + Self::send_to_devtools(global.as_global_scope(), LogLevel::Debug, message); } } @@ -49,7 +49,7 @@ impl Console { pub fn Info(global: GlobalRef, messages: Vec) { for message in messages { println!("{}", message); - Self::send_to_devtools(global, LogLevel::Info, message); + Self::send_to_devtools(global.as_global_scope(), LogLevel::Info, message); } } @@ -57,7 +57,7 @@ impl Console { pub fn Warn(global: GlobalRef, messages: Vec) { for message in messages { println!("{}", message); - Self::send_to_devtools(global, LogLevel::Warn, message); + Self::send_to_devtools(global.as_global_scope(), LogLevel::Warn, message); } } @@ -65,7 +65,7 @@ impl Console { pub fn Error(global: GlobalRef, messages: Vec) { for message in messages { println!("{}", message); - Self::send_to_devtools(global, LogLevel::Error, message); + Self::send_to_devtools(global.as_global_scope(), LogLevel::Error, message); } } @@ -74,7 +74,7 @@ impl Console { if !condition { let message = message.unwrap_or_else(|| DOMString::from("no message")); println!("Assertion failed: {}", message); - Self::send_to_devtools(global, LogLevel::Error, message); + Self::send_to_devtools(global.as_global_scope(), LogLevel::Error, message); } } @@ -83,7 +83,7 @@ impl Console { if let Ok(()) = global.as_global_scope().time(label.clone()) { let message = DOMString::from(format!("{}: timer started", label)); println!("{}", message); - Self::send_to_devtools(global, LogLevel::Log, message); + Self::send_to_devtools(global.as_global_scope(), LogLevel::Log, message); } } @@ -94,7 +94,7 @@ impl Console { format!("{}: {}ms", label, delta) ); println!("{}", message); - Self::send_to_devtools(global, LogLevel::Log, message); + Self::send_to_devtools(global.as_global_scope(), LogLevel::Log, message); }; } } From f38159b7d39acccef464857b101e9c8a6855aa6e Mon Sep 17 00:00:00 2001 From: Anthony Ramine Date: Sun, 2 Oct 2016 14:29:01 +0200 Subject: [PATCH 28/66] Introduce GlobalScope::get_url --- components/script/dom/bindings/global.rs | 11 +---------- components/script/dom/blob.rs | 16 ++++++---------- components/script/dom/eventsource.rs | 5 +++-- components/script/dom/globalscope.rs | 11 +++++++++++ components/script/dom/request.rs | 9 +++++---- components/script/dom/response.rs | 5 +++-- components/script/dom/storage.rs | 4 +--- components/script/dom/url.rs | 4 ++-- components/script/dom/websocket.rs | 5 +++-- components/script/dom/xmlhttprequest.rs | 8 ++++---- 10 files changed, 39 insertions(+), 39 deletions(-) diff --git a/components/script/dom/bindings/global.rs b/components/script/dom/bindings/global.rs index fd3cba582f7..84b75cc9443 100644 --- a/components/script/dom/bindings/global.rs +++ b/components/script/dom/bindings/global.rs @@ -32,7 +32,6 @@ use std::ffi::CString; use std::panic; use task_source::file_reading::FileReadingTaskSource; use timers::{OneshotTimerCallback, OneshotTimerHandle}; -use url::Url; /// A freely-copyable reference to a rooted global object. #[derive(Copy, Clone)] @@ -91,14 +90,6 @@ impl<'a> GlobalRef<'a> { self.resource_threads().sender() } - /// Get the URL for this global scope. - pub fn get_url(&self) -> Url { - match *self { - GlobalRef::Window(ref window) => window.get_url(), - GlobalRef::Worker(ref worker) => worker.get_url().clone(), - } - } - /// `ScriptChan` used to send messages to the event loop of this global's /// thread. pub fn script_chan(&self) -> Box { @@ -158,7 +149,7 @@ impl<'a> GlobalRef<'a> { &self, code: &str, filename: &str, rval: MutableHandleValue) { let metadata = time::TimerMetadata { url: if filename.is_empty() { - self.get_url().as_str().into() + self.as_global_scope().get_url().as_str().into() } else { filename.into() }, diff --git a/components/script/dom/blob.rs b/components/script/dom/blob.rs index 997edb52d6c..fa6600224e8 100644 --- a/components/script/dom/blob.rs +++ b/components/script/dom/blob.rs @@ -190,6 +190,7 @@ impl Blob { /// valid or invalid Blob URL. fn promote(&self, set_valid: bool) -> Uuid { let mut bytes = vec![]; + let global_url = self.global_scope().get_url(); match *self.blob_impl.borrow_mut() { BlobImpl::Sliced(_, _) => { @@ -199,8 +200,7 @@ impl Blob { } BlobImpl::File(ref f) => { if set_valid { - let global = self.global(); - let origin = get_blob_origin(&global.r().get_url()); + let origin = get_blob_origin(&global_url); let (tx, rx) = ipc::channel().unwrap(); let msg = FileManagerThreadMsg::ActivateBlobURL(f.id.clone(), tx, origin.clone()); @@ -219,8 +219,7 @@ impl Blob { BlobImpl::Memory(ref mut bytes_in) => mem::swap(bytes_in, &mut bytes), }; - let global = self.global(); - let origin = get_blob_origin(&global.r().get_url()); + let origin = get_blob_origin(&global_url); let blob_buf = BlobBuf { filename: None, @@ -251,9 +250,7 @@ impl Blob { /// Get a FileID representing sliced parent-blob content fn create_sliced_url_id(&self, parent_id: &Uuid, rel_pos: &RelativePos, parent_len: u64) -> Uuid { - let global = self.global(); - - let origin = get_blob_origin(&global.r().get_url()); + let origin = get_blob_origin(&self.global_scope().get_url()); let (tx, rx) = ipc::channel().unwrap(); let msg = FileManagerThreadMsg::AddSlicedURLEntry(parent_id.clone(), @@ -282,8 +279,7 @@ impl Blob { /// Cleanups at the time of destruction/closing fn clean_up_file_resource(&self) { if let BlobImpl::File(ref f) = *self.blob_impl.borrow() { - let global = self.global(); - let origin = get_blob_origin(&global.r().get_url()); + let origin = get_blob_origin(&self.global_scope().get_url()); let (tx, rx) = ipc::channel().unwrap(); @@ -311,7 +307,7 @@ impl Drop for Blob { fn read_file(global: GlobalRef, id: Uuid) -> Result, ()> { let resource_threads = global.resource_threads(); let (chan, recv) = ipc::channel().map_err(|_|())?; - let origin = get_blob_origin(&global.get_url()); + let origin = get_blob_origin(&global.as_global_scope().get_url()); let check_url_validity = false; let msg = FileManagerThreadMsg::ReadFile(chan, id, check_url_validity, origin); let _ = resource_threads.send(CoreResourceMsg::ToFileManager(msg)); diff --git a/components/script/dom/eventsource.rs b/components/script/dom/eventsource.rs index 667627e1e83..bf83bed4c5c 100644 --- a/components/script/dom/eventsource.rs +++ b/components/script/dom/eventsource.rs @@ -52,14 +52,15 @@ impl EventSource { pub fn Constructor(global: GlobalRef, url_str: DOMString, event_source_init: &EventSourceInit) -> Fallible> { + let global_scope = global.as_global_scope(); // Steps 1-2 - let base_url = global.get_url(); + let base_url = global_scope.get_url(); let url = match base_url.join(&*url_str) { Ok(u) => u, Err(_) => return Err(Error::Syntax) }; // Step 3 - let event_source = EventSource::new(global.as_global_scope(), url, event_source_init.withCredentials); + let event_source = EventSource::new(global_scope, url, event_source_init.withCredentials); // Step 4 // Step 5 // Step 6 diff --git a/components/script/dom/globalscope.rs b/components/script/dom/globalscope.rs index 96787adb303..4828dfec696 100644 --- a/components/script/dom/globalscope.rs +++ b/components/script/dom/globalscope.rs @@ -179,6 +179,17 @@ impl GlobalScope { } unreachable!(); } + + /// Get the URL for this global scope. + pub fn get_url(&self) -> Url { + if let Some(window) = self.downcast::() { + return window.get_url(); + } + if let Some(worker) = self.downcast::() { + return worker.get_url().clone(); + } + unreachable!(); + } } fn timestamp_in_ms(time: Timespec) -> u64 { diff --git a/components/script/dom/request.rs b/components/script/dom/request.rs index 1060f4b963b..7d18a3d0ce0 100644 --- a/components/script/dom/request.rs +++ b/components/script/dom/request.rs @@ -92,7 +92,7 @@ impl Request { // Step 4 // TODO: `entry settings object` is not implemented in Servo yet. - let base_url = global.get_url(); + let base_url = global.as_global_scope().get_url(); match input { // Step 5 @@ -130,7 +130,7 @@ impl Request { // Step 7 // TODO: `entry settings object` is not implemented yet. - let origin = global.get_url().origin(); + let origin = base_url.origin(); // Step 8 let mut window = Window::Client; @@ -450,8 +450,9 @@ impl Request { fn net_request_from_global(global: GlobalRef, url: Url, is_service_worker_global_scope: bool) -> NetTraitsRequest { - let origin = Origin::Origin(global.get_url().origin()); - let pipeline_id = global.as_global_scope().pipeline_id(); + let global_scope = global.as_global_scope(); + let origin = Origin::Origin(global_scope.get_url().origin()); + let pipeline_id = global_scope.pipeline_id(); NetTraitsRequest::new(url, Some(origin), is_service_worker_global_scope, diff --git a/components/script/dom/response.rs b/components/script/dom/response.rs index 5306a152156..4e7d4967d28 100644 --- a/components/script/dom/response.rs +++ b/components/script/dom/response.rs @@ -149,9 +149,10 @@ impl Response { // https://fetch.spec.whatwg.org/#dom-response-redirect pub fn Redirect(global: GlobalRef, url: USVString, status: u16) -> Fallible> { + let global_scope = global.as_global_scope(); // Step 1 // TODO: `entry settings object` is not implemented in Servo yet. - let base_url = global.get_url(); + let base_url = global_scope.get_url(); let parsed_url = base_url.join(&url.0); // Step 2 @@ -167,7 +168,7 @@ impl Response { // Step 4 // see Step 4 continued - let r = Response::new(global.as_global_scope()); + let r = Response::new(global_scope); // Step 5 *r.status.borrow_mut() = Some(StatusCode::from_u16(status)); diff --git a/components/script/dom/storage.rs b/components/script/dom/storage.rs index 7152e27acc7..2f0ff42125a 100644 --- a/components/script/dom/storage.rs +++ b/components/script/dom/storage.rs @@ -40,9 +40,7 @@ impl Storage { } fn get_url(&self) -> Url { - let global_root = self.global(); - let global_ref = global_root.r(); - global_ref.get_url() + self.global_scope().get_url() } fn get_storage_thread(&self) -> IpcSender { diff --git a/components/script/dom/url.rs b/components/script/dom/url.rs index 2d5968e9e07..33520beee9d 100644 --- a/components/script/dom/url.rs +++ b/components/script/dom/url.rs @@ -118,7 +118,7 @@ impl URL { pub fn CreateObjectURL(global: GlobalRef, blob: &Blob) -> DOMString { /// XXX: Second field is an unicode-serialized Origin, it is a temporary workaround /// and should not be trusted. See issue https://github.com/servo/servo/issues/11722 - let origin = get_blob_origin(&global.get_url()); + let origin = get_blob_origin(&global.as_global_scope().get_url()); if blob.IsClosed() { // Generate a dummy id @@ -142,7 +142,7 @@ impl URL { NOTE: The first step is unnecessary, since closed blobs do not exist in the store */ - let origin = get_blob_origin(&global.get_url()); + let origin = get_blob_origin(&global.as_global_scope().get_url()); if let Ok(url) = Url::parse(&url) { if let Ok((id, _, _)) = parse_blob_url(&url) { diff --git a/components/script/dom/websocket.rs b/components/script/dom/websocket.rs index bbdc6a1c9b5..1b790d532d2 100644 --- a/components/script/dom/websocket.rs +++ b/components/script/dom/websocket.rs @@ -239,10 +239,11 @@ impl WebSocket { } // Step 6: Origin. - let origin = UrlHelper::Origin(&global.get_url()).0; + let global_scope = global.as_global_scope(); + let origin = UrlHelper::Origin(&global_scope.get_url()).0; // Step 7. - let ws = WebSocket::new(global.as_global_scope(), resource_url.clone()); + let ws = WebSocket::new(global_scope, resource_url.clone()); let address = Trusted::new(ws.r()); let connect_data = WebSocketConnectData { diff --git a/components/script/dom/xmlhttprequest.rs b/components/script/dom/xmlhttprequest.rs index 844d46f904e..a87d64e3e61 100644 --- a/components/script/dom/xmlhttprequest.rs +++ b/components/script/dom/xmlhttprequest.rs @@ -595,7 +595,7 @@ impl XMLHttpRequestMethods for XMLHttpRequest { use_cors_preflight: has_handlers, credentials_mode: credentials_mode, use_url_credentials: use_url_credentials, - origin: self.global().r().get_url(), + origin: self.global_scope().get_url(), referrer_url: self.referrer_url.clone(), referrer_policy: self.referrer_policy.clone(), pipeline_id: self.pipeline_id(), @@ -1204,7 +1204,7 @@ impl XMLHttpRequest { // TODO: Disable scripting while parsing parse_html(document.r(), DOMString::from(decoded), - wr.get_url(), + wr.as_global_scope().get_url(), ParseContext::Owner(Some(wr.as_global_scope().pipeline_id()))); document } @@ -1218,7 +1218,7 @@ impl XMLHttpRequest { // TODO: Disable scripting while parsing parse_xml(document.r(), DOMString::from(decoded), - wr.get_url(), + wr.as_global_scope().get_url(), xml::ParseContext::Owner(Some(wr.as_global_scope().pipeline_id()))); document } @@ -1230,7 +1230,7 @@ impl XMLHttpRequest { let doc = win.Document(); let doc = doc.r(); let docloader = DocumentLoader::new(&*doc.loader()); - let base = self.global().r().get_url(); + let base = self.global_scope().get_url(); let parsed_url = match base.join(&self.ResponseURL().0) { Ok(parsed) => Some(parsed), Err(_) => None // Step 7 From 99b346ac52ecdf977844044f02756eb412eb9090 Mon Sep 17 00:00:00 2001 From: Anthony Ramine Date: Sun, 2 Oct 2016 14:40:08 +0200 Subject: [PATCH 29/66] Make Request::new take a &GlobalScope --- components/script/dom/request.rs | 28 +++++++++++++++------------- 1 file changed, 15 insertions(+), 13 deletions(-) diff --git a/components/script/dom/request.rs b/components/script/dom/request.rs index 7d18a3d0ce0..664b2ca5302 100644 --- a/components/script/dom/request.rs +++ b/components/script/dom/request.rs @@ -21,6 +21,7 @@ use dom::bindings::global::GlobalRef; use dom::bindings::js::{JS, MutNullableHeap, Root}; use dom::bindings::reflector::{Reflectable, Reflector, reflect_dom_object}; use dom::bindings::str::{ByteString, DOMString, USVString}; +use dom::globalscope::GlobalScope; use dom::headers::{Guard, Headers}; use dom::promise::Promise; use dom::xmlhttprequest::Extractable; @@ -51,7 +52,7 @@ pub struct Request { } impl Request { - fn new_inherited(global: GlobalRef, + fn new_inherited(global: &GlobalScope, url: Url, is_service_worker_global_scope: bool) -> Request { Request { @@ -67,13 +68,13 @@ impl Request { } } - pub fn new(global: GlobalRef, + pub fn new(global: &GlobalScope, url: Url, is_service_worker_global_scope: bool) -> Root { reflect_dom_object(box Request::new_inherited(global, url, is_service_worker_global_scope), - global.as_global_scope(), RequestBinding::Wrap) + global, RequestBinding::Wrap) } // https://fetch.spec.whatwg.org/#dom-request @@ -81,6 +82,8 @@ impl Request { input: RequestInfo, init: &RequestInit) -> Fallible> { + let global_scope = global.as_global_scope(); + // Step 1 let temporary_request: NetTraitsRequest; @@ -92,7 +95,7 @@ impl Request { // Step 4 // TODO: `entry settings object` is not implemented in Servo yet. - let base_url = global.as_global_scope().get_url(); + let base_url = global_scope.get_url(); match input { // Step 5 @@ -109,7 +112,7 @@ impl Request { return Err(Error::Type("Url includes credentials".to_string())) } // Step 5.4 - temporary_request = net_request_from_global(global, + temporary_request = net_request_from_global(&global_scope, url, false); // Step 5.5 @@ -150,7 +153,7 @@ impl Request { // Step 12 let mut request: NetTraitsRequest; - request = net_request_from_global(global, + request = net_request_from_global(&global_scope, temporary_request.current_url(), false); request.method = temporary_request.method; @@ -302,7 +305,7 @@ impl Request { } // Step 26 - let r = Request::from_net_request(global, + let r = Request::from_net_request(&global_scope, false, request); r.headers.or_init(|| Headers::for_request(&r.global_scope())); @@ -412,7 +415,7 @@ impl Request { } impl Request { - fn from_net_request(global: GlobalRef, + fn from_net_request(global: &GlobalScope, is_service_worker_global_scope: bool, net_request: NetTraitsRequest) -> Root { let r = Request::new(global, @@ -429,7 +432,7 @@ impl Request { let body_used = r.body_used.get(); let mime_type = r.mime_type.borrow().clone(); let headers_guard = r.Headers().get_guard(); - let r_clone = Request::new(r.global().r(), url, is_service_worker_global_scope); + let r_clone = Request::new(&r.global_scope(), url, is_service_worker_global_scope); r_clone.request.borrow_mut().pipeline_id.set(req.pipeline_id.get()); { let mut borrowed_r_request = r_clone.request.borrow_mut(); @@ -447,12 +450,11 @@ impl Request { } } -fn net_request_from_global(global: GlobalRef, +fn net_request_from_global(global: &GlobalScope, url: Url, is_service_worker_global_scope: bool) -> NetTraitsRequest { - let global_scope = global.as_global_scope(); - let origin = Origin::Origin(global_scope.get_url().origin()); - let pipeline_id = global_scope.pipeline_id(); + let origin = Origin::Origin(global.get_url().origin()); + let pipeline_id = global.pipeline_id(); NetTraitsRequest::new(url, Some(origin), is_service_worker_global_scope, From 2f54022761b0b1251bb0b18fc367b568d1c4c4ac Mon Sep 17 00:00:00 2001 From: Anthony Ramine Date: Sun, 2 Oct 2016 14:53:21 +0200 Subject: [PATCH 30/66] Remove some duplication in XMLHttpRequest methods --- components/script/dom/xmlhttprequest.rs | 14 ++++++-------- 1 file changed, 6 insertions(+), 8 deletions(-) diff --git a/components/script/dom/xmlhttprequest.rs b/components/script/dom/xmlhttprequest.rs index a87d64e3e61..84c7c903c7a 100644 --- a/components/script/dom/xmlhttprequest.rs +++ b/components/script/dom/xmlhttprequest.rs @@ -1197,29 +1197,27 @@ impl XMLHttpRequest { fn document_text_html(&self) -> Root{ let charset = self.final_charset().unwrap_or(UTF_8); - let wr = self.global(); - let wr = wr.r(); + let wr = self.global_scope(); let decoded = charset.decode(&self.response.borrow(), DecoderTrap::Replace).unwrap(); let document = self.new_doc(IsHTMLDocument::HTMLDocument); // TODO: Disable scripting while parsing parse_html(document.r(), DOMString::from(decoded), - wr.as_global_scope().get_url(), - ParseContext::Owner(Some(wr.as_global_scope().pipeline_id()))); + wr.get_url(), + ParseContext::Owner(Some(wr.pipeline_id()))); document } fn handle_xml(&self) -> Root { let charset = self.final_charset().unwrap_or(UTF_8); - let wr = self.global(); - let wr = wr.r(); + let wr = self.global_scope(); let decoded = charset.decode(&self.response.borrow(), DecoderTrap::Replace).unwrap(); let document = self.new_doc(IsHTMLDocument::NonHTMLDocument); // TODO: Disable scripting while parsing parse_xml(document.r(), DOMString::from(decoded), - wr.as_global_scope().get_url(), - xml::ParseContext::Owner(Some(wr.as_global_scope().pipeline_id()))); + wr.get_url(), + xml::ParseContext::Owner(Some(wr.pipeline_id()))); document } From 766010379e4c10d9cfaa9e319ec7c50bc30dfba5 Mon Sep 17 00:00:00 2001 From: Anthony Ramine Date: Sun, 2 Oct 2016 16:19:43 +0200 Subject: [PATCH 31/66] Introduce GlobalScope::as_window --- components/script/dom/bindings/global.rs | 9 --------- components/script/dom/bluetooth.rs | 4 +--- .../script/dom/bluetoothremotegattcharacteristic.rs | 4 +--- components/script/dom/bluetoothremotegattdescriptor.rs | 4 +--- components/script/dom/bluetoothremotegattserver.rs | 4 +--- components/script/dom/bluetoothremotegattservice.rs | 4 +--- components/script/dom/comment.rs | 2 +- components/script/dom/document.rs | 2 +- components/script/dom/documentfragment.rs | 2 +- components/script/dom/domparser.rs | 2 +- components/script/dom/focusevent.rs | 3 ++- components/script/dom/globalscope.rs | 5 +++++ components/script/dom/htmlformcontrolscollection.rs | 3 +-- components/script/dom/htmlimageelement.rs | 2 +- components/script/dom/keyboardevent.rs | 3 ++- components/script/dom/mouseevent.rs | 3 ++- components/script/dom/range.rs | 2 +- components/script/dom/storage.rs | 6 ++---- components/script/dom/testbinding.rs | 2 +- components/script/dom/text.rs | 2 +- components/script/dom/uievent.rs | 3 ++- components/script/dom/xmlhttprequest.rs | 2 +- 22 files changed, 30 insertions(+), 43 deletions(-) diff --git a/components/script/dom/bindings/global.rs b/components/script/dom/bindings/global.rs index 84b75cc9443..7366d507649 100644 --- a/components/script/dom/bindings/global.rs +++ b/components/script/dom/bindings/global.rs @@ -68,15 +68,6 @@ impl<'a> GlobalRef<'a> { } } - /// Extract a `Window`, causing thread failure if the global object is not - /// a `Window`. - pub fn as_window(&self) -> &window::Window { - match *self { - GlobalRef::Window(window) => window, - GlobalRef::Worker(_) => panic!("expected a Window scope"), - } - } - /// Get the `ResourceThreads` for this global scope. pub fn resource_threads(&self) -> ResourceThreads { match *self { diff --git a/components/script/dom/bluetooth.rs b/components/script/dom/bluetooth.rs index 02bccb80f91..143bc04855a 100644 --- a/components/script/dom/bluetooth.rs +++ b/components/script/dom/bluetooth.rs @@ -60,9 +60,7 @@ impl Bluetooth { } fn get_bluetooth_thread(&self) -> IpcSender { - let global_root = self.global(); - let global_ref = global_root.r(); - global_ref.as_window().bluetooth_thread() + self.global_scope().as_window().bluetooth_thread() } fn request_device(&self, option: &RequestDeviceOptions) -> Fallible> { diff --git a/components/script/dom/bluetoothremotegattcharacteristic.rs b/components/script/dom/bluetoothremotegattcharacteristic.rs index 0dbb7c4670e..faa6eba4bef 100644 --- a/components/script/dom/bluetoothremotegattcharacteristic.rs +++ b/components/script/dom/bluetoothremotegattcharacteristic.rs @@ -74,9 +74,7 @@ impl BluetoothRemoteGATTCharacteristic { } fn get_bluetooth_thread(&self) -> IpcSender { - let global_root = self.global(); - let global_ref = global_root.r(); - global_ref.as_window().bluetooth_thread() + self.global_scope().as_window().bluetooth_thread() } fn get_instance_id(&self) -> String { diff --git a/components/script/dom/bluetoothremotegattdescriptor.rs b/components/script/dom/bluetoothremotegattdescriptor.rs index ee4c6ce1af5..2bc2821f607 100644 --- a/components/script/dom/bluetoothremotegattdescriptor.rs +++ b/components/script/dom/bluetoothremotegattdescriptor.rs @@ -61,9 +61,7 @@ impl BluetoothRemoteGATTDescriptor { } fn get_bluetooth_thread(&self) -> IpcSender { - let global_root = self.global(); - let global_ref = global_root.r(); - global_ref.as_window().bluetooth_thread() + self.global_scope().as_window().bluetooth_thread() } fn get_instance_id(&self) -> String { diff --git a/components/script/dom/bluetoothremotegattserver.rs b/components/script/dom/bluetoothremotegattserver.rs index 7bb4d8fb05d..a9712216d61 100644 --- a/components/script/dom/bluetoothremotegattserver.rs +++ b/components/script/dom/bluetoothremotegattserver.rs @@ -46,9 +46,7 @@ impl BluetoothRemoteGATTServer { } fn get_bluetooth_thread(&self) -> IpcSender { - let global_root = self.global(); - let global_ref = global_root.r(); - global_ref.as_window().bluetooth_thread() + self.global_scope().as_window().bluetooth_thread() } // https://webbluetoothcg.github.io/web-bluetooth/#dom-bluetoothremotegattserver-connect diff --git a/components/script/dom/bluetoothremotegattservice.rs b/components/script/dom/bluetoothremotegattservice.rs index df1718ef403..29e2625b818 100644 --- a/components/script/dom/bluetoothremotegattservice.rs +++ b/components/script/dom/bluetoothremotegattservice.rs @@ -61,9 +61,7 @@ impl BluetoothRemoteGATTService { } fn get_bluetooth_thread(&self) -> IpcSender { - let global_root = self.global(); - let global_ref = global_root.r(); - global_ref.as_window().bluetooth_thread() + self.global_scope().as_window().bluetooth_thread() } fn get_instance_id(&self) -> String { diff --git a/components/script/dom/comment.rs b/components/script/dom/comment.rs index 43115e1dd51..2eec7652e25 100644 --- a/components/script/dom/comment.rs +++ b/components/script/dom/comment.rs @@ -32,7 +32,7 @@ impl Comment { } pub fn Constructor(global: GlobalRef, data: DOMString) -> Fallible> { - let document = global.as_window().Document(); + let document = global.as_global_scope().as_window().Document(); Ok(Comment::new(data, document.r())) } } diff --git a/components/script/dom/document.rs b/components/script/dom/document.rs index da7b895a4f3..5a5507b0c20 100644 --- a/components/script/dom/document.rs +++ b/components/script/dom/document.rs @@ -1820,7 +1820,7 @@ impl Document { // https://dom.spec.whatwg.org/#dom-document pub fn Constructor(global: GlobalRef) -> Fallible> { - let win = global.as_window(); + let win = global.as_global_scope().as_window(); let doc = win.Document(); let doc = doc.r(); let docloader = DocumentLoader::new(&*doc.loader()); diff --git a/components/script/dom/documentfragment.rs b/components/script/dom/documentfragment.rs index 0fba19d5aff..bf05e36fce3 100644 --- a/components/script/dom/documentfragment.rs +++ b/components/script/dom/documentfragment.rs @@ -39,7 +39,7 @@ impl DocumentFragment { } pub fn Constructor(global: GlobalRef) -> Fallible> { - let document = global.as_window().Document(); + let document = global.as_global_scope().as_window().Document(); Ok(DocumentFragment::new(document.r())) } diff --git a/components/script/dom/domparser.rs b/components/script/dom/domparser.rs index cf82cad01ca..6d830e40bfd 100644 --- a/components/script/dom/domparser.rs +++ b/components/script/dom/domparser.rs @@ -43,7 +43,7 @@ impl DOMParser { } pub fn Constructor(global: GlobalRef) -> Fallible> { - Ok(DOMParser::new(global.as_window())) + Ok(DOMParser::new(global.as_global_scope().as_window())) } } diff --git a/components/script/dom/focusevent.rs b/components/script/dom/focusevent.rs index cb65d40088f..8d3f6b57256 100644 --- a/components/script/dom/focusevent.rs +++ b/components/script/dom/focusevent.rs @@ -59,7 +59,8 @@ impl FocusEvent { init: &FocusEventBinding::FocusEventInit) -> Fallible> { let bubbles = EventBubbles::from(init.parent.parent.bubbles); let cancelable = EventCancelable::from(init.parent.parent.cancelable); - let event = FocusEvent::new(global.as_window(), type_, + let event = FocusEvent::new(global.as_global_scope().as_window(), + type_, bubbles, cancelable, init.parent.view.r(), diff --git a/components/script/dom/globalscope.rs b/components/script/dom/globalscope.rs index 4828dfec696..33873f4668f 100644 --- a/components/script/dom/globalscope.rs +++ b/components/script/dom/globalscope.rs @@ -190,6 +190,11 @@ impl GlobalScope { } unreachable!(); } + + /// Extract a `Window`, panic if the global object is not a `Window`. + pub fn as_window(&self) -> &Window { + self.downcast::().expect("expected a Window scope") + } } fn timestamp_in_ms(time: Timespec) -> u64 { diff --git a/components/script/dom/htmlformcontrolscollection.rs b/components/script/dom/htmlformcontrolscollection.rs index 2450b26c179..5edc19232d4 100644 --- a/components/script/dom/htmlformcontrolscollection.rs +++ b/components/script/dom/htmlformcontrolscollection.rs @@ -65,8 +65,7 @@ impl HTMLFormControlsCollectionMethods for HTMLFormControlsCollection { // Step 4-5 let once = iter::once(Root::upcast::(elem)); let list = once.chain(peekable.map(Root::upcast)); - let global = self.global(); - let global = global.r(); + let global = self.global_scope(); let window = global.as_window(); Some(RadioNodeListOrElement::RadioNodeList(RadioNodeList::new_simple_list(window, list))) } diff --git a/components/script/dom/htmlimageelement.rs b/components/script/dom/htmlimageelement.rs index c6652913c42..d96bb0cab3a 100644 --- a/components/script/dom/htmlimageelement.rs +++ b/components/script/dom/htmlimageelement.rs @@ -228,7 +228,7 @@ impl HTMLImageElement { pub fn Image(global: GlobalRef, width: Option, height: Option) -> Fallible> { - let document = global.as_window().Document(); + let document = global.as_global_scope().as_window().Document(); let image = HTMLImageElement::new(atom!("img"), None, document.r()); if let Some(w) = width { image.SetWidth(w); diff --git a/components/script/dom/keyboardevent.rs b/components/script/dom/keyboardevent.rs index 06987f55b12..812b9f63051 100644 --- a/components/script/dom/keyboardevent.rs +++ b/components/script/dom/keyboardevent.rs @@ -104,7 +104,8 @@ impl KeyboardEvent { pub fn Constructor(global: GlobalRef, type_: DOMString, init: &KeyboardEventBinding::KeyboardEventInit) -> Fallible> { - let event = KeyboardEvent::new(global.as_window(), type_, + let event = KeyboardEvent::new(global.as_global_scope().as_window(), + type_, init.parent.parent.parent.bubbles, init.parent.parent.parent.cancelable, init.parent.parent.view.r(), diff --git a/components/script/dom/mouseevent.rs b/components/script/dom/mouseevent.rs index 096b119641f..41c7d88dc6d 100644 --- a/components/script/dom/mouseevent.rs +++ b/components/script/dom/mouseevent.rs @@ -87,7 +87,8 @@ impl MouseEvent { init: &MouseEventBinding::MouseEventInit) -> Fallible> { let bubbles = EventBubbles::from(init.parent.parent.parent.bubbles); let cancelable = EventCancelable::from(init.parent.parent.parent.cancelable); - let event = MouseEvent::new(global.as_window(), type_, + let event = MouseEvent::new(global.as_global_scope().as_window(), + type_, bubbles, cancelable, init.parent.parent.view.r(), diff --git a/components/script/dom/range.rs b/components/script/dom/range.rs index 80018b661f3..7e636164da5 100644 --- a/components/script/dom/range.rs +++ b/components/script/dom/range.rs @@ -71,7 +71,7 @@ impl Range { // https://dom.spec.whatwg.org/#dom-range pub fn Constructor(global: GlobalRef) -> Fallible> { - let document = global.as_window().Document(); + let document = global.as_global_scope().as_window().Document(); Ok(Range::new_with_doc(document.r())) } diff --git a/components/script/dom/storage.rs b/components/script/dom/storage.rs index 2f0ff42125a..76b04f60d6f 100644 --- a/components/script/dom/storage.rs +++ b/components/script/dom/storage.rs @@ -44,9 +44,7 @@ impl Storage { } fn get_storage_thread(&self) -> IpcSender { - let global_root = self.global(); - let global_ref = global_root.r(); - global_ref.as_window().resource_threads().sender() + self.global_scope().as_window().resource_threads().sender() } } @@ -154,7 +152,7 @@ impl Storage { new_value: Option) { let global_root = self.global(); let global_ref = global_root.r(); - let window = global_ref.as_window(); + let window = global_ref.as_global_scope().as_window(); let task_source = window.dom_manipulation_task_source(); let trusted_storage = Trusted::new(self); task_source.queue(box StorageEventRunnable::new(trusted_storage, key, old_value, new_value), diff --git a/components/script/dom/testbinding.rs b/components/script/dom/testbinding.rs index fdb20fc5114..eb3defbe6a5 100644 --- a/components/script/dom/testbinding.rs +++ b/components/script/dom/testbinding.rs @@ -750,7 +750,7 @@ impl TestBindingMethods for TestBinding { } fn AdvanceClock(&self, ms: i32, tick: bool) { - self.global().r().as_window().advance_animation_clock(ms, tick); + self.global_scope().as_window().advance_animation_clock(ms, tick); } fn Panic(&self) { panic!("explicit panic from script") } diff --git a/components/script/dom/text.rs b/components/script/dom/text.rs index 5d377e1e05d..fec47d6fc84 100644 --- a/components/script/dom/text.rs +++ b/components/script/dom/text.rs @@ -36,7 +36,7 @@ impl Text { } pub fn Constructor(global: GlobalRef, text: DOMString) -> Fallible> { - let document = global.as_window().Document(); + let document = global.as_global_scope().as_window().Document(); Ok(Text::new(text, document.r())) } } diff --git a/components/script/dom/uievent.rs b/components/script/dom/uievent.rs index 0b64e36c62f..698645f5a6c 100644 --- a/components/script/dom/uievent.rs +++ b/components/script/dom/uievent.rs @@ -57,7 +57,8 @@ impl UIEvent { init: &UIEventBinding::UIEventInit) -> Fallible> { let bubbles = EventBubbles::from(init.parent.bubbles); let cancelable = EventCancelable::from(init.parent.cancelable); - let event = UIEvent::new(global.as_window(), type_, + let event = UIEvent::new(global.as_global_scope().as_window(), + type_, bubbles, cancelable, init.view.r(), init.detail); Ok(event) diff --git a/components/script/dom/xmlhttprequest.rs b/components/script/dom/xmlhttprequest.rs index 84c7c903c7a..c08ea52dae8 100644 --- a/components/script/dom/xmlhttprequest.rs +++ b/components/script/dom/xmlhttprequest.rs @@ -1224,7 +1224,7 @@ impl XMLHttpRequest { fn new_doc(&self, is_html_document: IsHTMLDocument) -> Root { let wr = self.global(); let wr = wr.r(); - let win = wr.as_window(); + let win = wr.as_global_scope().as_window(); let doc = win.Document(); let doc = doc.r(); let docloader = DocumentLoader::new(&*doc.loader()); From 918352519293cbf3ac86df7cfbe5f3cb9d07f0bc Mon Sep 17 00:00:00 2001 From: Anthony Ramine Date: Sun, 2 Oct 2016 16:20:33 +0200 Subject: [PATCH 32/66] Make XMLHttpRequest::new_doc use Reflectable::global_scope --- components/script/dom/xmlhttprequest.rs | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-) diff --git a/components/script/dom/xmlhttprequest.rs b/components/script/dom/xmlhttprequest.rs index c08ea52dae8..87793f2d0b6 100644 --- a/components/script/dom/xmlhttprequest.rs +++ b/components/script/dom/xmlhttprequest.rs @@ -1222,13 +1222,12 @@ impl XMLHttpRequest { } fn new_doc(&self, is_html_document: IsHTMLDocument) -> Root { - let wr = self.global(); - let wr = wr.r(); - let win = wr.as_global_scope().as_window(); + let wr = self.global_scope(); + let win = wr.as_window(); let doc = win.Document(); let doc = doc.r(); let docloader = DocumentLoader::new(&*doc.loader()); - let base = self.global_scope().get_url(); + let base = wr.get_url(); let parsed_url = match base.join(&self.ResponseURL().0) { Ok(parsed) => Some(parsed), Err(_) => None // Step 7 From d4fccbace431b003abbc49f2fbc5e8b2de6b3f2a Mon Sep 17 00:00:00 2001 From: Anthony Ramine Date: Sun, 2 Oct 2016 17:11:29 +0200 Subject: [PATCH 33/66] Make bluetooth::result_to_promise take a &GlobalScope --- components/script/dom/bluetooth.rs | 7 +++---- .../script/dom/bluetoothremotegattcharacteristic.rs | 8 ++++---- components/script/dom/bluetoothremotegattdescriptor.rs | 4 ++-- components/script/dom/bluetoothremotegattserver.rs | 6 +++--- components/script/dom/bluetoothremotegattservice.rs | 8 ++++---- 5 files changed, 16 insertions(+), 17 deletions(-) diff --git a/components/script/dom/bluetooth.rs b/components/script/dom/bluetooth.rs index 143bc04855a..a0e5484abd3 100644 --- a/components/script/dom/bluetooth.rs +++ b/components/script/dom/bluetooth.rs @@ -8,7 +8,6 @@ use dom::bindings::codegen::Bindings::BluetoothBinding::{self, BluetoothMethods, use dom::bindings::codegen::Bindings::BluetoothBinding::RequestDeviceOptions; use dom::bindings::error::Error::{self, Security, Type}; use dom::bindings::error::Fallible; -use dom::bindings::global::GlobalRef; use dom::bindings::js::Root; use dom::bindings::reflector::{Reflectable, Reflector, reflect_dom_object}; use dom::bindings::str::DOMString; @@ -271,10 +270,10 @@ fn canonicalize_filter(filter: &BluetoothRequestDeviceFilter) -> Fallible(global_ref: GlobalRef, +pub fn result_to_promise(global: &GlobalScope, bluetooth_result: Fallible) -> Rc { - let p = Promise::new(global_ref.as_global_scope()); + let p = Promise::new(global); match bluetooth_result { Ok(v) => p.resolve_native(p.global().r().get_cx(), &v), Err(e) => p.reject_error(p.global().r().get_cx(), e), @@ -298,6 +297,6 @@ impl BluetoothMethods for Bluetooth { #[allow(unrooted_must_root)] // https://webbluetoothcg.github.io/web-bluetooth/#dom-bluetooth-requestdevice fn RequestDevice(&self, option: &RequestDeviceOptions) -> Rc { - result_to_promise(self.global().r(), self.request_device(option)) + result_to_promise(&self.global_scope(), self.request_device(option)) } } diff --git a/components/script/dom/bluetoothremotegattcharacteristic.rs b/components/script/dom/bluetoothremotegattcharacteristic.rs index faa6eba4bef..425fcffb9cb 100644 --- a/components/script/dom/bluetoothremotegattcharacteristic.rs +++ b/components/script/dom/bluetoothremotegattcharacteristic.rs @@ -212,7 +212,7 @@ impl BluetoothRemoteGATTCharacteristicMethods for BluetoothRemoteGATTCharacteris #[allow(unrooted_must_root)] // https://webbluetoothcg.github.io/web-bluetooth/#dom-bluetoothremotegattcharacteristic-getdescriptor fn GetDescriptor(&self, descriptor: BluetoothDescriptorUUID) -> Rc { - result_to_promise(self.global().r(), self.get_descriptor(descriptor)) + result_to_promise(&self.global_scope(), self.get_descriptor(descriptor)) } #[allow(unrooted_must_root)] @@ -220,7 +220,7 @@ impl BluetoothRemoteGATTCharacteristicMethods for BluetoothRemoteGATTCharacteris fn GetDescriptors(&self, descriptor: Option) -> Rc { - result_to_promise(self.global().r(), self.get_descriptors(descriptor)) + result_to_promise(&self.global_scope(), self.get_descriptors(descriptor)) } // https://webbluetoothcg.github.io/web-bluetooth/#dom-bluetoothremotegattcharacteristic-value @@ -231,12 +231,12 @@ impl BluetoothRemoteGATTCharacteristicMethods for BluetoothRemoteGATTCharacteris #[allow(unrooted_must_root)] // https://webbluetoothcg.github.io/web-bluetooth/#dom-bluetoothremotegattcharacteristic-readvalue fn ReadValue(&self) -> Rc { - result_to_promise(self.global().r(), self.read_value()) + result_to_promise(&self.global_scope(), self.read_value()) } #[allow(unrooted_must_root)] // https://webbluetoothcg.github.io/web-bluetooth/#dom-bluetoothremotegattcharacteristic-writevalue fn WriteValue(&self, value: Vec) -> Rc { - result_to_promise(self.global().r(), self.write_value(value)) + result_to_promise(&self.global_scope(), self.write_value(value)) } } diff --git a/components/script/dom/bluetoothremotegattdescriptor.rs b/components/script/dom/bluetoothremotegattdescriptor.rs index 2bc2821f607..d42742bc235 100644 --- a/components/script/dom/bluetoothremotegattdescriptor.rs +++ b/components/script/dom/bluetoothremotegattdescriptor.rs @@ -135,12 +135,12 @@ impl BluetoothRemoteGATTDescriptorMethods for BluetoothRemoteGATTDescriptor { #[allow(unrooted_must_root)] // https://webbluetoothcg.github.io/web-bluetooth/#dom-bluetoothremotegattdescriptor-readvalue fn ReadValue(&self) -> Rc { - result_to_promise(self.global().r(), self.read_value()) + result_to_promise(&self.global_scope(), self.read_value()) } #[allow(unrooted_must_root)] // https://webbluetoothcg.github.io/web-bluetooth/#dom-bluetoothremotegattdescriptor-writevalue fn WriteValue(&self, value: Vec) -> Rc { - result_to_promise(self.global().r(), self.write_value(value)) + result_to_promise(&self.global_scope(), self.write_value(value)) } } diff --git a/components/script/dom/bluetoothremotegattserver.rs b/components/script/dom/bluetoothremotegattserver.rs index a9712216d61..703be681a23 100644 --- a/components/script/dom/bluetoothremotegattserver.rs +++ b/components/script/dom/bluetoothremotegattserver.rs @@ -138,7 +138,7 @@ impl BluetoothRemoteGATTServerMethods for BluetoothRemoteGATTServer { #[allow(unrooted_must_root)] // https://webbluetoothcg.github.io/web-bluetooth/#dom-bluetoothremotegattserver-connect fn Connect(&self) -> Rc { - result_to_promise(self.global().r(), self.connect()) + result_to_promise(&self.global_scope(), self.connect()) } // https://webbluetoothcg.github.io/web-bluetooth/#dom-bluetoothremotegattserver-disconnect @@ -161,7 +161,7 @@ impl BluetoothRemoteGATTServerMethods for BluetoothRemoteGATTServer { #[allow(unrooted_must_root)] // https://webbluetoothcg.github.io/web-bluetooth/#dom-bluetoothremotegattserver-getprimaryservice fn GetPrimaryService(&self, service: BluetoothServiceUUID) -> Rc { - result_to_promise(self.global().r(), self.get_primary_service(service)) + result_to_promise(&self.global_scope(), self.get_primary_service(service)) } #[allow(unrooted_must_root)] @@ -169,6 +169,6 @@ impl BluetoothRemoteGATTServerMethods for BluetoothRemoteGATTServer { fn GetPrimaryServices(&self, service: Option) -> Rc { - result_to_promise(self.global().r(), self.get_primary_services(service)) + result_to_promise(&self.global_scope(), self.get_primary_services(service)) } } diff --git a/components/script/dom/bluetoothremotegattservice.rs b/components/script/dom/bluetoothremotegattservice.rs index 29e2625b818..94082277768 100644 --- a/components/script/dom/bluetoothremotegattservice.rs +++ b/components/script/dom/bluetoothremotegattservice.rs @@ -236,7 +236,7 @@ impl BluetoothRemoteGATTServiceMethods for BluetoothRemoteGATTService { fn GetCharacteristic(&self, characteristic: BluetoothCharacteristicUUID) -> Rc { - result_to_promise(self.global().r(), self.get_characteristic(characteristic)) + result_to_promise(&self.global_scope(), self.get_characteristic(characteristic)) } #[allow(unrooted_must_root)] @@ -244,7 +244,7 @@ impl BluetoothRemoteGATTServiceMethods for BluetoothRemoteGATTService { fn GetCharacteristics(&self, characteristic: Option) -> Rc { - result_to_promise(self.global().r(), self.get_characteristics(characteristic)) + result_to_promise(&self.global_scope(), self.get_characteristics(characteristic)) } #[allow(unrooted_must_root)] @@ -252,7 +252,7 @@ impl BluetoothRemoteGATTServiceMethods for BluetoothRemoteGATTService { fn GetIncludedService(&self, service: BluetoothServiceUUID) -> Rc { - result_to_promise(self.global().r(), self.get_included_service(service)) + result_to_promise(&self.global_scope(), self.get_included_service(service)) } #[allow(unrooted_must_root)] @@ -260,6 +260,6 @@ impl BluetoothRemoteGATTServiceMethods for BluetoothRemoteGATTService { fn GetIncludedServices(&self, service: Option) -> Rc { - result_to_promise(self.global().r(), self.get_included_services(service)) + result_to_promise(&self.global_scope(), self.get_included_services(service)) } } From 86d2008137f48432ba14aed5009775cfd4dadcc5 Mon Sep 17 00:00:00 2001 From: Anthony Ramine Date: Mon, 3 Oct 2016 02:26:05 +0200 Subject: [PATCH 34/66] Introduce GlobalScope::report_an_error --- components/script/dom/bindings/error.rs | 6 +-- components/script/dom/bindings/global.rs | 21 +++++----- components/script/dom/globalscope.rs | 47 +++++++++++++++++++++- components/script/dom/window.rs | 39 +----------------- components/script/dom/worker.rs | 6 +-- components/script/dom/workerglobalscope.rs | 47 +--------------------- 6 files changed, 65 insertions(+), 101 deletions(-) diff --git a/components/script/dom/bindings/error.rs b/components/script/dom/bindings/error.rs index ed274426bd3..7e0f55d86bf 100644 --- a/components/script/dom/bindings/error.rs +++ b/components/script/dom/bindings/error.rs @@ -8,7 +8,7 @@ use dom::bindings::codegen::Bindings::DOMExceptionBinding::DOMExceptionMethods; use dom::bindings::codegen::PrototypeList::proto_id_to_name; use dom::bindings::conversions::{ConversionResult, FromJSValConvertible, ToJSValConvertible}; use dom::bindings::conversions::root_from_object; -use dom::bindings::global::global_root_from_context; +use dom::bindings::global::global_scope_from_context; use dom::bindings::str::USVString; use dom::domexception::{DOMErrorName, DOMException}; use dom::globalscope::GlobalScope; @@ -246,8 +246,8 @@ pub unsafe fn report_pending_exception(cx: *mut JSContext, dispatch_event: bool) error_info.message); if dispatch_event { - let global = global_root_from_context(cx); - global.r().report_an_error(error_info, value.handle()); + let global = global_scope_from_context(cx); + global.report_an_error(error_info, value.handle()); } } } diff --git a/components/script/dom/bindings/global.rs b/components/script/dom/bindings/global.rs index 7366d507649..9ff4ae047da 100644 --- a/components/script/dom/bindings/global.rs +++ b/components/script/dom/bindings/global.rs @@ -8,7 +8,7 @@ //! code that works in workers as well as window scopes. use dom::bindings::conversions::root_from_object; -use dom::bindings::error::{ErrorInfo, report_pending_exception}; +use dom::bindings::error::report_pending_exception; use dom::bindings::inheritance::Castable; use dom::bindings::js::Root; use dom::bindings::reflector::{Reflectable, Reflector}; @@ -18,8 +18,8 @@ use dom::workerglobalscope::WorkerGlobalScope; use js::{JSCLASS_IS_DOMJSCLASS, JSCLASS_IS_GLOBAL}; use js::glue::{IsWrapper, UnwrapObject}; use js::jsapi::{CurrentGlobalOrNull, Evaluate2, GetGlobalForObjectCrossCompartment}; -use js::jsapi::{HandleValue, JS_GetClass, JSAutoCompartment, JSContext}; -use js::jsapi::{JSObject, MutableHandleValue}; +use js::jsapi::{JSAutoCompartment, JSContext, JSObject}; +use js::jsapi::{JS_GetClass, MutableHandleValue}; use js::rust::CompileOptionsWrapper; use libc; use net_traits::{CoreResourceThread, IpcSend, ResourceThreads}; @@ -220,14 +220,6 @@ impl<'a> GlobalRef<'a> { GlobalRef::Worker(ref worker) => worker.flush_promise_jobs(), } } - - /// https://html.spec.whatwg.org/multipage/#report-the-error - pub fn report_an_error(&self, error_info: ErrorInfo, value: HandleValue) { - match *self { - GlobalRef::Window(ref window) => window.report_an_error(error_info, value), - GlobalRef::Worker(ref worker) => worker.report_an_error(error_info, value), - } - } } impl<'a> Reflectable for GlobalRef<'a> { @@ -296,6 +288,13 @@ pub unsafe fn global_root_from_object(obj: *mut JSObject) -> GlobalRoot { global_root_from_global(global) } +/// Returns the global scope for the given JSContext +#[allow(unrooted_must_root)] +pub unsafe fn global_scope_from_context(cx: *mut JSContext) -> Root { + let global = CurrentGlobalOrNull(cx); + global_scope_from_global(global) +} + /// Returns the global object for the given JSContext #[allow(unrooted_must_root)] pub unsafe fn global_root_from_context(cx: *mut JSContext) -> GlobalRoot { diff --git a/components/script/dom/globalscope.rs b/components/script/dom/globalscope.rs index 33873f4668f..95cd8c4bd4a 100644 --- a/components/script/dom/globalscope.rs +++ b/components/script/dom/globalscope.rs @@ -5,16 +5,21 @@ use devtools_traits::{ScriptToDevtoolsControlMsg, WorkerId}; use dom::bindings::cell::DOMRefCell; use dom::bindings::codegen::Bindings::WindowBinding::WindowMethods; +use dom::bindings::error::ErrorInfo; use dom::bindings::inheritance::Castable; use dom::bindings::js::{JS, MutNullableHeap, Root}; use dom::bindings::reflector::Reflectable; use dom::bindings::str::DOMString; use dom::crypto::Crypto; +use dom::dedicatedworkerglobalscope::DedicatedWorkerGlobalScope; +use dom::errorevent::ErrorEvent; +use dom::event::{Event, EventBubbles, EventCancelable}; +use dom::eventdispatcher::EventStatus; use dom::eventtarget::EventTarget; use dom::window::Window; use dom::workerglobalscope::WorkerGlobalScope; use ipc_channel::ipc::IpcSender; -use js::jsapi::{JS_GetContext, JS_GetObjectRuntime, JSContext}; +use js::jsapi::{HandleValue, JS_GetContext, JS_GetObjectRuntime, JSContext}; use msg::constellation_msg::PipelineId; use profile_traits::{mem, time}; use script_traits::{ScriptMsg as ConstellationMsg, TimerEventRequest}; @@ -58,6 +63,9 @@ pub struct GlobalScope { #[ignore_heap_size_of = "channels are hard"] scheduler_chan: IpcSender, + + /// https://html.spec.whatwg.org/multipage/#in-error-reporting-mode + in_error_reporting_mode: Cell, } impl GlobalScope { @@ -81,6 +89,7 @@ impl GlobalScope { time_profiler_chan: time_profiler_chan, constellation_chan: constellation_chan, scheduler_chan: scheduler_chan, + in_error_reporting_mode: Default::default(), } } @@ -195,6 +204,42 @@ impl GlobalScope { pub fn as_window(&self) -> &Window { self.downcast::().expect("expected a Window scope") } + + /// https://html.spec.whatwg.org/multipage/#report-the-error + pub fn report_an_error(&self, error_info: ErrorInfo, value: HandleValue) { + // Step 1. + if self.in_error_reporting_mode.get() { + return; + } + + // Step 2. + self.in_error_reporting_mode.set(true); + + // Steps 3-12. + // FIXME(#13195): muted errors. + let event = ErrorEvent::new(self, + atom!("error"), + EventBubbles::DoesNotBubble, + EventCancelable::Cancelable, + error_info.message.as_str().into(), + error_info.filename.as_str().into(), + error_info.lineno, + error_info.column, + value); + + // Step 13. + let event_status = event.upcast::().fire(self.upcast::()); + + // Step 15 + if event_status == EventStatus::NotCanceled { + if let Some(dedicated) = self.downcast::() { + dedicated.forward_error_to_worker_object(error_info); + } + } + + // Step 14 + self.in_error_reporting_mode.set(false); + } } fn timestamp_in_ms(time: Timespec) -> u64 { diff --git a/components/script/dom/window.rs b/components/script/dom/window.rs index f5b021feea6..21b108360f0 100644 --- a/components/script/dom/window.rs +++ b/components/script/dom/window.rs @@ -16,7 +16,7 @@ use dom::bindings::codegen::Bindings::RequestBinding::RequestInit; use dom::bindings::codegen::Bindings::WindowBinding::{self, FrameRequestCallback, WindowMethods}; use dom::bindings::codegen::Bindings::WindowBinding::{ScrollBehavior, ScrollToOptions}; use dom::bindings::codegen::UnionTypes::RequestOrUSVString; -use dom::bindings::error::{Error, ErrorInfo, ErrorResult, Fallible}; +use dom::bindings::error::{Error, ErrorResult, Fallible}; use dom::bindings::global::{GlobalRef, global_root_from_object}; use dom::bindings::inheritance::Castable; use dom::bindings::js::{JS, MutNullableHeap, Root}; @@ -31,9 +31,7 @@ use dom::crypto::Crypto; use dom::cssstyledeclaration::{CSSModificationAccess, CSSStyleDeclaration}; use dom::document::Document; use dom::element::Element; -use dom::errorevent::ErrorEvent; -use dom::event::{Event, EventBubbles, EventCancelable}; -use dom::eventtarget::EventTarget; +use dom::event::Event; use dom::globalscope::GlobalScope; use dom::history::History; use dom::htmliframeelement::build_mozbrowser_custom_event; @@ -242,9 +240,6 @@ pub struct Window { /// A list of scroll offsets for each scrollable element. scroll_offsets: DOMRefCell>>, - - /// https://html.spec.whatwg.org/multipage/#in-error-reporting-mode - in_error_reporting_mode: Cell, } impl Window { @@ -1634,40 +1629,10 @@ impl Window { ignore_further_async_events: Arc::new(AtomicBool::new(false)), error_reporter: error_reporter, scroll_offsets: DOMRefCell::new(HashMap::new()), - in_error_reporting_mode: Cell::new(false), }; WindowBinding::Wrap(runtime.cx(), win) } - - /// https://html.spec.whatwg.org/multipage/#report-the-error - pub fn report_an_error(&self, error_info: ErrorInfo, value: HandleValue) { - // Step 1. - if self.in_error_reporting_mode.get() { - return; - } - - // Step 2. - self.in_error_reporting_mode.set(true); - - // Steps 3-12. - // FIXME(#13195): muted errors. - let event = ErrorEvent::new(self.upcast(), - atom!("error"), - EventBubbles::DoesNotBubble, - EventCancelable::Cancelable, - error_info.message.into(), - error_info.filename.into(), - error_info.lineno, - error_info.column, - value); - - // Step 13. - event.upcast::().fire(self.upcast::()); - - // Step 14. - self.in_error_reporting_mode.set(false); - } } fn should_move_clip_rect(clip_rect: Rect, new_viewport: Rect) -> bool { diff --git a/components/script/dom/worker.rs b/components/script/dom/worker.rs index 833675fa1e3..9e590b0f7da 100644 --- a/components/script/dom/worker.rs +++ b/components/script/dom/worker.rs @@ -145,8 +145,8 @@ impl Worker { #[allow(unsafe_code)] fn dispatch_error(&self, error_info: ErrorInfo) { - let global = self.global(); - let event = ErrorEvent::new(global.r().as_global_scope(), + let global = self.global_scope(); + let event = ErrorEvent::new(&global, atom!("error"), EventBubbles::DoesNotBubble, EventCancelable::Cancelable, @@ -161,7 +161,7 @@ impl Worker { return; } - global.r().report_an_error(error_info, unsafe { NullHandleValue }); + global.report_an_error(error_info, unsafe { NullHandleValue }); } } diff --git a/components/script/dom/workerglobalscope.rs b/components/script/dom/workerglobalscope.rs index 55326f20277..b83c36a1aee 100644 --- a/components/script/dom/workerglobalscope.rs +++ b/components/script/dom/workerglobalscope.rs @@ -8,7 +8,7 @@ use dom::bindings::codegen::Bindings::FunctionBinding::Function; use dom::bindings::codegen::Bindings::RequestBinding::RequestInit; use dom::bindings::codegen::Bindings::WorkerGlobalScopeBinding::WorkerGlobalScopeMethods; use dom::bindings::codegen::UnionTypes::RequestOrUSVString; -use dom::bindings::error::{Error, ErrorInfo, ErrorResult, Fallible, report_pending_exception}; +use dom::bindings::error::{Error, ErrorResult, Fallible, report_pending_exception}; use dom::bindings::global::{GlobalRef, GlobalRoot}; use dom::bindings::inheritance::Castable; use dom::bindings::js::{JS, MutNullableHeap, Root}; @@ -17,10 +17,6 @@ use dom::bindings::reflector::Reflectable; use dom::bindings::str::DOMString; use dom::crypto::Crypto; use dom::dedicatedworkerglobalscope::DedicatedWorkerGlobalScope; -use dom::errorevent::ErrorEvent; -use dom::event::{Event, EventBubbles, EventCancelable}; -use dom::eventdispatcher::EventStatus; -use dom::eventtarget::EventTarget; use dom::globalscope::GlobalScope; use dom::promise::Promise; use dom::serviceworkerglobalscope::ServiceWorkerGlobalScope; @@ -40,7 +36,6 @@ use script_runtime::{ScriptThreadEventCategory, PromiseJobQueue, EnqueuedPromise use script_thread::{Runnable, RunnableWrapper}; use script_traits::{MsDuration, TimerEvent, TimerEventId, TimerSource}; use script_traits::WorkerGlobalScopeInit; -use std::cell::Cell; use std::default::Default; use std::panic; use std::rc::Rc; @@ -104,9 +99,6 @@ pub struct WorkerGlobalScope { from_devtools_receiver: Receiver, promise_job_queue: PromiseJobQueue, - - /// https://html.spec.whatwg.org/multipage/#in-error-reporting-mode - in_error_reporting_mode: Cell } impl WorkerGlobalScope { @@ -137,7 +129,6 @@ impl WorkerGlobalScope { from_devtools_sender: init.from_devtools_sender, from_devtools_receiver: from_devtools_receiver, promise_job_queue: PromiseJobQueue::new(), - in_error_reporting_mode: Default::default(), } } @@ -431,42 +422,6 @@ impl WorkerGlobalScope { closing.store(true, Ordering::SeqCst); } } - - /// https://html.spec.whatwg.org/multipage/#report-the-error - pub fn report_an_error(&self, error_info: ErrorInfo, value: HandleValue) { - // Step 1. - if self.in_error_reporting_mode.get() { - return; - } - - // Step 2. - self.in_error_reporting_mode.set(true); - - // Steps 3-12. - // FIXME(#13195): muted errors. - let event = ErrorEvent::new(self.upcast(), - atom!("error"), - EventBubbles::DoesNotBubble, - EventCancelable::Cancelable, - error_info.message.as_str().into(), - error_info.filename.as_str().into(), - error_info.lineno, - error_info.column, - value); - - // Step 13. - let event_status = event.upcast::().fire(self.upcast::()); - - // Step 15 - if event_status == EventStatus::NotCanceled { - if let Some(dedicated) = self.downcast::() { - dedicated.forward_error_to_worker_object(error_info); - } - } - - // Step 14 - self.in_error_reporting_mode.set(false); - } } struct FlushPromiseJobs { From bad49e46964915afeac3aab4f7de9a9d6c2c55c6 Mon Sep 17 00:00:00 2001 From: Anthony Ramine Date: Mon, 3 Oct 2016 18:39:03 +0200 Subject: [PATCH 35/66] Introduce GlobalScope::resource_threads --- components/script/dom/bindings/global.rs | 12 ++---------- components/script/dom/blob.rs | 6 +++--- components/script/dom/document.rs | 6 +++++- components/script/dom/globalscope.rs | 14 +++++++++++++- components/script/dom/htmlinputelement.rs | 2 +- components/script/dom/storage.rs | 2 +- components/script/dom/url.rs | 5 +++-- components/script/dom/window.rs | 12 ++---------- components/script/dom/workerglobalscope.rs | 18 +++++++----------- components/script/webdriver_handlers.rs | 8 ++++---- 10 files changed, 41 insertions(+), 44 deletions(-) diff --git a/components/script/dom/bindings/global.rs b/components/script/dom/bindings/global.rs index 9ff4ae047da..eac887b8a2f 100644 --- a/components/script/dom/bindings/global.rs +++ b/components/script/dom/bindings/global.rs @@ -22,7 +22,7 @@ use js::jsapi::{JSAutoCompartment, JSContext, JSObject}; use js::jsapi::{JS_GetClass, MutableHandleValue}; use js::rust::CompileOptionsWrapper; use libc; -use net_traits::{CoreResourceThread, IpcSend, ResourceThreads}; +use net_traits::{CoreResourceThread, IpcSend}; use profile_traits::time; use script_runtime::{CommonScriptMsg, EnqueuedPromiseCallback, ScriptChan}; use script_runtime::{ScriptPort, maybe_take_panic_result}; @@ -68,17 +68,9 @@ impl<'a> GlobalRef<'a> { } } - /// Get the `ResourceThreads` for this global scope. - pub fn resource_threads(&self) -> ResourceThreads { - match *self { - GlobalRef::Window(ref window) => window.resource_threads().clone(), - GlobalRef::Worker(ref worker) => worker.resource_threads().clone(), - } - } - /// Get the `CoreResourceThread` for this global scope pub fn core_resource_thread(&self) -> CoreResourceThread { - self.resource_threads().sender() + self.as_global_scope().resource_threads().sender() } /// `ScriptChan` used to send messages to the event loop of this global's diff --git a/components/script/dom/blob.rs b/components/script/dom/blob.rs index fa6600224e8..52248c25845 100644 --- a/components/script/dom/blob.rs +++ b/components/script/dom/blob.rs @@ -290,8 +290,8 @@ impl Blob { } fn send_to_file_manager(&self, msg: FileManagerThreadMsg) { - let global = self.global(); - let resource_threads = global.r().resource_threads(); + let global = self.global_scope(); + let resource_threads = global.resource_threads(); let _ = resource_threads.send(CoreResourceMsg::ToFileManager(msg)); } } @@ -305,7 +305,7 @@ impl Drop for Blob { } fn read_file(global: GlobalRef, id: Uuid) -> Result, ()> { - let resource_threads = global.resource_threads(); + let resource_threads = global.as_global_scope().resource_threads(); let (chan, recv) = ipc::channel().map_err(|_|())?; let origin = get_blob_origin(&global.as_global_scope().get_url()); let check_url_validity = false; diff --git a/components/script/dom/document.rs b/components/script/dom/document.rs index 5a5507b0c20..0fbf4eb9c0c 100644 --- a/components/script/dom/document.rs +++ b/components/script/dom/document.rs @@ -2728,7 +2728,10 @@ impl DocumentMethods for Document { let url = self.url(); let (tx, rx) = ipc::channel().unwrap(); - let _ = self.window.resource_threads().send(GetCookiesForUrl((*url).clone(), tx, NonHTTP)); + let _ = self.window + .upcast::() + .resource_threads() + .send(GetCookiesForUrl((*url).clone(), tx, NonHTTP)); let cookies = rx.recv().unwrap(); Ok(cookies.map_or(DOMString::new(), DOMString::from)) } @@ -2745,6 +2748,7 @@ impl DocumentMethods for Document { let url = self.url(); let _ = self.window + .upcast::() .resource_threads() .send(SetCookiesForUrl((*url).clone(), String::from(cookie), NonHTTP)); Ok(()) diff --git a/components/script/dom/globalscope.rs b/components/script/dom/globalscope.rs index 95cd8c4bd4a..08e5f84ab06 100644 --- a/components/script/dom/globalscope.rs +++ b/components/script/dom/globalscope.rs @@ -21,6 +21,7 @@ use dom::workerglobalscope::WorkerGlobalScope; use ipc_channel::ipc::IpcSender; use js::jsapi::{HandleValue, JS_GetContext, JS_GetObjectRuntime, JSContext}; use msg::constellation_msg::PipelineId; +use net_traits::ResourceThreads; use profile_traits::{mem, time}; use script_traits::{ScriptMsg as ConstellationMsg, TimerEventRequest}; use std::cell::Cell; @@ -66,6 +67,10 @@ pub struct GlobalScope { /// https://html.spec.whatwg.org/multipage/#in-error-reporting-mode in_error_reporting_mode: Cell, + + /// Associated resource threads for use by DOM objects like XMLHttpRequest, + /// including resource_thread, filemanager_thread and storage_thread + resource_threads: ResourceThreads, } impl GlobalScope { @@ -75,7 +80,8 @@ impl GlobalScope { mem_profiler_chan: mem::ProfilerChan, time_profiler_chan: time::ProfilerChan, constellation_chan: IpcSender, - scheduler_chan: IpcSender) + scheduler_chan: IpcSender, + resource_threads: ResourceThreads) -> Self { GlobalScope { eventtarget: EventTarget::new_inherited(), @@ -90,6 +96,7 @@ impl GlobalScope { constellation_chan: constellation_chan, scheduler_chan: scheduler_chan, in_error_reporting_mode: Default::default(), + resource_threads: resource_threads, } } @@ -240,6 +247,11 @@ impl GlobalScope { // Step 14 self.in_error_reporting_mode.set(false); } + + /// Get the `&ResourceThreads` for this global scope. + pub fn resource_threads(&self) -> &ResourceThreads { + &self.resource_threads + } } fn timestamp_in_ms(time: Timespec) -> u64 { diff --git a/components/script/dom/htmlinputelement.rs b/components/script/dom/htmlinputelement.rs index 4097b885d91..ab184463bb2 100644 --- a/components/script/dom/htmlinputelement.rs +++ b/components/script/dom/htmlinputelement.rs @@ -795,7 +795,7 @@ impl HTMLInputElement { fn select_files(&self, opt_test_paths: Option>) { let window = window_from_node(self); let origin = get_blob_origin(&window.get_url()); - let resource_threads = window.resource_threads(); + let resource_threads = window.upcast::().resource_threads(); let mut files: Vec> = vec![]; let mut error = None; diff --git a/components/script/dom/storage.rs b/components/script/dom/storage.rs index 76b04f60d6f..f19ac5ebbb6 100644 --- a/components/script/dom/storage.rs +++ b/components/script/dom/storage.rs @@ -44,7 +44,7 @@ impl Storage { } fn get_storage_thread(&self) -> IpcSender { - self.global_scope().as_window().resource_threads().sender() + self.global_scope().resource_threads().sender() } } diff --git a/components/script/dom/url.rs b/components/script/dom/url.rs index 33520beee9d..8912ece7183 100644 --- a/components/script/dom/url.rs +++ b/components/script/dom/url.rs @@ -133,6 +133,7 @@ impl URL { // https://w3c.github.io/FileAPI/#dfn-revokeObjectURL pub fn RevokeObjectURL(global: GlobalRef, url: DOMString) { + let global_scope = global.as_global_scope(); /* If the url refers to a Blob that has a readability state of CLOSED OR if the value provided for the url argument is not a Blob URL, OR @@ -142,11 +143,11 @@ impl URL { NOTE: The first step is unnecessary, since closed blobs do not exist in the store */ - let origin = get_blob_origin(&global.as_global_scope().get_url()); + let origin = get_blob_origin(&global_scope.get_url()); if let Ok(url) = Url::parse(&url) { if let Ok((id, _, _)) = parse_blob_url(&url) { - let resource_threads = global.resource_threads(); + let resource_threads = global_scope.resource_threads(); let (tx, rx) = ipc::channel().unwrap(); let msg = FileManagerThreadMsg::RevokeBlobURL(id, origin, tx); let _ = resource_threads.send(CoreResourceMsg::ToFileManager(msg)); diff --git a/components/script/dom/window.rs b/components/script/dom/window.rs index 21b108360f0..0d55cb98f91 100644 --- a/components/script/dom/window.rs +++ b/components/script/dom/window.rs @@ -200,10 +200,6 @@ pub struct Window { /// The current size of the window, in pixels. window_size: Cell>, - /// Associated resource threads for use by DOM objects like XMLHttpRequest, - /// including resource_thread, filemanager_thread and storage_thread - resource_threads: ResourceThreads, - /// A handle for communicating messages to the bluetooth thread. #[ignore_heap_size_of = "channels are hard"] bluetooth_thread: IpcSender, @@ -1371,10 +1367,6 @@ impl Window { (*self.Document().url()).clone() } - pub fn resource_threads(&self) -> &ResourceThreads { - &self.resource_threads - } - pub fn layout_chan(&self) -> &Sender { &self.layout_chan } @@ -1587,7 +1579,8 @@ impl Window { mem_profiler_chan, time_profiler_chan, constellation_chan, - scheduler_chan.clone()), + scheduler_chan.clone(), + resource_threads), script_chan: script_chan, dom_manipulation_task_source: dom_task_source, user_interaction_task_source: user_task_source, @@ -1610,7 +1603,6 @@ impl Window { parent_info: parent_info, dom_static: GlobalStaticData::new(), js_runtime: DOMRefCell::new(Some(runtime.clone())), - resource_threads: resource_threads, bluetooth_thread: bluetooth_thread, page_clip_rect: Cell::new(max_rect()), fragment_name: DOMRefCell::new(None), diff --git a/components/script/dom/workerglobalscope.rs b/components/script/dom/workerglobalscope.rs index b83c36a1aee..59478818cfa 100644 --- a/components/script/dom/workerglobalscope.rs +++ b/components/script/dom/workerglobalscope.rs @@ -30,7 +30,7 @@ use js::jsval::UndefinedValue; use js::rust::Runtime; use msg::constellation_msg::{PipelineId, ReferrerPolicy}; use net_traits::{IpcSend, LoadOrigin}; -use net_traits::{LoadContext, ResourceThreads, load_whole_resource}; +use net_traits::{LoadContext, load_whole_resource}; use script_runtime::{CommonScriptMsg, ScriptChan, ScriptPort, maybe_take_panic_result}; use script_runtime::{ScriptThreadEventCategory, PromiseJobQueue, EnqueuedPromiseCallback}; use script_thread::{Runnable, RunnableWrapper}; @@ -56,8 +56,9 @@ pub fn prepare_workerscope_init(global: GlobalRef, let constellation_chan = global_scope.constellation_chan().clone(); let scheduler_chan = global_scope.scheduler_chan().clone(); let pipeline_id = global_scope.pipeline_id(); + let resource_threads = global_scope.resource_threads().clone(); let init = WorkerGlobalScopeInit { - resource_threads: global.resource_threads(), + resource_threads: resource_threads, mem_profiler_chan: mem_profiler_chan, to_devtools_sender: to_devtools_sender, time_profiler_chan: time_profiler_chan, @@ -82,8 +83,6 @@ pub struct WorkerGlobalScope { closing: Option>, #[ignore_heap_size_of = "Defined in js"] runtime: Runtime, - #[ignore_heap_size_of = "Defined in std"] - resource_threads: ResourceThreads, location: MutNullableHeap>, navigator: MutNullableHeap>, timers: OneshotTimers, @@ -117,12 +116,12 @@ impl WorkerGlobalScope { init.mem_profiler_chan, init.time_profiler_chan, init.constellation_chan, - init.scheduler_chan.clone()), + init.scheduler_chan.clone(), + init.resource_threads), worker_id: init.worker_id, worker_url: worker_url, closing: closing, runtime: runtime, - resource_threads: init.resource_threads, location: Default::default(), navigator: Default::default(), timers: OneshotTimers::new(timer_event_chan, init.scheduler_chan), @@ -166,10 +165,6 @@ impl WorkerGlobalScope { } } - pub fn resource_threads(&self) -> &ResourceThreads { - &self.resource_threads - } - pub fn get_url(&self) -> &Url { &self.worker_url } @@ -245,8 +240,9 @@ impl WorkerGlobalScopeMethods for WorkerGlobalScope { rooted!(in(self.runtime.cx()) let mut rval = UndefinedValue()); for url in urls { + let global_scope = self.upcast::(); let (url, source) = match load_whole_resource(LoadContext::Script, - &self.resource_threads.sender(), + &global_scope.resource_threads().sender(), url, self) { Err(_) => return Err(Error::Network), diff --git a/components/script/webdriver_handlers.rs b/components/script/webdriver_handlers.rs index 870b3235d38..95e300b1527 100644 --- a/components/script/webdriver_handlers.rs +++ b/components/script/webdriver_handlers.rs @@ -209,7 +209,7 @@ pub fn handle_get_cookies(context: &BrowsingContext, let document = context.active_document(); let url = document.url(); let (sender, receiver) = ipc::channel().unwrap(); - let _ = document.window().resource_threads().send( + let _ = document.window().upcast::().resource_threads().send( GetCookiesDataForUrl(url.clone(), sender, NonHTTP) ); let cookies = receiver.recv().unwrap(); @@ -224,7 +224,7 @@ pub fn handle_get_cookie(context: &BrowsingContext, let document = context.active_document(); let url = document.url(); let (sender, receiver) = ipc::channel().unwrap(); - let _ = document.window().resource_threads().send( + let _ = document.window().upcast::().resource_threads().send( GetCookiesDataForUrl(url.clone(), sender, NonHTTP) ); let cookies = receiver.recv().unwrap(); @@ -246,13 +246,13 @@ pub fn handle_add_cookie(context: &BrowsingContext, reply.send(match (document.is_cookie_averse(), cookie.domain.clone()) { (true, _) => Err(WebDriverCookieError::InvalidDomain), (false, Some(ref domain)) if url.host_str().map(|x| { x == &**domain }).unwrap_or(false) => { - let _ = document.window().resource_threads().send( + let _ = document.window().upcast::().resource_threads().send( SetCookiesForUrlWithData(url.clone(), cookie, method) ); Ok(()) }, (false, None) => { - let _ = document.window().resource_threads().send( + let _ = document.window().upcast::().resource_threads().send( SetCookiesForUrlWithData(url.clone(), cookie, method) ); Ok(()) From 9a48ebb24559969b1473ae9489507d4ade0d3d25 Mon Sep 17 00:00:00 2001 From: Anthony Ramine Date: Mon, 3 Oct 2016 18:43:02 +0200 Subject: [PATCH 36/66] Make dom::blob::read_file take a &GlobalScope --- components/script/dom/blob.rs | 9 ++++----- 1 file changed, 4 insertions(+), 5 deletions(-) diff --git a/components/script/dom/blob.rs b/components/script/dom/blob.rs index 52248c25845..c472554357c 100644 --- a/components/script/dom/blob.rs +++ b/components/script/dom/blob.rs @@ -144,8 +144,7 @@ impl Blob { let (buffer, is_new_buffer) = match *f.cache.borrow() { Some(ref bytes) => (bytes.clone(), false), None => { - let global = self.global(); - let bytes = read_file(global.r(), f.id.clone())?; + let bytes = read_file(&self.global_scope(), f.id.clone())?; (bytes, true) } }; @@ -304,10 +303,10 @@ impl Drop for Blob { } } -fn read_file(global: GlobalRef, id: Uuid) -> Result, ()> { - let resource_threads = global.as_global_scope().resource_threads(); +fn read_file(global: &GlobalScope, id: Uuid) -> Result, ()> { + let resource_threads = global.resource_threads(); let (chan, recv) = ipc::channel().map_err(|_|())?; - let origin = get_blob_origin(&global.as_global_scope().get_url()); + let origin = get_blob_origin(&global.get_url()); let check_url_validity = false; let msg = FileManagerThreadMsg::ReadFile(chan, id, check_url_validity, origin); let _ = resource_threads.send(CoreResourceMsg::ToFileManager(msg)); From 83feb7dee32f602280ff6894c1b0a091698e29d4 Mon Sep 17 00:00:00 2001 From: Anthony Ramine Date: Mon, 3 Oct 2016 18:47:58 +0200 Subject: [PATCH 37/66] Make prepare_workerscope_init take a &GlobalScope --- .../script/dom/serviceworkerregistration.rs | 2 +- components/script/dom/worker.rs | 2 +- components/script/dom/workerglobalscope.rs | 27 +++++++------------ 3 files changed, 11 insertions(+), 20 deletions(-) diff --git a/components/script/dom/serviceworkerregistration.rs b/components/script/dom/serviceworkerregistration.rs index 87226207266..e274e5a6e51 100644 --- a/components/script/dom/serviceworkerregistration.rs +++ b/components/script/dom/serviceworkerregistration.rs @@ -60,7 +60,7 @@ impl ServiceWorkerRegistration { let worker_id = global_scope.get_next_worker_id(); let devtools_chan = global_scope.devtools_chan().cloned(); - let init = prepare_workerscope_init(global, None); + let init = prepare_workerscope_init(global_scope, None); ScopeThings { script_url: script_url, init: init, diff --git a/components/script/dom/worker.rs b/components/script/dom/worker.rs index 9e590b0f7da..1ef6242720d 100644 --- a/components/script/dom/worker.rs +++ b/components/script/dom/worker.rs @@ -105,7 +105,7 @@ impl Worker { page_info)); } - let init = prepare_workerscope_init(global, Some(devtools_sender)); + let init = prepare_workerscope_init(global_scope, Some(devtools_sender)); DedicatedWorkerGlobalScope::run_worker_scope( init, worker_url, devtools_receiver, worker.runtime.clone(), worker_ref, diff --git a/components/script/dom/workerglobalscope.rs b/components/script/dom/workerglobalscope.rs index 59478818cfa..93361d8e620 100644 --- a/components/script/dom/workerglobalscope.rs +++ b/components/script/dom/workerglobalscope.rs @@ -46,27 +46,18 @@ use task_source::file_reading::FileReadingTaskSource; use timers::{IsInterval, OneshotTimerCallback, OneshotTimerHandle, OneshotTimers, TimerCallback}; use url::Url; -pub fn prepare_workerscope_init(global: GlobalRef, +pub fn prepare_workerscope_init(global: &GlobalScope, devtools_sender: Option>) -> WorkerGlobalScopeInit { - let global_scope = global.as_global_scope(); - let worker_id = global_scope.get_next_worker_id(); - let to_devtools_sender = global_scope.devtools_chan().cloned(); - let mem_profiler_chan = global_scope.mem_profiler_chan().clone(); - let time_profiler_chan = global_scope.time_profiler_chan().clone(); - let constellation_chan = global_scope.constellation_chan().clone(); - let scheduler_chan = global_scope.scheduler_chan().clone(); - let pipeline_id = global_scope.pipeline_id(); - let resource_threads = global_scope.resource_threads().clone(); let init = WorkerGlobalScopeInit { - resource_threads: resource_threads, - mem_profiler_chan: mem_profiler_chan, - to_devtools_sender: to_devtools_sender, - time_profiler_chan: time_profiler_chan, + resource_threads: global.resource_threads().clone(), + mem_profiler_chan: global.mem_profiler_chan().clone(), + to_devtools_sender: global.devtools_chan().cloned(), + time_profiler_chan: global.time_profiler_chan().clone(), from_devtools_sender: devtools_sender, - constellation_chan: constellation_chan, - scheduler_chan: scheduler_chan, - worker_id: worker_id, - pipeline_id: pipeline_id, + constellation_chan: global.constellation_chan().clone(), + scheduler_chan: global.scheduler_chan().clone(), + worker_id: global.get_next_worker_id(), + pipeline_id: global.pipeline_id(), }; init From de846f25a65cf080ed8fc3bd201627872bd83f15 Mon Sep 17 00:00:00 2001 From: Anthony Ramine Date: Mon, 3 Oct 2016 18:58:03 +0200 Subject: [PATCH 38/66] Make create_scope_things take a &GlobalScope --- components/script/dom/serviceworkerregistration.rs | 12 +++++------- components/script/script_thread.rs | 5 ++--- 2 files changed, 7 insertions(+), 10 deletions(-) diff --git a/components/script/dom/serviceworkerregistration.rs b/components/script/dom/serviceworkerregistration.rs index e274e5a6e51..c3a08e514e4 100644 --- a/components/script/dom/serviceworkerregistration.rs +++ b/components/script/dom/serviceworkerregistration.rs @@ -4,7 +4,6 @@ use dom::bindings::codegen::Bindings::ServiceWorkerBinding::ServiceWorkerState; use dom::bindings::codegen::Bindings::ServiceWorkerRegistrationBinding::{ServiceWorkerRegistrationMethods, Wrap}; -use dom::bindings::global::GlobalRef; use dom::bindings::js::{JS, Root}; use dom::bindings::reflector::reflect_dom_object; use dom::bindings::str::USVString; @@ -50,17 +49,16 @@ impl ServiceWorkerRegistration { self.active.as_ref().unwrap() } - pub fn create_scope_things(global: GlobalRef, script_url: Url) -> ScopeThings { - let global_scope = global.as_global_scope(); + pub fn create_scope_things(global: &GlobalScope, script_url: Url) -> ScopeThings { let worker_load_origin = WorkerScriptLoadOrigin { referrer_url: None, referrer_policy: None, - pipeline_id: Some(global_scope.pipeline_id()) + pipeline_id: Some(global.pipeline_id()) }; - let worker_id = global_scope.get_next_worker_id(); - let devtools_chan = global_scope.devtools_chan().cloned(); - let init = prepare_workerscope_init(global_scope, None); + let worker_id = global.get_next_worker_id(); + let devtools_chan = global.devtools_chan().cloned(); + let init = prepare_workerscope_init(global, None); ScopeThings { script_url: script_url, init: init, diff --git a/components/script/script_thread.rs b/components/script/script_thread.rs index 8699a56742b..582ebfdb153 100644 --- a/components/script/script_thread.rs +++ b/components/script/script_thread.rs @@ -1449,10 +1449,9 @@ impl ScriptThread { None => return }; if let Some(context) = self.root_browsing_context().find(pipeline_id) { - let window = context.active_window(); - let global_ref = GlobalRef::Window(window.r()); let script_url = maybe_registration.get_installed().get_script_url(); - let scope_things = ServiceWorkerRegistration::create_scope_things(global_ref, script_url); + let scope_things = ServiceWorkerRegistration::create_scope_things( + context.active_window().upcast(), script_url); let _ = self.constellation_chan.send(ConstellationMsg::RegisterServiceWorker(scope_things, scope)); } else { warn!("Registration failed for {}", scope); From 71236e168ac9c1e85c370be09a5566ec299b7bb6 Mon Sep 17 00:00:00 2001 From: Anthony Ramine Date: Mon, 3 Oct 2016 23:16:55 +0200 Subject: [PATCH 39/66] Introduce GlobalScope::core_resource_thread --- components/script/dom/bindings/global.rs | 6 ------ components/script/dom/globalscope.rs | 7 ++++++- components/script/dom/websocket.rs | 7 +++---- components/script/dom/xmlhttprequest.rs | 2 +- components/script/fetch.rs | 4 ++-- 5 files changed, 12 insertions(+), 14 deletions(-) diff --git a/components/script/dom/bindings/global.rs b/components/script/dom/bindings/global.rs index eac887b8a2f..ecca46a5a5e 100644 --- a/components/script/dom/bindings/global.rs +++ b/components/script/dom/bindings/global.rs @@ -22,7 +22,6 @@ use js::jsapi::{JSAutoCompartment, JSContext, JSObject}; use js::jsapi::{JS_GetClass, MutableHandleValue}; use js::rust::CompileOptionsWrapper; use libc; -use net_traits::{CoreResourceThread, IpcSend}; use profile_traits::time; use script_runtime::{CommonScriptMsg, EnqueuedPromiseCallback, ScriptChan}; use script_runtime::{ScriptPort, maybe_take_panic_result}; @@ -68,11 +67,6 @@ impl<'a> GlobalRef<'a> { } } - /// Get the `CoreResourceThread` for this global scope - pub fn core_resource_thread(&self) -> CoreResourceThread { - self.as_global_scope().resource_threads().sender() - } - /// `ScriptChan` used to send messages to the event loop of this global's /// thread. pub fn script_chan(&self) -> Box { diff --git a/components/script/dom/globalscope.rs b/components/script/dom/globalscope.rs index 08e5f84ab06..71405239122 100644 --- a/components/script/dom/globalscope.rs +++ b/components/script/dom/globalscope.rs @@ -21,7 +21,7 @@ use dom::workerglobalscope::WorkerGlobalScope; use ipc_channel::ipc::IpcSender; use js::jsapi::{HandleValue, JS_GetContext, JS_GetObjectRuntime, JSContext}; use msg::constellation_msg::PipelineId; -use net_traits::ResourceThreads; +use net_traits::{CoreResourceThread, ResourceThreads, IpcSend}; use profile_traits::{mem, time}; use script_traits::{ScriptMsg as ConstellationMsg, TimerEventRequest}; use std::cell::Cell; @@ -252,6 +252,11 @@ impl GlobalScope { pub fn resource_threads(&self) -> &ResourceThreads { &self.resource_threads } + + /// Get the `CoreResourceThread` for this global scope. + pub fn core_resource_thread(&self) -> CoreResourceThread { + self.resource_threads().sender() + } } fn timestamp_in_ms(time: Timespec) -> u64 { diff --git a/components/script/dom/websocket.rs b/components/script/dom/websocket.rs index 1b790d532d2..aa2a61b6c38 100644 --- a/components/script/dom/websocket.rs +++ b/components/script/dom/websocket.rs @@ -265,7 +265,7 @@ impl WebSocket { action_receiver: resource_action_receiver, }; - let _ = global.core_resource_thread().send(WebsocketConnect(connect, connect_data)); + let _ = global_scope.core_resource_thread().send(WebsocketConnect(connect, connect_data)); *ws.sender.borrow_mut() = Some(dom_action_sender); @@ -492,9 +492,8 @@ impl Runnable for ConnectionEstablishedTask { if let Some(cookies) = self.headers.get_raw("set-cookie") { for cookie in cookies.iter() { if let Ok(cookie_value) = String::from_utf8(cookie.clone()) { - let _ = ws.global().r().core_resource_thread().send(SetCookiesForUrl(ws.url.clone(), - cookie_value, - HTTP)); + let _ = ws.global_scope().core_resource_thread().send( + SetCookiesForUrl(ws.url.clone(), cookie_value, HTTP)); } } } diff --git a/components/script/dom/xmlhttprequest.rs b/components/script/dom/xmlhttprequest.rs index 87793f2d0b6..907f8ba2653 100644 --- a/components/script/dom/xmlhttprequest.rs +++ b/components/script/dom/xmlhttprequest.rs @@ -1303,7 +1303,7 @@ impl XMLHttpRequest { (global.networking_task_source(), None) }; - let core_resource_thread = global.core_resource_thread(); + let core_resource_thread = global.as_global_scope().core_resource_thread(); XMLHttpRequest::initiate_async_xhr(context.clone(), script_chan, core_resource_thread, init); diff --git a/components/script/fetch.rs b/components/script/fetch.rs index bc04a5ecd92..a50f781d0b0 100644 --- a/components/script/fetch.rs +++ b/components/script/fetch.rs @@ -67,10 +67,10 @@ fn request_init_from_request(request: NetTraitsRequest) -> NetTraitsRequestInit // https://fetch.spec.whatwg.org/#fetch-method #[allow(unrooted_must_root)] pub fn Fetch(global: GlobalRef, input: RequestOrUSVString, init: &RequestInit) -> Rc { - let core_resource_thread = global.core_resource_thread(); + let global_scope = global.as_global_scope(); + let core_resource_thread = global_scope.core_resource_thread(); // Step 1 - let global_scope = global.as_global_scope(); let promise = Promise::new(global_scope); let response = Response::new(global_scope); From a7305b7fc4e4b9c70e9a5ef43f66a7b6be6731ec Mon Sep 17 00:00:00 2001 From: Anthony Ramine Date: Tue, 4 Oct 2016 00:35:16 +0200 Subject: [PATCH 40/66] Introduce GlobalScope::script_chan --- components/script/dom/bindings/global.rs | 12 +----------- components/script/dom/globalscope.rs | 13 +++++++++++++ components/script/dom/websocket.rs | 6 ++++-- components/script/dom/worker.rs | 2 +- 4 files changed, 19 insertions(+), 14 deletions(-) diff --git a/components/script/dom/bindings/global.rs b/components/script/dom/bindings/global.rs index ecca46a5a5e..67ed8766932 100644 --- a/components/script/dom/bindings/global.rs +++ b/components/script/dom/bindings/global.rs @@ -25,7 +25,7 @@ use libc; use profile_traits::time; use script_runtime::{CommonScriptMsg, EnqueuedPromiseCallback, ScriptChan}; use script_runtime::{ScriptPort, maybe_take_panic_result}; -use script_thread::{MainThreadScriptChan, RunnableWrapper, ScriptThread}; +use script_thread::{RunnableWrapper, ScriptThread}; use script_traits::MsDuration; use std::ffi::CString; use std::panic; @@ -67,16 +67,6 @@ impl<'a> GlobalRef<'a> { } } - /// `ScriptChan` used to send messages to the event loop of this global's - /// thread. - pub fn script_chan(&self) -> Box { - match *self { - GlobalRef::Window(ref window) => - MainThreadScriptChan(window.main_thread_script_chan().clone()).clone(), - GlobalRef::Worker(ref worker) => worker.script_chan(), - } - } - /// `ScriptChan` used to send messages to the event loop of this global's /// thread. pub fn networking_task_source(&self) -> Box { diff --git a/components/script/dom/globalscope.rs b/components/script/dom/globalscope.rs index 71405239122..7e5f0407e36 100644 --- a/components/script/dom/globalscope.rs +++ b/components/script/dom/globalscope.rs @@ -23,6 +23,8 @@ use js::jsapi::{HandleValue, JS_GetContext, JS_GetObjectRuntime, JSContext}; use msg::constellation_msg::PipelineId; use net_traits::{CoreResourceThread, ResourceThreads, IpcSend}; use profile_traits::{mem, time}; +use script_runtime::ScriptChan; +use script_thread::MainThreadScriptChan; use script_traits::{ScriptMsg as ConstellationMsg, TimerEventRequest}; use std::cell::Cell; use std::collections::HashMap; @@ -257,6 +259,17 @@ impl GlobalScope { pub fn core_resource_thread(&self) -> CoreResourceThread { self.resource_threads().sender() } + + /// `ScriptChan` to send messages to the event loop of this global scope. + pub fn script_chan(&self) -> Box { + if let Some(window) = self.downcast::() { + return MainThreadScriptChan(window.main_thread_script_chan().clone()).clone(); + } + if let Some(worker) = self.downcast::() { + return worker.script_chan(); + } + unreachable!(); + } } fn timestamp_in_ms(time: Timespec) -> u64 { diff --git a/components/script/dom/websocket.rs b/components/script/dom/websocket.rs index aa2a61b6c38..ac1cf53b2ae 100644 --- a/components/script/dom/websocket.rs +++ b/components/script/dom/websocket.rs @@ -330,8 +330,10 @@ impl WebSocket { address: address, }; - let global = self.global(); - global.r().script_chan().send(CommonScriptMsg::RunnableMsg(WebSocketEvent, task)).unwrap(); + self.global_scope() + .script_chan() + .send(CommonScriptMsg::RunnableMsg(WebSocketEvent, task)) + .unwrap(); } Ok(true) diff --git a/components/script/dom/worker.rs b/components/script/dom/worker.rs index 1ef6242720d..035aa83bdf9 100644 --- a/components/script/dom/worker.rs +++ b/components/script/dom/worker.rs @@ -109,7 +109,7 @@ impl Worker { DedicatedWorkerGlobalScope::run_worker_scope( init, worker_url, devtools_receiver, worker.runtime.clone(), worker_ref, - global.script_chan(), sender, receiver, worker_load_origin, closing); + global_scope.script_chan(), sender, receiver, worker_load_origin, closing); Ok(worker) } From 1fd470889dd9b4e6c3a871b6b40b50e30114443d Mon Sep 17 00:00:00 2001 From: Anthony Ramine Date: Tue, 4 Oct 2016 00:46:27 +0200 Subject: [PATCH 41/66] Introduce GlobalScope::networking_task_source --- components/script/dom/bindings/global.rs | 9 --------- components/script/dom/globalscope.rs | 12 ++++++++++++ components/script/dom/websocket.rs | 7 +++---- components/script/dom/xmlhttprequest.rs | 5 +++-- components/script/fetch.rs | 2 +- 5 files changed, 19 insertions(+), 16 deletions(-) diff --git a/components/script/dom/bindings/global.rs b/components/script/dom/bindings/global.rs index 67ed8766932..35541148fda 100644 --- a/components/script/dom/bindings/global.rs +++ b/components/script/dom/bindings/global.rs @@ -67,15 +67,6 @@ impl<'a> GlobalRef<'a> { } } - /// `ScriptChan` used to send messages to the event loop of this global's - /// thread. - pub fn networking_task_source(&self) -> Box { - match *self { - GlobalRef::Window(ref window) => window.networking_task_source(), - GlobalRef::Worker(ref worker) => worker.script_chan(), - } - } - /// `ScriptChan` used to send messages to the event loop of this global's /// thread. pub fn file_reading_task_source(&self) -> FileReadingTaskSource { diff --git a/components/script/dom/globalscope.rs b/components/script/dom/globalscope.rs index 7e5f0407e36..29c918d28f0 100644 --- a/components/script/dom/globalscope.rs +++ b/components/script/dom/globalscope.rs @@ -270,6 +270,18 @@ impl GlobalScope { } unreachable!(); } + + /// `ScriptChan` to send messages to the networking task source of + /// this of this global scope. + pub fn networking_task_source(&self) -> Box { + if let Some(window) = self.downcast::() { + return window.networking_task_source(); + } + if let Some(worker) = self.downcast::() { + return worker.script_chan(); + } + unreachable!(); + } } fn timestamp_in_ms(time: Timespec) -> u64 { diff --git a/components/script/dom/websocket.rs b/components/script/dom/websocket.rs index ac1cf53b2ae..242f8124721 100644 --- a/components/script/dom/websocket.rs +++ b/components/script/dom/websocket.rs @@ -270,7 +270,7 @@ impl WebSocket { *ws.sender.borrow_mut() = Some(dom_action_sender); let moved_address = address.clone(); - let sender = global.networking_task_source(); + let sender = global_scope.networking_task_source(); thread::spawn(move || { while let Ok(event) = dom_event_receiver.recv() { match event { @@ -438,7 +438,7 @@ impl WebSocketMethods for WebSocket { self.ready_state.set(WebSocketRequestState::Closing); let address = Trusted::new(self); - let sender = self.global().r().networking_task_source(); + let sender = self.global_scope().networking_task_source(); fail_the_websocket_connection(address, sender); } WebSocketRequestState::Open => { @@ -469,11 +469,10 @@ impl Runnable for ConnectionEstablishedTask { fn handler(self: Box) { let ws = self.address.root(); - let global = ws.r().global(); // Step 1: Protocols. if !self.protocols.is_empty() && self.headers.get::().is_none() { - let sender = global.r().networking_task_source(); + let sender = ws.global_scope().networking_task_source(); fail_the_websocket_connection(self.address, sender); return; } diff --git a/components/script/dom/xmlhttprequest.rs b/components/script/dom/xmlhttprequest.rs index 907f8ba2653..5e7f156931e 100644 --- a/components/script/dom/xmlhttprequest.rs +++ b/components/script/dom/xmlhttprequest.rs @@ -1296,14 +1296,15 @@ impl XMLHttpRequest { sync_status: DOMRefCell::new(None), })); + let global_scope = global.as_global_scope(); let (script_chan, script_port) = if self.sync.get() { let (tx, rx) = global.new_script_pair(); (tx, Some(rx)) } else { - (global.networking_task_source(), None) + (global_scope.networking_task_source(), None) }; - let core_resource_thread = global.as_global_scope().core_resource_thread(); + let core_resource_thread = global_scope.core_resource_thread(); XMLHttpRequest::initiate_async_xhr(context.clone(), script_chan, core_resource_thread, init); diff --git a/components/script/fetch.rs b/components/script/fetch.rs index a50f781d0b0..b23f8f8f8dd 100644 --- a/components/script/fetch.rs +++ b/components/script/fetch.rs @@ -96,7 +96,7 @@ pub fn Fetch(global: GlobalRef, input: RequestOrUSVString, init: &RequestInit) - })); let listener = NetworkListener { context: fetch_context, - script_chan: global.networking_task_source(), + script_chan: global_scope.networking_task_source(), wrapper: None, }; From 19108aa3305df2172208c83500f5ac67d2dee104 Mon Sep 17 00:00:00 2001 From: Anthony Ramine Date: Tue, 4 Oct 2016 00:54:05 +0200 Subject: [PATCH 42/66] Pass a &GlobalScope to WebIDL static methods and constructors --- .../dom/bindings/codegen/CodegenRust.py | 8 ++-- components/script/dom/bindings/mod.rs | 7 ++-- components/script/dom/blob.rs | 5 +-- components/script/dom/bluetoothuuid.rs | 10 ++--- components/script/dom/closeevent.rs | 5 +-- components/script/dom/comment.rs | 6 +-- components/script/dom/console.rs | 37 +++++++++---------- components/script/dom/css.rs | 4 +- components/script/dom/customevent.rs | 6 +-- components/script/dom/document.rs | 5 +-- components/script/dom/documentfragment.rs | 6 +-- components/script/dom/dommatrix.rs | 11 +++--- components/script/dom/dommatrixreadonly.rs | 13 +++---- components/script/dom/domparser.rs | 6 +-- components/script/dom/dompoint.rs | 5 +-- components/script/dom/dompointreadonly.rs | 5 +-- components/script/dom/domquad.rs | 10 ++--- components/script/dom/domrect.rs | 5 +-- components/script/dom/domrectreadonly.rs | 5 +-- components/script/dom/errorevent.rs | 5 +-- components/script/dom/event.rs | 5 +-- components/script/dom/eventsource.rs | 8 ++-- components/script/dom/extendableevent.rs | 5 +-- .../script/dom/extendablemessageevent.rs | 5 +-- components/script/dom/file.rs | 13 +++---- components/script/dom/filereader.rs | 5 +-- components/script/dom/filereadersync.rs | 5 +-- components/script/dom/focusevent.rs | 5 +-- components/script/dom/formdata.rs | 5 +-- components/script/dom/hashchangeevent.rs | 5 +-- components/script/dom/headers.rs | 5 +-- components/script/dom/htmlimageelement.rs | 5 ++- components/script/dom/keyboardevent.rs | 6 +-- components/script/dom/messageevent.rs | 5 +-- components/script/dom/mouseevent.rs | 6 +-- components/script/dom/pagetransitionevent.rs | 5 +-- components/script/dom/popstateevent.rs | 5 +-- components/script/dom/progressevent.rs | 5 +-- components/script/dom/range.rs | 6 +-- components/script/dom/request.rs | 13 +++---- components/script/dom/response.rs | 16 ++++---- components/script/dom/storageevent.rs | 5 +-- components/script/dom/testbinding.rs | 36 +++++++++--------- components/script/dom/testbindingiterable.rs | 5 +-- .../script/dom/testbindingpairiterable.rs | 5 +-- components/script/dom/text.rs | 6 +-- components/script/dom/textdecoder.rs | 5 +-- components/script/dom/textencoder.rs | 5 +-- components/script/dom/uievent.rs | 6 +-- components/script/dom/url.rs | 20 +++++----- components/script/dom/urlsearchparams.rs | 5 +-- components/script/dom/webglcontextevent.rs | 5 +-- components/script/dom/websocket.rs | 12 +++--- components/script/dom/worker.rs | 20 +++++----- components/script/dom/xmlhttprequest.rs | 4 +- components/script/fetch.rs | 2 +- 56 files changed, 198 insertions(+), 245 deletions(-) diff --git a/components/script/dom/bindings/codegen/CodegenRust.py b/components/script/dom/bindings/codegen/CodegenRust.py index 3bc6f088a23..8a2ea4ed2c3 100644 --- a/components/script/dom/bindings/codegen/CodegenRust.py +++ b/components/script/dom/bindings/codegen/CodegenRust.py @@ -3438,7 +3438,7 @@ class CGStaticMethod(CGAbstractStaticBindingMethod): nativeName = CGSpecializedMethod.makeNativeName(self.descriptor, self.method) setupArgs = CGGeneric("let args = CallArgs::from_vp(vp, argc);\n") - call = CGMethodCall(["global.r()"], nativeName, True, self.descriptor, self.method) + call = CGMethodCall(["global.r().as_global_scope()"], nativeName, True, self.descriptor, self.method) return CGList([setupArgs, call]) @@ -3492,7 +3492,7 @@ class CGStaticGetter(CGAbstractStaticBindingMethod): nativeName = CGSpecializedGetter.makeNativeName(self.descriptor, self.attr) setupArgs = CGGeneric("let args = CallArgs::from_vp(vp, argc);\n") - call = CGGetterCall(["global.r()"], self.attr.type, nativeName, self.descriptor, + call = CGGetterCall(["global.r().as_global_scope()"], self.attr.type, nativeName, self.descriptor, self.attr) return CGList([setupArgs, call]) @@ -3545,7 +3545,7 @@ class CGStaticSetter(CGAbstractStaticBindingMethod): " throw_type_error(cx, \"Not enough arguments to %s setter.\");\n" " return false;\n" "}" % self.attr.identifier.name) - call = CGSetterCall(["global.r()"], self.attr.type, nativeName, self.descriptor, + call = CGSetterCall(["global.r().as_global_scope()"], self.attr.type, nativeName, self.descriptor, self.attr) return CGList([checkForArg, call]) @@ -5257,7 +5257,7 @@ let args = CallArgs::from_vp(vp, argc); """) name = self.constructor.identifier.name nativeName = MakeNativeName(self.descriptor.binaryNameFor(name)) - callGenerator = CGMethodCall(["global.r()"], nativeName, True, + callGenerator = CGMethodCall(["global.r().as_global_scope()"], nativeName, True, self.descriptor, self.constructor) return CGList([preamble, callGenerator]) diff --git a/components/script/dom/bindings/mod.rs b/components/script/dom/bindings/mod.rs index 013484a47b9..56cff520ef0 100644 --- a/components/script/dom/bindings/mod.rs +++ b/components/script/dom/bindings/mod.rs @@ -43,8 +43,9 @@ //! [`Fallible`](error/type.Fallible.html). //! Methods that use certain WebIDL types like `any` or `object` will get a //! `*mut JSContext` argument prepended to the argument list. Static methods -//! will be passed a [`GlobalRef`](global/enum.GlobalRef.html) for the relevant -//! global. This argument comes before the `*mut JSContext` argument, if any. +//! will be passed a [`&GlobalScope`](../globalscope/struct.GlobalScope.html) +//! for the relevant global. This argument comes before the `*mut JSContext` +//! argument, if any. //! //! Rust reflections of WebIDL operations (methods) //! ----------------------------------------------- @@ -79,7 +80,7 @@ //! //! A WebIDL constructor is turned into a static class method named //! `Constructor`. The arguments of this method will be the arguments of the -//! WebIDL constructor, with a `GlobalRef` for the relevant global prepended. +//! WebIDL constructor, with a `&GlobalScope` for the relevant global prepended. //! The return value of the constructor for MyInterface is exactly the same as //! that of a method returning an instance of MyInterface. Constructors are //! always [allowed to throw](#throwing-exceptions). diff --git a/components/script/dom/blob.rs b/components/script/dom/blob.rs index c472554357c..ad8e9a5d898 100644 --- a/components/script/dom/blob.rs +++ b/components/script/dom/blob.rs @@ -7,7 +7,6 @@ use dom::bindings::codegen::Bindings::BlobBinding; use dom::bindings::codegen::Bindings::BlobBinding::BlobMethods; use dom::bindings::codegen::UnionTypes::BlobOrString; use dom::bindings::error::{Error, Fallible}; -use dom::bindings::global::GlobalRef; use dom::bindings::js::{JS, Root}; use dom::bindings::reflector::{Reflectable, Reflector, reflect_dom_object}; use dom::bindings::str::DOMString; @@ -121,7 +120,7 @@ impl Blob { } // https://w3c.github.io/FileAPI/#constructorBlob - pub fn Constructor(global: GlobalRef, + pub fn Constructor(global: &GlobalScope, blobParts: Option>, blobPropertyBag: &BlobBinding::BlobPropertyBag) -> Fallible> { @@ -134,7 +133,7 @@ impl Blob { } }; - Ok(Blob::new(global.as_global_scope(), BlobImpl::new_from_bytes(bytes), blobPropertyBag.type_.to_string())) + Ok(Blob::new(global, BlobImpl::new_from_bytes(bytes), blobPropertyBag.type_.to_string())) } /// Get a slice to inner data, this might incur synchronous read and caching diff --git a/components/script/dom/bluetoothuuid.rs b/components/script/dom/bluetoothuuid.rs index e9669cc8acb..11fb7af94cb 100644 --- a/components/script/dom/bluetoothuuid.rs +++ b/components/script/dom/bluetoothuuid.rs @@ -5,9 +5,9 @@ use dom::bindings::codegen::UnionTypes::StringOrUnsignedLong; use dom::bindings::error::Error::Syntax; use dom::bindings::error::Fallible; -use dom::bindings::global::GlobalRef; use dom::bindings::reflector::Reflector; use dom::bindings::str::DOMString; +use dom::globalscope::GlobalScope; use regex::Regex; pub type UUID = DOMString; @@ -271,22 +271,22 @@ const VALID_UUID_REGEX: &'static str = "^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0- impl BluetoothUUID { // https://webbluetoothcg.github.io/web-bluetooth/#dom-bluetoothuuid-canonicaluuid - pub fn CanonicalUUID(_: GlobalRef, alias: u32) -> UUID { + pub fn CanonicalUUID(_: &GlobalScope, alias: u32) -> UUID { canonical_uuid(alias) } // https://webbluetoothcg.github.io/web-bluetooth/#dom-bluetoothuuid-getservice - pub fn GetService(_: GlobalRef, name: BluetoothServiceUUID) -> Fallible { + pub fn GetService(_: &GlobalScope, name: BluetoothServiceUUID) -> Fallible { Self::service(name) } // https://webbluetoothcg.github.io/web-bluetooth/#dom-bluetoothuuid-getcharacteristic - pub fn GetCharacteristic(_: GlobalRef, name: BluetoothCharacteristicUUID) -> Fallible { + pub fn GetCharacteristic(_: &GlobalScope, name: BluetoothCharacteristicUUID) -> Fallible { Self::characteristic(name) } // https://webbluetoothcg.github.io/web-bluetooth/#dom-bluetoothuuid-getdescriptor - pub fn GetDescriptor(_: GlobalRef, name: BluetoothDescriptorUUID) -> Fallible { + pub fn GetDescriptor(_: &GlobalScope, name: BluetoothDescriptorUUID) -> Fallible { Self::descriptor(name) } } diff --git a/components/script/dom/closeevent.rs b/components/script/dom/closeevent.rs index 7a076df8362..a66af7bd75f 100644 --- a/components/script/dom/closeevent.rs +++ b/components/script/dom/closeevent.rs @@ -6,7 +6,6 @@ use dom::bindings::codegen::Bindings::CloseEventBinding; use dom::bindings::codegen::Bindings::CloseEventBinding::CloseEventMethods; use dom::bindings::codegen::Bindings::EventBinding::EventMethods; use dom::bindings::error::Fallible; -use dom::bindings::global::GlobalRef; use dom::bindings::inheritance::Castable; use dom::bindings::js::Root; use dom::bindings::reflector::reflect_dom_object; @@ -58,13 +57,13 @@ impl CloseEvent { ev } - pub fn Constructor(global: GlobalRef, + pub fn Constructor(global: &GlobalScope, type_: DOMString, init: &CloseEventBinding::CloseEventInit) -> Fallible> { let bubbles = EventBubbles::from(init.parent.bubbles); let cancelable = EventCancelable::from(init.parent.cancelable); - Ok(CloseEvent::new(global.as_global_scope(), + Ok(CloseEvent::new(global, Atom::from(type_), bubbles, cancelable, diff --git a/components/script/dom/comment.rs b/components/script/dom/comment.rs index 2eec7652e25..875544202d7 100644 --- a/components/script/dom/comment.rs +++ b/components/script/dom/comment.rs @@ -5,11 +5,11 @@ use dom::bindings::codegen::Bindings::CommentBinding; use dom::bindings::codegen::Bindings::WindowBinding::WindowMethods; use dom::bindings::error::Fallible; -use dom::bindings::global::GlobalRef; use dom::bindings::js::Root; use dom::bindings::str::DOMString; use dom::characterdata::CharacterData; use dom::document::Document; +use dom::globalscope::GlobalScope; use dom::node::Node; /// An HTML comment. @@ -31,8 +31,8 @@ impl Comment { CommentBinding::Wrap) } - pub fn Constructor(global: GlobalRef, data: DOMString) -> Fallible> { - let document = global.as_global_scope().as_window().Document(); + pub fn Constructor(global: &GlobalScope, data: DOMString) -> Fallible> { + let document = global.as_window().Document(); Ok(Comment::new(data, document.r())) } } diff --git a/components/script/dom/console.rs b/components/script/dom/console.rs index 8350b05b10f..d9df56ebef0 100644 --- a/components/script/dom/console.rs +++ b/components/script/dom/console.rs @@ -3,7 +3,6 @@ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use devtools_traits::{ConsoleMessage, LogLevel, ScriptToDevtoolsControlMsg}; -use dom::bindings::global::GlobalRef; use dom::bindings::inheritance::Castable; use dom::bindings::str::DOMString; use dom::globalscope::GlobalScope; @@ -30,71 +29,71 @@ impl Console { impl Console { // https://developer.mozilla.org/en-US/docs/Web/API/Console/log - pub fn Log(global: GlobalRef, messages: Vec) { + pub fn Log(global: &GlobalScope, messages: Vec) { for message in messages { println!("{}", message); - Self::send_to_devtools(global.as_global_scope(), LogLevel::Log, message); + Self::send_to_devtools(global, LogLevel::Log, message); } } // https://developer.mozilla.org/en-US/docs/Web/API/Console - pub fn Debug(global: GlobalRef, messages: Vec) { + pub fn Debug(global: &GlobalScope, messages: Vec) { for message in messages { println!("{}", message); - Self::send_to_devtools(global.as_global_scope(), LogLevel::Debug, message); + Self::send_to_devtools(global, LogLevel::Debug, message); } } // https://developer.mozilla.org/en-US/docs/Web/API/Console/info - pub fn Info(global: GlobalRef, messages: Vec) { + pub fn Info(global: &GlobalScope, messages: Vec) { for message in messages { println!("{}", message); - Self::send_to_devtools(global.as_global_scope(), LogLevel::Info, message); + Self::send_to_devtools(global, LogLevel::Info, message); } } // https://developer.mozilla.org/en-US/docs/Web/API/Console/warn - pub fn Warn(global: GlobalRef, messages: Vec) { + pub fn Warn(global: &GlobalScope, messages: Vec) { for message in messages { println!("{}", message); - Self::send_to_devtools(global.as_global_scope(), LogLevel::Warn, message); + Self::send_to_devtools(global, LogLevel::Warn, message); } } // https://developer.mozilla.org/en-US/docs/Web/API/Console/error - pub fn Error(global: GlobalRef, messages: Vec) { + pub fn Error(global: &GlobalScope, messages: Vec) { for message in messages { println!("{}", message); - Self::send_to_devtools(global.as_global_scope(), LogLevel::Error, message); + Self::send_to_devtools(global, LogLevel::Error, message); } } // https://developer.mozilla.org/en-US/docs/Web/API/Console/assert - pub fn Assert(global: GlobalRef, condition: bool, message: Option) { + pub fn Assert(global: &GlobalScope, condition: bool, message: Option) { if !condition { let message = message.unwrap_or_else(|| DOMString::from("no message")); println!("Assertion failed: {}", message); - Self::send_to_devtools(global.as_global_scope(), LogLevel::Error, message); + Self::send_to_devtools(global, LogLevel::Error, message); } } // https://developer.mozilla.org/en-US/docs/Web/API/Console/time - pub fn Time(global: GlobalRef, label: DOMString) { - if let Ok(()) = global.as_global_scope().time(label.clone()) { + pub fn Time(global: &GlobalScope, label: DOMString) { + if let Ok(()) = global.time(label.clone()) { let message = DOMString::from(format!("{}: timer started", label)); println!("{}", message); - Self::send_to_devtools(global.as_global_scope(), LogLevel::Log, message); + Self::send_to_devtools(global, LogLevel::Log, message); } } // https://developer.mozilla.org/en-US/docs/Web/API/Console/timeEnd - pub fn TimeEnd(global: GlobalRef, label: DOMString) { - if let Ok(delta) = global.as_global_scope().time_end(&label) { + pub fn TimeEnd(global: &GlobalScope, label: DOMString) { + if let Ok(delta) = global.time_end(&label) { let message = DOMString::from( format!("{}: {}ms", label, delta) ); println!("{}", message); - Self::send_to_devtools(global.as_global_scope(), LogLevel::Log, message); + Self::send_to_devtools(global, LogLevel::Log, message); }; } } diff --git a/components/script/dom/css.rs b/components/script/dom/css.rs index 105de8ec9c1..f2256007aeb 100644 --- a/components/script/dom/css.rs +++ b/components/script/dom/css.rs @@ -4,9 +4,9 @@ use cssparser::serialize_identifier; use dom::bindings::error::Fallible; -use dom::bindings::global::GlobalRef; use dom::bindings::reflector::Reflector; use dom::bindings::str::DOMString; +use dom::globalscope::GlobalScope; #[dom_struct] pub struct CSS { @@ -15,7 +15,7 @@ pub struct CSS { impl CSS { // http://dev.w3.org/csswg/cssom/#serialize-an-identifier - pub fn Escape(_: GlobalRef, ident: DOMString) -> Fallible { + pub fn Escape(_: &GlobalScope, ident: DOMString) -> Fallible { let mut escaped = String::new(); serialize_identifier(&ident, &mut escaped).unwrap(); Ok(DOMString::from(escaped)) diff --git a/components/script/dom/customevent.rs b/components/script/dom/customevent.rs index 043fd98193c..d7e026d69bc 100644 --- a/components/script/dom/customevent.rs +++ b/components/script/dom/customevent.rs @@ -6,7 +6,6 @@ use dom::bindings::codegen::Bindings::CustomEventBinding; use dom::bindings::codegen::Bindings::CustomEventBinding::CustomEventMethods; use dom::bindings::codegen::Bindings::EventBinding::EventMethods; use dom::bindings::error::Fallible; -use dom::bindings::global::GlobalRef; use dom::bindings::inheritance::Castable; use dom::bindings::js::{MutHeapJSVal, Root}; use dom::bindings::reflector::reflect_dom_object; @@ -48,12 +47,13 @@ impl CustomEvent { ev.init_custom_event(type_, bubbles, cancelable, detail); ev } + #[allow(unsafe_code)] - pub fn Constructor(global: GlobalRef, + pub fn Constructor(global: &GlobalScope, type_: DOMString, init: &CustomEventBinding::CustomEventInit) -> Fallible> { - Ok(CustomEvent::new(global.as_global_scope(), + Ok(CustomEvent::new(global, Atom::from(type_), init.parent.bubbles, init.parent.cancelable, diff --git a/components/script/dom/document.rs b/components/script/dom/document.rs index 0fbf4eb9c0c..bf2088bc15c 100644 --- a/components/script/dom/document.rs +++ b/components/script/dom/document.rs @@ -21,7 +21,6 @@ use dom::bindings::codegen::Bindings::TouchBinding::TouchMethods; use dom::bindings::codegen::Bindings::WindowBinding::WindowMethods; use dom::bindings::codegen::UnionTypes::NodeOrString; use dom::bindings::error::{Error, ErrorResult, Fallible}; -use dom::bindings::global::GlobalRef; use dom::bindings::inheritance::{Castable, ElementTypeId, HTMLElementTypeId, NodeTypeId}; use dom::bindings::js::{JS, LayoutJS, MutNullableHeap, Root}; use dom::bindings::js::RootedReference; @@ -1819,8 +1818,8 @@ impl Document { } // https://dom.spec.whatwg.org/#dom-document - pub fn Constructor(global: GlobalRef) -> Fallible> { - let win = global.as_global_scope().as_window(); + pub fn Constructor(global: &GlobalScope) -> Fallible> { + let win = global.as_window(); let doc = win.Document(); let doc = doc.r(); let docloader = DocumentLoader::new(&*doc.loader()); diff --git a/components/script/dom/documentfragment.rs b/components/script/dom/documentfragment.rs index bf05e36fce3..e71ce0f2d26 100644 --- a/components/script/dom/documentfragment.rs +++ b/components/script/dom/documentfragment.rs @@ -7,12 +7,12 @@ use dom::bindings::codegen::Bindings::DocumentFragmentBinding::DocumentFragmentM use dom::bindings::codegen::Bindings::WindowBinding::WindowMethods; use dom::bindings::codegen::UnionTypes::NodeOrString; use dom::bindings::error::{ErrorResult, Fallible}; -use dom::bindings::global::GlobalRef; use dom::bindings::inheritance::Castable; use dom::bindings::js::Root; use dom::bindings::str::DOMString; use dom::document::Document; use dom::element::Element; +use dom::globalscope::GlobalScope; use dom::htmlcollection::HTMLCollection; use dom::node::{Node, window_from_node}; use dom::nodelist::NodeList; @@ -38,8 +38,8 @@ impl DocumentFragment { DocumentFragmentBinding::Wrap) } - pub fn Constructor(global: GlobalRef) -> Fallible> { - let document = global.as_global_scope().as_window().Document(); + pub fn Constructor(global: &GlobalScope) -> Fallible> { + let document = global.as_window().Document(); Ok(DocumentFragment::new(document.r())) } diff --git a/components/script/dom/dommatrix.rs b/components/script/dom/dommatrix.rs index 2ccf4b126fb..dbe7a27516c 100644 --- a/components/script/dom/dommatrix.rs +++ b/components/script/dom/dommatrix.rs @@ -5,7 +5,6 @@ use dom::bindings::codegen::Bindings::DOMMatrixBinding::{Wrap, DOMMatrixMethods, DOMMatrixInit}; use dom::bindings::codegen::Bindings::DOMMatrixReadOnlyBinding::DOMMatrixReadOnlyMethods; use dom::bindings::error::Fallible; -use dom::bindings::global::GlobalRef; use dom::bindings::inheritance::Castable; use dom::bindings::js::Root; use dom::bindings::reflector::reflect_dom_object; @@ -33,23 +32,23 @@ impl DOMMatrix { } // https://drafts.fxtf.org/geometry-1/#dom-dommatrix-dommatrix - pub fn Constructor(global: GlobalRef) -> Fallible> { + pub fn Constructor(global: &GlobalScope) -> Fallible> { Self::Constructor_(global, vec![1.0, 0.0, 0.0, 1.0, 0.0, 0.0]) } // https://drafts.fxtf.org/geometry-1/#dom-dommatrix-dommatrix-numbersequence - pub fn Constructor_(global: GlobalRef, entries: Vec) -> Fallible> { + pub fn Constructor_(global: &GlobalScope, entries: Vec) -> Fallible> { entries_to_matrix(&entries[..]) .map(|(is2D, matrix)| { - Self::new(global.as_global_scope(), is2D, matrix) + Self::new(global, is2D, matrix) }) } // https://drafts.fxtf.org/geometry-1/#dom-dommatrix-frommatrix - pub fn FromMatrix(global: GlobalRef, other: &DOMMatrixInit) -> Fallible> { + pub fn FromMatrix(global: &GlobalScope, other: &DOMMatrixInit) -> Fallible> { dommatrixinit_to_matrix(&other) .map(|(is2D, matrix)| { - Self::new(global.as_global_scope(), is2D, matrix) + Self::new(global, is2D, matrix) }) } diff --git a/components/script/dom/dommatrixreadonly.rs b/components/script/dom/dommatrixreadonly.rs index 23feb88a348..1f4a2fc1446 100644 --- a/components/script/dom/dommatrixreadonly.rs +++ b/components/script/dom/dommatrixreadonly.rs @@ -8,7 +8,6 @@ use dom::bindings::codegen::Bindings::DOMMatrixReadOnlyBinding::{DOMMatrixReadOn use dom::bindings::codegen::Bindings::DOMPointBinding::DOMPointInit; use dom::bindings::error; use dom::bindings::error::Fallible; -use dom::bindings::global::GlobalRef; use dom::bindings::js::Root; use dom::bindings::reflector::{reflect_dom_object, Reflectable, Reflector}; use dom::dommatrix::DOMMatrix; @@ -41,23 +40,23 @@ impl DOMMatrixReadOnly { } // https://drafts.fxtf.org/geometry-1/#dom-dommatrixreadonly-dommatrixreadonly - pub fn Constructor(global: GlobalRef) -> Fallible> { - Ok(Self::new(global.as_global_scope(), true, Matrix4D::identity())) + pub fn Constructor(global: &GlobalScope) -> Fallible> { + Ok(Self::new(global, true, Matrix4D::identity())) } // https://drafts.fxtf.org/geometry-1/#dom-dommatrixreadonly-dommatrixreadonly-numbersequence - pub fn Constructor_(global: GlobalRef, entries: Vec) -> Fallible> { + pub fn Constructor_(global: &GlobalScope, entries: Vec) -> Fallible> { entries_to_matrix(&entries[..]) .map(|(is2D, matrix)| { - Self::new(global.as_global_scope(), is2D, matrix) + Self::new(global, is2D, matrix) }) } // https://drafts.fxtf.org/geometry-1/#dom-dommatrixreadonly-frommatrix - pub fn FromMatrix(global: GlobalRef, other: &DOMMatrixInit) -> Fallible> { + pub fn FromMatrix(global: &GlobalScope, other: &DOMMatrixInit) -> Fallible> { dommatrixinit_to_matrix(&other) .map(|(is2D, matrix)| { - Self::new(global.as_global_scope(), is2D, matrix) + Self::new(global, is2D, matrix) }) } diff --git a/components/script/dom/domparser.rs b/components/script/dom/domparser.rs index 6d830e40bfd..e73d9bf1aad 100644 --- a/components/script/dom/domparser.rs +++ b/components/script/dom/domparser.rs @@ -12,12 +12,12 @@ use dom::bindings::codegen::Bindings::DOMParserBinding::SupportedType::Text_xml; use dom::bindings::codegen::Bindings::DocumentBinding::DocumentReadyState; use dom::bindings::codegen::Bindings::WindowBinding::WindowMethods; use dom::bindings::error::Fallible; -use dom::bindings::global::GlobalRef; use dom::bindings::js::{JS, Root}; use dom::bindings::reflector::{Reflector, reflect_dom_object}; use dom::bindings::str::DOMString; use dom::document::{Document, IsHTMLDocument}; use dom::document::DocumentSource; +use dom::globalscope::GlobalScope; use dom::window::Window; use parse::html::{ParseContext, parse_html}; use parse::xml::{self, parse_xml}; @@ -42,8 +42,8 @@ impl DOMParser { DOMParserBinding::Wrap) } - pub fn Constructor(global: GlobalRef) -> Fallible> { - Ok(DOMParser::new(global.as_global_scope().as_window())) + pub fn Constructor(global: &GlobalScope) -> Fallible> { + Ok(DOMParser::new(global.as_window())) } } diff --git a/components/script/dom/dompoint.rs b/components/script/dom/dompoint.rs index 49a873a25fc..2f77f77c2c1 100644 --- a/components/script/dom/dompoint.rs +++ b/components/script/dom/dompoint.rs @@ -5,7 +5,6 @@ use dom::bindings::codegen::Bindings::DOMPointBinding::{DOMPointInit, DOMPointMethods, Wrap}; use dom::bindings::codegen::Bindings::DOMPointReadOnlyBinding::DOMPointReadOnlyMethods; use dom::bindings::error::Fallible; -use dom::bindings::global::GlobalRef; use dom::bindings::js::Root; use dom::bindings::reflector::reflect_dom_object; use dom::dompointreadonly::{DOMPointReadOnly, DOMPointWriteMethods}; @@ -28,13 +27,13 @@ impl DOMPoint { reflect_dom_object(box DOMPoint::new_inherited(x, y, z, w), global, Wrap) } - pub fn Constructor(global: GlobalRef, + pub fn Constructor(global: &GlobalScope, x: f64, y: f64, z: f64, w: f64) -> Fallible> { - Ok(DOMPoint::new(global.as_global_scope(), x, y, z, w)) + Ok(DOMPoint::new(global, x, y, z, w)) } pub fn new_from_init(global: &GlobalScope, p: &DOMPointInit) -> Root { diff --git a/components/script/dom/dompointreadonly.rs b/components/script/dom/dompointreadonly.rs index f905db356ca..9da4e27a984 100644 --- a/components/script/dom/dompointreadonly.rs +++ b/components/script/dom/dompointreadonly.rs @@ -4,7 +4,6 @@ use dom::bindings::codegen::Bindings::DOMPointReadOnlyBinding::{DOMPointReadOnlyMethods, Wrap}; use dom::bindings::error::Fallible; -use dom::bindings::global::GlobalRef; use dom::bindings::js::Root; use dom::bindings::reflector::{Reflector, reflect_dom_object}; use dom::globalscope::GlobalScope; @@ -37,13 +36,13 @@ impl DOMPointReadOnly { Wrap) } - pub fn Constructor(global: GlobalRef, + pub fn Constructor(global: &GlobalScope, x: f64, y: f64, z: f64, w: f64) -> Fallible> { - Ok(DOMPointReadOnly::new(global.as_global_scope(), x, y, z, w)) + Ok(DOMPointReadOnly::new(global, x, y, z, w)) } } diff --git a/components/script/dom/domquad.rs b/components/script/dom/domquad.rs index f4a388df284..abe30f80bdd 100644 --- a/components/script/dom/domquad.rs +++ b/components/script/dom/domquad.rs @@ -6,7 +6,6 @@ use dom::bindings::codegen::Bindings::DOMPointBinding::{DOMPointInit, DOMPointMe use dom::bindings::codegen::Bindings::DOMQuadBinding::{DOMQuadInit, DOMQuadMethods, Wrap}; use dom::bindings::codegen::Bindings::DOMRectReadOnlyBinding::DOMRectInit; use dom::bindings::error::Fallible; -use dom::bindings::global::GlobalRef; use dom::bindings::js::{Root, JS}; use dom::bindings::reflector::{Reflectable, Reflector, reflect_dom_object}; use dom::dompoint::DOMPoint; @@ -48,13 +47,12 @@ impl DOMQuad { Wrap) } - pub fn Constructor(global: GlobalRef, + pub fn Constructor(global: &GlobalScope, p1: &DOMPointInit, p2: &DOMPointInit, p3: &DOMPointInit, p4: &DOMPointInit) -> Fallible> { - let global = global.as_global_scope(); Ok(DOMQuad::new(global, &*DOMPoint::new_from_init(global, p1), &*DOMPoint::new_from_init(global, p2), @@ -63,8 +61,7 @@ impl DOMQuad { } // https://drafts.fxtf.org/geometry/#dom-domquad-fromrect - pub fn FromRect(global: GlobalRef, other: &DOMRectInit) -> Root { - let global = global.as_global_scope(); + pub fn FromRect(global: &GlobalScope, other: &DOMRectInit) -> Root { DOMQuad::new(global, &*DOMPoint::new(global, other.x, other.y, 0f64, 1f64), &*DOMPoint::new(global, other.x + other.width, other.y, 0f64, 1f64), @@ -73,8 +70,7 @@ impl DOMQuad { } // https://drafts.fxtf.org/geometry/#dom-domquad-fromquad - pub fn FromQuad(global: GlobalRef, other: &DOMQuadInit) -> Root { - let global = global.as_global_scope(); + pub fn FromQuad(global: &GlobalScope, other: &DOMQuadInit) -> Root { DOMQuad::new(global, &DOMPoint::new_from_init(global, &other.p1), &DOMPoint::new_from_init(global, &other.p2), diff --git a/components/script/dom/domrect.rs b/components/script/dom/domrect.rs index f70eda2ead1..78e1b2db22e 100644 --- a/components/script/dom/domrect.rs +++ b/components/script/dom/domrect.rs @@ -6,7 +6,6 @@ use dom::bindings::codegen::Bindings::DOMRectBinding; use dom::bindings::codegen::Bindings::DOMRectBinding::DOMRectMethods; use dom::bindings::codegen::Bindings::DOMRectReadOnlyBinding::DOMRectReadOnlyMethods; use dom::bindings::error::Fallible; -use dom::bindings::global::GlobalRef; use dom::bindings::js::Root; use dom::bindings::reflector::reflect_dom_object; use dom::domrectreadonly::DOMRectReadOnly; @@ -30,13 +29,13 @@ impl DOMRect { DOMRectBinding::Wrap) } - pub fn Constructor(global: GlobalRef, + pub fn Constructor(global: &GlobalScope, x: f64, y: f64, width: f64, height: f64) -> Fallible> { - Ok(DOMRect::new(global.as_global_scope(), x, y, width, height)) + Ok(DOMRect::new(global, x, y, width, height)) } } diff --git a/components/script/dom/domrectreadonly.rs b/components/script/dom/domrectreadonly.rs index a9d87ec3947..ef0c7ce2c67 100644 --- a/components/script/dom/domrectreadonly.rs +++ b/components/script/dom/domrectreadonly.rs @@ -4,7 +4,6 @@ use dom::bindings::codegen::Bindings::DOMRectReadOnlyBinding::{DOMRectReadOnlyMethods, Wrap}; use dom::bindings::error::Fallible; -use dom::bindings::global::GlobalRef; use dom::bindings::js::Root; use dom::bindings::reflector::{Reflector, reflect_dom_object}; use dom::globalscope::GlobalScope; @@ -41,13 +40,13 @@ impl DOMRectReadOnly { Wrap) } - pub fn Constructor(global: GlobalRef, + pub fn Constructor(global: &GlobalScope, x: f64, y: f64, width: f64, height: f64) -> Fallible> { - Ok(DOMRectReadOnly::new(global.as_global_scope(), x, y, width, height)) + Ok(DOMRectReadOnly::new(global, x, y, width, height)) } pub fn set_x(&self, value: f64) { diff --git a/components/script/dom/errorevent.rs b/components/script/dom/errorevent.rs index 394ce749cdb..edf1118b58c 100644 --- a/components/script/dom/errorevent.rs +++ b/components/script/dom/errorevent.rs @@ -7,7 +7,6 @@ use dom::bindings::codegen::Bindings::ErrorEventBinding; use dom::bindings::codegen::Bindings::ErrorEventBinding::ErrorEventMethods; use dom::bindings::codegen::Bindings::EventBinding::EventMethods; use dom::bindings::error::Fallible; -use dom::bindings::global::GlobalRef; use dom::bindings::inheritance::Castable; use dom::bindings::js::{MutHeapJSVal, Root}; use dom::bindings::reflector::reflect_dom_object; @@ -71,7 +70,7 @@ impl ErrorEvent { ev } - pub fn Constructor(global: GlobalRef, + pub fn Constructor(global: &GlobalScope, type_: DOMString, init: &ErrorEventBinding::ErrorEventInit) -> Fallible>{ let msg = match init.message.as_ref() { @@ -96,7 +95,7 @@ impl ErrorEvent { // https://github.com/servo/servo/issues/6381 rooted!(in(global.get_cx()) let error = init.error); let event = ErrorEvent::new( - global.as_global_scope(), + global, Atom::from(type_), bubbles, cancelable, diff --git a/components/script/dom/event.rs b/components/script/dom/event.rs index 3f5a7c24c8a..cdbfdafec2e 100644 --- a/components/script/dom/event.rs +++ b/components/script/dom/event.rs @@ -6,7 +6,6 @@ use dom::bindings::cell::DOMRefCell; use dom::bindings::codegen::Bindings::EventBinding; use dom::bindings::codegen::Bindings::EventBinding::{EventConstants, EventMethods}; use dom::bindings::error::Fallible; -use dom::bindings::global::GlobalRef; use dom::bindings::js::{JS, MutNullableHeap, Root}; use dom::bindings::refcounted::Trusted; use dom::bindings::reflector::{Reflector, reflect_dom_object}; @@ -131,12 +130,12 @@ impl Event { event } - pub fn Constructor(global: GlobalRef, + pub fn Constructor(global: &GlobalScope, type_: DOMString, init: &EventBinding::EventInit) -> Fallible> { let bubbles = EventBubbles::from(init.bubbles); let cancelable = EventCancelable::from(init.cancelable); - Ok(Event::new(global.as_global_scope(), Atom::from(type_), bubbles, cancelable)) + Ok(Event::new(global, Atom::from(type_), bubbles, cancelable)) } pub fn init_event(&self, type_: Atom, bubbles: bool, cancelable: bool) { diff --git a/components/script/dom/eventsource.rs b/components/script/dom/eventsource.rs index bf83bed4c5c..f05e73beafa 100644 --- a/components/script/dom/eventsource.rs +++ b/components/script/dom/eventsource.rs @@ -6,7 +6,6 @@ use dom::bindings::cell::DOMRefCell; use dom::bindings::codegen::Bindings::EventHandlerBinding::EventHandlerNonNull; use dom::bindings::codegen::Bindings::EventSourceBinding::{EventSourceInit, EventSourceMethods, Wrap}; use dom::bindings::error::{Error, Fallible}; -use dom::bindings::global::GlobalRef; use dom::bindings::js::Root; use dom::bindings::reflector::reflect_dom_object; use dom::bindings::str::DOMString; @@ -49,18 +48,17 @@ impl EventSource { Wrap) } - pub fn Constructor(global: GlobalRef, + pub fn Constructor(global: &GlobalScope, url_str: DOMString, event_source_init: &EventSourceInit) -> Fallible> { - let global_scope = global.as_global_scope(); // Steps 1-2 - let base_url = global_scope.get_url(); + let base_url = global.get_url(); let url = match base_url.join(&*url_str) { Ok(u) => u, Err(_) => return Err(Error::Syntax) }; // Step 3 - let event_source = EventSource::new(global_scope, url, event_source_init.withCredentials); + let event_source = EventSource::new(global, url, event_source_init.withCredentials); // Step 4 // Step 5 // Step 6 diff --git a/components/script/dom/extendableevent.rs b/components/script/dom/extendableevent.rs index 1888888e841..d859d8f4724 100644 --- a/components/script/dom/extendableevent.rs +++ b/components/script/dom/extendableevent.rs @@ -5,7 +5,6 @@ use dom::bindings::codegen::Bindings::EventBinding::EventMethods; use dom::bindings::codegen::Bindings::ExtendableEventBinding; use dom::bindings::error::{Error, ErrorResult, Fallible}; -use dom::bindings::global::GlobalRef; use dom::bindings::inheritance::Castable; use dom::bindings::js::Root; use dom::bindings::reflector::reflect_dom_object; @@ -42,10 +41,10 @@ impl ExtendableEvent { ev } - pub fn Constructor(global: GlobalRef, + pub fn Constructor(global: &GlobalScope, type_: DOMString, init: &ExtendableEventBinding::ExtendableEventInit) -> Fallible> { - Ok(ExtendableEvent::new(global.as_global_scope(), + Ok(ExtendableEvent::new(global, Atom::from(type_), init.parent.bubbles, init.parent.cancelable)) diff --git a/components/script/dom/extendablemessageevent.rs b/components/script/dom/extendablemessageevent.rs index 8acddbaf7fa..0a5968d1d99 100644 --- a/components/script/dom/extendablemessageevent.rs +++ b/components/script/dom/extendablemessageevent.rs @@ -5,7 +5,6 @@ use dom::bindings::codegen::Bindings::ExtendableMessageEventBinding; use dom::bindings::codegen::Bindings::ExtendableMessageEventBinding::ExtendableMessageEventMethods; use dom::bindings::error::Fallible; -use dom::bindings::global::GlobalRef; use dom::bindings::inheritance::Castable; use dom::bindings::js::Root; use dom::bindings::reflector::reflect_dom_object; @@ -47,12 +46,12 @@ impl ExtendableMessageEvent { ev } - pub fn Constructor(global: GlobalRef, + pub fn Constructor(global: &GlobalScope, type_: DOMString, init: &ExtendableMessageEventBinding::ExtendableMessageEventInit) -> Fallible> { rooted!(in(global.get_cx()) let data = init.data); - let ev = ExtendableMessageEvent::new(global.as_global_scope(), + let ev = ExtendableMessageEvent::new(global, Atom::from(type_), init.parent.parent.bubbles, init.parent.parent.cancelable, diff --git a/components/script/dom/file.rs b/components/script/dom/file.rs index 6ee2f0c3771..dba94a85e50 100644 --- a/components/script/dom/file.rs +++ b/components/script/dom/file.rs @@ -6,7 +6,6 @@ use dom::bindings::codegen::Bindings::FileBinding; use dom::bindings::codegen::Bindings::FileBinding::FileMethods; use dom::bindings::codegen::UnionTypes::BlobOrString; use dom::bindings::error::{Error, Fallible}; -use dom::bindings::global::GlobalRef; use dom::bindings::inheritance::Castable; use dom::bindings::js::Root; use dom::bindings::reflector::reflect_dom_object; @@ -59,7 +58,7 @@ impl File { } // https://w3c.github.io/FileAPI/#file-constructor - pub fn Constructor(global: GlobalRef, + pub fn Constructor(global: &GlobalScope, fileBits: Vec, filename: DOMString, filePropertyBag: &FileBinding::FilePropertyBag) @@ -76,11 +75,11 @@ impl File { // NOTE: Following behaviour might be removed in future, // see https://github.com/w3c/FileAPI/issues/41 let replaced_filename = DOMString::from_string(filename.replace("/", ":")); - Ok(File::new(global.as_global_scope(), - BlobImpl::new_from_bytes(bytes), - replaced_filename, - modified, - typeString)) + Ok(File::new(global, + BlobImpl::new_from_bytes(bytes), + replaced_filename, + modified, + typeString)) } pub fn name(&self) -> &DOMString { diff --git a/components/script/dom/filereader.rs b/components/script/dom/filereader.rs index afd291c8f62..4ba5af109be 100644 --- a/components/script/dom/filereader.rs +++ b/components/script/dom/filereader.rs @@ -7,7 +7,6 @@ use dom::bindings::codegen::Bindings::BlobBinding::BlobMethods; use dom::bindings::codegen::Bindings::EventHandlerBinding::EventHandlerNonNull; use dom::bindings::codegen::Bindings::FileReaderBinding::{self, FileReaderConstants, FileReaderMethods}; use dom::bindings::error::{Error, ErrorResult, Fallible}; -use dom::bindings::global::GlobalRef; use dom::bindings::inheritance::Castable; use dom::bindings::js::{JS, MutNullableHeap, Root}; use dom::bindings::refcounted::Trusted; @@ -94,8 +93,8 @@ impl FileReader { global, FileReaderBinding::Wrap) } - pub fn Constructor(global: GlobalRef) -> Fallible> { - Ok(FileReader::new(global.as_global_scope())) + pub fn Constructor(global: &GlobalScope) -> Fallible> { + Ok(FileReader::new(global)) } //https://w3c.github.io/FileAPI/#dfn-error-steps diff --git a/components/script/dom/filereadersync.rs b/components/script/dom/filereadersync.rs index 3e8800a65bf..875843ea0c6 100644 --- a/components/script/dom/filereadersync.rs +++ b/components/script/dom/filereadersync.rs @@ -4,7 +4,6 @@ use dom::bindings::codegen::Bindings::FileReaderSyncBinding; use dom::bindings::error::Fallible; -use dom::bindings::global::GlobalRef; use dom::bindings::js::Root; use dom::bindings::reflector::reflect_dom_object; use dom::eventtarget::EventTarget; @@ -27,7 +26,7 @@ impl FileReaderSync { global, FileReaderSyncBinding::Wrap) } - pub fn Constructor(global: GlobalRef) -> Fallible> { - Ok(FileReaderSync::new(global.as_global_scope())) + pub fn Constructor(global: &GlobalScope) -> Fallible> { + Ok(FileReaderSync::new(global)) } } diff --git a/components/script/dom/focusevent.rs b/components/script/dom/focusevent.rs index 8d3f6b57256..d06b725286d 100644 --- a/components/script/dom/focusevent.rs +++ b/components/script/dom/focusevent.rs @@ -6,7 +6,6 @@ use dom::bindings::codegen::Bindings::FocusEventBinding; use dom::bindings::codegen::Bindings::FocusEventBinding::FocusEventMethods; use dom::bindings::codegen::Bindings::UIEventBinding::UIEventMethods; use dom::bindings::error::Fallible; -use dom::bindings::global::GlobalRef; use dom::bindings::inheritance::Castable; use dom::bindings::js::{JS, MutNullableHeap, Root, RootedReference}; use dom::bindings::reflector::reflect_dom_object; @@ -54,12 +53,12 @@ impl FocusEvent { ev } - pub fn Constructor(global: GlobalRef, + pub fn Constructor(global: &GlobalScope, type_: DOMString, init: &FocusEventBinding::FocusEventInit) -> Fallible> { let bubbles = EventBubbles::from(init.parent.parent.bubbles); let cancelable = EventCancelable::from(init.parent.parent.cancelable); - let event = FocusEvent::new(global.as_global_scope().as_window(), + let event = FocusEvent::new(global.as_window(), type_, bubbles, cancelable, diff --git a/components/script/dom/formdata.rs b/components/script/dom/formdata.rs index 50747245c21..8bbd46833b3 100644 --- a/components/script/dom/formdata.rs +++ b/components/script/dom/formdata.rs @@ -7,7 +7,6 @@ use dom::bindings::codegen::Bindings::FormDataBinding::FormDataMethods; use dom::bindings::codegen::Bindings::FormDataBinding::FormDataWrap; use dom::bindings::codegen::UnionTypes::FileOrUSVString; use dom::bindings::error::Fallible; -use dom::bindings::global::GlobalRef; use dom::bindings::iterable::Iterable; use dom::bindings::js::Root; use dom::bindings::reflector::{Reflectable, Reflector, reflect_dom_object}; @@ -51,9 +50,9 @@ impl FormData { global, FormDataWrap) } - pub fn Constructor(global: GlobalRef, form: Option<&HTMLFormElement>) -> Fallible> { + pub fn Constructor(global: &GlobalScope, form: Option<&HTMLFormElement>) -> Fallible> { // TODO: Construct form data set for form if it is supplied - Ok(FormData::new(form, global.as_global_scope())) + Ok(FormData::new(form, global)) } } diff --git a/components/script/dom/hashchangeevent.rs b/components/script/dom/hashchangeevent.rs index c97599b25a3..0fd753c433c 100644 --- a/components/script/dom/hashchangeevent.rs +++ b/components/script/dom/hashchangeevent.rs @@ -6,7 +6,6 @@ use dom::bindings::codegen::Bindings::EventBinding::EventMethods; use dom::bindings::codegen::Bindings::HashChangeEventBinding; use dom::bindings::codegen::Bindings::HashChangeEventBinding::HashChangeEventMethods; use dom::bindings::error::Fallible; -use dom::bindings::global::GlobalRef; use dom::bindings::inheritance::Castable; use dom::bindings::js::Root; use dom::bindings::reflector::reflect_dom_object; @@ -55,11 +54,11 @@ impl HashChangeEvent { ev } - pub fn Constructor(global: GlobalRef, + pub fn Constructor(global: &GlobalScope, type_: DOMString, init: &HashChangeEventBinding::HashChangeEventInit) -> Fallible> { - Ok(HashChangeEvent::new(global.as_global_scope(), + Ok(HashChangeEvent::new(global, Atom::from(type_), init.parent.bubbles, init.parent.cancelable, diff --git a/components/script/dom/headers.rs b/components/script/dom/headers.rs index 68c3d92c0ad..02262dbb475 100644 --- a/components/script/dom/headers.rs +++ b/components/script/dom/headers.rs @@ -5,7 +5,6 @@ use dom::bindings::cell::DOMRefCell; use dom::bindings::codegen::Bindings::HeadersBinding::{HeadersInit, HeadersMethods, HeadersWrap}; use dom::bindings::error::{Error, ErrorResult, Fallible}; -use dom::bindings::global::GlobalRef; use dom::bindings::iterable::Iterable; use dom::bindings::js::Root; use dom::bindings::reflector::{Reflector, reflect_dom_object}; @@ -49,9 +48,9 @@ impl Headers { } // https://fetch.spec.whatwg.org/#dom-headers - pub fn Constructor(global: GlobalRef, init: Option) + pub fn Constructor(global: &GlobalScope, init: Option) -> Fallible> { - let dom_headers_new = Headers::new(global.as_global_scope()); + let dom_headers_new = Headers::new(global); try!(dom_headers_new.fill(init)); Ok(dom_headers_new) } diff --git a/components/script/dom/htmlimageelement.rs b/components/script/dom/htmlimageelement.rs index d96bb0cab3a..489a6821824 100644 --- a/components/script/dom/htmlimageelement.rs +++ b/components/script/dom/htmlimageelement.rs @@ -17,6 +17,7 @@ use dom::bindings::str::DOMString; use dom::document::Document; use dom::element::{AttributeMutation, Element, RawLayoutElementHelpers}; use dom::eventtarget::EventTarget; +use dom::globalscope::GlobalScope; use dom::htmlelement::HTMLElement; use dom::node::{Node, NodeDamage, document_from_node, window_from_node}; use dom::values::UNSIGNED_LONG_MAX; @@ -225,10 +226,10 @@ impl HTMLImageElement { HTMLImageElementBinding::Wrap) } - pub fn Image(global: GlobalRef, + pub fn Image(global: &GlobalScope, width: Option, height: Option) -> Fallible> { - let document = global.as_global_scope().as_window().Document(); + let document = global.as_window().Document(); let image = HTMLImageElement::new(atom!("img"), None, document.r()); if let Some(w) = width { image.SetWidth(w); diff --git a/components/script/dom/keyboardevent.rs b/components/script/dom/keyboardevent.rs index 812b9f63051..4da24309e18 100644 --- a/components/script/dom/keyboardevent.rs +++ b/components/script/dom/keyboardevent.rs @@ -7,12 +7,12 @@ use dom::bindings::codegen::Bindings::KeyboardEventBinding; use dom::bindings::codegen::Bindings::KeyboardEventBinding::{KeyboardEventConstants, KeyboardEventMethods}; use dom::bindings::codegen::Bindings::UIEventBinding::UIEventMethods; use dom::bindings::error::Fallible; -use dom::bindings::global::GlobalRef; use dom::bindings::inheritance::Castable; use dom::bindings::js::{Root, RootedReference}; use dom::bindings::reflector::reflect_dom_object; use dom::bindings::str::DOMString; use dom::event::Event; +use dom::globalscope::GlobalScope; use dom::uievent::UIEvent; use dom::window::Window; use msg::constellation_msg; @@ -101,10 +101,10 @@ impl KeyboardEvent { ev } - pub fn Constructor(global: GlobalRef, + pub fn Constructor(global: &GlobalScope, type_: DOMString, init: &KeyboardEventBinding::KeyboardEventInit) -> Fallible> { - let event = KeyboardEvent::new(global.as_global_scope().as_window(), + let event = KeyboardEvent::new(global.as_window(), type_, init.parent.parent.parent.bubbles, init.parent.parent.parent.cancelable, diff --git a/components/script/dom/messageevent.rs b/components/script/dom/messageevent.rs index 8192c8301cf..53143711cf0 100644 --- a/components/script/dom/messageevent.rs +++ b/components/script/dom/messageevent.rs @@ -6,7 +6,6 @@ use dom::bindings::codegen::Bindings::EventBinding::EventMethods; use dom::bindings::codegen::Bindings::MessageEventBinding; use dom::bindings::codegen::Bindings::MessageEventBinding::MessageEventMethods; use dom::bindings::error::Fallible; -use dom::bindings::global::GlobalRef; use dom::bindings::inheritance::Castable; use dom::bindings::js::Root; use dom::bindings::reflector::reflect_dom_object; @@ -61,14 +60,14 @@ impl MessageEvent { ev } - pub fn Constructor(global: GlobalRef, + pub fn Constructor(global: &GlobalScope, type_: DOMString, init: &MessageEventBinding::MessageEventInit) -> Fallible> { // Dictionaries need to be rooted // https://github.com/servo/servo/issues/6381 rooted!(in(global.get_cx()) let data = init.data); - let ev = MessageEvent::new(global.as_global_scope(), + let ev = MessageEvent::new(global, Atom::from(type_), init.parent.bubbles, init.parent.cancelable, diff --git a/components/script/dom/mouseevent.rs b/components/script/dom/mouseevent.rs index 41c7d88dc6d..27a61c79400 100644 --- a/components/script/dom/mouseevent.rs +++ b/components/script/dom/mouseevent.rs @@ -6,13 +6,13 @@ use dom::bindings::codegen::Bindings::MouseEventBinding; use dom::bindings::codegen::Bindings::MouseEventBinding::MouseEventMethods; use dom::bindings::codegen::Bindings::UIEventBinding::UIEventMethods; use dom::bindings::error::Fallible; -use dom::bindings::global::GlobalRef; use dom::bindings::inheritance::Castable; use dom::bindings::js::{JS, MutNullableHeap, Root, RootedReference}; use dom::bindings::reflector::reflect_dom_object; use dom::bindings::str::DOMString; use dom::event::{Event, EventBubbles, EventCancelable}; use dom::eventtarget::EventTarget; +use dom::globalscope::GlobalScope; use dom::uievent::UIEvent; use dom::window::Window; use std::cell::Cell; @@ -82,12 +82,12 @@ impl MouseEvent { ev } - pub fn Constructor(global: GlobalRef, + pub fn Constructor(global: &GlobalScope, type_: DOMString, init: &MouseEventBinding::MouseEventInit) -> Fallible> { let bubbles = EventBubbles::from(init.parent.parent.parent.bubbles); let cancelable = EventCancelable::from(init.parent.parent.parent.cancelable); - let event = MouseEvent::new(global.as_global_scope().as_window(), + let event = MouseEvent::new(global.as_window(), type_, bubbles, cancelable, diff --git a/components/script/dom/pagetransitionevent.rs b/components/script/dom/pagetransitionevent.rs index c25281dcc31..883f3319394 100644 --- a/components/script/dom/pagetransitionevent.rs +++ b/components/script/dom/pagetransitionevent.rs @@ -6,7 +6,6 @@ use dom::bindings::codegen::Bindings::EventBinding::EventMethods; use dom::bindings::codegen::Bindings::PageTransitionEventBinding; use dom::bindings::codegen::Bindings::PageTransitionEventBinding::PageTransitionEventMethods; use dom::bindings::error::Fallible; -use dom::bindings::global::GlobalRef; use dom::bindings::inheritance::Castable; use dom::bindings::js::Root; use dom::bindings::reflector::reflect_dom_object; @@ -52,11 +51,11 @@ impl PageTransitionEvent { ev } - pub fn Constructor(global: GlobalRef, + pub fn Constructor(global: &GlobalScope, type_: DOMString, init: &PageTransitionEventBinding::PageTransitionEventInit) -> Fallible> { - Ok(PageTransitionEvent::new(global.as_global_scope(), + Ok(PageTransitionEvent::new(global, Atom::from(type_), init.parent.bubbles, init.parent.cancelable, diff --git a/components/script/dom/popstateevent.rs b/components/script/dom/popstateevent.rs index 621c9d4199f..7b7af62a6fe 100644 --- a/components/script/dom/popstateevent.rs +++ b/components/script/dom/popstateevent.rs @@ -6,7 +6,6 @@ use dom::bindings::codegen::Bindings::EventBinding::EventMethods; use dom::bindings::codegen::Bindings::PopStateEventBinding; use dom::bindings::codegen::Bindings::PopStateEventBinding::PopStateEventMethods; use dom::bindings::error::Fallible; -use dom::bindings::global::GlobalRef; use dom::bindings::inheritance::Castable; use dom::bindings::js::{MutHeapJSVal, Root}; use dom::bindings::reflector::reflect_dom_object; @@ -55,11 +54,11 @@ impl PopStateEvent { } #[allow(unsafe_code)] - pub fn Constructor(global: GlobalRef, + pub fn Constructor(global: &GlobalScope, type_: DOMString, init: &PopStateEventBinding::PopStateEventInit) -> Fallible> { - Ok(PopStateEvent::new(global.as_global_scope(), + Ok(PopStateEvent::new(global, Atom::from(type_), init.parent.bubbles, init.parent.cancelable, diff --git a/components/script/dom/progressevent.rs b/components/script/dom/progressevent.rs index 2f25df109fa..189f65412fe 100644 --- a/components/script/dom/progressevent.rs +++ b/components/script/dom/progressevent.rs @@ -6,7 +6,6 @@ use dom::bindings::codegen::Bindings::EventBinding::EventMethods; use dom::bindings::codegen::Bindings::ProgressEventBinding; use dom::bindings::codegen::Bindings::ProgressEventBinding::ProgressEventMethods; use dom::bindings::error::Fallible; -use dom::bindings::global::GlobalRef; use dom::bindings::inheritance::Castable; use dom::bindings::js::Root; use dom::bindings::reflector::reflect_dom_object; @@ -49,13 +48,13 @@ impl ProgressEvent { } ev } - pub fn Constructor(global: GlobalRef, + pub fn Constructor(global: &GlobalScope, type_: DOMString, init: &ProgressEventBinding::ProgressEventInit) -> Fallible> { let bubbles = EventBubbles::from(init.parent.bubbles); let cancelable = EventCancelable::from(init.parent.cancelable); - let ev = ProgressEvent::new(global.as_global_scope(), Atom::from(type_), bubbles, cancelable, + let ev = ProgressEvent::new(global, Atom::from(type_), bubbles, cancelable, init.lengthComputable, init.loaded, init.total); Ok(ev) } diff --git a/components/script/dom/range.rs b/components/script/dom/range.rs index 7e636164da5..480740fa19f 100644 --- a/components/script/dom/range.rs +++ b/components/script/dom/range.rs @@ -11,7 +11,6 @@ use dom::bindings::codegen::Bindings::RangeBinding::RangeMethods; use dom::bindings::codegen::Bindings::TextBinding::TextMethods; use dom::bindings::codegen::Bindings::WindowBinding::WindowMethods; use dom::bindings::error::{Error, ErrorResult, Fallible}; -use dom::bindings::global::GlobalRef; use dom::bindings::inheritance::{CharacterDataTypeId, NodeTypeId}; use dom::bindings::inheritance::Castable; use dom::bindings::js::{JS, MutHeap, Root, RootedReference}; @@ -23,6 +22,7 @@ use dom::characterdata::CharacterData; use dom::document::Document; use dom::documentfragment::DocumentFragment; use dom::element::Element; +use dom::globalscope::GlobalScope; use dom::htmlbodyelement::HTMLBodyElement; use dom::htmlscriptelement::HTMLScriptElement; use dom::node::{Node, UnbindContext}; @@ -70,8 +70,8 @@ impl Range { } // https://dom.spec.whatwg.org/#dom-range - pub fn Constructor(global: GlobalRef) -> Fallible> { - let document = global.as_global_scope().as_window().Document(); + pub fn Constructor(global: &GlobalScope) -> Fallible> { + let document = global.as_window().Document(); Ok(Range::new_with_doc(document.r())) } diff --git a/components/script/dom/request.rs b/components/script/dom/request.rs index 664b2ca5302..623a8037f62 100644 --- a/components/script/dom/request.rs +++ b/components/script/dom/request.rs @@ -17,7 +17,6 @@ use dom::bindings::codegen::Bindings::RequestBinding::RequestMode; use dom::bindings::codegen::Bindings::RequestBinding::RequestRedirect; use dom::bindings::codegen::Bindings::RequestBinding::RequestType; use dom::bindings::error::{Error, Fallible}; -use dom::bindings::global::GlobalRef; use dom::bindings::js::{JS, MutNullableHeap, Root}; use dom::bindings::reflector::{Reflectable, Reflector, reflect_dom_object}; use dom::bindings::str::{ByteString, DOMString, USVString}; @@ -78,12 +77,10 @@ impl Request { } // https://fetch.spec.whatwg.org/#dom-request - pub fn Constructor(global: GlobalRef, + pub fn Constructor(global: &GlobalScope, input: RequestInfo, init: &RequestInit) -> Fallible> { - let global_scope = global.as_global_scope(); - // Step 1 let temporary_request: NetTraitsRequest; @@ -95,7 +92,7 @@ impl Request { // Step 4 // TODO: `entry settings object` is not implemented in Servo yet. - let base_url = global_scope.get_url(); + let base_url = global.get_url(); match input { // Step 5 @@ -112,7 +109,7 @@ impl Request { return Err(Error::Type("Url includes credentials".to_string())) } // Step 5.4 - temporary_request = net_request_from_global(&global_scope, + temporary_request = net_request_from_global(global, url, false); // Step 5.5 @@ -153,7 +150,7 @@ impl Request { // Step 12 let mut request: NetTraitsRequest; - request = net_request_from_global(&global_scope, + request = net_request_from_global(global, temporary_request.current_url(), false); request.method = temporary_request.method; @@ -305,7 +302,7 @@ impl Request { } // Step 26 - let r = Request::from_net_request(&global_scope, + let r = Request::from_net_request(global, false, request); r.headers.or_init(|| Headers::for_request(&r.global_scope())); diff --git a/components/script/dom/response.rs b/components/script/dom/response.rs index 4e7d4967d28..febff29f97b 100644 --- a/components/script/dom/response.rs +++ b/components/script/dom/response.rs @@ -10,7 +10,6 @@ use dom::bindings::codegen::Bindings::ResponseBinding; use dom::bindings::codegen::Bindings::ResponseBinding::{ResponseMethods, ResponseType as DOMResponseType}; use dom::bindings::codegen::Bindings::XMLHttpRequestBinding::BodyInit; use dom::bindings::error::{Error, Fallible}; -use dom::bindings::global::GlobalRef; use dom::bindings::js::{JS, MutNullableHeap, Root}; use dom::bindings::reflector::{Reflectable, Reflector, reflect_dom_object}; use dom::bindings::str::{ByteString, USVString}; @@ -71,7 +70,7 @@ impl Response { reflect_dom_object(box Response::new_inherited(), global, ResponseBinding::Wrap) } - pub fn Constructor(global: GlobalRef, body: Option, init: &ResponseBinding::ResponseInit) + pub fn Constructor(global: &GlobalScope, body: Option, init: &ResponseBinding::ResponseInit) -> Fallible> { // Step 1 if init.status < 200 || init.status > 599 { @@ -87,7 +86,7 @@ impl Response { } // Step 3 - let r = Response::new(global.as_global_scope()); + let r = Response::new(global); // Step 4 *r.status.borrow_mut() = Some(StatusCode::from_u16(init.status)); @@ -139,8 +138,8 @@ impl Response { } // https://fetch.spec.whatwg.org/#dom-response-error - pub fn Error(global: GlobalRef) -> Root { - let r = Response::new(global.as_global_scope()); + pub fn Error(global: &GlobalScope) -> Root { + let r = Response::new(global); *r.response_type.borrow_mut() = DOMResponseType::Error; r.Headers().set_guard(Guard::Immutable); *r.raw_status.borrow_mut() = Some((0, b"".to_vec())); @@ -148,11 +147,10 @@ impl Response { } // https://fetch.spec.whatwg.org/#dom-response-redirect - pub fn Redirect(global: GlobalRef, url: USVString, status: u16) -> Fallible> { - let global_scope = global.as_global_scope(); + pub fn Redirect(global: &GlobalScope, url: USVString, status: u16) -> Fallible> { // Step 1 // TODO: `entry settings object` is not implemented in Servo yet. - let base_url = global_scope.get_url(); + let base_url = global.get_url(); let parsed_url = base_url.join(&url.0); // Step 2 @@ -168,7 +166,7 @@ impl Response { // Step 4 // see Step 4 continued - let r = Response::new(global_scope); + let r = Response::new(global); // Step 5 *r.status.borrow_mut() = Some(StatusCode::from_u16(status)); diff --git a/components/script/dom/storageevent.rs b/components/script/dom/storageevent.rs index 0b4a484ebc0..21c16f1db78 100644 --- a/components/script/dom/storageevent.rs +++ b/components/script/dom/storageevent.rs @@ -6,7 +6,6 @@ use dom::bindings::codegen::Bindings::EventBinding::EventMethods; use dom::bindings::codegen::Bindings::StorageEventBinding; use dom::bindings::codegen::Bindings::StorageEventBinding::StorageEventMethods; use dom::bindings::error::Fallible; -use dom::bindings::global::GlobalRef; use dom::bindings::inheritance::Castable; use dom::bindings::js::{JS, MutNullableHeap, Root, RootedReference}; use dom::bindings::reflector::reflect_dom_object; @@ -71,7 +70,7 @@ impl StorageEvent { ev } - pub fn Constructor(global: GlobalRef, + pub fn Constructor(global: &GlobalScope, type_: DOMString, init: &StorageEventBinding::StorageEventInit) -> Fallible> { let key = init.key.clone(); @@ -81,7 +80,7 @@ impl StorageEvent { let storageArea = init.storageArea.r(); let bubbles = EventBubbles::from(init.parent.bubbles); let cancelable = EventCancelable::from(init.parent.cancelable); - let event = StorageEvent::new(global.as_global_scope(), Atom::from(type_), + let event = StorageEvent::new(global, Atom::from(type_), bubbles, cancelable, key, oldValue, newValue, url, storageArea); diff --git a/components/script/dom/testbinding.rs b/components/script/dom/testbinding.rs index eb3defbe6a5..3f4d3dbcaf1 100644 --- a/components/script/dom/testbinding.rs +++ b/components/script/dom/testbinding.rs @@ -21,7 +21,7 @@ use dom::bindings::codegen::UnionTypes::{HTMLElementOrUnsignedLongOrStringOrBool use dom::bindings::codegen::UnionTypes::{StringOrLongSequence, StringOrStringSequence, StringSequenceOrUnsignedLong}; use dom::bindings::codegen::UnionTypes::{StringOrUnsignedLong, StringOrBoolean, UnsignedLongOrBoolean}; use dom::bindings::error::{Error, Fallible}; -use dom::bindings::global::{GlobalRef, global_root_from_context}; +use dom::bindings::global::global_root_from_context; use dom::bindings::js::Root; use dom::bindings::mozmap::MozMap; use dom::bindings::num::Finite; @@ -63,18 +63,18 @@ impl TestBinding { global, TestBindingBinding::Wrap) } - pub fn Constructor(global: GlobalRef) -> Fallible> { - Ok(TestBinding::new(global.as_global_scope())) + pub fn Constructor(global: &GlobalScope) -> Fallible> { + Ok(TestBinding::new(global)) } #[allow(unused_variables)] - pub fn Constructor_(global: GlobalRef, nums: Vec) -> Fallible> { - Ok(TestBinding::new(global.as_global_scope())) + pub fn Constructor_(global: &GlobalScope, nums: Vec) -> Fallible> { + Ok(TestBinding::new(global)) } #[allow(unused_variables)] - pub fn Constructor__(global: GlobalRef, num: f64) -> Fallible> { - Ok(TestBinding::new(global.as_global_scope())) + pub fn Constructor__(global: &GlobalScope, num: f64) -> Fallible> { + Ok(TestBinding::new(global)) } } @@ -757,17 +757,17 @@ impl TestBindingMethods for TestBinding { } impl TestBinding { - pub fn BooleanAttributeStatic(_: GlobalRef) -> bool { false } - pub fn SetBooleanAttributeStatic(_: GlobalRef, _: bool) {} - pub fn ReceiveVoidStatic(_: GlobalRef) {} - pub fn PrefControlledStaticAttributeDisabled(_: GlobalRef) -> bool { false } - pub fn PrefControlledStaticAttributeEnabled(_: GlobalRef) -> bool { false } - pub fn PrefControlledStaticMethodDisabled(_: GlobalRef) {} - pub fn PrefControlledStaticMethodEnabled(_: GlobalRef) {} - pub fn FuncControlledStaticAttributeDisabled(_: GlobalRef) -> bool { false } - pub fn FuncControlledStaticAttributeEnabled(_: GlobalRef) -> bool { false } - pub fn FuncControlledStaticMethodDisabled(_: GlobalRef) {} - pub fn FuncControlledStaticMethodEnabled(_: GlobalRef) {} + pub fn BooleanAttributeStatic(_: &GlobalScope) -> bool { false } + pub fn SetBooleanAttributeStatic(_: &GlobalScope, _: bool) {} + pub fn ReceiveVoidStatic(_: &GlobalScope) {} + pub fn PrefControlledStaticAttributeDisabled(_: &GlobalScope) -> bool { false } + pub fn PrefControlledStaticAttributeEnabled(_: &GlobalScope) -> bool { false } + pub fn PrefControlledStaticMethodDisabled(_: &GlobalScope) {} + pub fn PrefControlledStaticMethodEnabled(_: &GlobalScope) {} + pub fn FuncControlledStaticAttributeDisabled(_: &GlobalScope) -> bool { false } + pub fn FuncControlledStaticAttributeEnabled(_: &GlobalScope) -> bool { false } + pub fn FuncControlledStaticMethodDisabled(_: &GlobalScope) {} + pub fn FuncControlledStaticMethodEnabled(_: &GlobalScope) {} } #[allow(unsafe_code)] diff --git a/components/script/dom/testbindingiterable.rs b/components/script/dom/testbindingiterable.rs index 6023051d8f6..10045705192 100644 --- a/components/script/dom/testbindingiterable.rs +++ b/components/script/dom/testbindingiterable.rs @@ -7,7 +7,6 @@ use dom::bindings::cell::DOMRefCell; use dom::bindings::codegen::Bindings::TestBindingIterableBinding::{self, TestBindingIterableMethods}; use dom::bindings::error::Fallible; -use dom::bindings::global::GlobalRef; use dom::bindings::js::Root; use dom::bindings::reflector::{Reflector, reflect_dom_object}; use dom::bindings::str::DOMString; @@ -27,8 +26,8 @@ impl TestBindingIterable { }, global, TestBindingIterableBinding::Wrap) } - pub fn Constructor(global: GlobalRef) -> Fallible> { - Ok(TestBindingIterable::new(global.as_global_scope())) + pub fn Constructor(global: &GlobalScope) -> Fallible> { + Ok(TestBindingIterable::new(global)) } } diff --git a/components/script/dom/testbindingpairiterable.rs b/components/script/dom/testbindingpairiterable.rs index 7e3ad537aa5..f536459c1e9 100644 --- a/components/script/dom/testbindingpairiterable.rs +++ b/components/script/dom/testbindingpairiterable.rs @@ -8,7 +8,6 @@ use dom::bindings::cell::DOMRefCell; use dom::bindings::codegen::Bindings::TestBindingPairIterableBinding; use dom::bindings::codegen::Bindings::TestBindingPairIterableBinding::TestBindingPairIterableMethods; use dom::bindings::error::Fallible; -use dom::bindings::global::GlobalRef; use dom::bindings::iterable::Iterable; use dom::bindings::js::Root; use dom::bindings::reflector::{Reflector, reflect_dom_object}; @@ -43,8 +42,8 @@ impl TestBindingPairIterable { }, global, TestBindingPairIterableBinding::TestBindingPairIterableWrap) } - pub fn Constructor(global: GlobalRef) -> Fallible> { - Ok(TestBindingPairIterable::new(global.as_global_scope())) + pub fn Constructor(global: &GlobalScope) -> Fallible> { + Ok(TestBindingPairIterable::new(global)) } } diff --git a/components/script/dom/text.rs b/components/script/dom/text.rs index fec47d6fc84..914d415dc0a 100644 --- a/components/script/dom/text.rs +++ b/components/script/dom/text.rs @@ -8,13 +8,13 @@ use dom::bindings::codegen::Bindings::NodeBinding::NodeMethods; use dom::bindings::codegen::Bindings::TextBinding::{self, TextMethods}; use dom::bindings::codegen::Bindings::WindowBinding::WindowMethods; use dom::bindings::error::{Error, Fallible}; -use dom::bindings::global::GlobalRef; use dom::bindings::inheritance::Castable; use dom::bindings::js::Root; use dom::bindings::js::RootedReference; use dom::bindings::str::DOMString; use dom::characterdata::CharacterData; use dom::document::Document; +use dom::globalscope::GlobalScope; use dom::node::Node; /// An HTML text node. @@ -35,8 +35,8 @@ impl Text { document, TextBinding::Wrap) } - pub fn Constructor(global: GlobalRef, text: DOMString) -> Fallible> { - let document = global.as_global_scope().as_window().Document(); + pub fn Constructor(global: &GlobalScope, text: DOMString) -> Fallible> { + let document = global.as_window().Document(); Ok(Text::new(text, document.r())) } } diff --git a/components/script/dom/textdecoder.rs b/components/script/dom/textdecoder.rs index 4d0e18e87f6..db18d9a5be4 100644 --- a/components/script/dom/textdecoder.rs +++ b/components/script/dom/textdecoder.rs @@ -6,7 +6,6 @@ use dom::bindings::codegen::Bindings::TextDecoderBinding; use dom::bindings::codegen::Bindings::TextDecoderBinding::TextDecoderMethods; use dom::bindings::conversions::array_buffer_view_data; use dom::bindings::error::{Error, Fallible}; -use dom::bindings::global::GlobalRef; use dom::bindings::js::Root; use dom::bindings::reflector::{Reflector, reflect_dom_object}; use dom::bindings::str::{DOMString, USVString}; @@ -44,7 +43,7 @@ impl TextDecoder { } /// https://encoding.spec.whatwg.org/#dom-textdecoder - pub fn Constructor(global: GlobalRef, + pub fn Constructor(global: &GlobalScope, label: DOMString, options: &TextDecoderBinding::TextDecoderOptions) -> Fallible> { @@ -61,7 +60,7 @@ impl TextDecoder { Some("replacement") => return TextDecoder::make_range_error(), _ => () }; - Ok(TextDecoder::new(global.as_global_scope(), encoding, options.fatal)) + Ok(TextDecoder::new(global, encoding, options.fatal)) } } diff --git a/components/script/dom/textencoder.rs b/components/script/dom/textencoder.rs index 5076c82190d..9c8ad647080 100644 --- a/components/script/dom/textencoder.rs +++ b/components/script/dom/textencoder.rs @@ -6,7 +6,6 @@ use core::nonzero::NonZero; use dom::bindings::codegen::Bindings::TextEncoderBinding; use dom::bindings::codegen::Bindings::TextEncoderBinding::TextEncoderMethods; use dom::bindings::error::Fallible; -use dom::bindings::global::GlobalRef; use dom::bindings::js::Root; use dom::bindings::reflector::{Reflector, reflect_dom_object}; use dom::bindings::str::{DOMString, USVString}; @@ -38,8 +37,8 @@ impl TextEncoder { } // https://encoding.spec.whatwg.org/#dom-textencoder - pub fn Constructor(global: GlobalRef) -> Fallible> { - Ok(TextEncoder::new(global.as_global_scope())) + pub fn Constructor(global: &GlobalScope) -> Fallible> { + Ok(TextEncoder::new(global)) } } diff --git a/components/script/dom/uievent.rs b/components/script/dom/uievent.rs index 698645f5a6c..99e25b80902 100644 --- a/components/script/dom/uievent.rs +++ b/components/script/dom/uievent.rs @@ -6,13 +6,13 @@ use dom::bindings::codegen::Bindings::EventBinding::EventMethods; use dom::bindings::codegen::Bindings::UIEventBinding; use dom::bindings::codegen::Bindings::UIEventBinding::UIEventMethods; use dom::bindings::error::Fallible; -use dom::bindings::global::GlobalRef; use dom::bindings::inheritance::Castable; use dom::bindings::js::{JS, MutNullableHeap, RootedReference}; use dom::bindings::js::Root; use dom::bindings::reflector::reflect_dom_object; use dom::bindings::str::DOMString; use dom::event::{Event, EventBubbles, EventCancelable}; +use dom::globalscope::GlobalScope; use dom::window::Window; use std::cell::Cell; use std::default::Default; @@ -52,12 +52,12 @@ impl UIEvent { ev } - pub fn Constructor(global: GlobalRef, + pub fn Constructor(global: &GlobalScope, type_: DOMString, init: &UIEventBinding::UIEventInit) -> Fallible> { let bubbles = EventBubbles::from(init.parent.bubbles); let cancelable = EventCancelable::from(init.parent.cancelable); - let event = UIEvent::new(global.as_global_scope().as_window(), + let event = UIEvent::new(global.as_window(), type_, bubbles, cancelable, init.view.r(), init.detail); diff --git a/components/script/dom/url.rs b/components/script/dom/url.rs index 8912ece7183..9ff223a74c6 100644 --- a/components/script/dom/url.rs +++ b/components/script/dom/url.rs @@ -6,7 +6,6 @@ use dom::bindings::cell::DOMRefCell; use dom::bindings::codegen::Bindings::BlobBinding::BlobMethods; use dom::bindings::codegen::Bindings::URLBinding::{self, URLMethods}; use dom::bindings::error::{Error, ErrorResult, Fallible}; -use dom::bindings::global::GlobalRef; use dom::bindings::js::{JS, MutNullableHeap, Root}; use dom::bindings::reflector::{Reflectable, Reflector, reflect_dom_object}; use dom::bindings::str::{DOMString, USVString}; @@ -62,7 +61,7 @@ impl URL { impl URL { // https://url.spec.whatwg.org/#constructors - pub fn Constructor(global: GlobalRef, url: USVString, + pub fn Constructor(global: &GlobalScope, url: USVString, base: Option) -> Fallible> { let parsed_base = match base { @@ -90,7 +89,7 @@ impl URL { }; // Step 5: Skip (see step 8 below). // Steps 6-7. - let result = URL::new(global.as_global_scope(), parsed_url); + let result = URL::new(global, parsed_url); // Step 8: Instead of construcing a new `URLSearchParams` object here, construct it // on-demand inside `URL::SearchParams`. // Step 9. @@ -98,7 +97,7 @@ impl URL { } // https://url.spec.whatwg.org/#dom-url-domaintoasciidomain - pub fn DomainToASCII(_: GlobalRef, origin: USVString) -> USVString { + pub fn DomainToASCII(_: &GlobalScope, origin: USVString) -> USVString { // Step 1. let ascii_domain = Host::parse(&origin.0); if let Ok(Host::Domain(string)) = ascii_domain { @@ -110,15 +109,15 @@ impl URL { } } - pub fn DomainToUnicode(_: GlobalRef, origin: USVString) -> USVString { + pub fn DomainToUnicode(_: &GlobalScope, origin: USVString) -> USVString { USVString(domain_to_unicode(&origin.0)) } // https://w3c.github.io/FileAPI/#dfn-createObjectURL - pub fn CreateObjectURL(global: GlobalRef, blob: &Blob) -> DOMString { + pub fn CreateObjectURL(global: &GlobalScope, blob: &Blob) -> DOMString { /// XXX: Second field is an unicode-serialized Origin, it is a temporary workaround /// and should not be trusted. See issue https://github.com/servo/servo/issues/11722 - let origin = get_blob_origin(&global.as_global_scope().get_url()); + let origin = get_blob_origin(&global.get_url()); if blob.IsClosed() { // Generate a dummy id @@ -132,8 +131,7 @@ impl URL { } // https://w3c.github.io/FileAPI/#dfn-revokeObjectURL - pub fn RevokeObjectURL(global: GlobalRef, url: DOMString) { - let global_scope = global.as_global_scope(); + pub fn RevokeObjectURL(global: &GlobalScope, url: DOMString) { /* If the url refers to a Blob that has a readability state of CLOSED OR if the value provided for the url argument is not a Blob URL, OR @@ -143,11 +141,11 @@ impl URL { NOTE: The first step is unnecessary, since closed blobs do not exist in the store */ - let origin = get_blob_origin(&global_scope.get_url()); + let origin = get_blob_origin(&global.get_url()); if let Ok(url) = Url::parse(&url) { if let Ok((id, _, _)) = parse_blob_url(&url) { - let resource_threads = global_scope.resource_threads(); + let resource_threads = global.resource_threads(); let (tx, rx) = ipc::channel().unwrap(); let msg = FileManagerThreadMsg::RevokeBlobURL(id, origin, tx); let _ = resource_threads.send(CoreResourceMsg::ToFileManager(msg)); diff --git a/components/script/dom/urlsearchparams.rs b/components/script/dom/urlsearchparams.rs index a7b1672852f..2718f278dc3 100644 --- a/components/script/dom/urlsearchparams.rs +++ b/components/script/dom/urlsearchparams.rs @@ -7,7 +7,6 @@ use dom::bindings::codegen::Bindings::URLSearchParamsBinding; use dom::bindings::codegen::Bindings::URLSearchParamsBinding::URLSearchParamsMethods; use dom::bindings::codegen::UnionTypes::USVStringOrURLSearchParams; use dom::bindings::error::Fallible; -use dom::bindings::global::GlobalRef; use dom::bindings::js::Root; use dom::bindings::reflector::{Reflector, reflect_dom_object}; use dom::bindings::str::{DOMString, USVString}; @@ -42,10 +41,10 @@ impl URLSearchParams { } // https://url.spec.whatwg.org/#dom-urlsearchparams-urlsearchparams - pub fn Constructor(global: GlobalRef, init: Option) -> + pub fn Constructor(global: &GlobalScope, init: Option) -> Fallible> { // Step 1. - let query = URLSearchParams::new(global.as_global_scope(), None); + let query = URLSearchParams::new(global, None); match init { Some(USVStringOrURLSearchParams::USVString(init)) => { // Step 2. diff --git a/components/script/dom/webglcontextevent.rs b/components/script/dom/webglcontextevent.rs index 01ab7e0eec1..079218ab3ae 100644 --- a/components/script/dom/webglcontextevent.rs +++ b/components/script/dom/webglcontextevent.rs @@ -7,7 +7,6 @@ use dom::bindings::codegen::Bindings::WebGLContextEventBinding; use dom::bindings::codegen::Bindings::WebGLContextEventBinding::WebGLContextEventInit; use dom::bindings::codegen::Bindings::WebGLContextEventBinding::WebGLContextEventMethods; use dom::bindings::error::Fallible; -use dom::bindings::global::GlobalRef; use dom::bindings::inheritance::Castable; use dom::bindings::js::Root; use dom::bindings::reflector::reflect_dom_object; @@ -71,7 +70,7 @@ impl WebGLContextEvent { event } - pub fn Constructor(global: GlobalRef, + pub fn Constructor(global: &GlobalScope, type_: DOMString, init: &WebGLContextEventInit) -> Fallible> { let status_message = match init.statusMessage.as_ref() { @@ -83,7 +82,7 @@ impl WebGLContextEvent { let cancelable = EventCancelable::from(init.parent.cancelable); - Ok(WebGLContextEvent::new(global.as_global_scope(), + Ok(WebGLContextEvent::new(global, Atom::from(type_), bubbles, cancelable, diff --git a/components/script/dom/websocket.rs b/components/script/dom/websocket.rs index 242f8124721..eb8b3cebf4f 100644 --- a/components/script/dom/websocket.rs +++ b/components/script/dom/websocket.rs @@ -10,7 +10,6 @@ use dom::bindings::codegen::Bindings::WebSocketBinding::{BinaryType, WebSocketMe use dom::bindings::codegen::UnionTypes::StringOrStringSequence; use dom::bindings::conversions::ToJSValConvertible; use dom::bindings::error::{Error, ErrorResult, Fallible}; -use dom::bindings::global::GlobalRef; use dom::bindings::inheritance::Castable; use dom::bindings::js::Root; use dom::bindings::refcounted::Trusted; @@ -196,7 +195,7 @@ impl WebSocket { global, WebSocketBinding::Wrap) } - pub fn Constructor(global: GlobalRef, + pub fn Constructor(global: &GlobalScope, url: DOMString, protocols: Option) -> Fallible> { @@ -239,11 +238,10 @@ impl WebSocket { } // Step 6: Origin. - let global_scope = global.as_global_scope(); - let origin = UrlHelper::Origin(&global_scope.get_url()).0; + let origin = UrlHelper::Origin(&global.get_url()).0; // Step 7. - let ws = WebSocket::new(global_scope, resource_url.clone()); + let ws = WebSocket::new(global, resource_url.clone()); let address = Trusted::new(ws.r()); let connect_data = WebSocketConnectData { @@ -265,12 +263,12 @@ impl WebSocket { action_receiver: resource_action_receiver, }; - let _ = global_scope.core_resource_thread().send(WebsocketConnect(connect, connect_data)); + let _ = global.core_resource_thread().send(WebsocketConnect(connect, connect_data)); *ws.sender.borrow_mut() = Some(dom_action_sender); let moved_address = address.clone(); - let sender = global_scope.networking_task_source(); + let sender = global.networking_task_source(); thread::spawn(move || { while let Ok(event) = dom_event_receiver.recv() { match event { diff --git a/components/script/dom/worker.rs b/components/script/dom/worker.rs index 035aa83bdf9..328471be089 100644 --- a/components/script/dom/worker.rs +++ b/components/script/dom/worker.rs @@ -9,7 +9,6 @@ use dom::bindings::codegen::Bindings::EventHandlerBinding::EventHandlerNonNull; use dom::bindings::codegen::Bindings::WorkerBinding; use dom::bindings::codegen::Bindings::WorkerBinding::WorkerMethods; use dom::bindings::error::{Error, ErrorResult, Fallible, ErrorInfo}; -use dom::bindings::global::GlobalRef; use dom::bindings::inheritance::Castable; use dom::bindings::js::Root; use dom::bindings::refcounted::Trusted; @@ -72,29 +71,28 @@ impl Worker { // https://html.spec.whatwg.org/multipage/#dom-worker #[allow(unsafe_code)] - pub fn Constructor(global: GlobalRef, script_url: DOMString) -> Fallible> { - let global_scope = global.as_global_scope(); + pub fn Constructor(global: &GlobalScope, script_url: DOMString) -> Fallible> { // Step 2-4. - let worker_url = match global_scope.api_base_url().join(&script_url) { + let worker_url = match global.api_base_url().join(&script_url) { Ok(url) => url, Err(_) => return Err(Error::Syntax), }; let (sender, receiver) = channel(); let closing = Arc::new(AtomicBool::new(false)); - let worker = Worker::new(global_scope, sender.clone(), closing.clone()); + let worker = Worker::new(global, sender.clone(), closing.clone()); let worker_ref = Trusted::new(worker.r()); let worker_load_origin = WorkerScriptLoadOrigin { referrer_url: None, referrer_policy: None, - pipeline_id: Some(global_scope.pipeline_id()), + pipeline_id: Some(global.pipeline_id()), }; let (devtools_sender, devtools_receiver) = ipc::channel().unwrap(); - let worker_id = global_scope.get_next_worker_id(); - if let Some(ref chan) = global_scope.devtools_chan() { - let pipeline_id = global_scope.pipeline_id(); + let worker_id = global.get_next_worker_id(); + if let Some(ref chan) = global.devtools_chan() { + let pipeline_id = global.pipeline_id(); let title = format!("Worker for {}", worker_url); let page_info = DevtoolsPageInfo { title: title, @@ -105,11 +103,11 @@ impl Worker { page_info)); } - let init = prepare_workerscope_init(global_scope, Some(devtools_sender)); + let init = prepare_workerscope_init(global, Some(devtools_sender)); DedicatedWorkerGlobalScope::run_worker_scope( init, worker_url, devtools_receiver, worker.runtime.clone(), worker_ref, - global_scope.script_chan(), sender, receiver, worker_load_origin, closing); + global.script_chan(), sender, receiver, worker_load_origin, closing); Ok(worker) } diff --git a/components/script/dom/xmlhttprequest.rs b/components/script/dom/xmlhttprequest.rs index 5e7f156931e..a5b09193b7f 100644 --- a/components/script/dom/xmlhttprequest.rs +++ b/components/script/dom/xmlhttprequest.rs @@ -206,8 +206,8 @@ impl XMLHttpRequest { } // https://xhr.spec.whatwg.org/#constructors - pub fn Constructor(global: GlobalRef) -> Fallible> { - Ok(XMLHttpRequest::new(global.as_global_scope())) + pub fn Constructor(global: &GlobalScope) -> Fallible> { + Ok(XMLHttpRequest::new(global)) } fn sync_in_window(&self) -> bool { diff --git a/components/script/fetch.rs b/components/script/fetch.rs index b23f8f8f8dd..f7398ca1d30 100644 --- a/components/script/fetch.rs +++ b/components/script/fetch.rs @@ -75,7 +75,7 @@ pub fn Fetch(global: GlobalRef, input: RequestOrUSVString, init: &RequestInit) - let response = Response::new(global_scope); // Step 2 - let request = match Request::Constructor(global, input, init) { + let request = match Request::Constructor(global_scope, input, init) { Err(e) => { promise.reject_error(promise.global().r().get_cx(), e); return promise; From 9c04eb60bdcb31221d93f8d6b7ebcb3728836625 Mon Sep 17 00:00:00 2001 From: Anthony Ramine Date: Tue, 4 Oct 2016 01:15:43 +0200 Subject: [PATCH 43/66] Move JS evaluation functions to GlobalScope --- components/script/devtools.rs | 2 +- components/script/dom/bindings/global.rs | 61 ++-------------------- components/script/dom/globalscope.rs | 58 ++++++++++++++++++-- components/script/dom/htmlscriptelement.rs | 4 +- components/script/script_thread.rs | 2 +- components/script/timers.rs | 6 +-- components/script/webdriver_handlers.rs | 5 +- 7 files changed, 67 insertions(+), 71 deletions(-) diff --git a/components/script/devtools.rs b/components/script/devtools.rs index eb4a31d794c..d12e24f5152 100644 --- a/components/script/devtools.rs +++ b/components/script/devtools.rs @@ -41,7 +41,7 @@ pub fn handle_evaluate_js(global: &GlobalRef, eval: String, reply: IpcSender GlobalRef<'a> { } } - /// Evaluate JS code on this global. - pub fn evaluate_js_on_global_with_result( - &self, code: &str, rval: MutableHandleValue) { - self.evaluate_script_on_global_with_result(code, "", rval) - } - - /// Evaluate a JS script on this global. - #[allow(unsafe_code)] - pub fn evaluate_script_on_global_with_result( - &self, code: &str, filename: &str, rval: MutableHandleValue) { - let metadata = time::TimerMetadata { - url: if filename.is_empty() { - self.as_global_scope().get_url().as_str().into() - } else { - filename.into() - }, - iframe: time::TimerMetadataFrameType::RootWindow, - incremental: time::TimerMetadataReflowType::FirstReflow, - }; - time::profile( - time::ProfilerCategory::ScriptEvaluate, - Some(metadata), - self.as_global_scope().time_profiler_chan().clone(), - || { - let cx = self.get_cx(); - let globalhandle = self.reflector().get_jsobject(); - let code: Vec = code.encode_utf16().collect(); - let filename = CString::new(filename).unwrap(); - - let _ac = JSAutoCompartment::new(cx, globalhandle.get()); - let options = CompileOptionsWrapper::new(cx, filename.as_ptr(), 1); - unsafe { - if !Evaluate2(cx, options.ptr, code.as_ptr(), - code.len() as libc::size_t, - rval) { - debug!("error evaluating JS string"); - report_pending_exception(cx, true); - } - } - - if let Some(error) = maybe_take_panic_result() { - panic::resume_unwind(error); - } - } - ) - } - /// Schedule the given `callback` to be invoked after at least `duration` milliseconds have /// passed. pub fn schedule_callback(&self, diff --git a/components/script/dom/globalscope.rs b/components/script/dom/globalscope.rs index 29c918d28f0..64f932c31f9 100644 --- a/components/script/dom/globalscope.rs +++ b/components/script/dom/globalscope.rs @@ -5,7 +5,7 @@ use devtools_traits::{ScriptToDevtoolsControlMsg, WorkerId}; use dom::bindings::cell::DOMRefCell; use dom::bindings::codegen::Bindings::WindowBinding::WindowMethods; -use dom::bindings::error::ErrorInfo; +use dom::bindings::error::{ErrorInfo, report_pending_exception}; use dom::bindings::inheritance::Castable; use dom::bindings::js::{JS, MutNullableHeap, Root}; use dom::bindings::reflector::Reflectable; @@ -19,16 +19,21 @@ use dom::eventtarget::EventTarget; use dom::window::Window; use dom::workerglobalscope::WorkerGlobalScope; use ipc_channel::ipc::IpcSender; -use js::jsapi::{HandleValue, JS_GetContext, JS_GetObjectRuntime, JSContext}; +use js::jsapi::{HandleValue, Evaluate2, JS_GetContext, JS_GetObjectRuntime}; +use js::jsapi::{JSAutoCompartment, JSContext, MutableHandleValue}; +use js::rust::CompileOptionsWrapper; +use libc; use msg::constellation_msg::PipelineId; use net_traits::{CoreResourceThread, ResourceThreads, IpcSend}; use profile_traits::{mem, time}; -use script_runtime::ScriptChan; +use script_runtime::{ScriptChan, maybe_take_panic_result}; use script_thread::MainThreadScriptChan; use script_traits::{ScriptMsg as ConstellationMsg, TimerEventRequest}; use std::cell::Cell; use std::collections::HashMap; use std::collections::hash_map::Entry; +use std::ffi::CString; +use std::panic; use time::{Timespec, get_time}; use url::Url; @@ -282,6 +287,53 @@ impl GlobalScope { } unreachable!(); } + + /// Evaluate JS code on this global scope. + pub fn evaluate_js_on_global_with_result( + &self, code: &str, rval: MutableHandleValue) { + self.evaluate_script_on_global_with_result(code, "", rval) + } + + /// Evaluate a JS script on this global scope. + #[allow(unsafe_code)] + pub fn evaluate_script_on_global_with_result( + &self, code: &str, filename: &str, rval: MutableHandleValue) { + let metadata = time::TimerMetadata { + url: if filename.is_empty() { + self.get_url().as_str().into() + } else { + filename.into() + }, + iframe: time::TimerMetadataFrameType::RootWindow, + incremental: time::TimerMetadataReflowType::FirstReflow, + }; + time::profile( + time::ProfilerCategory::ScriptEvaluate, + Some(metadata), + self.time_profiler_chan().clone(), + || { + let cx = self.get_cx(); + let globalhandle = self.reflector().get_jsobject(); + let code: Vec = code.encode_utf16().collect(); + let filename = CString::new(filename).unwrap(); + + let _ac = JSAutoCompartment::new(cx, globalhandle.get()); + let options = CompileOptionsWrapper::new(cx, filename.as_ptr(), 1); + unsafe { + if !Evaluate2(cx, options.ptr, code.as_ptr(), + code.len() as libc::size_t, + rval) { + debug!("error evaluating JS string"); + report_pending_exception(cx, true); + } + } + + if let Some(error) = maybe_take_panic_result() { + panic::resume_unwind(error); + } + } + ) + } } fn timestamp_in_ms(time: Timespec) -> u64 { diff --git a/components/script/dom/htmlscriptelement.rs b/components/script/dom/htmlscriptelement.rs index 2132d41edf7..1bee0c9c32f 100644 --- a/components/script/dom/htmlscriptelement.rs +++ b/components/script/dom/htmlscriptelement.rs @@ -10,7 +10,6 @@ use dom::bindings::codegen::Bindings::DocumentBinding::DocumentMethods; use dom::bindings::codegen::Bindings::HTMLScriptElementBinding; use dom::bindings::codegen::Bindings::HTMLScriptElementBinding::HTMLScriptElementMethods; use dom::bindings::codegen::Bindings::NodeBinding::NodeMethods; -use dom::bindings::global::GlobalRef; use dom::bindings::inheritance::Castable; use dom::bindings::js::{JS, Root}; use dom::bindings::js::RootedReference; @@ -21,6 +20,7 @@ use dom::document::Document; use dom::element::{AttributeMutation, Element, ElementCreator}; use dom::event::{Event, EventBubbles, EventCancelable}; use dom::eventdispatcher::EventStatus; +use dom::globalscope::GlobalScope; use dom::htmlelement::HTMLElement; use dom::node::{ChildrenMutation, CloneChildrenFlag, Node}; use dom::node::{document_from_node, window_from_node}; @@ -504,7 +504,7 @@ impl HTMLScriptElement { // Step 5.a.2. let window = window_from_node(self); rooted!(in(window.get_cx()) let mut rval = UndefinedValue()); - GlobalRef::Window(&window).evaluate_script_on_global_with_result( + window.upcast::().evaluate_script_on_global_with_result( &script.text, script.url.as_str(), rval.handle_mut()); // Step 6. diff --git a/components/script/script_thread.rs b/components/script/script_thread.rs index 582ebfdb153..0669808c7ac 100644 --- a/components/script/script_thread.rs +++ b/components/script/script_thread.rs @@ -1767,7 +1767,7 @@ impl ScriptThread { unsafe { let _ac = JSAutoCompartment::new(self.get_cx(), window.reflector().get_jsobject().get()); rooted!(in(self.get_cx()) let mut jsval = UndefinedValue()); - GlobalRef::Window(&window).evaluate_js_on_global_with_result( + window.upcast::().evaluate_js_on_global_with_result( &script_source, jsval.handle_mut()); let strval = DOMString::from_jsval(self.get_cx(), jsval.handle(), diff --git a/components/script/timers.rs b/components/script/timers.rs index 601755c6fc4..7b326f6b164 100644 --- a/components/script/timers.rs +++ b/components/script/timers.rs @@ -489,11 +489,11 @@ impl JsTimerTask { // step 4.2 match *&self.callback { InternalTimerCallback::StringTimerCallback(ref code_str) => { - let global = this.global(); - let cx = global.r().get_cx(); + let global = this.global_scope(); + let cx = global.get_cx(); rooted!(in(cx) let mut rval = UndefinedValue()); - global.r().evaluate_js_on_global_with_result( + global.evaluate_js_on_global_with_result( code_str, rval.handle_mut()); }, InternalTimerCallback::FunctionTimerCallback(ref function, ref arguments) => { diff --git a/components/script/webdriver_handlers.rs b/components/script/webdriver_handlers.rs index 95e300b1527..bcb0186d8e6 100644 --- a/components/script/webdriver_handlers.rs +++ b/components/script/webdriver_handlers.rs @@ -13,7 +13,6 @@ use dom::bindings::codegen::Bindings::NodeBinding::NodeMethods; use dom::bindings::codegen::Bindings::NodeListBinding::NodeListMethods; use dom::bindings::codegen::Bindings::WindowBinding::WindowMethods; use dom::bindings::conversions::{ConversionResult, FromJSValConvertible, StringificationBehavior}; -use dom::bindings::global::GlobalRef; use dom::bindings::inheritance::Castable; use dom::bindings::js::Root; use dom::bindings::str::DOMString; @@ -93,7 +92,7 @@ pub fn handle_execute_script(context: &BrowsingContext, let result = unsafe { let cx = window.get_cx(); rooted!(in(cx) let mut rval = UndefinedValue()); - GlobalRef::Window(&window).evaluate_js_on_global_with_result( + window.upcast::().evaluate_js_on_global_with_result( &eval, rval.handle_mut()); jsval_to_webdriver(cx, rval.handle()) }; @@ -113,7 +112,7 @@ pub fn handle_execute_async_script(context: &BrowsingContext, let cx = window.get_cx(); window.set_webdriver_script_chan(Some(reply)); rooted!(in(cx) let mut rval = UndefinedValue()); - GlobalRef::Window(&window).evaluate_js_on_global_with_result( + window.upcast::().evaluate_js_on_global_with_result( &eval, rval.handle_mut()); } From 5d8979237b4bd44ab336f1c54ce728a33218da38 Mon Sep 17 00:00:00 2001 From: Anthony Ramine Date: Tue, 4 Oct 2016 01:28:08 +0200 Subject: [PATCH 44/66] Make devtools::handle_evaluate_js take a &GlobalScope --- components/script/devtools.rs | 5 ++--- components/script/dom/dedicatedworkerglobalscope.rs | 3 +-- components/script/dom/serviceworkerglobalscope.rs | 3 +-- components/script/script_thread.rs | 3 +-- 4 files changed, 5 insertions(+), 9 deletions(-) diff --git a/components/script/devtools.rs b/components/script/devtools.rs index d12e24f5152..dcaee91c843 100644 --- a/components/script/devtools.rs +++ b/components/script/devtools.rs @@ -13,7 +13,6 @@ use dom::bindings::codegen::Bindings::ElementBinding::ElementMethods; use dom::bindings::codegen::Bindings::LocationBinding::LocationMethods; use dom::bindings::codegen::Bindings::WindowBinding::WindowMethods; use dom::bindings::conversions::{ConversionResult, FromJSValConvertible, jsstring_to_str}; -use dom::bindings::global::GlobalRef; use dom::bindings::inheritance::Castable; use dom::bindings::js::Root; use dom::bindings::reflector::Reflectable; @@ -34,14 +33,14 @@ use uuid::Uuid; #[allow(unsafe_code)] -pub fn handle_evaluate_js(global: &GlobalRef, eval: String, reply: IpcSender) { +pub fn handle_evaluate_js(global: &GlobalScope, eval: String, reply: IpcSender) { // global.get_cx() returns a valid `JSContext` pointer, so this is safe. let result = unsafe { let cx = global.get_cx(); let globalhandle = global.reflector().get_jsobject(); let _ac = JSAutoCompartment::new(cx, globalhandle.get()); rooted!(in(cx) let mut rval = UndefinedValue()); - global.as_global_scope().evaluate_js_on_global_with_result(&eval, rval.handle_mut()); + global.evaluate_js_on_global_with_result(&eval, rval.handle_mut()); if rval.is_undefined() { EvaluateJSReply::VoidValue diff --git a/components/script/dom/dedicatedworkerglobalscope.rs b/components/script/dom/dedicatedworkerglobalscope.rs index bc4a34eeb1b..f362f4b2f7a 100644 --- a/components/script/dom/dedicatedworkerglobalscope.rs +++ b/components/script/dom/dedicatedworkerglobalscope.rs @@ -301,10 +301,9 @@ impl DedicatedWorkerGlobalScope { fn handle_event(&self, event: MixedMessage) { match event { MixedMessage::FromDevtools(msg) => { - let global_ref = GlobalRef::Worker(self.upcast()); match msg { DevtoolScriptControlMsg::EvaluateJS(_pipe_id, string, sender) => - devtools::handle_evaluate_js(&global_ref, string, sender), + devtools::handle_evaluate_js(self.upcast(), string, sender), DevtoolScriptControlMsg::GetCachedMessages(pipe_id, message_types, sender) => devtools::handle_get_cached_messages(pipe_id, message_types, sender), DevtoolScriptControlMsg::WantsLiveNotifications(_pipe_id, bool_val) => diff --git a/components/script/dom/serviceworkerglobalscope.rs b/components/script/dom/serviceworkerglobalscope.rs index 52cfbff5bff..62037763a6e 100644 --- a/components/script/dom/serviceworkerglobalscope.rs +++ b/components/script/dom/serviceworkerglobalscope.rs @@ -206,10 +206,9 @@ impl ServiceWorkerGlobalScope { fn handle_event(&self, event: MixedMessage) -> bool { match event { MixedMessage::FromDevtools(msg) => { - let global_ref = GlobalRef::Worker(self.upcast()); match msg { DevtoolScriptControlMsg::EvaluateJS(_pipe_id, string, sender) => - devtools::handle_evaluate_js(&global_ref, string, sender), + devtools::handle_evaluate_js(self.upcast(), string, sender), DevtoolScriptControlMsg::GetCachedMessages(pipe_id, message_types, sender) => devtools::handle_get_cached_messages(pipe_id, message_types, sender), DevtoolScriptControlMsg::WantsLiveNotifications(_pipe_id, bool_val) => diff --git a/components/script/script_thread.rs b/components/script/script_thread.rs index 0669808c7ac..cbfcbd0cca4 100644 --- a/components/script/script_thread.rs +++ b/components/script/script_thread.rs @@ -985,8 +985,7 @@ impl ScriptThread { Some(browsing_context) => browsing_context.active_window(), None => return warn!("Message sent to closed pipeline {}.", id), }; - let global_ref = GlobalRef::Window(window.r()); - devtools::handle_evaluate_js(&global_ref, s, reply) + devtools::handle_evaluate_js(window.upcast(), s, reply) }, DevtoolScriptControlMsg::GetRootNode(id, reply) => devtools::handle_get_root_node(&context, id, reply), From 991801488c97fd74d814c6591064379400e06d1e Mon Sep 17 00:00:00 2001 From: Anthony Ramine Date: Tue, 4 Oct 2016 13:06:37 +0200 Subject: [PATCH 45/66] Move timers to GlobalScope --- components/script/dom/bindings/global.rs | 22 ------ components/script/dom/globalscope.rs | 68 ++++++++++++++++- components/script/dom/testbinding.rs | 6 +- components/script/dom/window.rs | 85 ++++++++-------------- components/script/dom/workerglobalscope.rs | 75 ++++++++----------- components/script/dom/xmlhttprequest.rs | 7 +- components/script/script_thread.rs | 8 +- components/script/timers.rs | 18 ++--- 8 files changed, 144 insertions(+), 145 deletions(-) diff --git a/components/script/dom/bindings/global.rs b/components/script/dom/bindings/global.rs index 5904488c37f..3c2d0533ac7 100644 --- a/components/script/dom/bindings/global.rs +++ b/components/script/dom/bindings/global.rs @@ -20,9 +20,7 @@ use js::jsapi::{CurrentGlobalOrNull, GetGlobalForObjectCrossCompartment}; use js::jsapi::{JSContext, JSObject, JS_GetClass}; use script_runtime::{CommonScriptMsg, EnqueuedPromiseCallback, ScriptChan, ScriptPort}; use script_thread::{RunnableWrapper, ScriptThread}; -use script_traits::MsDuration; use task_source::file_reading::FileReadingTaskSource; -use timers::{OneshotTimerCallback, OneshotTimerHandle}; /// A freely-copyable reference to a rooted global object. #[derive(Copy, Clone)] @@ -87,26 +85,6 @@ impl<'a> GlobalRef<'a> { } } - /// Schedule the given `callback` to be invoked after at least `duration` milliseconds have - /// passed. - pub fn schedule_callback(&self, - callback: OneshotTimerCallback, - duration: MsDuration) - -> OneshotTimerHandle { - match *self { - GlobalRef::Window(window) => window.schedule_callback(callback, duration), - GlobalRef::Worker(worker) => worker.schedule_callback(callback, duration), - } - } - - /// Unschedule a previously-scheduled callback. - pub fn unschedule_callback(&self, handle: OneshotTimerHandle) { - match *self { - GlobalRef::Window(window) => window.unschedule_callback(handle), - GlobalRef::Worker(worker) => worker.unschedule_callback(handle), - } - } - /// Returns a wrapper for runnables to ensure they are cancelled if the global /// is being destroyed. pub fn get_runnable_wrapper(&self) -> RunnableWrapper { diff --git a/components/script/dom/globalscope.rs b/components/script/dom/globalscope.rs index 64f932c31f9..96528a80164 100644 --- a/components/script/dom/globalscope.rs +++ b/components/script/dom/globalscope.rs @@ -28,13 +28,16 @@ use net_traits::{CoreResourceThread, ResourceThreads, IpcSend}; use profile_traits::{mem, time}; use script_runtime::{ScriptChan, maybe_take_panic_result}; use script_thread::MainThreadScriptChan; -use script_traits::{ScriptMsg as ConstellationMsg, TimerEventRequest}; +use script_traits::{MsDuration, ScriptMsg as ConstellationMsg, TimerEvent}; +use script_traits::{TimerEventId, TimerEventRequest, TimerSource}; use std::cell::Cell; use std::collections::HashMap; use std::collections::hash_map::Entry; use std::ffi::CString; use std::panic; use time::{Timespec, get_time}; +use timers::{IsInterval, OneshotTimerCallback, OneshotTimerHandle}; +use timers::{OneshotTimers, TimerCallback}; use url::Url; #[dom_struct] @@ -78,6 +81,8 @@ pub struct GlobalScope { /// Associated resource threads for use by DOM objects like XMLHttpRequest, /// including resource_thread, filemanager_thread and storage_thread resource_threads: ResourceThreads, + + timers: OneshotTimers, } impl GlobalScope { @@ -88,7 +93,8 @@ impl GlobalScope { time_profiler_chan: time::ProfilerChan, constellation_chan: IpcSender, scheduler_chan: IpcSender, - resource_threads: ResourceThreads) + resource_threads: ResourceThreads, + timer_event_chan: IpcSender) -> Self { GlobalScope { eventtarget: EventTarget::new_inherited(), @@ -101,9 +107,10 @@ impl GlobalScope { mem_profiler_chan: mem_profiler_chan, time_profiler_chan: time_profiler_chan, constellation_chan: constellation_chan, - scheduler_chan: scheduler_chan, + scheduler_chan: scheduler_chan.clone(), in_error_reporting_mode: Default::default(), resource_threads: resource_threads, + timers: OneshotTimers::new(timer_event_chan, scheduler_chan), } } @@ -334,6 +341,61 @@ impl GlobalScope { } ) } + + pub fn schedule_callback( + &self, callback: OneshotTimerCallback, duration: MsDuration) + -> OneshotTimerHandle { + self.timers.schedule_callback(callback, duration, self.timer_source()) + } + + pub fn unschedule_callback(&self, handle: OneshotTimerHandle) { + self.timers.unschedule_callback(handle); + } + + pub fn set_timeout_or_interval( + &self, + callback: TimerCallback, + arguments: Vec, + timeout: i32, + is_interval: IsInterval) + -> i32 { + self.timers.set_timeout_or_interval( + self, callback, arguments, timeout, is_interval, self.timer_source()) + } + + pub fn clear_timeout_or_interval(&self, handle: i32) { + self.timers.clear_timeout_or_interval(self, handle) + } + + pub fn fire_timer(&self, handle: TimerEventId) { + self.timers.fire_timer(handle, self) + } + + pub fn resume(&self) { + self.timers.resume() + } + + pub fn suspend(&self) { + self.timers.suspend() + } + + pub fn slow_down_timers(&self) { + self.timers.slow_down() + } + + pub fn speed_up_timers(&self) { + self.timers.speed_up() + } + + fn timer_source(&self) -> TimerSource { + if self.is::() { + return TimerSource::FromWindow(self.pipeline_id()); + } + if self.is::() { + return TimerSource::FromWorker; + } + unreachable!(); + } } fn timestamp_in_ms(time: Timespec) -> u64 { diff --git a/components/script/dom/testbinding.rs b/components/script/dom/testbinding.rs index 3f4d3dbcaf1..bc7c5643533 100644 --- a/components/script/dom/testbinding.rs +++ b/components/script/dom/testbinding.rs @@ -683,8 +683,10 @@ impl TestBindingMethods for TestBinding { promise: TrustedPromise::new(promise), value: value, }; - let _ = self.global().r().schedule_callback(OneshotTimerCallback::TestBindingCallback(cb), - MsDuration::new(delay)); + let _ = self.global_scope() + .schedule_callback( + OneshotTimerCallback::TestBindingCallback(cb), + MsDuration::new(delay)); } #[allow(unrooted_must_root)] diff --git a/components/script/dom/window.rs b/components/script/dom/window.rs index 0d55cb98f91..4365ba44999 100644 --- a/components/script/dom/window.rs +++ b/components/script/dom/window.rs @@ -71,8 +71,8 @@ use script_runtime::{CommonScriptMsg, ScriptChan, ScriptPort, ScriptThreadEventC use script_thread::{MainThreadScriptChan, MainThreadScriptMsg, Runnable, RunnableWrapper}; use script_thread::SendableMainThreadScriptChan; use script_traits::{ConstellationControlMsg, MozBrowserEvent, UntrustedNodeAddress}; -use script_traits::{DocumentState, MsDuration, TimerEvent, TimerEventId}; -use script_traits::{ScriptMsg as ConstellationMsg, TimerEventRequest, TimerSource, WindowSizeData}; +use script_traits::{DocumentState, TimerEvent, TimerEventId}; +use script_traits::{ScriptMsg as ConstellationMsg, TimerEventRequest, WindowSizeData}; use script_traits::webdriver_msg::{WebDriverJSError, WebDriverJSResult}; use std::ascii::AsciiExt; use std::borrow::ToOwned; @@ -97,7 +97,7 @@ use task_source::history_traversal::HistoryTraversalTaskSource; use task_source::networking::NetworkingTaskSource; use task_source::user_interaction::UserInteractionTaskSource; use time; -use timers::{IsInterval, OneshotTimerCallback, OneshotTimerHandle, OneshotTimers, TimerCallback}; +use timers::{IsInterval, TimerCallback}; #[cfg(any(target_os = "macos", target_os = "linux", target_os = "windows"))] use tinyfiledialogs::{self, MessageBoxIcon}; use url::Url; @@ -168,7 +168,6 @@ pub struct Window { session_storage: MutNullableHeap>, local_storage: MutNullableHeap>, status: DOMRefCell, - timers: OneshotTimers, /// For sending timeline markers. Will be ignored if /// no devtools server @@ -475,47 +474,43 @@ impl WindowMethods for Window { // https://html.spec.whatwg.org/multipage/#dom-windowtimers-settimeout fn SetTimeout(&self, _cx: *mut JSContext, callback: Rc, timeout: i32, args: Vec) -> i32 { - self.timers.set_timeout_or_interval(GlobalRef::Window(self), - TimerCallback::FunctionTimerCallback(callback), - args, - timeout, - IsInterval::NonInterval, - TimerSource::FromWindow(self.upcast::().pipeline_id())) + self.upcast::().set_timeout_or_interval( + TimerCallback::FunctionTimerCallback(callback), + args, + timeout, + IsInterval::NonInterval) } // https://html.spec.whatwg.org/multipage/#dom-windowtimers-settimeout fn SetTimeout_(&self, _cx: *mut JSContext, callback: DOMString, timeout: i32, args: Vec) -> i32 { - self.timers.set_timeout_or_interval(GlobalRef::Window(self), - TimerCallback::StringTimerCallback(callback), - args, - timeout, - IsInterval::NonInterval, - TimerSource::FromWindow(self.upcast::().pipeline_id())) + self.upcast::().set_timeout_or_interval( + TimerCallback::StringTimerCallback(callback), + args, + timeout, + IsInterval::NonInterval) } // https://html.spec.whatwg.org/multipage/#dom-windowtimers-cleartimeout fn ClearTimeout(&self, handle: i32) { - self.timers.clear_timeout_or_interval(GlobalRef::Window(self), handle); + self.upcast::().clear_timeout_or_interval(handle); } // https://html.spec.whatwg.org/multipage/#dom-windowtimers-setinterval fn SetInterval(&self, _cx: *mut JSContext, callback: Rc, timeout: i32, args: Vec) -> i32 { - self.timers.set_timeout_or_interval(GlobalRef::Window(self), - TimerCallback::FunctionTimerCallback(callback), - args, - timeout, - IsInterval::Interval, - TimerSource::FromWindow(self.upcast::().pipeline_id())) + self.upcast::().set_timeout_or_interval( + TimerCallback::FunctionTimerCallback(callback), + args, + timeout, + IsInterval::Interval) } // https://html.spec.whatwg.org/multipage/#dom-windowtimers-setinterval fn SetInterval_(&self, _cx: *mut JSContext, callback: DOMString, timeout: i32, args: Vec) -> i32 { - self.timers.set_timeout_or_interval(GlobalRef::Window(self), - TimerCallback::StringTimerCallback(callback), - args, - timeout, - IsInterval::Interval, - TimerSource::FromWindow(self.upcast::().pipeline_id())) + self.upcast::().set_timeout_or_interval( + TimerCallback::StringTimerCallback(callback), + args, + timeout, + IsInterval::Interval) } // https://html.spec.whatwg.org/multipage/#dom-windowtimers-clearinterval @@ -1341,7 +1336,7 @@ impl Window { } pub fn handle_fire_timer(&self, timer_id: TimerEventId) { - self.timers.fire_timer(timer_id, self); + self.upcast::().fire_timer(timer_id); self.reflow(ReflowGoal::ForDisplay, ReflowQueryType::NoQuery, ReflowReason::Timer); @@ -1371,16 +1366,6 @@ impl Window { &self.layout_chan } - pub fn schedule_callback(&self, callback: OneshotTimerCallback, duration: MsDuration) -> OneshotTimerHandle { - self.timers.schedule_callback(callback, - duration, - TimerSource::FromWindow(self.upcast::().pipeline_id())) - } - - pub fn unschedule_callback(&self, handle: OneshotTimerHandle) { - self.timers.unschedule_callback(handle); - } - pub fn windowproxy_handler(&self) -> WindowProxyHandler { WindowProxyHandler(self.dom_static.windowproxy_handler.0) } @@ -1436,25 +1421,13 @@ impl Window { } pub fn thaw(&self) { - self.timers.resume(); + self.upcast::().resume(); // Push the document title to the compositor since we are // activating this document due to a navigation. self.Document().title_changed(); } - pub fn freeze(&self) { - self.timers.suspend(); - } - - pub fn slow_down_timers(&self) { - self.timers.slow_down(); - } - - pub fn speed_up_timers(&self) { - self.timers.speed_up(); - } - pub fn need_emit_timeline_marker(&self, timeline_type: TimelineMarkerType) -> bool { let markers = self.devtools_markers.borrow(); markers.contains(&timeline_type) @@ -1579,8 +1552,9 @@ impl Window { mem_profiler_chan, time_profiler_chan, constellation_chan, - scheduler_chan.clone(), - resource_threads), + scheduler_chan, + resource_threads, + timer_event_chan), script_chan: script_chan, dom_manipulation_task_source: dom_task_source, user_interaction_task_source: user_task_source, @@ -1599,7 +1573,6 @@ impl Window { session_storage: Default::default(), local_storage: Default::default(), status: DOMRefCell::new(DOMString::new()), - timers: OneshotTimers::new(timer_event_chan, scheduler_chan), parent_info: parent_info, dom_static: GlobalStaticData::new(), js_runtime: DOMRefCell::new(Some(runtime.clone())), diff --git a/components/script/dom/workerglobalscope.rs b/components/script/dom/workerglobalscope.rs index 93361d8e620..49b1d4e3257 100644 --- a/components/script/dom/workerglobalscope.rs +++ b/components/script/dom/workerglobalscope.rs @@ -34,7 +34,7 @@ use net_traits::{LoadContext, load_whole_resource}; use script_runtime::{CommonScriptMsg, ScriptChan, ScriptPort, maybe_take_panic_result}; use script_runtime::{ScriptThreadEventCategory, PromiseJobQueue, EnqueuedPromiseCallback}; use script_thread::{Runnable, RunnableWrapper}; -use script_traits::{MsDuration, TimerEvent, TimerEventId, TimerSource}; +use script_traits::{TimerEvent, TimerEventId}; use script_traits::WorkerGlobalScopeInit; use std::default::Default; use std::panic; @@ -43,7 +43,7 @@ use std::sync::Arc; use std::sync::atomic::{AtomicBool, Ordering}; use std::sync::mpsc::Receiver; use task_source::file_reading::FileReadingTaskSource; -use timers::{IsInterval, OneshotTimerCallback, OneshotTimerHandle, OneshotTimers, TimerCallback}; +use timers::{IsInterval, TimerCallback}; use url::Url; pub fn prepare_workerscope_init(global: &GlobalScope, @@ -76,7 +76,6 @@ pub struct WorkerGlobalScope { runtime: Runtime, location: MutNullableHeap>, navigator: MutNullableHeap>, - timers: OneshotTimers, #[ignore_heap_size_of = "Defined in ipc-channel"] /// Optional `IpcSender` for sending the `DevtoolScriptControlMsg` @@ -107,15 +106,15 @@ impl WorkerGlobalScope { init.mem_profiler_chan, init.time_profiler_chan, init.constellation_chan, - init.scheduler_chan.clone(), - init.resource_threads), + init.scheduler_chan, + init.resource_threads, + timer_event_chan), worker_id: init.worker_id, worker_url: worker_url, closing: closing, runtime: runtime, location: Default::default(), navigator: Default::default(), - timers: OneshotTimers::new(timer_event_chan, init.scheduler_chan), from_devtools_sender: init.from_devtools_sender, from_devtools_receiver: from_devtools_receiver, promise_job_queue: PromiseJobQueue::new(), @@ -130,16 +129,6 @@ impl WorkerGlobalScope { &self.from_devtools_receiver } - pub fn schedule_callback(&self, callback: OneshotTimerCallback, duration: MsDuration) -> OneshotTimerHandle { - self.timers.schedule_callback(callback, - duration, - TimerSource::FromWorker) - } - - pub fn unschedule_callback(&self, handle: OneshotTimerHandle) { - self.timers.unschedule_callback(handle); - } - pub fn runtime(&self) -> *mut JSRuntime { self.runtime.rt() } @@ -281,49 +270,45 @@ impl WorkerGlobalScopeMethods for WorkerGlobalScope { base64_atob(atob) } - // https://html.spec.whatwg.org/multipage/#dom-windowtimers-setinterval + // https://html.spec.whatwg.org/multipage/#dom-windowtimers-settimeout fn SetTimeout(&self, _cx: *mut JSContext, callback: Rc, timeout: i32, args: Vec) -> i32 { - self.timers.set_timeout_or_interval(GlobalRef::Worker(self), - TimerCallback::FunctionTimerCallback(callback), - args, - timeout, - IsInterval::NonInterval, - TimerSource::FromWorker) + self.upcast::().set_timeout_or_interval( + TimerCallback::FunctionTimerCallback(callback), + args, + timeout, + IsInterval::NonInterval) } - // https://html.spec.whatwg.org/multipage/#dom-windowtimers-setinterval + // https://html.spec.whatwg.org/multipage/#dom-windowtimers-settimeout fn SetTimeout_(&self, _cx: *mut JSContext, callback: DOMString, timeout: i32, args: Vec) -> i32 { - self.timers.set_timeout_or_interval(GlobalRef::Worker(self), - TimerCallback::StringTimerCallback(callback), - args, - timeout, - IsInterval::NonInterval, - TimerSource::FromWorker) + self.upcast::().set_timeout_or_interval( + TimerCallback::StringTimerCallback(callback), + args, + timeout, + IsInterval::NonInterval) } - // https://html.spec.whatwg.org/multipage/#dom-windowtimers-clearinterval + // https://html.spec.whatwg.org/multipage/#dom-windowtimers-cleartimeout fn ClearTimeout(&self, handle: i32) { - self.timers.clear_timeout_or_interval(GlobalRef::Worker(self), handle); + self.upcast::().clear_timeout_or_interval(handle); } // https://html.spec.whatwg.org/multipage/#dom-windowtimers-setinterval fn SetInterval(&self, _cx: *mut JSContext, callback: Rc, timeout: i32, args: Vec) -> i32 { - self.timers.set_timeout_or_interval(GlobalRef::Worker(self), - TimerCallback::FunctionTimerCallback(callback), - args, - timeout, - IsInterval::Interval, - TimerSource::FromWorker) + self.upcast::().set_timeout_or_interval( + TimerCallback::FunctionTimerCallback(callback), + args, + timeout, + IsInterval::Interval) } // https://html.spec.whatwg.org/multipage/#dom-windowtimers-setinterval fn SetInterval_(&self, _cx: *mut JSContext, callback: DOMString, timeout: i32, args: Vec) -> i32 { - self.timers.set_timeout_or_interval(GlobalRef::Worker(self), - TimerCallback::StringTimerCallback(callback), - args, - timeout, - IsInterval::Interval, - TimerSource::FromWorker) + self.upcast::().set_timeout_or_interval( + TimerCallback::StringTimerCallback(callback), + args, + timeout, + IsInterval::Interval) } // https://html.spec.whatwg.org/multipage/#dom-windowtimers-clearinterval @@ -401,7 +386,7 @@ impl WorkerGlobalScope { } pub fn handle_fire_timer(&self, timer_id: TimerEventId) { - self.timers.fire_timer(timer_id, self); + self.upcast::().fire_timer(timer_id); } pub fn close(&self) { diff --git a/components/script/dom/xmlhttprequest.rs b/components/script/dom/xmlhttprequest.rs index a5b09193b7f..7a586cfe6a1 100644 --- a/components/script/dom/xmlhttprequest.rs +++ b/components/script/dom/xmlhttprequest.rs @@ -1077,15 +1077,14 @@ impl XMLHttpRequest { xhr: Trusted::new(self), generation_id: self.generation_id.get(), }); - let global = self.global(); let duration = Length::new(duration_ms as u64); - *self.timeout_cancel.borrow_mut() = Some(global.r().schedule_callback(callback, duration)); + *self.timeout_cancel.borrow_mut() = + Some(self.global_scope().schedule_callback(callback, duration)); } fn cancel_timeout(&self) { if let Some(handle) = self.timeout_cancel.borrow_mut().take() { - let global = self.global(); - global.r().unschedule_callback(handle); + self.global_scope().unschedule_callback(handle); } } diff --git a/components/script/script_thread.rs b/components/script/script_thread.rs index cbfcbd0cca4..0d3f605fac1 100644 --- a/components/script/script_thread.rs +++ b/components/script/script_thread.rs @@ -1244,9 +1244,9 @@ impl ScriptThread { if let Some(ref inner_context) = root_context.find(id) { let window = inner_context.active_window(); if visible { - window.speed_up_timers(); + window.upcast::().speed_up_timers(); } else { - window.slow_down_timers(); + window.upcast::().slow_down_timers(); } return true; } @@ -1291,7 +1291,7 @@ impl ScriptThread { if let Some(root_context) = self.browsing_context.get() { if let Some(ref inner_context) = root_context.find(id) { let window = inner_context.active_window(); - window.freeze(); + window.upcast::().suspend(); return; } } @@ -1805,7 +1805,7 @@ impl ScriptThread { } if incomplete.is_frozen { - window.freeze(); + window.upcast::().suspend(); } if !incomplete.is_visible { diff --git a/components/script/timers.rs b/components/script/timers.rs index 7b326f6b164..ddfd336cd4f 100644 --- a/components/script/timers.rs +++ b/components/script/timers.rs @@ -5,9 +5,9 @@ use dom::bindings::callback::ExceptionHandling::Report; use dom::bindings::cell::DOMRefCell; use dom::bindings::codegen::Bindings::FunctionBinding::Function; -use dom::bindings::global::GlobalRef; use dom::bindings::reflector::Reflectable; use dom::bindings::str::DOMString; +use dom::globalscope::GlobalScope; use dom::testbinding::TestBindingCallback; use dom::xmlhttprequest::XHRTimeoutCallback; use euclid::length::Length; @@ -167,7 +167,7 @@ impl OneshotTimers { } } - pub fn fire_timer(&self, id: TimerEventId, this: &T) { + pub fn fire_timer(&self, id: TimerEventId, global: &GlobalScope) { let expected_id = self.expected_event_id.get(); if expected_id != id { debug!("ignoring timer fire event {:?} (expected {:?})", id, expected_id); @@ -200,7 +200,7 @@ impl OneshotTimers { for timer in timers_to_run { let callback = timer.callback; - callback.invoke(this, &self.js_timers); + callback.invoke(global, &self.js_timers); } self.schedule_timer_call(); @@ -272,7 +272,7 @@ impl OneshotTimers { } pub fn set_timeout_or_interval(&self, - global: GlobalRef, + global: &GlobalScope, callback: TimerCallback, arguments: Vec, timeout: i32, @@ -287,7 +287,7 @@ impl OneshotTimers { source) } - pub fn clear_timeout_or_interval(&self, global: GlobalRef, handle: i32) { + pub fn clear_timeout_or_interval(&self, global: &GlobalScope, handle: i32) { self.js_timers.clear_timeout_or_interval(global, handle) } } @@ -364,7 +364,7 @@ impl JsTimers { // see https://html.spec.whatwg.org/multipage/#timer-initialisation-steps pub fn set_timeout_or_interval(&self, - global: GlobalRef, + global: &GlobalScope, callback: TimerCallback, arguments: Vec, timeout: i32, @@ -414,7 +414,7 @@ impl JsTimers { new_handle } - pub fn clear_timeout_or_interval(&self, global: GlobalRef, handle: i32) { + pub fn clear_timeout_or_interval(&self, global: &GlobalScope, handle: i32) { let mut active_timers = self.active_timers.borrow_mut(); if let Some(entry) = active_timers.remove(&JsTimerHandle(handle)) { @@ -441,7 +441,7 @@ impl JsTimers { } // see https://html.spec.whatwg.org/multipage/#timer-initialisation-steps - fn initialize_and_schedule(&self, global: GlobalRef, mut task: JsTimerTask) { + fn initialize_and_schedule(&self, global: &GlobalScope, mut task: JsTimerTask) { let handle = task.handle; let mut active_timers = self.active_timers.borrow_mut(); @@ -514,7 +514,7 @@ impl JsTimerTask { // reschedule repeating timers when they were not canceled as part of step 4.2. if self.is_interval == IsInterval::Interval && timers.active_timers.borrow().contains_key(&self.handle) { - timers.initialize_and_schedule(this.global().r(), self); + timers.initialize_and_schedule(&this.global_scope(), self); } } } From ca8c6fb0724a364bdd11742a9c9611557595a6f7 Mon Sep 17 00:00:00 2001 From: Anthony Ramine Date: Tue, 4 Oct 2016 15:27:13 +0200 Subject: [PATCH 46/66] Make RunnableWrapper store an Option> This makes WorkerGlobalScope::get_runnable_wrapper not panic anymore when the worker is a ServiceWorkerGlobalScope. --- components/script/dom/window.rs | 2 +- components/script/dom/workerglobalscope.rs | 2 +- components/script/script_thread.rs | 8 +++++--- 3 files changed, 7 insertions(+), 5 deletions(-) diff --git a/components/script/dom/window.rs b/components/script/dom/window.rs index 4365ba44999..5f5b0bda04a 100644 --- a/components/script/dom/window.rs +++ b/components/script/dom/window.rs @@ -868,7 +868,7 @@ impl WindowMethods for Window { impl Window { pub fn get_runnable_wrapper(&self) -> RunnableWrapper { RunnableWrapper { - cancelled: self.ignore_further_async_events.clone() + cancelled: Some(self.ignore_further_async_events.clone()), } } diff --git a/components/script/dom/workerglobalscope.rs b/components/script/dom/workerglobalscope.rs index 49b1d4e3257..f1f2229c823 100644 --- a/components/script/dom/workerglobalscope.rs +++ b/components/script/dom/workerglobalscope.rs @@ -155,7 +155,7 @@ impl WorkerGlobalScope { pub fn get_runnable_wrapper(&self) -> RunnableWrapper { RunnableWrapper { - cancelled: self.closing.clone().unwrap(), + cancelled: self.closing.clone(), } } diff --git a/components/script/script_thread.rs b/components/script/script_thread.rs index 0d3f605fac1..bbdc766cea4 100644 --- a/components/script/script_thread.rs +++ b/components/script/script_thread.rs @@ -170,7 +170,7 @@ impl InProgressLoad { /// Encapsulated state required to create cancellable runnables from non-script threads. pub struct RunnableWrapper { - pub cancelled: Arc, + pub cancelled: Option>, } impl RunnableWrapper { @@ -184,7 +184,7 @@ impl RunnableWrapper { /// A runnable that can be discarded by toggling a shared flag. pub struct CancellableRunnable { - cancelled: Arc, + cancelled: Option>, inner: Box, } @@ -192,7 +192,9 @@ impl Runnable for CancellableRunnable { fn name(&self) -> &'static str { self.inner.name() } fn is_cancelled(&self) -> bool { - self.cancelled.load(Ordering::SeqCst) + self.cancelled.as_ref() + .map(|cancelled| cancelled.load(Ordering::SeqCst)) + .unwrap_or(false) } fn main_thread_handler(self: Box>, script_thread: &ScriptThread) { From 514819f37a12c79c0398863c2ef817c9a4337f56 Mon Sep 17 00:00:00 2001 From: Anthony Ramine Date: Tue, 4 Oct 2016 15:36:20 +0200 Subject: [PATCH 47/66] Introduce GlobalScope::get_runnable_wrapper --- components/script/dom/bindings/global.rs | 11 +---------- components/script/dom/filereader.rs | 2 +- components/script/dom/globalscope.rs | 14 +++++++++++++- components/script/task_source/mod.rs | 2 +- 4 files changed, 16 insertions(+), 13 deletions(-) diff --git a/components/script/dom/bindings/global.rs b/components/script/dom/bindings/global.rs index 3c2d0533ac7..2d984db4598 100644 --- a/components/script/dom/bindings/global.rs +++ b/components/script/dom/bindings/global.rs @@ -19,7 +19,7 @@ use js::glue::{IsWrapper, UnwrapObject}; use js::jsapi::{CurrentGlobalOrNull, GetGlobalForObjectCrossCompartment}; use js::jsapi::{JSContext, JSObject, JS_GetClass}; use script_runtime::{CommonScriptMsg, EnqueuedPromiseCallback, ScriptChan, ScriptPort}; -use script_thread::{RunnableWrapper, ScriptThread}; +use script_thread::ScriptThread; use task_source::file_reading::FileReadingTaskSource; /// A freely-copyable reference to a rooted global object. @@ -85,15 +85,6 @@ impl<'a> GlobalRef<'a> { } } - /// Returns a wrapper for runnables to ensure they are cancelled if the global - /// is being destroyed. - pub fn get_runnable_wrapper(&self) -> RunnableWrapper { - match *self { - GlobalRef::Window(ref window) => window.get_runnable_wrapper(), - GlobalRef::Worker(ref worker) => worker.get_runnable_wrapper(), - } - } - /// Enqueue a promise callback for subsequent execution. pub fn enqueue_promise_job(&self, job: EnqueuedPromiseCallback) { match *self { diff --git a/components/script/dom/filereader.rs b/components/script/dom/filereader.rs index 4ba5af109be..ebfb5060a58 100644 --- a/components/script/dom/filereader.rs +++ b/components/script/dom/filereader.rs @@ -354,7 +354,7 @@ impl FileReader { let fr = Trusted::new(self); let gen_id = self.generation_id.get(); - let wrapper = self.global().r().get_runnable_wrapper(); + let wrapper = self.global_scope().get_runnable_wrapper(); let task_source = self.global().r().file_reading_task_source(); spawn_named("file reader async operation".to_owned(), move || { diff --git a/components/script/dom/globalscope.rs b/components/script/dom/globalscope.rs index 96528a80164..159b934f8ae 100644 --- a/components/script/dom/globalscope.rs +++ b/components/script/dom/globalscope.rs @@ -27,7 +27,7 @@ use msg::constellation_msg::PipelineId; use net_traits::{CoreResourceThread, ResourceThreads, IpcSend}; use profile_traits::{mem, time}; use script_runtime::{ScriptChan, maybe_take_panic_result}; -use script_thread::MainThreadScriptChan; +use script_thread::{MainThreadScriptChan, RunnableWrapper}; use script_traits::{MsDuration, ScriptMsg as ConstellationMsg, TimerEvent}; use script_traits::{TimerEventId, TimerEventRequest, TimerSource}; use std::cell::Cell; @@ -396,6 +396,18 @@ impl GlobalScope { } unreachable!(); } + + /// Returns a wrapper for runnables to ensure they are cancelled if + /// the global scope is being destroyed. + pub fn get_runnable_wrapper(&self) -> RunnableWrapper { + if let Some(window) = self.downcast::() { + return window.get_runnable_wrapper(); + } + if let Some(worker) = self.downcast::() { + return worker.get_runnable_wrapper(); + } + unreachable!(); + } } fn timestamp_in_ms(time: Timespec) -> u64 { diff --git a/components/script/task_source/mod.rs b/components/script/task_source/mod.rs index cb607c57acb..bddc4f82173 100644 --- a/components/script/task_source/mod.rs +++ b/components/script/task_source/mod.rs @@ -19,6 +19,6 @@ pub trait TaskSource { -> Result<(), ()> where T: Runnable + Send + 'static; fn queue(&self, msg: Box, global: GlobalRef) -> Result<(), ()> { - self.queue_with_wrapper(msg, &global.get_runnable_wrapper()) + self.queue_with_wrapper(msg, &global.as_global_scope().get_runnable_wrapper()) } } From 44ca9f3d712e9b49681e9848db089a1c05c7ffff Mon Sep 17 00:00:00 2001 From: Anthony Ramine Date: Tue, 4 Oct 2016 15:49:48 +0200 Subject: [PATCH 48/66] Make TaskSource::queue take a &GlobalScope --- components/script/dom/htmldetailselement.rs | 3 +-- components/script/dom/htmlformelement.rs | 3 +-- components/script/dom/htmlimageelement.rs | 3 +-- components/script/dom/htmlmediaelement.rs | 11 +++++------ components/script/dom/storage.rs | 11 ++++++----- components/script/script_thread.rs | 5 +++-- components/script/task_source/dom_manipulation.rs | 6 +++--- components/script/task_source/mod.rs | 6 +++--- components/script/task_source/user_interaction.rs | 4 ++-- 9 files changed, 25 insertions(+), 27 deletions(-) diff --git a/components/script/dom/htmldetailselement.rs b/components/script/dom/htmldetailselement.rs index 61f02d0899f..9a7cf6e13f8 100644 --- a/components/script/dom/htmldetailselement.rs +++ b/components/script/dom/htmldetailselement.rs @@ -5,7 +5,6 @@ use dom::attr::Attr; use dom::bindings::codegen::Bindings::HTMLDetailsElementBinding; use dom::bindings::codegen::Bindings::HTMLDetailsElementBinding::HTMLDetailsElementMethods; -use dom::bindings::global::GlobalRef; use dom::bindings::inheritance::Castable; use dom::bindings::js::Root; use dom::bindings::refcounted::Trusted; @@ -79,7 +78,7 @@ impl VirtualMethods for HTMLDetailsElement { element: details, toggle_number: counter }; - let _ = task_source.queue(runnable, GlobalRef::Window(&window)); + let _ = task_source.queue(runnable, window.upcast()); } } } diff --git a/components/script/dom/htmlformelement.rs b/components/script/dom/htmlformelement.rs index 58454eed0dc..e1c53a41e12 100644 --- a/components/script/dom/htmlformelement.rs +++ b/components/script/dom/htmlformelement.rs @@ -12,7 +12,6 @@ use dom::bindings::codegen::Bindings::HTMLFormElementBinding::HTMLFormElementMet use dom::bindings::codegen::Bindings::HTMLInputElementBinding::HTMLInputElementMethods; use dom::bindings::codegen::Bindings::HTMLTextAreaElementBinding::HTMLTextAreaElementMethods; use dom::bindings::conversions::DerivedFrom; -use dom::bindings::global::GlobalRef; use dom::bindings::inheritance::{Castable, ElementTypeId, HTMLElementTypeId, NodeTypeId}; use dom::bindings::js::{JS, MutNullableHeap, Root}; use dom::bindings::refcounted::Trusted; @@ -444,7 +443,7 @@ impl HTMLFormElement { }; // Step 3 - window.dom_manipulation_task_source().queue(nav, GlobalRef::Window(&window)).unwrap(); + window.dom_manipulation_task_source().queue(nav, window.upcast()).unwrap(); } /// Interactively validate the constraints of form elements diff --git a/components/script/dom/htmlimageelement.rs b/components/script/dom/htmlimageelement.rs index 489a6821824..428cfb97343 100644 --- a/components/script/dom/htmlimageelement.rs +++ b/components/script/dom/htmlimageelement.rs @@ -9,7 +9,6 @@ use dom::bindings::codegen::Bindings::HTMLImageElementBinding; use dom::bindings::codegen::Bindings::HTMLImageElementBinding::HTMLImageElementMethods; use dom::bindings::codegen::Bindings::WindowBinding::WindowMethods; use dom::bindings::error::Fallible; -use dom::bindings::global::GlobalRef; use dom::bindings::inheritance::Castable; use dom::bindings::js::{LayoutJS, Root}; use dom::bindings::refcounted::Trusted; @@ -192,7 +191,7 @@ impl HTMLImageElement { src: src.into(), }; let task = window.dom_manipulation_task_source(); - let _ = task.queue(runnable, GlobalRef::Window(window)); + let _ = task.queue(runnable, window.upcast()); } } } diff --git a/components/script/dom/htmlmediaelement.rs b/components/script/dom/htmlmediaelement.rs index 24ae7542880..31140185ce2 100644 --- a/components/script/dom/htmlmediaelement.rs +++ b/components/script/dom/htmlmediaelement.rs @@ -12,7 +12,6 @@ use dom::bindings::codegen::Bindings::HTMLMediaElementBinding::HTMLMediaElementC use dom::bindings::codegen::Bindings::HTMLMediaElementBinding::HTMLMediaElementMethods; use dom::bindings::codegen::Bindings::MediaErrorBinding::MediaErrorConstants::*; use dom::bindings::codegen::Bindings::MediaErrorBinding::MediaErrorMethods; -use dom::bindings::global::GlobalRef; use dom::bindings::inheritance::Castable; use dom::bindings::js::{Root, MutNullableHeap, JS}; use dom::bindings::refcounted::Trusted; @@ -276,7 +275,7 @@ impl HTMLMediaElement { elem: Trusted::new(self), }; let win = window_from_node(self); - let _ = win.dom_manipulation_task_source().queue(task, GlobalRef::Window(&win)); + let _ = win.dom_manipulation_task_source().queue(task, win.upcast()); } // https://html.spec.whatwg.org/multipage/#internal-pause-steps step 2.2 @@ -300,13 +299,13 @@ impl HTMLMediaElement { elem: Trusted::new(self), }; let win = window_from_node(self); - let _ = win.dom_manipulation_task_source().queue(task, GlobalRef::Window(&win)); + let _ = win.dom_manipulation_task_source().queue(task, win.upcast()); } fn queue_fire_simple_event(&self, type_: &'static str) { let win = window_from_node(self); let task = box FireSimpleEventTask::new(self, type_); - let _ = win.dom_manipulation_task_source().queue(task, GlobalRef::Window(&win)); + let _ = win.dom_manipulation_task_source().queue(task, win.upcast()); } fn fire_simple_event(&self, type_: &str) { @@ -533,8 +532,8 @@ impl HTMLMediaElement { fn queue_dedicated_media_source_failure_steps(&self) { let window = window_from_node(self); - let _ = window.dom_manipulation_task_source().queue(box DedicatedMediaSourceFailureTask::new(self), - GlobalRef::Window(&window)); + let _ = window.dom_manipulation_task_source().queue( + box DedicatedMediaSourceFailureTask::new(self), window.upcast()); } // https://html.spec.whatwg.org/multipage/#dedicated-media-source-failure-steps diff --git a/components/script/dom/storage.rs b/components/script/dom/storage.rs index f19ac5ebbb6..83d9ab4bf61 100644 --- a/components/script/dom/storage.rs +++ b/components/script/dom/storage.rs @@ -150,13 +150,14 @@ impl Storage { /// https://html.spec.whatwg.org/multipage/#send-a-storage-notification fn broadcast_change_notification(&self, key: Option, old_value: Option, new_value: Option) { - let global_root = self.global(); - let global_ref = global_root.r(); - let window = global_ref.as_global_scope().as_window(); + let global = self.global_scope(); + let window = global.as_window(); let task_source = window.dom_manipulation_task_source(); let trusted_storage = Trusted::new(self); - task_source.queue(box StorageEventRunnable::new(trusted_storage, key, old_value, new_value), - global_ref).unwrap(); + task_source + .queue( + box StorageEventRunnable::new(trusted_storage, key, old_value, new_value), &global) + .unwrap(); } } diff --git a/components/script/script_thread.rs b/components/script/script_thread.rs index bbdc766cea4..b495cbadd06 100644 --- a/components/script/script_thread.rs +++ b/components/script/script_thread.rs @@ -1192,7 +1192,7 @@ impl ScriptThread { // https://html.spec.whatwg.org/multipage/#the-end step 7 let handler = box DocumentProgressHandler::new(Trusted::new(doc)); - self.dom_manipulation_task_source.queue(handler, GlobalRef::Window(doc.window())).unwrap(); + self.dom_manipulation_task_source.queue(handler, doc.window().upcast()).unwrap(); if let Some(fragment) = doc.url().fragment() { self.check_and_scroll_fragment(fragment, pipeline, doc); @@ -2183,7 +2183,8 @@ impl ScriptThread { pub fn flush_promise_jobs(global: GlobalRef) { SCRIPT_THREAD_ROOT.with(|root| { let script_thread = unsafe { &*root.get().unwrap() }; - let _ = script_thread.dom_manipulation_task_source.queue(box FlushPromiseJobs, global); + let _ = script_thread.dom_manipulation_task_source.queue( + box FlushPromiseJobs, global.as_global_scope()); }) } diff --git a/components/script/task_source/dom_manipulation.rs b/components/script/task_source/dom_manipulation.rs index 4f5384ae2ed..c5b4e4b5f73 100644 --- a/components/script/task_source/dom_manipulation.rs +++ b/components/script/task_source/dom_manipulation.rs @@ -2,7 +2,7 @@ * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ -use dom::bindings::global::GlobalRef; +use dom::bindings::inheritance::Castable; use dom::bindings::refcounted::Trusted; use dom::event::{EventBubbles, EventCancelable, EventRunnable, SimpleEventRunnable}; use dom::eventtarget::EventTarget; @@ -41,7 +41,7 @@ impl DOMManipulationTaskSource { bubbles: bubbles, cancelable: cancelable, }; - let _ = self.queue(runnable, GlobalRef::Window(window)); + let _ = self.queue(runnable, window.upcast()); } pub fn queue_simple_event(&self, target: &EventTarget, name: Atom, window: &Window) { @@ -50,7 +50,7 @@ impl DOMManipulationTaskSource { target: target, name: name, }; - let _ = self.queue(runnable, GlobalRef::Window(window)); + let _ = self.queue(runnable, window.upcast()); } } diff --git a/components/script/task_source/mod.rs b/components/script/task_source/mod.rs index bddc4f82173..6e2a9985fa0 100644 --- a/components/script/task_source/mod.rs +++ b/components/script/task_source/mod.rs @@ -8,7 +8,7 @@ pub mod history_traversal; pub mod networking; pub mod user_interaction; -use dom::bindings::global::GlobalRef; +use dom::globalscope::GlobalScope; use script_thread::{Runnable, RunnableWrapper}; use std::result::Result; @@ -18,7 +18,7 @@ pub trait TaskSource { wrapper: &RunnableWrapper) -> Result<(), ()> where T: Runnable + Send + 'static; - fn queue(&self, msg: Box, global: GlobalRef) -> Result<(), ()> { - self.queue_with_wrapper(msg, &global.as_global_scope().get_runnable_wrapper()) + fn queue(&self, msg: Box, global: &GlobalScope) -> Result<(), ()> { + self.queue_with_wrapper(msg, &global.get_runnable_wrapper()) } } diff --git a/components/script/task_source/user_interaction.rs b/components/script/task_source/user_interaction.rs index cddafb80ee4..d3850e9f813 100644 --- a/components/script/task_source/user_interaction.rs +++ b/components/script/task_source/user_interaction.rs @@ -2,7 +2,7 @@ * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ -use dom::bindings::global::GlobalRef; +use dom::bindings::inheritance::Castable; use dom::bindings::refcounted::Trusted; use dom::event::{EventBubbles, EventCancelable, EventRunnable}; use dom::eventtarget::EventTarget; @@ -41,7 +41,7 @@ impl UserInteractionTaskSource { bubbles: bubbles, cancelable: cancelable, }; - let _ = self.queue(runnable, GlobalRef::Window(window)); + let _ = self.queue(runnable, window.upcast()); } } From 6e3be6d894e311f2f2331d9437b4956fb5fd4752 Mon Sep 17 00:00:00 2001 From: Anthony Ramine Date: Tue, 4 Oct 2016 16:00:40 +0200 Subject: [PATCH 49/66] Introduce GlobalScope::flush_promise_jobs --- components/script/dom/bindings/global.rs | 9 --------- components/script/dom/globalscope.rs | 14 +++++++++++++- components/script/script_runtime.rs | 2 +- components/script/script_thread.rs | 4 ++-- 4 files changed, 16 insertions(+), 13 deletions(-) diff --git a/components/script/dom/bindings/global.rs b/components/script/dom/bindings/global.rs index 2d984db4598..92b79e352e2 100644 --- a/components/script/dom/bindings/global.rs +++ b/components/script/dom/bindings/global.rs @@ -92,15 +92,6 @@ impl<'a> GlobalRef<'a> { GlobalRef::Worker(ref worker) => worker.enqueue_promise_job(job), } } - - /// Start the process of executing the pending promise callbacks. They will be invoked - /// in FIFO order, synchronously, at some point in the future. - pub fn flush_promise_jobs(&self) { - match *self { - GlobalRef::Window(_) => ScriptThread::flush_promise_jobs(*self), - GlobalRef::Worker(ref worker) => worker.flush_promise_jobs(), - } - } } impl<'a> Reflectable for GlobalRef<'a> { diff --git a/components/script/dom/globalscope.rs b/components/script/dom/globalscope.rs index 159b934f8ae..f9eaead2189 100644 --- a/components/script/dom/globalscope.rs +++ b/components/script/dom/globalscope.rs @@ -27,7 +27,7 @@ use msg::constellation_msg::PipelineId; use net_traits::{CoreResourceThread, ResourceThreads, IpcSend}; use profile_traits::{mem, time}; use script_runtime::{ScriptChan, maybe_take_panic_result}; -use script_thread::{MainThreadScriptChan, RunnableWrapper}; +use script_thread::{MainThreadScriptChan, RunnableWrapper, ScriptThread}; use script_traits::{MsDuration, ScriptMsg as ConstellationMsg, TimerEvent}; use script_traits::{TimerEventId, TimerEventRequest, TimerSource}; use std::cell::Cell; @@ -408,6 +408,18 @@ impl GlobalScope { } unreachable!(); } + + /// Start the process of executing the pending promise callbacks. They will be invoked + /// in FIFO order, synchronously, at some point in the future. + pub fn flush_promise_jobs(&self) { + if self.is::() { + return ScriptThread::flush_promise_jobs(self); + } + if let Some(worker) = self.downcast::() { + return worker.flush_promise_jobs(); + } + unreachable!(); + } } fn timestamp_in_ms(time: Timespec) -> u64 { diff --git a/components/script/script_runtime.rs b/components/script/script_runtime.rs index ab7cb607985..df9341a3777 100644 --- a/components/script/script_runtime.rs +++ b/components/script/script_runtime.rs @@ -142,7 +142,7 @@ impl PromiseJobQueue { self.promise_job_queue.borrow_mut().push(job); if !self.pending_promise_job_runnable.get() { self.pending_promise_job_runnable.set(true); - global.flush_promise_jobs(); + global.as_global_scope().flush_promise_jobs(); } } diff --git a/components/script/script_thread.rs b/components/script/script_thread.rs index b495cbadd06..b0814187f85 100644 --- a/components/script/script_thread.rs +++ b/components/script/script_thread.rs @@ -2180,11 +2180,11 @@ impl ScriptThread { }); } - pub fn flush_promise_jobs(global: GlobalRef) { + pub fn flush_promise_jobs(global: &GlobalScope) { SCRIPT_THREAD_ROOT.with(|root| { let script_thread = unsafe { &*root.get().unwrap() }; let _ = script_thread.dom_manipulation_task_source.queue( - box FlushPromiseJobs, global.as_global_scope()); + box FlushPromiseJobs, global); }) } From 2ee073053ab4718bced82197b2af2c77fc5f47a7 Mon Sep 17 00:00:00 2001 From: Anthony Ramine Date: Tue, 4 Oct 2016 16:08:12 +0200 Subject: [PATCH 50/66] Make PromiseJobQueue::enqueue take a &GlobalScope --- components/script/dom/workerglobalscope.rs | 4 ++-- components/script/script_runtime.rs | 7 ++++--- components/script/script_thread.rs | 2 +- 3 files changed, 7 insertions(+), 6 deletions(-) diff --git a/components/script/dom/workerglobalscope.rs b/components/script/dom/workerglobalscope.rs index f1f2229c823..93370debc9f 100644 --- a/components/script/dom/workerglobalscope.rs +++ b/components/script/dom/workerglobalscope.rs @@ -9,7 +9,7 @@ use dom::bindings::codegen::Bindings::RequestBinding::RequestInit; use dom::bindings::codegen::Bindings::WorkerGlobalScopeBinding::WorkerGlobalScopeMethods; use dom::bindings::codegen::UnionTypes::RequestOrUSVString; use dom::bindings::error::{Error, ErrorResult, Fallible, report_pending_exception}; -use dom::bindings::global::{GlobalRef, GlobalRoot}; +use dom::bindings::global::GlobalRoot; use dom::bindings::inheritance::Castable; use dom::bindings::js::{JS, MutNullableHeap, Root}; use dom::bindings::refcounted::Trusted; @@ -160,7 +160,7 @@ impl WorkerGlobalScope { } pub fn enqueue_promise_job(&self, job: EnqueuedPromiseCallback) { - self.promise_job_queue.enqueue(job, GlobalRef::Worker(self)); + self.promise_job_queue.enqueue(job, self.upcast()); } pub fn flush_promise_jobs(&self) { diff --git a/components/script/script_runtime.rs b/components/script/script_runtime.rs index df9341a3777..36ae678ade7 100644 --- a/components/script/script_runtime.rs +++ b/components/script/script_runtime.rs @@ -8,11 +8,12 @@ use dom::bindings::callback::ExceptionHandling; use dom::bindings::cell::DOMRefCell; use dom::bindings::codegen::Bindings::PromiseBinding::PromiseJobCallback; -use dom::bindings::global::{global_root_from_object, GlobalRoot, GlobalRef}; +use dom::bindings::global::{global_root_from_object, GlobalRoot}; use dom::bindings::js::{RootCollection, RootCollectionPtr, trace_roots}; use dom::bindings::refcounted::{LiveDOMReferences, trace_refcounted_objects}; use dom::bindings::trace::trace_traceables; use dom::bindings::utils::DOM_CALLBACKS; +use dom::globalscope::GlobalScope; use js::glue::CollectServoSizes; use js::jsapi::{DisableIncrementalGC, GCDescription, GCProgress, HandleObject}; use js::jsapi::{JSContext, JS_GetRuntime, JSRuntime, JSTracer, SetDOMCallbacks, SetGCSliceCallback}; @@ -138,11 +139,11 @@ impl PromiseJobQueue { /// Add a new promise job callback to this queue. It will be invoked as part of the next /// microtask checkpoint. - pub fn enqueue(&self, job: EnqueuedPromiseCallback, global: GlobalRef) { + pub fn enqueue(&self, job: EnqueuedPromiseCallback, global: &GlobalScope) { self.promise_job_queue.borrow_mut().push(job); if !self.pending_promise_job_runnable.get() { self.pending_promise_job_runnable.set(true); - global.as_global_scope().flush_promise_jobs(); + global.flush_promise_jobs(); } } diff --git a/components/script/script_thread.rs b/components/script/script_thread.rs index b0814187f85..467b77d1f76 100644 --- a/components/script/script_thread.rs +++ b/components/script/script_thread.rs @@ -2176,7 +2176,7 @@ impl ScriptThread { pub fn enqueue_promise_job(job: EnqueuedPromiseCallback, global: GlobalRef) { SCRIPT_THREAD_ROOT.with(|root| { let script_thread = unsafe { &*root.get().unwrap() }; - script_thread.promise_job_queue.enqueue(job, global); + script_thread.promise_job_queue.enqueue(job, global.as_global_scope()); }); } From 4d9347d5b35a9b354577bf76f2251c97edde7eef Mon Sep 17 00:00:00 2001 From: Anthony Ramine Date: Tue, 4 Oct 2016 16:19:05 +0200 Subject: [PATCH 51/66] Introduce GlobalScope::enqueue_promise_job --- components/script/dom/bindings/global.rs | 10 +--------- components/script/dom/globalscope.rs | 13 ++++++++++++- components/script/script_runtime.rs | 8 ++++---- components/script/script_thread.rs | 6 +++--- 4 files changed, 20 insertions(+), 17 deletions(-) diff --git a/components/script/dom/bindings/global.rs b/components/script/dom/bindings/global.rs index 92b79e352e2..0cbb3ec302b 100644 --- a/components/script/dom/bindings/global.rs +++ b/components/script/dom/bindings/global.rs @@ -18,7 +18,7 @@ use js::{JSCLASS_IS_DOMJSCLASS, JSCLASS_IS_GLOBAL}; use js::glue::{IsWrapper, UnwrapObject}; use js::jsapi::{CurrentGlobalOrNull, GetGlobalForObjectCrossCompartment}; use js::jsapi::{JSContext, JSObject, JS_GetClass}; -use script_runtime::{CommonScriptMsg, EnqueuedPromiseCallback, ScriptChan, ScriptPort}; +use script_runtime::{CommonScriptMsg, ScriptChan, ScriptPort}; use script_thread::ScriptThread; use task_source::file_reading::FileReadingTaskSource; @@ -84,14 +84,6 @@ impl<'a> GlobalRef<'a> { GlobalRef::Worker(ref worker) => worker.process_event(msg), } } - - /// Enqueue a promise callback for subsequent execution. - pub fn enqueue_promise_job(&self, job: EnqueuedPromiseCallback) { - match *self { - GlobalRef::Window(_) => ScriptThread::enqueue_promise_job(job, *self), - GlobalRef::Worker(ref worker) => worker.enqueue_promise_job(job), - } - } } impl<'a> Reflectable for GlobalRef<'a> { diff --git a/components/script/dom/globalscope.rs b/components/script/dom/globalscope.rs index f9eaead2189..cd8fca9a0e4 100644 --- a/components/script/dom/globalscope.rs +++ b/components/script/dom/globalscope.rs @@ -26,7 +26,7 @@ use libc; use msg::constellation_msg::PipelineId; use net_traits::{CoreResourceThread, ResourceThreads, IpcSend}; use profile_traits::{mem, time}; -use script_runtime::{ScriptChan, maybe_take_panic_result}; +use script_runtime::{EnqueuedPromiseCallback, ScriptChan, maybe_take_panic_result}; use script_thread::{MainThreadScriptChan, RunnableWrapper, ScriptThread}; use script_traits::{MsDuration, ScriptMsg as ConstellationMsg, TimerEvent}; use script_traits::{TimerEventId, TimerEventRequest, TimerSource}; @@ -420,6 +420,17 @@ impl GlobalScope { } unreachable!(); } + + /// Enqueue a promise callback for subsequent execution. + pub fn enqueue_promise_job(&self, job: EnqueuedPromiseCallback) { + if self.is::() { + return ScriptThread::enqueue_promise_job(job, self); + } + if let Some(worker) = self.downcast::() { + return worker.enqueue_promise_job(job); + } + unreachable!(); + } } fn timestamp_in_ms(time: Timespec) -> u64 { diff --git a/components/script/script_runtime.rs b/components/script/script_runtime.rs index 36ae678ade7..145ef1ef19e 100644 --- a/components/script/script_runtime.rs +++ b/components/script/script_runtime.rs @@ -8,7 +8,7 @@ use dom::bindings::callback::ExceptionHandling; use dom::bindings::cell::DOMRefCell; use dom::bindings::codegen::Bindings::PromiseBinding::PromiseJobCallback; -use dom::bindings::global::{global_root_from_object, GlobalRoot}; +use dom::bindings::global::{GlobalRoot, global_scope_from_object}; use dom::bindings::js::{RootCollection, RootCollectionPtr, trace_roots}; use dom::bindings::refcounted::{LiveDOMReferences, trace_refcounted_objects}; use dom::bindings::trace::trace_traceables; @@ -178,9 +178,9 @@ unsafe extern "C" fn enqueue_job(_cx: *mut JSContext, _allocation_site: HandleObject, _data: *mut c_void) -> bool { let result = panic::catch_unwind(AssertUnwindSafe(|| { - let global = global_root_from_object(job.get()); - let pipeline = global.r().as_global_scope().pipeline_id(); - global.r().enqueue_promise_job(EnqueuedPromiseCallback { + let global = global_scope_from_object(job.get()); + let pipeline = global.pipeline_id(); + global.enqueue_promise_job(EnqueuedPromiseCallback { callback: PromiseJobCallback::new(job.get()), pipeline: pipeline, }); diff --git a/components/script/script_thread.rs b/components/script/script_thread.rs index 467b77d1f76..22ca69c78df 100644 --- a/components/script/script_thread.rs +++ b/components/script/script_thread.rs @@ -27,7 +27,7 @@ use dom::bindings::codegen::Bindings::DocumentBinding::{DocumentMethods, Documen use dom::bindings::codegen::Bindings::LocationBinding::LocationMethods; use dom::bindings::codegen::Bindings::WindowBinding::WindowMethods; use dom::bindings::conversions::{ConversionResult, FromJSValConvertible, StringificationBehavior}; -use dom::bindings::global::{GlobalRef, GlobalRoot}; +use dom::bindings::global::GlobalRoot; use dom::bindings::inheritance::Castable; use dom::bindings::js::{JS, MutNullableHeap, Root, RootCollection}; use dom::bindings::js::{RootCollectionPtr, RootedReference}; @@ -2173,10 +2173,10 @@ impl ScriptThread { } } - pub fn enqueue_promise_job(job: EnqueuedPromiseCallback, global: GlobalRef) { + pub fn enqueue_promise_job(job: EnqueuedPromiseCallback, global: &GlobalScope) { SCRIPT_THREAD_ROOT.with(|root| { let script_thread = unsafe { &*root.get().unwrap() }; - script_thread.promise_job_queue.enqueue(job, global.as_global_scope()); + script_thread.promise_job_queue.enqueue(job, global); }); } From 1fed45e393781a6d550c1e2de89a3fcc6b3d05d8 Mon Sep 17 00:00:00 2001 From: Anthony Ramine Date: Tue, 4 Oct 2016 16:25:44 +0200 Subject: [PATCH 52/66] Use global_scope_from_object in Window::global_is_mozbrowser --- components/script/dom/window.rs | 9 ++++----- 1 file changed, 4 insertions(+), 5 deletions(-) diff --git a/components/script/dom/window.rs b/components/script/dom/window.rs index 5f5b0bda04a..38b08e0ba25 100644 --- a/components/script/dom/window.rs +++ b/components/script/dom/window.rs @@ -17,7 +17,7 @@ use dom::bindings::codegen::Bindings::WindowBinding::{self, FrameRequestCallback use dom::bindings::codegen::Bindings::WindowBinding::{ScrollBehavior, ScrollToOptions}; use dom::bindings::codegen::UnionTypes::RequestOrUSVString; use dom::bindings::error::{Error, ErrorResult, Fallible}; -use dom::bindings::global::{GlobalRef, global_root_from_object}; +use dom::bindings::global::global_scope_from_object; use dom::bindings::inheritance::Castable; use dom::bindings::js::{JS, MutNullableHeap, Root}; use dom::bindings::num::Finite; @@ -1496,10 +1496,9 @@ impl Window { /// in a top-level `Window` global. #[allow(unsafe_code)] pub unsafe fn global_is_mozbrowser(_: *mut JSContext, obj: HandleObject) -> bool { - match global_root_from_object(obj.get()).r() { - GlobalRef::Window(window) => window.is_mozbrowser(), - _ => false, - } + global_scope_from_object(obj.get()) + .downcast::() + .map_or(false, |window| window.is_mozbrowser()) } #[allow(unsafe_code)] From 26455b8a67771ff82ce70f21b131d452518e0c50 Mon Sep 17 00:00:00 2001 From: Anthony Ramine Date: Wed, 5 Oct 2016 01:01:22 +0200 Subject: [PATCH 53/66] Remove global_root_from_reflector --- components/script/dom/bindings/callback.rs | 6 +++--- components/script/dom/bindings/codegen/CodegenRust.py | 1 - components/script/dom/bindings/global.rs | 5 ----- components/script/dom/bindings/reflector.rs | 4 ++-- 4 files changed, 5 insertions(+), 11 deletions(-) diff --git a/components/script/dom/bindings/callback.rs b/components/script/dom/bindings/callback.rs index 7e6bb3534fb..c9fb9fd8a53 100644 --- a/components/script/dom/bindings/callback.rs +++ b/components/script/dom/bindings/callback.rs @@ -5,7 +5,7 @@ //! Base classes to work with IDL callbacks. use dom::bindings::error::{Error, Fallible, report_pending_exception}; -use dom::bindings::global::global_root_from_object; +use dom::bindings::global::global_scope_from_object; use dom::bindings::reflector::Reflectable; use js::jsapi::{Heap, MutableHandleObject, RootedObject}; use js::jsapi::{IsCallable, JSContext, JSObject, JS_WrapObject}; @@ -165,8 +165,8 @@ impl<'a> CallSetup<'a> { callback: &T, handling: ExceptionHandling) -> CallSetup<'a> { - let global = unsafe { global_root_from_object(callback.callback()) }; - let cx = global.r().get_cx(); + let global = unsafe { global_scope_from_object(callback.callback()) }; + let cx = global.get_cx(); exception_compartment.ptr = unsafe { GetGlobalForObjectCrossCompartment(callback.callback()) diff --git a/components/script/dom/bindings/codegen/CodegenRust.py b/components/script/dom/bindings/codegen/CodegenRust.py index 8a2ea4ed2c3..e85865ed143 100644 --- a/components/script/dom/bindings/codegen/CodegenRust.py +++ b/components/script/dom/bindings/codegen/CodegenRust.py @@ -5502,7 +5502,6 @@ def generate_imports(config, cgthings, descriptors, callbacks=None, dictionaries 'dom::bindings::global::GlobalRef', 'dom::bindings::global::global_root_from_object', 'dom::bindings::global::global_root_from_object_maybe_wrapped', - 'dom::bindings::global::global_root_from_reflector', 'dom::bindings::global::global_scope_from_reflector', 'dom::bindings::interface::ConstructorClassHook', 'dom::bindings::interface::InterfaceConstructorBehavior', diff --git a/components/script/dom/bindings/global.rs b/components/script/dom/bindings/global.rs index 0cbb3ec302b..2c4fa189ce6 100644 --- a/components/script/dom/bindings/global.rs +++ b/components/script/dom/bindings/global.rs @@ -111,11 +111,6 @@ pub fn global_scope_from_reflector(reflector: &T) -> Root(reflector: &T) -> GlobalRoot { - unsafe { global_root_from_object(*reflector.reflector().get_jsobject()) } -} - /// Returns the Rust global scope from a JS global object. unsafe fn global_scope_from_global(global: *mut JSObject) -> Root { assert!(!global.is_null()); diff --git a/components/script/dom/bindings/reflector.rs b/components/script/dom/bindings/reflector.rs index bb48cee0b1a..946c31ca290 100644 --- a/components/script/dom/bindings/reflector.rs +++ b/components/script/dom/bindings/reflector.rs @@ -5,7 +5,7 @@ //! The `Reflector` struct. use dom::bindings::conversions::DerivedFrom; -use dom::bindings::global::{GlobalRoot, global_root_from_reflector, global_scope_from_reflector}; +use dom::bindings::global::{GlobalRoot, global_root_from_object, global_scope_from_reflector}; use dom::bindings::js::Root; use dom::globalscope::GlobalScope; use js::jsapi::{HandleObject, JSContext, JSObject}; @@ -87,7 +87,7 @@ pub trait Reflectable { /// Returns the global object of the realm that the Reflectable was created in. fn global(&self) -> GlobalRoot where Self: Sized { - global_root_from_reflector(self) + unsafe { global_root_from_object(*self.reflector().get_jsobject()) } } } From 02d38e74e90dd06f9083731a5101ad6b05be20dc Mon Sep 17 00:00:00 2001 From: Anthony Ramine Date: Wed, 5 Oct 2016 01:14:46 +0200 Subject: [PATCH 54/66] Make Promise::Reject and Resolve take a &GlobalScope --- components/script/dom/bindings/codegen/CodegenRust.py | 8 ++++---- components/script/dom/bindings/global.rs | 6 ++++-- components/script/dom/promise.rs | 5 ++--- components/script/dom/testbinding.rs | 4 ++-- 4 files changed, 12 insertions(+), 11 deletions(-) diff --git a/components/script/dom/bindings/codegen/CodegenRust.py b/components/script/dom/bindings/codegen/CodegenRust.py index e85865ed143..b5baf961c57 100644 --- a/components/script/dom/bindings/codegen/CodegenRust.py +++ b/components/script/dom/bindings/codegen/CodegenRust.py @@ -817,16 +817,16 @@ def getJSToNativeConversionInfo(type, descriptorProvider, failureCode=None, { // Scope for our JSAutoCompartment. rooted!(in(cx) let globalObj = CurrentGlobalOrNull(cx)); - let promiseGlobal = global_root_from_object_maybe_wrapped(globalObj.handle().get()); + let promiseGlobal = global_scope_from_object_maybe_wrapped(globalObj.handle().get()); rooted!(in(cx) let mut valueToResolve = $${val}.get()); if !JS_WrapValue(cx, valueToResolve.handle_mut()) { $*{exceptionCode} } - match Promise::Resolve(promiseGlobal.r(), cx, valueToResolve.handle()) { + match Promise::Resolve(&promiseGlobal, cx, valueToResolve.handle()) { Ok(value) => value, Err(error) => { - throw_dom_exception(cx, promiseGlobal.r().as_global_scope(), error); + throw_dom_exception(cx, &promiseGlobal, error); $*{exceptionCode} } } @@ -5501,7 +5501,7 @@ def generate_imports(config, cgthings, descriptors, callbacks=None, dictionaries 'dom::bindings::constant::ConstantVal', 'dom::bindings::global::GlobalRef', 'dom::bindings::global::global_root_from_object', - 'dom::bindings::global::global_root_from_object_maybe_wrapped', + 'dom::bindings::global::global_scope_from_object_maybe_wrapped', 'dom::bindings::global::global_scope_from_reflector', 'dom::bindings::interface::ConstructorClassHook', 'dom::bindings::interface::InterfaceConstructorBehavior', diff --git a/components/script/dom/bindings/global.rs b/components/script/dom/bindings/global.rs index 2c4fa189ce6..d2b693dbf08 100644 --- a/components/script/dom/bindings/global.rs +++ b/components/script/dom/bindings/global.rs @@ -163,10 +163,12 @@ pub unsafe fn global_root_from_context(cx: *mut JSContext) -> GlobalRoot { /// Returns the global object of the realm that the given JS object was created in, /// after unwrapping any wrappers. -pub unsafe fn global_root_from_object_maybe_wrapped(mut obj: *mut JSObject) -> GlobalRoot { +pub unsafe fn global_scope_from_object_maybe_wrapped( + mut obj: *mut JSObject) + -> Root { if IsWrapper(obj) { obj = UnwrapObject(obj, /* stopAtWindowProxy = */ 0); assert!(!obj.is_null()); } - global_root_from_object(obj) + global_scope_from_object(obj) } diff --git a/components/script/dom/promise.rs b/components/script/dom/promise.rs index fe63cff9b94..14f53bf8466 100644 --- a/components/script/dom/promise.rs +++ b/components/script/dom/promise.rs @@ -15,7 +15,6 @@ use dom::bindings::callback::CallbackContainer; use dom::bindings::codegen::Bindings::PromiseBinding::AnyCallback; use dom::bindings::conversions::root_from_object; use dom::bindings::error::{Error, Fallible}; -use dom::bindings::global::GlobalRef; use dom::bindings::js::MutHeapJSVal; use dom::bindings::reflector::{Reflectable, MutReflectable, Reflector}; use dom::globalscope::GlobalScope; @@ -113,7 +112,7 @@ impl Promise { } #[allow(unrooted_must_root, unsafe_code)] - pub fn Resolve(global: GlobalRef, + pub fn Resolve(global: &GlobalScope, cx: *mut JSContext, value: HandleValue) -> Fallible> { let _ac = JSAutoCompartment::new(cx, global.reflector().get_jsobject().get()); @@ -125,7 +124,7 @@ impl Promise { } #[allow(unrooted_must_root, unsafe_code)] - pub fn Reject(global: GlobalRef, + pub fn Reject(global: &GlobalScope, cx: *mut JSContext, value: HandleValue) -> Fallible> { let _ac = JSAutoCompartment::new(cx, global.reflector().get_jsobject().get()); diff --git a/components/script/dom/testbinding.rs b/components/script/dom/testbinding.rs index bc7c5643533..8362daa0d12 100644 --- a/components/script/dom/testbinding.rs +++ b/components/script/dom/testbinding.rs @@ -656,12 +656,12 @@ impl TestBindingMethods for TestBinding { #[allow(unrooted_must_root)] fn ReturnResolvedPromise(&self, cx: *mut JSContext, v: HandleValue) -> Fallible> { - Promise::Resolve(self.global().r(), cx, v) + Promise::Resolve(&self.global_scope(), cx, v) } #[allow(unrooted_must_root)] fn ReturnRejectedPromise(&self, cx: *mut JSContext, v: HandleValue) -> Fallible> { - Promise::Reject(self.global().r(), cx, v) + Promise::Reject(&self.global_scope(), cx, v) } fn PromiseResolveNative(&self, cx: *mut JSContext, p: &Promise, v: HandleValue) { From 144dc6257517a81fc96d3783b83fe0c82d502a36 Mon Sep 17 00:00:00 2001 From: Anthony Ramine Date: Wed, 5 Oct 2016 01:25:58 +0200 Subject: [PATCH 55/66] Do not use GlobalRoot in CodegenRust anymore --- .../script/dom/bindings/codegen/CodegenRust.py | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/components/script/dom/bindings/codegen/CodegenRust.py b/components/script/dom/bindings/codegen/CodegenRust.py index b5baf961c57..46285bcf406 100644 --- a/components/script/dom/bindings/codegen/CodegenRust.py +++ b/components/script/dom/bindings/codegen/CodegenRust.py @@ -3168,7 +3168,7 @@ class CGCallGenerator(CGThing): if isFallible: if static: - glob = "global.r().as_global_scope()" + glob = "&global" else: glob = "&global_scope_from_reflector(this)" @@ -3386,7 +3386,7 @@ class CGAbstractStaticBindingMethod(CGAbstractMethod): def definition_body(self): preamble = CGGeneric("""\ -let global = global_root_from_object(JS_CALLEE(cx, vp).to_object()); +let global = global_scope_from_object(JS_CALLEE(cx, vp).to_object()); """) return CGList([preamble, self.generate_code()]) @@ -3438,7 +3438,7 @@ class CGStaticMethod(CGAbstractStaticBindingMethod): nativeName = CGSpecializedMethod.makeNativeName(self.descriptor, self.method) setupArgs = CGGeneric("let args = CallArgs::from_vp(vp, argc);\n") - call = CGMethodCall(["global.r().as_global_scope()"], nativeName, True, self.descriptor, self.method) + call = CGMethodCall(["&global"], nativeName, True, self.descriptor, self.method) return CGList([setupArgs, call]) @@ -3492,7 +3492,7 @@ class CGStaticGetter(CGAbstractStaticBindingMethod): nativeName = CGSpecializedGetter.makeNativeName(self.descriptor, self.attr) setupArgs = CGGeneric("let args = CallArgs::from_vp(vp, argc);\n") - call = CGGetterCall(["global.r().as_global_scope()"], self.attr.type, nativeName, self.descriptor, + call = CGGetterCall(["&global"], self.attr.type, nativeName, self.descriptor, self.attr) return CGList([setupArgs, call]) @@ -3545,7 +3545,7 @@ class CGStaticSetter(CGAbstractStaticBindingMethod): " throw_type_error(cx, \"Not enough arguments to %s setter.\");\n" " return false;\n" "}" % self.attr.identifier.name) - call = CGSetterCall(["global.r().as_global_scope()"], self.attr.type, nativeName, self.descriptor, + call = CGSetterCall(["&global"], self.attr.type, nativeName, self.descriptor, self.attr) return CGList([checkForArg, call]) @@ -5252,12 +5252,12 @@ class CGClassConstructHook(CGAbstractExternMethod): def definition_body(self): preamble = CGGeneric("""\ -let global = global_root_from_object(JS_CALLEE(cx, vp).to_object()); +let global = global_scope_from_object(JS_CALLEE(cx, vp).to_object()); let args = CallArgs::from_vp(vp, argc); """) name = self.constructor.identifier.name nativeName = MakeNativeName(self.descriptor.binaryNameFor(name)) - callGenerator = CGMethodCall(["global.r().as_global_scope()"], nativeName, True, + callGenerator = CGMethodCall(["&global"], nativeName, True, self.descriptor, self.constructor) return CGList([preamble, callGenerator]) @@ -5500,9 +5500,9 @@ def generate_imports(config, cgthings, descriptors, callbacks=None, dictionaries 'dom::bindings::constant::ConstantSpec', 'dom::bindings::constant::ConstantVal', 'dom::bindings::global::GlobalRef', - 'dom::bindings::global::global_root_from_object', 'dom::bindings::global::global_scope_from_object_maybe_wrapped', 'dom::bindings::global::global_scope_from_reflector', + 'dom::bindings::global::global_scope_from_object', 'dom::bindings::interface::ConstructorClassHook', 'dom::bindings::interface::InterfaceConstructorBehavior', 'dom::bindings::interface::NonCallbackInterfaceObjectClass', From 1f8bb3a89f50f4edf5d37f6d7c4c9d1480876753 Mon Sep 17 00:00:00 2001 From: Anthony Ramine Date: Wed, 5 Oct 2016 01:48:25 +0200 Subject: [PATCH 56/66] Make Fetch take a &GlobalScope --- components/script/dom/window.rs | 2 +- components/script/dom/workerglobalscope.rs | 2 +- components/script/fetch.rs | 17 ++++++++--------- 3 files changed, 10 insertions(+), 11 deletions(-) diff --git a/components/script/dom/window.rs b/components/script/dom/window.rs index 38b08e0ba25..e1f47cc8163 100644 --- a/components/script/dom/window.rs +++ b/components/script/dom/window.rs @@ -861,7 +861,7 @@ impl WindowMethods for Window { #[allow(unrooted_must_root)] // https://fetch.spec.whatwg.org/#fetch-method fn Fetch(&self, input: RequestOrUSVString, init: &RequestInit) -> Rc { - fetch::Fetch(self.global().r(), input, init) + fetch::Fetch(&self.upcast(), input, init) } } diff --git a/components/script/dom/workerglobalscope.rs b/components/script/dom/workerglobalscope.rs index 93370debc9f..042f2b3d1e3 100644 --- a/components/script/dom/workerglobalscope.rs +++ b/components/script/dom/workerglobalscope.rs @@ -319,7 +319,7 @@ impl WorkerGlobalScopeMethods for WorkerGlobalScope { #[allow(unrooted_must_root)] // https://fetch.spec.whatwg.org/#fetch-method fn Fetch(&self, input: RequestOrUSVString, init: &RequestInit) -> Rc { - fetch::Fetch(self.global().r(), input, init) + fetch::Fetch(self.upcast(), input, init) } } diff --git a/components/script/fetch.rs b/components/script/fetch.rs index f7398ca1d30..1b2d5e77be9 100644 --- a/components/script/fetch.rs +++ b/components/script/fetch.rs @@ -7,10 +7,10 @@ use dom::bindings::codegen::Bindings::ResponseBinding::ResponseBinding::Response use dom::bindings::codegen::Bindings::ResponseBinding::ResponseType as DOMResponseType; use dom::bindings::codegen::UnionTypes::RequestOrUSVString; use dom::bindings::error::Error; -use dom::bindings::global::GlobalRef; use dom::bindings::js::Root; use dom::bindings::refcounted::{Trusted, TrustedPromise}; use dom::bindings::reflector::Reflectable; +use dom::globalscope::GlobalScope; use dom::headers::Guard; use dom::promise::Promise; use dom::request::Request; @@ -66,18 +66,17 @@ fn request_init_from_request(request: NetTraitsRequest) -> NetTraitsRequestInit // https://fetch.spec.whatwg.org/#fetch-method #[allow(unrooted_must_root)] -pub fn Fetch(global: GlobalRef, input: RequestOrUSVString, init: &RequestInit) -> Rc { - let global_scope = global.as_global_scope(); - let core_resource_thread = global_scope.core_resource_thread(); +pub fn Fetch(global: &GlobalScope, input: RequestOrUSVString, init: &RequestInit) -> Rc { + let core_resource_thread = global.core_resource_thread(); // Step 1 - let promise = Promise::new(global_scope); - let response = Response::new(global_scope); + let promise = Promise::new(global); + let response = Response::new(global); // Step 2 - let request = match Request::Constructor(global_scope, input, init) { + let request = match Request::Constructor(global, input, init) { Err(e) => { - promise.reject_error(promise.global().r().get_cx(), e); + promise.reject_error(promise.global_scope().get_cx(), e); return promise; }, Ok(r) => r.get_request(), @@ -96,7 +95,7 @@ pub fn Fetch(global: GlobalRef, input: RequestOrUSVString, init: &RequestInit) - })); let listener = NetworkListener { context: fetch_context, - script_chan: global_scope.networking_task_source(), + script_chan: global.networking_task_source(), wrapper: None, }; From cdf3ef05e78b3947cc7f29240106982f1c45d96b Mon Sep 17 00:00:00 2001 From: Anthony Ramine Date: Wed, 5 Oct 2016 09:40:04 +0200 Subject: [PATCH 57/66] Introduce GlobalScope::new_script_pair --- components/script/dom/bindings/global.rs | 12 +----------- components/script/dom/globalscope.rs | 16 +++++++++++++++- components/script/dom/xmlhttprequest.rs | 2 +- 3 files changed, 17 insertions(+), 13 deletions(-) diff --git a/components/script/dom/bindings/global.rs b/components/script/dom/bindings/global.rs index d2b693dbf08..26d7c061503 100644 --- a/components/script/dom/bindings/global.rs +++ b/components/script/dom/bindings/global.rs @@ -18,7 +18,7 @@ use js::{JSCLASS_IS_DOMJSCLASS, JSCLASS_IS_GLOBAL}; use js::glue::{IsWrapper, UnwrapObject}; use js::jsapi::{CurrentGlobalOrNull, GetGlobalForObjectCrossCompartment}; use js::jsapi::{JSContext, JSObject, JS_GetClass}; -use script_runtime::{CommonScriptMsg, ScriptChan, ScriptPort}; +use script_runtime::CommonScriptMsg; use script_thread::ScriptThread; use task_source::file_reading::FileReadingTaskSource; @@ -66,16 +66,6 @@ impl<'a> GlobalRef<'a> { } } - /// Create a new sender/receiver pair that can be used to implement an on-demand - /// event loop. Used for implementing web APIs that require blocking semantics - /// without resorting to nested event loops. - pub fn new_script_pair(&self) -> (Box, Box) { - match *self { - GlobalRef::Window(ref window) => window.new_script_pair(), - GlobalRef::Worker(ref worker) => worker.new_script_pair(), - } - } - /// Process a single event as if it were the next event in the thread queue for /// this global. pub fn process_event(&self, msg: CommonScriptMsg) { diff --git a/components/script/dom/globalscope.rs b/components/script/dom/globalscope.rs index cd8fca9a0e4..0b3b609d54b 100644 --- a/components/script/dom/globalscope.rs +++ b/components/script/dom/globalscope.rs @@ -26,7 +26,8 @@ use libc; use msg::constellation_msg::PipelineId; use net_traits::{CoreResourceThread, ResourceThreads, IpcSend}; use profile_traits::{mem, time}; -use script_runtime::{EnqueuedPromiseCallback, ScriptChan, maybe_take_panic_result}; +use script_runtime::{EnqueuedPromiseCallback, ScriptChan}; +use script_runtime::{ScriptPort, maybe_take_panic_result}; use script_thread::{MainThreadScriptChan, RunnableWrapper, ScriptThread}; use script_traits::{MsDuration, ScriptMsg as ConstellationMsg, TimerEvent}; use script_traits::{TimerEventId, TimerEventRequest, TimerSource}; @@ -431,6 +432,19 @@ impl GlobalScope { } unreachable!(); } + + /// Create a new sender/receiver pair that can be used to implement an on-demand + /// event loop. Used for implementing web APIs that require blocking semantics + /// without resorting to nested event loops. + pub fn new_script_pair(&self) -> (Box, Box) { + if let Some(window) = self.downcast::() { + return window.new_script_pair(); + } + if let Some(worker) = self.downcast::() { + return worker.new_script_pair(); + } + unreachable!(); + } } fn timestamp_in_ms(time: Timespec) -> u64 { diff --git a/components/script/dom/xmlhttprequest.rs b/components/script/dom/xmlhttprequest.rs index 7a586cfe6a1..e8254be3e70 100644 --- a/components/script/dom/xmlhttprequest.rs +++ b/components/script/dom/xmlhttprequest.rs @@ -1297,7 +1297,7 @@ impl XMLHttpRequest { let global_scope = global.as_global_scope(); let (script_chan, script_port) = if self.sync.get() { - let (tx, rx) = global.new_script_pair(); + let (tx, rx) = global_scope.new_script_pair(); (tx, Some(rx)) } else { (global_scope.networking_task_source(), None) From ca15dd5eeabf49a69207c69db939cc419c69bbf2 Mon Sep 17 00:00:00 2001 From: Anthony Ramine Date: Wed, 5 Oct 2016 09:44:11 +0200 Subject: [PATCH 58/66] Introduce GlobalScope::process_event --- components/script/dom/bindings/global.rs | 11 ----------- components/script/dom/globalscope.rs | 14 +++++++++++++- components/script/dom/xmlhttprequest.rs | 2 +- 3 files changed, 14 insertions(+), 13 deletions(-) diff --git a/components/script/dom/bindings/global.rs b/components/script/dom/bindings/global.rs index 26d7c061503..051a28439bd 100644 --- a/components/script/dom/bindings/global.rs +++ b/components/script/dom/bindings/global.rs @@ -18,8 +18,6 @@ use js::{JSCLASS_IS_DOMJSCLASS, JSCLASS_IS_GLOBAL}; use js::glue::{IsWrapper, UnwrapObject}; use js::jsapi::{CurrentGlobalOrNull, GetGlobalForObjectCrossCompartment}; use js::jsapi::{JSContext, JSObject, JS_GetClass}; -use script_runtime::CommonScriptMsg; -use script_thread::ScriptThread; use task_source::file_reading::FileReadingTaskSource; /// A freely-copyable reference to a rooted global object. @@ -65,15 +63,6 @@ impl<'a> GlobalRef<'a> { GlobalRef::Worker(ref worker) => worker.file_reading_task_source(), } } - - /// Process a single event as if it were the next event in the thread queue for - /// this global. - pub fn process_event(&self, msg: CommonScriptMsg) { - match *self { - GlobalRef::Window(_) => ScriptThread::process_event(msg), - GlobalRef::Worker(ref worker) => worker.process_event(msg), - } - } } impl<'a> Reflectable for GlobalRef<'a> { diff --git a/components/script/dom/globalscope.rs b/components/script/dom/globalscope.rs index 0b3b609d54b..fd5046c64c6 100644 --- a/components/script/dom/globalscope.rs +++ b/components/script/dom/globalscope.rs @@ -26,7 +26,7 @@ use libc; use msg::constellation_msg::PipelineId; use net_traits::{CoreResourceThread, ResourceThreads, IpcSend}; use profile_traits::{mem, time}; -use script_runtime::{EnqueuedPromiseCallback, ScriptChan}; +use script_runtime::{CommonScriptMsg, EnqueuedPromiseCallback, ScriptChan}; use script_runtime::{ScriptPort, maybe_take_panic_result}; use script_thread::{MainThreadScriptChan, RunnableWrapper, ScriptThread}; use script_traits::{MsDuration, ScriptMsg as ConstellationMsg, TimerEvent}; @@ -445,6 +445,18 @@ impl GlobalScope { } unreachable!(); } + + /// Process a single event as if it were the next event + /// in the thread queue for this global scope. + pub fn process_event(&self, msg: CommonScriptMsg) { + if self.is::() { + return ScriptThread::process_event(msg); + } + if let Some(worker) = self.downcast::() { + return worker.process_event(msg); + } + unreachable!(); + } } fn timestamp_in_ms(time: Timespec) -> u64 { diff --git a/components/script/dom/xmlhttprequest.rs b/components/script/dom/xmlhttprequest.rs index e8254be3e70..4429ec71380 100644 --- a/components/script/dom/xmlhttprequest.rs +++ b/components/script/dom/xmlhttprequest.rs @@ -1309,7 +1309,7 @@ impl XMLHttpRequest { if let Some(script_port) = script_port { loop { - global.process_event(script_port.recv().unwrap()); + global_scope.process_event(script_port.recv().unwrap()); let context = context.lock().unwrap(); let sync_status = context.sync_status.borrow(); if let Some(ref status) = *sync_status { From 0a11c48e89dfc839319a7cb2bd9ba06df5251f57 Mon Sep 17 00:00:00 2001 From: Anthony Ramine Date: Wed, 5 Oct 2016 09:46:53 +0200 Subject: [PATCH 59/66] Make XMLHttpRequest::fetch take a &GlobalScope --- components/script/dom/xmlhttprequest.rs | 14 ++++++-------- 1 file changed, 6 insertions(+), 8 deletions(-) diff --git a/components/script/dom/xmlhttprequest.rs b/components/script/dom/xmlhttprequest.rs index 4429ec71380..9b0cbeeb580 100644 --- a/components/script/dom/xmlhttprequest.rs +++ b/components/script/dom/xmlhttprequest.rs @@ -13,7 +13,6 @@ use dom::bindings::codegen::Bindings::XMLHttpRequestBinding::XMLHttpRequestMetho use dom::bindings::codegen::Bindings::XMLHttpRequestBinding::XMLHttpRequestResponseType; use dom::bindings::conversions::ToJSValConvertible; use dom::bindings::error::{Error, ErrorResult, Fallible}; -use dom::bindings::global::GlobalRef; use dom::bindings::inheritance::Castable; use dom::bindings::js::{JS, MutHeapJSVal, MutNullableHeap}; use dom::bindings::js::{Root, RootedReference}; @@ -650,7 +649,7 @@ impl XMLHttpRequestMethods for XMLHttpRequest { self.fetch_time.set(time::now().to_timespec().sec); - let rv = self.fetch(request, self.global().r()); + let rv = self.fetch(request, &self.global_scope()); // Step 10 if self.sync.get() { return rv; @@ -1285,7 +1284,7 @@ impl XMLHttpRequest { fn fetch(&self, init: RequestInit, - global: GlobalRef) -> ErrorResult { + global: &GlobalScope) -> ErrorResult { let xhr = Trusted::new(self); let context = Arc::new(Mutex::new(XHRContext { @@ -1295,21 +1294,20 @@ impl XMLHttpRequest { sync_status: DOMRefCell::new(None), })); - let global_scope = global.as_global_scope(); let (script_chan, script_port) = if self.sync.get() { - let (tx, rx) = global_scope.new_script_pair(); + let (tx, rx) = global.new_script_pair(); (tx, Some(rx)) } else { - (global_scope.networking_task_source(), None) + (global.networking_task_source(), None) }; - let core_resource_thread = global_scope.core_resource_thread(); + let core_resource_thread = global.core_resource_thread(); XMLHttpRequest::initiate_async_xhr(context.clone(), script_chan, core_resource_thread, init); if let Some(script_port) = script_port { loop { - global_scope.process_event(script_port.recv().unwrap()); + global.process_event(script_port.recv().unwrap()); let context = context.lock().unwrap(); let sync_status = context.sync_status.borrow(); if let Some(ref status) = *sync_status { From e7a1149984a4d249efb603c16007ab3100abd444 Mon Sep 17 00:00:00 2001 From: Anthony Ramine Date: Wed, 5 Oct 2016 09:52:30 +0200 Subject: [PATCH 60/66] Introduce GlobalScope::file_reading_task_source --- components/script/dom/bindings/global.rs | 10 ---------- components/script/dom/filereader.rs | 7 ++++--- components/script/dom/globalscope.rs | 13 +++++++++++++ 3 files changed, 17 insertions(+), 13 deletions(-) diff --git a/components/script/dom/bindings/global.rs b/components/script/dom/bindings/global.rs index 051a28439bd..e62573b5a9a 100644 --- a/components/script/dom/bindings/global.rs +++ b/components/script/dom/bindings/global.rs @@ -18,7 +18,6 @@ use js::{JSCLASS_IS_DOMJSCLASS, JSCLASS_IS_GLOBAL}; use js::glue::{IsWrapper, UnwrapObject}; use js::jsapi::{CurrentGlobalOrNull, GetGlobalForObjectCrossCompartment}; use js::jsapi::{JSContext, JSObject, JS_GetClass}; -use task_source::file_reading::FileReadingTaskSource; /// A freely-copyable reference to a rooted global object. #[derive(Copy, Clone)] @@ -54,15 +53,6 @@ impl<'a> GlobalRef<'a> { GlobalRef::Worker(ref worker) => worker.get_cx(), } } - - /// `ScriptChan` used to send messages to the event loop of this global's - /// thread. - pub fn file_reading_task_source(&self) -> FileReadingTaskSource { - match *self { - GlobalRef::Window(ref window) => window.file_reading_task_source(), - GlobalRef::Worker(ref worker) => worker.file_reading_task_source(), - } - } } impl<'a> Reflectable for GlobalRef<'a> { diff --git a/components/script/dom/filereader.rs b/components/script/dom/filereader.rs index ebfb5060a58..2872aa2d325 100644 --- a/components/script/dom/filereader.rs +++ b/components/script/dom/filereader.rs @@ -333,8 +333,9 @@ impl FileReader { return Err(Error::InvalidState); } // Step 2 + let global = self.global_scope(); if blob.IsClosed() { - let exception = DOMException::new(&self.global_scope(), DOMErrorName::InvalidStateError); + let exception = DOMException::new(&global, DOMErrorName::InvalidStateError); self.error.set(Some(&exception)); self.dispatch_progress_event(atom!("error"), 0, None); @@ -354,8 +355,8 @@ impl FileReader { let fr = Trusted::new(self); let gen_id = self.generation_id.get(); - let wrapper = self.global_scope().get_runnable_wrapper(); - let task_source = self.global().r().file_reading_task_source(); + let wrapper = global.get_runnable_wrapper(); + let task_source = global.file_reading_task_source(); spawn_named("file reader async operation".to_owned(), move || { perform_annotated_read_operation(gen_id, load_data, blob_contents, fr, task_source, wrapper) diff --git a/components/script/dom/globalscope.rs b/components/script/dom/globalscope.rs index fd5046c64c6..553393e3195 100644 --- a/components/script/dom/globalscope.rs +++ b/components/script/dom/globalscope.rs @@ -36,6 +36,7 @@ use std::collections::HashMap; use std::collections::hash_map::Entry; use std::ffi::CString; use std::panic; +use task_source::file_reading::FileReadingTaskSource; use time::{Timespec, get_time}; use timers::{IsInterval, OneshotTimerCallback, OneshotTimerHandle}; use timers::{OneshotTimers, TimerCallback}; @@ -457,6 +458,18 @@ impl GlobalScope { } unreachable!(); } + + /// Channel to send messages to the file reading task source of + /// this of this global scope. + pub fn file_reading_task_source(&self) -> FileReadingTaskSource { + if let Some(window) = self.downcast::() { + return window.file_reading_task_source(); + } + if let Some(worker) = self.downcast::() { + return worker.file_reading_task_source(); + } + unreachable!(); + } } fn timestamp_in_ms(time: Timespec) -> u64 { From 907781eb75b06bd11cccb2c3694ab5ce62bc548a Mon Sep 17 00:00:00 2001 From: Anthony Ramine Date: Wed, 5 Oct 2016 09:56:57 +0200 Subject: [PATCH 61/66] Remove Reflectable::global --- components/script/body.rs | 4 ++-- components/script/dom/bindings/reflector.rs | 7 +------ components/script/dom/bluetooth.rs | 4 ++-- components/script/dom/eventtarget.rs | 6 ++---- components/script/dom/filereader.rs | 1 + components/script/dom/promise.rs | 7 +++---- components/script/dom/testbinding.rs | 4 ++-- components/script/fetch.rs | 4 ++-- 8 files changed, 15 insertions(+), 22 deletions(-) diff --git a/components/script/body.rs b/components/script/body.rs index ade32161549..9ae98e8f43b 100644 --- a/components/script/body.rs +++ b/components/script/body.rs @@ -46,7 +46,7 @@ pub fn consume_body(object: &T, body_type: Body // Step 1 if object.get_body_used() || object.is_locked() { - promise.reject_error(promise.global().r().get_cx(), Error::Type( + promise.reject_error(promise.global_scope().get_cx(), Error::Type( "The response's stream is disturbed or locked".to_string())); return promise; } @@ -77,7 +77,7 @@ pub fn consume_body_with_promise(object: &T, body_type, object.get_mime_type()); - let cx = promise.global().r().get_cx(); + let cx = promise.global_scope().get_cx(); match pkg_data_results { Ok(results) => { match results { diff --git a/components/script/dom/bindings/reflector.rs b/components/script/dom/bindings/reflector.rs index 946c31ca290..580e3fa6fae 100644 --- a/components/script/dom/bindings/reflector.rs +++ b/components/script/dom/bindings/reflector.rs @@ -5,7 +5,7 @@ //! The `Reflector` struct. use dom::bindings::conversions::DerivedFrom; -use dom::bindings::global::{GlobalRoot, global_root_from_object, global_scope_from_reflector}; +use dom::bindings::global::global_scope_from_reflector; use dom::bindings::js::Root; use dom::globalscope::GlobalScope; use js::jsapi::{HandleObject, JSContext, JSObject}; @@ -84,11 +84,6 @@ pub trait Reflectable { fn global_scope(&self) -> Root where Self: Sized { global_scope_from_reflector(self) } - - /// Returns the global object of the realm that the Reflectable was created in. - fn global(&self) -> GlobalRoot where Self: Sized { - unsafe { global_root_from_object(*self.reflector().get_jsobject()) } - } } /// A trait to initialize the `Reflector` for a DOM object. diff --git a/components/script/dom/bluetooth.rs b/components/script/dom/bluetooth.rs index a0e5484abd3..bac83de3023 100644 --- a/components/script/dom/bluetooth.rs +++ b/components/script/dom/bluetooth.rs @@ -275,8 +275,8 @@ pub fn result_to_promise(global: &GlobalScope, -> Rc { let p = Promise::new(global); match bluetooth_result { - Ok(v) => p.resolve_native(p.global().r().get_cx(), &v), - Err(e) => p.reject_error(p.global().r().get_cx(), e), + Ok(v) => p.resolve_native(p.global_scope().get_cx(), &v), + Err(e) => p.reject_error(p.global_scope().get_cx(), e), } p } diff --git a/components/script/dom/eventtarget.rs b/components/script/dom/eventtarget.rs index af13822c456..b86e0991ccf 100644 --- a/components/script/dom/eventtarget.rs +++ b/components/script/dom/eventtarget.rs @@ -154,8 +154,7 @@ impl CompiledEventListener { match *handler { CommonEventHandler::ErrorEventHandler(ref handler) => { if let Some(event) = event.downcast::() { - let global = object.global(); - let cx = global.r().get_cx(); + let cx = object.global_scope().get_cx(); rooted!(in(cx) let error = event.Error(cx)); let return_value = handler.Call_(object, EventOrString::String(event.Message()), @@ -201,8 +200,7 @@ impl CompiledEventListener { CommonEventHandler::EventHandler(ref handler) => { if let Ok(value) = handler.Call_(object, event, exception_handle) { - let global = object.global(); - let cx = global.r().get_cx(); + let cx = object.global_scope().get_cx(); rooted!(in(cx) let value = value); let value = value.handle(); diff --git a/components/script/dom/filereader.rs b/components/script/dom/filereader.rs index 2872aa2d325..b6d1e5cf216 100644 --- a/components/script/dom/filereader.rs +++ b/components/script/dom/filereader.rs @@ -355,6 +355,7 @@ impl FileReader { let fr = Trusted::new(self); let gen_id = self.generation_id.get(); + let global = self.global_scope(); let wrapper = global.get_runnable_wrapper(); let task_source = global.file_reading_task_source(); diff --git a/components/script/dom/promise.rs b/components/script/dom/promise.rs index 14f53bf8466..9c1feb0154d 100644 --- a/components/script/dom/promise.rs +++ b/components/script/dom/promise.rs @@ -61,7 +61,7 @@ impl PromiseHelper for Rc { impl Drop for Promise { #[allow(unsafe_code)] fn drop(&mut self) { - let cx = self.global().r().get_cx(); + let cx = self.global_scope().get_cx(); unsafe { RemoveRawValueRoot(cx, self.permanent_js_root.get_unsafe()); } @@ -81,7 +81,7 @@ impl Promise { #[allow(unsafe_code, unrooted_must_root)] pub fn duplicate(&self) -> Rc { - let cx = self.global().r().get_cx(); + let cx = self.global_scope().get_cx(); unsafe { Promise::new_with_js_promise(self.reflector().get_jsobject(), cx) } @@ -210,8 +210,7 @@ impl Promise { #[allow(unsafe_code)] pub fn append_native_handler(&self, handler: &PromiseNativeHandler) { - let global = self.global(); - let cx = global.r().get_cx(); + let cx = self.global_scope().get_cx(); rooted!(in(cx) let resolve_func = create_native_handler_function(cx, handler.reflector().get_jsobject(), diff --git a/components/script/dom/testbinding.rs b/components/script/dom/testbinding.rs index 8362daa0d12..1da8cdf8a89 100644 --- a/components/script/dom/testbinding.rs +++ b/components/script/dom/testbinding.rs @@ -673,7 +673,7 @@ impl TestBindingMethods for TestBinding { } fn PromiseRejectWithTypeError(&self, p: &Promise, s: USVString) { - p.reject_error(self.global().r().get_cx(), Error::Type(s.0)); + p.reject_error(self.global_scope().get_cx(), Error::Type(s.0)); } #[allow(unrooted_must_root)] @@ -789,7 +789,7 @@ impl TestBindingCallback { #[allow(unrooted_must_root)] pub fn invoke(self) { let p = self.promise.root(); - let cx = p.global().r().get_cx(); + let cx = p.global_scope().get_cx(); let _ac = JSAutoCompartment::new(cx, p.reflector().get_jsobject().get()); p.resolve_native(cx, &self.value); } diff --git a/components/script/fetch.rs b/components/script/fetch.rs index 1b2d5e77be9..372c0d9ee6c 100644 --- a/components/script/fetch.rs +++ b/components/script/fetch.rs @@ -124,13 +124,13 @@ impl FetchResponseListener for FetchContext { // JSAutoCompartment needs to be manually made. // Otherwise, Servo will crash. - let promise_cx = promise.global().r().get_cx(); + let promise_cx = promise.global_scope().get_cx(); let _ac = JSAutoCompartment::new(promise_cx, promise.reflector().get_jsobject().get()); match fetch_metadata { // Step 4.1 Err(_) => { promise.reject_error( - promise.global().r().get_cx(), + promise.global_scope().get_cx(), Error::Type("Network error occurred".to_string())); self.fetch_promise = Some(TrustedPromise::new(promise)); return; From 00e66a777afba1f7f5ad189d38d7c58b1ef1cdab Mon Sep 17 00:00:00 2001 From: Anthony Ramine Date: Wed, 5 Oct 2016 10:07:53 +0200 Subject: [PATCH 62/66] Make workers' interrupt_callback use GlobalScope --- components/script/dom/dedicatedworkerglobalscope.rs | 10 ++++------ components/script/dom/serviceworkerglobalscope.rs | 10 ++++------ 2 files changed, 8 insertions(+), 12 deletions(-) diff --git a/components/script/dom/dedicatedworkerglobalscope.rs b/components/script/dom/dedicatedworkerglobalscope.rs index f362f4b2f7a..4418e0654f6 100644 --- a/components/script/dom/dedicatedworkerglobalscope.rs +++ b/components/script/dom/dedicatedworkerglobalscope.rs @@ -11,7 +11,7 @@ use dom::bindings::codegen::Bindings::DedicatedWorkerGlobalScopeBinding; use dom::bindings::codegen::Bindings::DedicatedWorkerGlobalScopeBinding::DedicatedWorkerGlobalScopeMethods; use dom::bindings::codegen::Bindings::EventHandlerBinding::EventHandlerNonNull; use dom::bindings::error::{ErrorInfo, ErrorResult}; -use dom::bindings::global::{GlobalRef, global_root_from_context}; +use dom::bindings::global::global_scope_from_context; use dom::bindings::inheritance::Castable; use dom::bindings::js::{Root, RootCollection}; use dom::bindings::reflector::Reflectable; @@ -342,11 +342,9 @@ impl DedicatedWorkerGlobalScope { #[allow(unsafe_code)] unsafe extern "C" fn interrupt_callback(cx: *mut JSContext) -> bool { - let global = global_root_from_context(cx); - let worker = match global.r() { - GlobalRef::Worker(w) => w, - _ => panic!("global for worker is not a worker scope") - }; + let worker = + Root::downcast::(global_scope_from_context(cx)) + .expect("global is not a worker scope"); assert!(worker.is::()); // A false response causes the script to terminate diff --git a/components/script/dom/serviceworkerglobalscope.rs b/components/script/dom/serviceworkerglobalscope.rs index 62037763a6e..c5f993fba02 100644 --- a/components/script/dom/serviceworkerglobalscope.rs +++ b/components/script/dom/serviceworkerglobalscope.rs @@ -8,7 +8,7 @@ use dom::abstractworker::WorkerScriptMsg; use dom::bindings::codegen::Bindings::EventHandlerBinding::EventHandlerNonNull; use dom::bindings::codegen::Bindings::ServiceWorkerGlobalScopeBinding; use dom::bindings::codegen::Bindings::ServiceWorkerGlobalScopeBinding::ServiceWorkerGlobalScopeMethods; -use dom::bindings::global::{GlobalRef, global_root_from_context}; +use dom::bindings::global::global_scope_from_context; use dom::bindings::inheritance::Castable; use dom::bindings::js::{Root, RootCollection}; use dom::bindings::reflector::Reflectable; @@ -310,11 +310,9 @@ impl ServiceWorkerGlobalScope { #[allow(unsafe_code)] unsafe extern "C" fn interrupt_callback(cx: *mut JSContext) -> bool { - let global = global_root_from_context(cx); - let worker = match global.r() { - GlobalRef::Worker(w) => w, - _ => panic!("global for worker is not a worker scope") - }; + let worker = + Root::downcast::(global_scope_from_context(cx)) + .expect("global is not a worker scope"); assert!(worker.is::()); // A false response causes the script to terminate From 996fd284e29c0406b185a429e7e5cd40405bee35 Mon Sep 17 00:00:00 2001 From: Anthony Ramine Date: Wed, 5 Oct 2016 10:18:15 +0200 Subject: [PATCH 63/66] Use global_scope_from_context in TestBinding::PromiseNativeHandler --- components/script/dom/testbinding.rs | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/components/script/dom/testbinding.rs b/components/script/dom/testbinding.rs index 1da8cdf8a89..e395dfa73d3 100644 --- a/components/script/dom/testbinding.rs +++ b/components/script/dom/testbinding.rs @@ -21,7 +21,7 @@ use dom::bindings::codegen::UnionTypes::{HTMLElementOrUnsignedLongOrStringOrBool use dom::bindings::codegen::UnionTypes::{StringOrLongSequence, StringOrStringSequence, StringSequenceOrUnsignedLong}; use dom::bindings::codegen::UnionTypes::{StringOrUnsignedLong, StringOrBoolean, UnsignedLongOrBoolean}; use dom::bindings::error::{Error, Fallible}; -use dom::bindings::global::global_root_from_context; +use dom::bindings::global::global_scope_from_context; use dom::bindings::js::Root; use dom::bindings::mozmap::MozMap; use dom::bindings::num::Finite; @@ -714,8 +714,8 @@ impl TestBindingMethods for TestBinding { impl Callback for SimpleHandler { #[allow(unsafe_code)] fn callback(&self, cx: *mut JSContext, v: HandleValue) { - let global = unsafe { global_root_from_context(cx) }; - let _ = self.handler.Call_(&global.r(), v, ExceptionHandling::Report); + let global = unsafe { global_scope_from_context(cx) }; + let _ = self.handler.Call_(&*global, v, ExceptionHandling::Report); } } } From c66cf46bee6306ba8cb51f22c0d704c31c17d0fd Mon Sep 17 00:00:00 2001 From: Anthony Ramine Date: Wed, 5 Oct 2016 10:24:21 +0200 Subject: [PATCH 64/66] Make the closure in flush_promise_jobs return a Root --- components/script/dom/workerglobalscope.rs | 6 +++--- components/script/script_runtime.rs | 8 ++++---- components/script/script_thread.rs | 5 +++-- 3 files changed, 10 insertions(+), 9 deletions(-) diff --git a/components/script/dom/workerglobalscope.rs b/components/script/dom/workerglobalscope.rs index 042f2b3d1e3..8cd09b3fdbe 100644 --- a/components/script/dom/workerglobalscope.rs +++ b/components/script/dom/workerglobalscope.rs @@ -9,7 +9,6 @@ use dom::bindings::codegen::Bindings::RequestBinding::RequestInit; use dom::bindings::codegen::Bindings::WorkerGlobalScopeBinding::WorkerGlobalScopeMethods; use dom::bindings::codegen::UnionTypes::RequestOrUSVString; use dom::bindings::error::{Error, ErrorResult, Fallible, report_pending_exception}; -use dom::bindings::global::GlobalRoot; use dom::bindings::inheritance::Castable; use dom::bindings::js::{JS, MutNullableHeap, Root}; use dom::bindings::refcounted::Trusted; @@ -173,8 +172,9 @@ impl WorkerGlobalScope { fn do_flush_promise_jobs(&self) { self.promise_job_queue.flush_promise_jobs(|id| { - assert_eq!(self.upcast::().pipeline_id(), id); - Some(GlobalRoot::Worker(Root::from_ref(self))) + let global = self.upcast::(); + assert_eq!(global.pipeline_id(), id); + Some(Root::from_ref(global)) }); } } diff --git a/components/script/script_runtime.rs b/components/script/script_runtime.rs index 145ef1ef19e..c1da1104cd4 100644 --- a/components/script/script_runtime.rs +++ b/components/script/script_runtime.rs @@ -8,8 +8,8 @@ use dom::bindings::callback::ExceptionHandling; use dom::bindings::cell::DOMRefCell; use dom::bindings::codegen::Bindings::PromiseBinding::PromiseJobCallback; -use dom::bindings::global::{GlobalRoot, global_scope_from_object}; -use dom::bindings::js::{RootCollection, RootCollectionPtr, trace_roots}; +use dom::bindings::global::global_scope_from_object; +use dom::bindings::js::{Root, RootCollection, RootCollectionPtr, trace_roots}; use dom::bindings::refcounted::{LiveDOMReferences, trace_refcounted_objects}; use dom::bindings::trace::trace_traceables; use dom::bindings::utils::DOM_CALLBACKS; @@ -150,7 +150,7 @@ impl PromiseJobQueue { /// Perform a microtask checkpoint, by invoking all of the pending promise job callbacks in /// FIFO order (#4283). pub fn flush_promise_jobs(&self, target_provider: F) - where F: Fn(PipelineId) -> Option + where F: Fn(PipelineId) -> Option> { self.pending_promise_job_runnable.set(false); { @@ -162,7 +162,7 @@ impl PromiseJobQueue { // `flushing_queue` is a static snapshot during this checkpoint. for job in &*self.flushing_job_queue.borrow() { if let Some(target) = target_provider(job.pipeline) { - let _ = job.callback.Call_(&target.r(), ExceptionHandling::Report); + let _ = job.callback.Call_(&*target, ExceptionHandling::Report); } } self.flushing_job_queue.borrow_mut().clear(); diff --git a/components/script/script_thread.rs b/components/script/script_thread.rs index 22ca69c78df..85f0cc2462e 100644 --- a/components/script/script_thread.rs +++ b/components/script/script_thread.rs @@ -27,7 +27,6 @@ use dom::bindings::codegen::Bindings::DocumentBinding::{DocumentMethods, Documen use dom::bindings::codegen::Bindings::LocationBinding::LocationMethods; use dom::bindings::codegen::Bindings::WindowBinding::WindowMethods; use dom::bindings::conversions::{ConversionResult, FromJSValConvertible, StringificationBehavior}; -use dom::bindings::global::GlobalRoot; use dom::bindings::inheritance::Castable; use dom::bindings::js::{JS, MutNullableHeap, Root, RootCollection}; use dom::bindings::js::{RootCollectionPtr, RootedReference}; @@ -2190,7 +2189,9 @@ impl ScriptThread { fn do_flush_promise_jobs(&self) { self.promise_job_queue.flush_promise_jobs(|id| { - self.find_child_context(id).map(|context| GlobalRoot::Window(context.active_window())) + self.find_child_context(id).map(|context| { + Root::upcast(context.active_window()) + }) }); } } From b6bbd41e11a8d73f884b7011905c05bd3efec3cd Mon Sep 17 00:00:00 2001 From: Anthony Ramine Date: Wed, 5 Oct 2016 10:29:38 +0200 Subject: [PATCH 65/66] Remove GlobalRoot and GlobalRef --- components/net_traits/request.rs | 2 - components/script/dom/bindings/callback.rs | 4 +- .../dom/bindings/codegen/CodegenRust.py | 12 +- components/script/dom/bindings/error.rs | 5 +- components/script/dom/bindings/global.rs | 143 ------------------ components/script/dom/bindings/mod.rs | 1 - components/script/dom/bindings/reflector.rs | 3 +- .../script/dom/dedicatedworkerglobalscope.rs | 3 +- components/script/dom/globalscope.rs | 51 ++++++- .../script/dom/serviceworkerglobalscope.rs | 3 +- components/script/dom/testbinding.rs | 3 +- components/script/dom/window.rs | 3 +- components/script/script_runtime.rs | 3 +- 13 files changed, 63 insertions(+), 173 deletions(-) delete mode 100644 components/script/dom/bindings/global.rs diff --git a/components/net_traits/request.rs b/components/net_traits/request.rs index 2a84c91c759..4380baf3a09 100644 --- a/components/net_traits/request.rs +++ b/components/net_traits/request.rs @@ -174,8 +174,6 @@ pub struct Request { pub body: RefCell>>, // TODO: client object pub is_service_worker_global_scope: bool, - // pub client: GlobalRef, // XXXManishearth copy over only the relevant fields of the global scope, - // not the entire scope to avoid the libscript dependency pub window: Cell, // TODO: target browsing context pub keep_alive: Cell, diff --git a/components/script/dom/bindings/callback.rs b/components/script/dom/bindings/callback.rs index c9fb9fd8a53..709dab31049 100644 --- a/components/script/dom/bindings/callback.rs +++ b/components/script/dom/bindings/callback.rs @@ -5,8 +5,8 @@ //! Base classes to work with IDL callbacks. use dom::bindings::error::{Error, Fallible, report_pending_exception}; -use dom::bindings::global::global_scope_from_object; use dom::bindings::reflector::Reflectable; +use dom::globalscope::GlobalScope; use js::jsapi::{Heap, MutableHandleObject, RootedObject}; use js::jsapi::{IsCallable, JSContext, JSObject, JS_WrapObject}; use js::jsapi::{JSCompartment, JS_EnterCompartment, JS_LeaveCompartment}; @@ -165,7 +165,7 @@ impl<'a> CallSetup<'a> { callback: &T, handling: ExceptionHandling) -> CallSetup<'a> { - let global = unsafe { global_scope_from_object(callback.callback()) }; + let global = unsafe { GlobalScope::from_object(callback.callback()) }; let cx = global.get_cx(); exception_compartment.ptr = unsafe { diff --git a/components/script/dom/bindings/codegen/CodegenRust.py b/components/script/dom/bindings/codegen/CodegenRust.py index 46285bcf406..be3cf7fb003 100644 --- a/components/script/dom/bindings/codegen/CodegenRust.py +++ b/components/script/dom/bindings/codegen/CodegenRust.py @@ -817,7 +817,7 @@ def getJSToNativeConversionInfo(type, descriptorProvider, failureCode=None, { // Scope for our JSAutoCompartment. rooted!(in(cx) let globalObj = CurrentGlobalOrNull(cx)); - let promiseGlobal = global_scope_from_object_maybe_wrapped(globalObj.handle().get()); + let promiseGlobal = GlobalScope::from_object_maybe_wrapped(globalObj.handle().get()); rooted!(in(cx) let mut valueToResolve = $${val}.get()); if !JS_WrapValue(cx, valueToResolve.handle_mut()) { @@ -3170,7 +3170,7 @@ class CGCallGenerator(CGThing): if static: glob = "&global" else: - glob = "&global_scope_from_reflector(this)" + glob = "&this.global_scope()" self.cgRoot.append(CGGeneric( "let result = match result {\n" @@ -3386,7 +3386,7 @@ class CGAbstractStaticBindingMethod(CGAbstractMethod): def definition_body(self): preamble = CGGeneric("""\ -let global = global_scope_from_object(JS_CALLEE(cx, vp).to_object()); +let global = GlobalScope::from_object(JS_CALLEE(cx, vp).to_object()); """) return CGList([preamble, self.generate_code()]) @@ -5252,7 +5252,7 @@ class CGClassConstructHook(CGAbstractExternMethod): def definition_body(self): preamble = CGGeneric("""\ -let global = global_scope_from_object(JS_CALLEE(cx, vp).to_object()); +let global = GlobalScope::from_object(JS_CALLEE(cx, vp).to_object()); let args = CallArgs::from_vp(vp, argc); """) name = self.constructor.identifier.name @@ -5499,10 +5499,6 @@ def generate_imports(config, cgthings, descriptors, callbacks=None, dictionaries 'dom::bindings::codegen::InterfaceObjectMap', 'dom::bindings::constant::ConstantSpec', 'dom::bindings::constant::ConstantVal', - 'dom::bindings::global::GlobalRef', - 'dom::bindings::global::global_scope_from_object_maybe_wrapped', - 'dom::bindings::global::global_scope_from_reflector', - 'dom::bindings::global::global_scope_from_object', 'dom::bindings::interface::ConstructorClassHook', 'dom::bindings::interface::InterfaceConstructorBehavior', 'dom::bindings::interface::NonCallbackInterfaceObjectClass', diff --git a/components/script/dom/bindings/error.rs b/components/script/dom/bindings/error.rs index 7e0f55d86bf..96ae220ce98 100644 --- a/components/script/dom/bindings/error.rs +++ b/components/script/dom/bindings/error.rs @@ -8,7 +8,6 @@ use dom::bindings::codegen::Bindings::DOMExceptionBinding::DOMExceptionMethods; use dom::bindings::codegen::PrototypeList::proto_id_to_name; use dom::bindings::conversions::{ConversionResult, FromJSValConvertible, ToJSValConvertible}; use dom::bindings::conversions::root_from_object; -use dom::bindings::global::global_scope_from_context; use dom::bindings::str::USVString; use dom::domexception::{DOMErrorName, DOMException}; use dom::globalscope::GlobalScope; @@ -246,8 +245,8 @@ pub unsafe fn report_pending_exception(cx: *mut JSContext, dispatch_event: bool) error_info.message); if dispatch_event { - let global = global_scope_from_context(cx); - global.report_an_error(error_info, value.handle()); + GlobalScope::from_context(cx) + .report_an_error(error_info, value.handle()); } } } diff --git a/components/script/dom/bindings/global.rs b/components/script/dom/bindings/global.rs deleted file mode 100644 index e62573b5a9a..00000000000 --- a/components/script/dom/bindings/global.rs +++ /dev/null @@ -1,143 +0,0 @@ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -//! Abstractions for global scopes. -//! -//! This module contains smart pointers to global scopes, to simplify writing -//! code that works in workers as well as window scopes. - -use dom::bindings::conversions::root_from_object; -use dom::bindings::inheritance::Castable; -use dom::bindings::js::Root; -use dom::bindings::reflector::{Reflectable, Reflector}; -use dom::globalscope::GlobalScope; -use dom::window; -use dom::workerglobalscope::WorkerGlobalScope; -use js::{JSCLASS_IS_DOMJSCLASS, JSCLASS_IS_GLOBAL}; -use js::glue::{IsWrapper, UnwrapObject}; -use js::jsapi::{CurrentGlobalOrNull, GetGlobalForObjectCrossCompartment}; -use js::jsapi::{JSContext, JSObject, JS_GetClass}; - -/// A freely-copyable reference to a rooted global object. -#[derive(Copy, Clone)] -pub enum GlobalRef<'a> { - /// A reference to a `Window` object. - Window(&'a window::Window), - /// A reference to a `WorkerGlobalScope` object. - Worker(&'a WorkerGlobalScope), -} - -/// A stack-based rooted reference to a global object. -pub enum GlobalRoot { - /// A root for a `Window` object. - Window(Root), - /// A root for a `WorkerGlobalScope` object. - Worker(Root), -} - -impl<'a> GlobalRef<'a> { - /// Returns that `GlobalRef` as a `GlobalScope` referengce. - pub fn as_global_scope(&self) -> &GlobalScope { - match *self { - GlobalRef::Window(window) => window.upcast(), - GlobalRef::Worker(worker) => worker.upcast(), - } - } - - /// Get the `JSContext` for the `JSRuntime` associated with the thread - /// this global object is on. - pub fn get_cx(&self) -> *mut JSContext { - match *self { - GlobalRef::Window(ref window) => window.get_cx(), - GlobalRef::Worker(ref worker) => worker.get_cx(), - } - } -} - -impl<'a> Reflectable for GlobalRef<'a> { - fn reflector(&self) -> &Reflector { - match *self { - GlobalRef::Window(ref window) => window.reflector(), - GlobalRef::Worker(ref worker) => worker.reflector(), - } - } -} - -impl GlobalRoot { - /// Obtain a safe reference to the global object that cannot outlive the - /// lifetime of this root. - pub fn r(&self) -> GlobalRef { - match *self { - GlobalRoot::Window(ref window) => GlobalRef::Window(window.r()), - GlobalRoot::Worker(ref worker) => GlobalRef::Worker(worker.r()), - } - } -} - -/// Returns the global scope of the realm that the given DOM object's reflector was created in. -pub fn global_scope_from_reflector(reflector: &T) -> Root { - unsafe { global_scope_from_object(*reflector.reflector().get_jsobject()) } -} - -/// Returns the Rust global scope from a JS global object. -unsafe fn global_scope_from_global(global: *mut JSObject) -> Root { - assert!(!global.is_null()); - let clasp = JS_GetClass(global); - assert!(((*clasp).flags & (JSCLASS_IS_DOMJSCLASS | JSCLASS_IS_GLOBAL)) != 0); - root_from_object(global).unwrap() -} - -/// Returns the Rust global object from a JS global object. -#[allow(unrooted_must_root)] -unsafe fn global_root_from_global(global: *mut JSObject) -> GlobalRoot { - let global_scope = global_scope_from_global(global); - if let Some(window) = global_scope.downcast::() { - return GlobalRoot::Window(Root::from_ref(window)); - } - if let Some(worker) = Root::downcast(global_scope) { - return GlobalRoot::Worker(worker); - } - panic!("found DOM global that doesn't unwrap to Window or WorkerGlobalScope") -} - -/// Returns the global scope of the realm that the given JS object was created in. -pub unsafe fn global_scope_from_object(obj: *mut JSObject) -> Root { - assert!(!obj.is_null()); - let global = GetGlobalForObjectCrossCompartment(obj); - global_scope_from_global(global) -} - -/// Returns the global object of the realm that the given JS object was created in. -#[allow(unrooted_must_root)] -pub unsafe fn global_root_from_object(obj: *mut JSObject) -> GlobalRoot { - assert!(!obj.is_null()); - let global = GetGlobalForObjectCrossCompartment(obj); - global_root_from_global(global) -} - -/// Returns the global scope for the given JSContext -#[allow(unrooted_must_root)] -pub unsafe fn global_scope_from_context(cx: *mut JSContext) -> Root { - let global = CurrentGlobalOrNull(cx); - global_scope_from_global(global) -} - -/// Returns the global object for the given JSContext -#[allow(unrooted_must_root)] -pub unsafe fn global_root_from_context(cx: *mut JSContext) -> GlobalRoot { - let global = CurrentGlobalOrNull(cx); - global_root_from_global(global) -} - -/// Returns the global object of the realm that the given JS object was created in, -/// after unwrapping any wrappers. -pub unsafe fn global_scope_from_object_maybe_wrapped( - mut obj: *mut JSObject) - -> Root { - if IsWrapper(obj) { - obj = UnwrapObject(obj, /* stopAtWindowProxy = */ 0); - assert!(!obj.is_null()); - } - global_scope_from_object(obj) -} diff --git a/components/script/dom/bindings/mod.rs b/components/script/dom/bindings/mod.rs index 56cff520ef0..27504efda7c 100644 --- a/components/script/dom/bindings/mod.rs +++ b/components/script/dom/bindings/mod.rs @@ -134,7 +134,6 @@ pub mod cell; pub mod constant; pub mod conversions; pub mod error; -pub mod global; pub mod guard; pub mod inheritance; pub mod interface; diff --git a/components/script/dom/bindings/reflector.rs b/components/script/dom/bindings/reflector.rs index 580e3fa6fae..3d23f4e9370 100644 --- a/components/script/dom/bindings/reflector.rs +++ b/components/script/dom/bindings/reflector.rs @@ -5,7 +5,6 @@ //! The `Reflector` struct. use dom::bindings::conversions::DerivedFrom; -use dom::bindings::global::global_scope_from_reflector; use dom::bindings::js::Root; use dom::globalscope::GlobalScope; use js::jsapi::{HandleObject, JSContext, JSObject}; @@ -82,7 +81,7 @@ pub trait Reflectable { /// Returns the global scope of the realm that the Reflectable was created in. fn global_scope(&self) -> Root where Self: Sized { - global_scope_from_reflector(self) + GlobalScope::from_reflector(self) } } diff --git a/components/script/dom/dedicatedworkerglobalscope.rs b/components/script/dom/dedicatedworkerglobalscope.rs index 4418e0654f6..fb818be3797 100644 --- a/components/script/dom/dedicatedworkerglobalscope.rs +++ b/components/script/dom/dedicatedworkerglobalscope.rs @@ -11,7 +11,6 @@ use dom::bindings::codegen::Bindings::DedicatedWorkerGlobalScopeBinding; use dom::bindings::codegen::Bindings::DedicatedWorkerGlobalScopeBinding::DedicatedWorkerGlobalScopeMethods; use dom::bindings::codegen::Bindings::EventHandlerBinding::EventHandlerNonNull; use dom::bindings::error::{ErrorInfo, ErrorResult}; -use dom::bindings::global::global_scope_from_context; use dom::bindings::inheritance::Castable; use dom::bindings::js::{Root, RootCollection}; use dom::bindings::reflector::Reflectable; @@ -343,7 +342,7 @@ impl DedicatedWorkerGlobalScope { #[allow(unsafe_code)] unsafe extern "C" fn interrupt_callback(cx: *mut JSContext) -> bool { let worker = - Root::downcast::(global_scope_from_context(cx)) + Root::downcast::(GlobalScope::from_context(cx)) .expect("global is not a worker scope"); assert!(worker.is::()); diff --git a/components/script/dom/globalscope.rs b/components/script/dom/globalscope.rs index 553393e3195..fc160675df5 100644 --- a/components/script/dom/globalscope.rs +++ b/components/script/dom/globalscope.rs @@ -5,6 +5,7 @@ use devtools_traits::{ScriptToDevtoolsControlMsg, WorkerId}; use dom::bindings::cell::DOMRefCell; use dom::bindings::codegen::Bindings::WindowBinding::WindowMethods; +use dom::bindings::conversions::root_from_object; use dom::bindings::error::{ErrorInfo, report_pending_exception}; use dom::bindings::inheritance::Castable; use dom::bindings::js::{JS, MutNullableHeap, Root}; @@ -19,8 +20,12 @@ use dom::eventtarget::EventTarget; use dom::window::Window; use dom::workerglobalscope::WorkerGlobalScope; use ipc_channel::ipc::IpcSender; -use js::jsapi::{HandleValue, Evaluate2, JS_GetContext, JS_GetObjectRuntime}; -use js::jsapi::{JSAutoCompartment, JSContext, MutableHandleValue}; +use js::{JSCLASS_IS_DOMJSCLASS, JSCLASS_IS_GLOBAL}; +use js::glue::{IsWrapper, UnwrapObject}; +use js::jsapi::{CurrentGlobalOrNull, GetGlobalForObjectCrossCompartment}; +use js::jsapi::{HandleValue, Evaluate2, JSAutoCompartment, JSContext}; +use js::jsapi::{JSObject, JS_GetClass, JS_GetContext}; +use js::jsapi::{JS_GetObjectRuntime, MutableHandleValue}; use js::rust::CompileOptionsWrapper; use libc; use msg::constellation_msg::PipelineId; @@ -116,6 +121,39 @@ impl GlobalScope { } } + /// Returns the global scope of the realm that the given DOM object's reflector + /// was created in. + #[allow(unsafe_code)] + pub fn from_reflector(reflector: &T) -> Root { + unsafe { GlobalScope::from_object(*reflector.reflector().get_jsobject()) } + } + + /// Returns the global scope of the realm that the given JS object was created in. + #[allow(unsafe_code)] + pub unsafe fn from_object(obj: *mut JSObject) -> Root { + assert!(!obj.is_null()); + let global = GetGlobalForObjectCrossCompartment(obj); + global_scope_from_global(global) + } + + /// Returns the global scope for the given JSContext + #[allow(unsafe_code)] + pub unsafe fn from_context(cx: *mut JSContext) -> Root { + let global = CurrentGlobalOrNull(cx); + global_scope_from_global(global) + } + + /// Returns the global object of the realm that the given JS object + /// was created in, after unwrapping any wrappers. + #[allow(unsafe_code)] + pub unsafe fn from_object_maybe_wrapped(mut obj: *mut JSObject) -> Root { + if IsWrapper(obj) { + obj = UnwrapObject(obj, /* stopAtWindowProxy = */ 0); + assert!(!obj.is_null()); + } + GlobalScope::from_object(obj) + } + #[allow(unsafe_code)] pub fn get_cx(&self) -> *mut JSContext { unsafe { @@ -475,3 +513,12 @@ impl GlobalScope { fn timestamp_in_ms(time: Timespec) -> u64 { (time.sec * 1000 + (time.nsec / 1000000) as i64) as u64 } + +/// Returns the Rust global scope from a JS global object. +#[allow(unsafe_code)] +unsafe fn global_scope_from_global(global: *mut JSObject) -> Root { + assert!(!global.is_null()); + let clasp = JS_GetClass(global); + assert!(((*clasp).flags & (JSCLASS_IS_DOMJSCLASS | JSCLASS_IS_GLOBAL)) != 0); + root_from_object(global).unwrap() +} diff --git a/components/script/dom/serviceworkerglobalscope.rs b/components/script/dom/serviceworkerglobalscope.rs index c5f993fba02..10d01d4b41a 100644 --- a/components/script/dom/serviceworkerglobalscope.rs +++ b/components/script/dom/serviceworkerglobalscope.rs @@ -8,7 +8,6 @@ use dom::abstractworker::WorkerScriptMsg; use dom::bindings::codegen::Bindings::EventHandlerBinding::EventHandlerNonNull; use dom::bindings::codegen::Bindings::ServiceWorkerGlobalScopeBinding; use dom::bindings::codegen::Bindings::ServiceWorkerGlobalScopeBinding::ServiceWorkerGlobalScopeMethods; -use dom::bindings::global::global_scope_from_context; use dom::bindings::inheritance::Castable; use dom::bindings::js::{Root, RootCollection}; use dom::bindings::reflector::Reflectable; @@ -311,7 +310,7 @@ impl ServiceWorkerGlobalScope { #[allow(unsafe_code)] unsafe extern "C" fn interrupt_callback(cx: *mut JSContext) -> bool { let worker = - Root::downcast::(global_scope_from_context(cx)) + Root::downcast::(GlobalScope::from_context(cx)) .expect("global is not a worker scope"); assert!(worker.is::()); diff --git a/components/script/dom/testbinding.rs b/components/script/dom/testbinding.rs index e395dfa73d3..b5d77809147 100644 --- a/components/script/dom/testbinding.rs +++ b/components/script/dom/testbinding.rs @@ -21,7 +21,6 @@ use dom::bindings::codegen::UnionTypes::{HTMLElementOrUnsignedLongOrStringOrBool use dom::bindings::codegen::UnionTypes::{StringOrLongSequence, StringOrStringSequence, StringSequenceOrUnsignedLong}; use dom::bindings::codegen::UnionTypes::{StringOrUnsignedLong, StringOrBoolean, UnsignedLongOrBoolean}; use dom::bindings::error::{Error, Fallible}; -use dom::bindings::global::global_scope_from_context; use dom::bindings::js::Root; use dom::bindings::mozmap::MozMap; use dom::bindings::num::Finite; @@ -714,7 +713,7 @@ impl TestBindingMethods for TestBinding { impl Callback for SimpleHandler { #[allow(unsafe_code)] fn callback(&self, cx: *mut JSContext, v: HandleValue) { - let global = unsafe { global_scope_from_context(cx) }; + let global = unsafe { GlobalScope::from_context(cx) }; let _ = self.handler.Call_(&*global, v, ExceptionHandling::Report); } } diff --git a/components/script/dom/window.rs b/components/script/dom/window.rs index e1f47cc8163..9bb813a2946 100644 --- a/components/script/dom/window.rs +++ b/components/script/dom/window.rs @@ -17,7 +17,6 @@ use dom::bindings::codegen::Bindings::WindowBinding::{self, FrameRequestCallback use dom::bindings::codegen::Bindings::WindowBinding::{ScrollBehavior, ScrollToOptions}; use dom::bindings::codegen::UnionTypes::RequestOrUSVString; use dom::bindings::error::{Error, ErrorResult, Fallible}; -use dom::bindings::global::global_scope_from_object; use dom::bindings::inheritance::Castable; use dom::bindings::js::{JS, MutNullableHeap, Root}; use dom::bindings::num::Finite; @@ -1496,7 +1495,7 @@ impl Window { /// in a top-level `Window` global. #[allow(unsafe_code)] pub unsafe fn global_is_mozbrowser(_: *mut JSContext, obj: HandleObject) -> bool { - global_scope_from_object(obj.get()) + GlobalScope::from_object(obj.get()) .downcast::() .map_or(false, |window| window.is_mozbrowser()) } diff --git a/components/script/script_runtime.rs b/components/script/script_runtime.rs index c1da1104cd4..603e24a1468 100644 --- a/components/script/script_runtime.rs +++ b/components/script/script_runtime.rs @@ -8,7 +8,6 @@ use dom::bindings::callback::ExceptionHandling; use dom::bindings::cell::DOMRefCell; use dom::bindings::codegen::Bindings::PromiseBinding::PromiseJobCallback; -use dom::bindings::global::global_scope_from_object; use dom::bindings::js::{Root, RootCollection, RootCollectionPtr, trace_roots}; use dom::bindings::refcounted::{LiveDOMReferences, trace_refcounted_objects}; use dom::bindings::trace::trace_traceables; @@ -178,7 +177,7 @@ unsafe extern "C" fn enqueue_job(_cx: *mut JSContext, _allocation_site: HandleObject, _data: *mut c_void) -> bool { let result = panic::catch_unwind(AssertUnwindSafe(|| { - let global = global_scope_from_object(job.get()); + let global = GlobalScope::from_object(job.get()); let pipeline = global.pipeline_id(); global.enqueue_promise_job(EnqueuedPromiseCallback { callback: PromiseJobCallback::new(job.get()), From d8e92bb271a9f9dd87bf77e38cd820d01f2f0ae4 Mon Sep 17 00:00:00 2001 From: Anthony Ramine Date: Wed, 5 Oct 2016 11:06:25 +0200 Subject: [PATCH 66/66] Rename Reflectable::global_scope to global --- components/script/body.rs | 8 ++--- .../dom/bindings/codegen/CodegenRust.py | 2 +- components/script/dom/bindings/iterable.rs | 2 +- components/script/dom/bindings/reflector.rs | 2 +- components/script/dom/blob.rs | 12 +++---- components/script/dom/bluetooth.rs | 10 +++--- components/script/dom/bluetoothdevice.rs | 2 +- .../dom/bluetoothremotegattcharacteristic.rs | 14 ++++---- .../dom/bluetoothremotegattdescriptor.rs | 6 ++-- .../script/dom/bluetoothremotegattserver.rs | 12 +++---- .../script/dom/bluetoothremotegattservice.rs | 18 +++++----- .../script/dom/canvasrenderingcontext2d.rs | 12 +++---- components/script/dom/dommatrixreadonly.rs | 26 +++++++------- components/script/dom/domquad.rs | 2 +- components/script/dom/eventdispatcher.rs | 2 +- components/script/dom/eventtarget.rs | 6 ++-- components/script/dom/filereader.rs | 10 +++--- components/script/dom/formdata.rs | 2 +- .../script/dom/htmlformcontrolscollection.rs | 2 +- components/script/dom/htmllinkelement.rs | 2 +- components/script/dom/htmlscriptelement.rs | 2 +- components/script/dom/navigator.rs | 8 ++--- components/script/dom/promise.rs | 8 ++--- components/script/dom/request.rs | 6 ++-- components/script/dom/response.rs | 4 +-- components/script/dom/serviceworker.rs | 2 +- .../script/dom/serviceworkercontainer.rs | 4 +-- components/script/dom/storage.rs | 8 ++--- components/script/dom/testbinding.rs | 26 +++++++------- components/script/dom/url.rs | 2 +- components/script/dom/webglprogram.rs | 4 +-- .../script/dom/webglrenderingcontext.rs | 14 ++++---- components/script/dom/websocket.rs | 12 +++---- components/script/dom/worker.rs | 4 +-- components/script/dom/xmlhttprequest.rs | 36 +++++++++---------- components/script/fetch.rs | 6 ++-- components/script/timers.rs | 4 +-- 37 files changed, 151 insertions(+), 151 deletions(-) diff --git a/components/script/body.rs b/components/script/body.rs index 9ae98e8f43b..c5b6008c363 100644 --- a/components/script/body.rs +++ b/components/script/body.rs @@ -42,11 +42,11 @@ pub enum FetchedData { // https://fetch.spec.whatwg.org/#concept-body-consume-body #[allow(unrooted_must_root)] pub fn consume_body(object: &T, body_type: BodyType) -> Rc { - let promise = Promise::new(&object.global_scope()); + let promise = Promise::new(&object.global()); // Step 1 if object.get_body_used() || object.is_locked() { - promise.reject_error(promise.global_scope().get_cx(), Error::Type( + promise.reject_error(promise.global().get_cx(), Error::Type( "The response's stream is disturbed or locked".to_string())); return promise; } @@ -77,7 +77,7 @@ pub fn consume_body_with_promise(object: &T, body_type, object.get_mime_type()); - let cx = promise.global_scope().get_cx(); + let cx = promise.global().get_cx(); match pkg_data_results { Ok(results) => { match results { @@ -98,7 +98,7 @@ fn run_package_data_algorithm(object: &T, body_type: BodyType, mime_type: Ref>) -> Fallible { - let global = object.global_scope(); + let global = object.global(); let cx = global.get_cx(); let mime = &*mime_type; match body_type { diff --git a/components/script/dom/bindings/codegen/CodegenRust.py b/components/script/dom/bindings/codegen/CodegenRust.py index be3cf7fb003..a3266bfeaa3 100644 --- a/components/script/dom/bindings/codegen/CodegenRust.py +++ b/components/script/dom/bindings/codegen/CodegenRust.py @@ -3170,7 +3170,7 @@ class CGCallGenerator(CGThing): if static: glob = "&global" else: - glob = "&this.global_scope()" + glob = "&this.global()" self.cgRoot.append(CGGeneric( "let result = match result {\n" diff --git a/components/script/dom/bindings/iterable.rs b/components/script/dom/bindings/iterable.rs index 8e316336607..3e6febeeb5d 100644 --- a/components/script/dom/bindings/iterable.rs +++ b/components/script/dom/bindings/iterable.rs @@ -93,7 +93,7 @@ impl IterableIterator { iterable: JS::from_ref(iterable), index: Cell::new(0), }; - reflect_dom_object(iterator, &*iterable.global_scope(), wrap) + reflect_dom_object(iterator, &*iterable.global(), wrap) } /// Return the next value from the iterable object. diff --git a/components/script/dom/bindings/reflector.rs b/components/script/dom/bindings/reflector.rs index 3d23f4e9370..737268bf7d0 100644 --- a/components/script/dom/bindings/reflector.rs +++ b/components/script/dom/bindings/reflector.rs @@ -80,7 +80,7 @@ pub trait Reflectable { fn reflector(&self) -> &Reflector; /// Returns the global scope of the realm that the Reflectable was created in. - fn global_scope(&self) -> Root where Self: Sized { + fn global(&self) -> Root where Self: Sized { GlobalScope::from_reflector(self) } } diff --git a/components/script/dom/blob.rs b/components/script/dom/blob.rs index ad8e9a5d898..a2ceed8b046 100644 --- a/components/script/dom/blob.rs +++ b/components/script/dom/blob.rs @@ -116,7 +116,7 @@ impl Blob { } }; - Blob::new(&parent.global_scope(), blob_impl, relative_content_type.into()) + Blob::new(&parent.global(), blob_impl, relative_content_type.into()) } // https://w3c.github.io/FileAPI/#constructorBlob @@ -143,7 +143,7 @@ impl Blob { let (buffer, is_new_buffer) = match *f.cache.borrow() { Some(ref bytes) => (bytes.clone(), false), None => { - let bytes = read_file(&self.global_scope(), f.id.clone())?; + let bytes = read_file(&self.global(), f.id.clone())?; (bytes, true) } }; @@ -188,7 +188,7 @@ impl Blob { /// valid or invalid Blob URL. fn promote(&self, set_valid: bool) -> Uuid { let mut bytes = vec![]; - let global_url = self.global_scope().get_url(); + let global_url = self.global().get_url(); match *self.blob_impl.borrow_mut() { BlobImpl::Sliced(_, _) => { @@ -248,7 +248,7 @@ impl Blob { /// Get a FileID representing sliced parent-blob content fn create_sliced_url_id(&self, parent_id: &Uuid, rel_pos: &RelativePos, parent_len: u64) -> Uuid { - let origin = get_blob_origin(&self.global_scope().get_url()); + let origin = get_blob_origin(&self.global().get_url()); let (tx, rx) = ipc::channel().unwrap(); let msg = FileManagerThreadMsg::AddSlicedURLEntry(parent_id.clone(), @@ -277,7 +277,7 @@ impl Blob { /// Cleanups at the time of destruction/closing fn clean_up_file_resource(&self) { if let BlobImpl::File(ref f) = *self.blob_impl.borrow() { - let origin = get_blob_origin(&self.global_scope().get_url()); + let origin = get_blob_origin(&self.global().get_url()); let (tx, rx) = ipc::channel().unwrap(); @@ -288,7 +288,7 @@ impl Blob { } fn send_to_file_manager(&self, msg: FileManagerThreadMsg) { - let global = self.global_scope(); + let global = self.global(); let resource_threads = global.resource_threads(); let _ = resource_threads.send(CoreResourceMsg::ToFileManager(msg)); } diff --git a/components/script/dom/bluetooth.rs b/components/script/dom/bluetooth.rs index bac83de3023..863d75bfec4 100644 --- a/components/script/dom/bluetooth.rs +++ b/components/script/dom/bluetooth.rs @@ -59,7 +59,7 @@ impl Bluetooth { } fn get_bluetooth_thread(&self) -> IpcSender { - self.global_scope().as_window().bluetooth_thread() + self.global().as_window().bluetooth_thread() } fn request_device(&self, option: &RequestDeviceOptions) -> Fallible> { @@ -103,7 +103,7 @@ impl Bluetooth { // Step 12-13. match device { Ok(device) => { - let global = self.global_scope(); + let global = self.global(); let ad_data = BluetoothAdvertisingData::new(&global, device.appearance, device.tx_power, @@ -275,8 +275,8 @@ pub fn result_to_promise(global: &GlobalScope, -> Rc { let p = Promise::new(global); match bluetooth_result { - Ok(v) => p.resolve_native(p.global_scope().get_cx(), &v), - Err(e) => p.reject_error(p.global_scope().get_cx(), e), + Ok(v) => p.resolve_native(p.global().get_cx(), &v), + Err(e) => p.reject_error(p.global().get_cx(), e), } p } @@ -297,6 +297,6 @@ impl BluetoothMethods for Bluetooth { #[allow(unrooted_must_root)] // https://webbluetoothcg.github.io/web-bluetooth/#dom-bluetooth-requestdevice fn RequestDevice(&self, option: &RequestDeviceOptions) -> Rc { - result_to_promise(&self.global_scope(), self.request_device(option)) + result_to_promise(&self.global(), self.request_device(option)) } } diff --git a/components/script/dom/bluetoothdevice.rs b/components/script/dom/bluetoothdevice.rs index c4ceaa333d0..f4348465108 100644 --- a/components/script/dom/bluetoothdevice.rs +++ b/components/script/dom/bluetoothdevice.rs @@ -67,7 +67,7 @@ impl BluetoothDeviceMethods for BluetoothDevice { // https://webbluetoothcg.github.io/web-bluetooth/#dom-bluetoothdevice-gatt fn Gatt(&self) -> Root { self.gatt.or_init(|| { - BluetoothRemoteGATTServer::new(&self.global_scope(), self) + BluetoothRemoteGATTServer::new(&self.global(), self) }) } } diff --git a/components/script/dom/bluetoothremotegattcharacteristic.rs b/components/script/dom/bluetoothremotegattcharacteristic.rs index 425fcffb9cb..95b26ff66c1 100644 --- a/components/script/dom/bluetoothremotegattcharacteristic.rs +++ b/components/script/dom/bluetoothremotegattcharacteristic.rs @@ -74,7 +74,7 @@ impl BluetoothRemoteGATTCharacteristic { } fn get_bluetooth_thread(&self) -> IpcSender { - self.global_scope().as_window().bluetooth_thread() + self.global().as_window().bluetooth_thread() } fn get_instance_id(&self) -> String { @@ -93,7 +93,7 @@ impl BluetoothRemoteGATTCharacteristic { let descriptor = receiver.recv().unwrap(); match descriptor { Ok(descriptor) => { - Ok(BluetoothRemoteGATTDescriptor::new(&self.global_scope(), + Ok(BluetoothRemoteGATTDescriptor::new(&self.global(), self, DOMString::from(descriptor.uuid), descriptor.instance_id)) @@ -124,7 +124,7 @@ impl BluetoothRemoteGATTCharacteristic { match descriptors_vec { Ok(descriptor_vec) => { Ok(descriptor_vec.into_iter() - .map(|desc| BluetoothRemoteGATTDescriptor::new(&self.global_scope(), + .map(|desc| BluetoothRemoteGATTDescriptor::new(&self.global(), self, DOMString::from(desc.uuid), desc.instance_id)) @@ -212,7 +212,7 @@ impl BluetoothRemoteGATTCharacteristicMethods for BluetoothRemoteGATTCharacteris #[allow(unrooted_must_root)] // https://webbluetoothcg.github.io/web-bluetooth/#dom-bluetoothremotegattcharacteristic-getdescriptor fn GetDescriptor(&self, descriptor: BluetoothDescriptorUUID) -> Rc { - result_to_promise(&self.global_scope(), self.get_descriptor(descriptor)) + result_to_promise(&self.global(), self.get_descriptor(descriptor)) } #[allow(unrooted_must_root)] @@ -220,7 +220,7 @@ impl BluetoothRemoteGATTCharacteristicMethods for BluetoothRemoteGATTCharacteris fn GetDescriptors(&self, descriptor: Option) -> Rc { - result_to_promise(&self.global_scope(), self.get_descriptors(descriptor)) + result_to_promise(&self.global(), self.get_descriptors(descriptor)) } // https://webbluetoothcg.github.io/web-bluetooth/#dom-bluetoothremotegattcharacteristic-value @@ -231,12 +231,12 @@ impl BluetoothRemoteGATTCharacteristicMethods for BluetoothRemoteGATTCharacteris #[allow(unrooted_must_root)] // https://webbluetoothcg.github.io/web-bluetooth/#dom-bluetoothremotegattcharacteristic-readvalue fn ReadValue(&self) -> Rc { - result_to_promise(&self.global_scope(), self.read_value()) + result_to_promise(&self.global(), self.read_value()) } #[allow(unrooted_must_root)] // https://webbluetoothcg.github.io/web-bluetooth/#dom-bluetoothremotegattcharacteristic-writevalue fn WriteValue(&self, value: Vec) -> Rc { - result_to_promise(&self.global_scope(), self.write_value(value)) + result_to_promise(&self.global(), self.write_value(value)) } } diff --git a/components/script/dom/bluetoothremotegattdescriptor.rs b/components/script/dom/bluetoothremotegattdescriptor.rs index d42742bc235..f066bb9d22a 100644 --- a/components/script/dom/bluetoothremotegattdescriptor.rs +++ b/components/script/dom/bluetoothremotegattdescriptor.rs @@ -61,7 +61,7 @@ impl BluetoothRemoteGATTDescriptor { } fn get_bluetooth_thread(&self) -> IpcSender { - self.global_scope().as_window().bluetooth_thread() + self.global().as_window().bluetooth_thread() } fn get_instance_id(&self) -> String { @@ -135,12 +135,12 @@ impl BluetoothRemoteGATTDescriptorMethods for BluetoothRemoteGATTDescriptor { #[allow(unrooted_must_root)] // https://webbluetoothcg.github.io/web-bluetooth/#dom-bluetoothremotegattdescriptor-readvalue fn ReadValue(&self) -> Rc { - result_to_promise(&self.global_scope(), self.read_value()) + result_to_promise(&self.global(), self.read_value()) } #[allow(unrooted_must_root)] // https://webbluetoothcg.github.io/web-bluetooth/#dom-bluetoothremotegattdescriptor-writevalue fn WriteValue(&self, value: Vec) -> Rc { - result_to_promise(&self.global_scope(), self.write_value(value)) + result_to_promise(&self.global(), self.write_value(value)) } } diff --git a/components/script/dom/bluetoothremotegattserver.rs b/components/script/dom/bluetoothremotegattserver.rs index 703be681a23..fe19651ebf4 100644 --- a/components/script/dom/bluetoothremotegattserver.rs +++ b/components/script/dom/bluetoothremotegattserver.rs @@ -46,7 +46,7 @@ impl BluetoothRemoteGATTServer { } fn get_bluetooth_thread(&self) -> IpcSender { - self.global_scope().as_window().bluetooth_thread() + self.global().as_window().bluetooth_thread() } // https://webbluetoothcg.github.io/web-bluetooth/#dom-bluetoothremotegattserver-connect @@ -78,7 +78,7 @@ impl BluetoothRemoteGATTServer { let service = receiver.recv().unwrap(); match service { Ok(service) => { - Ok(BluetoothRemoteGATTService::new(&self.global_scope(), + Ok(BluetoothRemoteGATTService::new(&self.global(), &self.device.get(), DOMString::from(service.uuid), service.is_primary, @@ -110,7 +110,7 @@ impl BluetoothRemoteGATTServer { match services_vec { Ok(service_vec) => { Ok(service_vec.into_iter() - .map(|service| BluetoothRemoteGATTService::new(&self.global_scope(), + .map(|service| BluetoothRemoteGATTService::new(&self.global(), &self.device.get(), DOMString::from(service.uuid), service.is_primary, @@ -138,7 +138,7 @@ impl BluetoothRemoteGATTServerMethods for BluetoothRemoteGATTServer { #[allow(unrooted_must_root)] // https://webbluetoothcg.github.io/web-bluetooth/#dom-bluetoothremotegattserver-connect fn Connect(&self) -> Rc { - result_to_promise(&self.global_scope(), self.connect()) + result_to_promise(&self.global(), self.connect()) } // https://webbluetoothcg.github.io/web-bluetooth/#dom-bluetoothremotegattserver-disconnect @@ -161,7 +161,7 @@ impl BluetoothRemoteGATTServerMethods for BluetoothRemoteGATTServer { #[allow(unrooted_must_root)] // https://webbluetoothcg.github.io/web-bluetooth/#dom-bluetoothremotegattserver-getprimaryservice fn GetPrimaryService(&self, service: BluetoothServiceUUID) -> Rc { - result_to_promise(&self.global_scope(), self.get_primary_service(service)) + result_to_promise(&self.global(), self.get_primary_service(service)) } #[allow(unrooted_must_root)] @@ -169,6 +169,6 @@ impl BluetoothRemoteGATTServerMethods for BluetoothRemoteGATTServer { fn GetPrimaryServices(&self, service: Option) -> Rc { - result_to_promise(&self.global_scope(), self.get_primary_services(service)) + result_to_promise(&self.global(), self.get_primary_services(service)) } } diff --git a/components/script/dom/bluetoothremotegattservice.rs b/components/script/dom/bluetoothremotegattservice.rs index 94082277768..bce51131649 100644 --- a/components/script/dom/bluetoothremotegattservice.rs +++ b/components/script/dom/bluetoothremotegattservice.rs @@ -61,7 +61,7 @@ impl BluetoothRemoteGATTService { } fn get_bluetooth_thread(&self) -> IpcSender { - self.global_scope().as_window().bluetooth_thread() + self.global().as_window().bluetooth_thread() } fn get_instance_id(&self) -> String { @@ -82,7 +82,7 @@ impl BluetoothRemoteGATTService { let characteristic = receiver.recv().unwrap(); match characteristic { Ok(characteristic) => { - let global = self.global_scope(); + let global = self.global(); let properties = BluetoothCharacteristicProperties::new(&global, characteristic.broadcast, characteristic.read, @@ -126,7 +126,7 @@ impl BluetoothRemoteGATTService { match characteristics_vec { Ok(characteristic_vec) => { for characteristic in characteristic_vec { - let global = self.global_scope(); + let global = self.global(); let properties = BluetoothCharacteristicProperties::new(&global, characteristic.broadcast, characteristic.read, @@ -167,7 +167,7 @@ impl BluetoothRemoteGATTService { let service = receiver.recv().unwrap(); match service { Ok(service) => { - Ok(BluetoothRemoteGATTService::new(&self.global_scope(), + Ok(BluetoothRemoteGATTService::new(&self.global(), &self.device.get(), DOMString::from(service.uuid), service.is_primary, @@ -201,7 +201,7 @@ impl BluetoothRemoteGATTService { match services_vec { Ok(service_vec) => { Ok(service_vec.into_iter() - .map(|service| BluetoothRemoteGATTService::new(&self.global_scope(), + .map(|service| BluetoothRemoteGATTService::new(&self.global(), &self.device.get(), DOMString::from(service.uuid), service.is_primary, @@ -236,7 +236,7 @@ impl BluetoothRemoteGATTServiceMethods for BluetoothRemoteGATTService { fn GetCharacteristic(&self, characteristic: BluetoothCharacteristicUUID) -> Rc { - result_to_promise(&self.global_scope(), self.get_characteristic(characteristic)) + result_to_promise(&self.global(), self.get_characteristic(characteristic)) } #[allow(unrooted_must_root)] @@ -244,7 +244,7 @@ impl BluetoothRemoteGATTServiceMethods for BluetoothRemoteGATTService { fn GetCharacteristics(&self, characteristic: Option) -> Rc { - result_to_promise(&self.global_scope(), self.get_characteristics(characteristic)) + result_to_promise(&self.global(), self.get_characteristics(characteristic)) } #[allow(unrooted_must_root)] @@ -252,7 +252,7 @@ impl BluetoothRemoteGATTServiceMethods for BluetoothRemoteGATTService { fn GetIncludedService(&self, service: BluetoothServiceUUID) -> Rc { - result_to_promise(&self.global_scope(), self.get_included_service(service)) + result_to_promise(&self.global(), self.get_included_service(service)) } #[allow(unrooted_must_root)] @@ -260,6 +260,6 @@ impl BluetoothRemoteGATTServiceMethods for BluetoothRemoteGATTService { fn GetIncludedServices(&self, service: Option) -> Rc { - result_to_promise(&self.global_scope(), self.get_included_services(service)) + result_to_promise(&self.global(), self.get_included_services(service)) } } diff --git a/components/script/dom/canvasrenderingcontext2d.rs b/components/script/dom/canvasrenderingcontext2d.rs index c95ada7054d..f2436f73419 100644 --- a/components/script/dom/canvasrenderingcontext2d.rs +++ b/components/script/dom/canvasrenderingcontext2d.rs @@ -1016,12 +1016,12 @@ impl CanvasRenderingContext2DMethods for CanvasRenderingContext2D { let sw = cmp::max(1, sw.abs().to_u32().unwrap()); let sh = cmp::max(1, sh.abs().to_u32().unwrap()); - Ok(ImageData::new(&self.global_scope(), sw, sh, None)) + Ok(ImageData::new(&self.global(), sw, sh, None)) } // https://html.spec.whatwg.org/multipage/#dom-context-2d-createimagedata fn CreateImageData_(&self, imagedata: &ImageData) -> Fallible> { - Ok(ImageData::new(&self.global_scope(), + Ok(ImageData::new(&self.global(), imagedata.Width(), imagedata.Height(), None)) @@ -1077,7 +1077,7 @@ impl CanvasRenderingContext2DMethods for CanvasRenderingContext2D { chunk[2] = UNPREMULTIPLY_TABLE[256 * alpha + chunk[2] as usize]; } - Ok(ImageData::new(&self.global_scope(), sw, sh, Some(data))) + Ok(ImageData::new(&self.global(), sw, sh, Some(data))) } // https://html.spec.whatwg.org/multipage/#dom-context-2d-putimagedata @@ -1121,7 +1121,7 @@ impl CanvasRenderingContext2DMethods for CanvasRenderingContext2D { x1: Finite, y1: Finite) -> Root { - CanvasGradient::new(&self.global_scope(), + CanvasGradient::new(&self.global(), CanvasGradientStyle::Linear(LinearGradientStyle::new(*x0, *y0, *x1, @@ -1142,7 +1142,7 @@ impl CanvasRenderingContext2DMethods for CanvasRenderingContext2D { return Err(Error::IndexSize); } - Ok(CanvasGradient::new(&self.global_scope(), + Ok(CanvasGradient::new(&self.global(), CanvasGradientStyle::Radial(RadialGradientStyle::new(*x0, *y0, *r0, @@ -1182,7 +1182,7 @@ impl CanvasRenderingContext2DMethods for CanvasRenderingContext2D { } if let Ok(rep) = RepetitionStyle::from_str(&repetition) { - Ok(CanvasPattern::new(&self.global_scope(), + Ok(CanvasPattern::new(&self.global(), image_data, image_size, rep, diff --git a/components/script/dom/dommatrixreadonly.rs b/components/script/dom/dommatrixreadonly.rs index 1f4a2fc1446..fa7c819a1ba 100644 --- a/components/script/dom/dommatrixreadonly.rs +++ b/components/script/dom/dommatrixreadonly.rs @@ -463,50 +463,50 @@ impl DOMMatrixReadOnlyMethods for DOMMatrixReadOnly { // https://drafts.fxtf.org/geometry-1/#dom-dommatrixreadonly-translate fn Translate(&self, tx: f64, ty: f64, tz: f64) -> Root { - DOMMatrix::from_readonly(&self.global_scope(), self).TranslateSelf(tx, ty, tz) + DOMMatrix::from_readonly(&self.global(), self).TranslateSelf(tx, ty, tz) } // https://drafts.fxtf.org/geometry-1/#dom-dommatrixreadonly-scale fn Scale(&self, scaleX: f64, scaleY: Option, scaleZ: f64, originX: f64, originY: f64, originZ: f64) -> Root { - DOMMatrix::from_readonly(&self.global_scope(), self) + DOMMatrix::from_readonly(&self.global(), self) .ScaleSelf(scaleX, scaleY, scaleZ, originX, originY, originZ) } // https://drafts.fxtf.org/geometry-1/#dom-dommatrixreadonly-scale3d fn Scale3d(&self, scale: f64, originX: f64, originY: f64, originZ: f64) -> Root { - DOMMatrix::from_readonly(&self.global_scope(), self) + DOMMatrix::from_readonly(&self.global(), self) .Scale3dSelf(scale, originX, originY, originZ) } // https://drafts.fxtf.org/geometry-1/#dom-dommatrixreadonly-rotate fn Rotate(&self, rotX: f64, rotY: Option, rotZ: Option) -> Root { - DOMMatrix::from_readonly(&self.global_scope(), self).RotateSelf(rotX, rotY, rotZ) + DOMMatrix::from_readonly(&self.global(), self).RotateSelf(rotX, rotY, rotZ) } // https://drafts.fxtf.org/geometry-1/#dom-dommatrixreadonly-rotatefromvector fn RotateFromVector(&self, x: f64, y: f64) -> Root { - DOMMatrix::from_readonly(&self.global_scope(), self).RotateFromVectorSelf(x, y) + DOMMatrix::from_readonly(&self.global(), self).RotateFromVectorSelf(x, y) } // https://drafts.fxtf.org/geometry-1/#dom-dommatrixreadonly-rotateaxisangle fn RotateAxisAngle(&self, x: f64, y: f64, z: f64, angle: f64) -> Root { - DOMMatrix::from_readonly(&self.global_scope(), self).RotateAxisAngleSelf(x, y, z, angle) + DOMMatrix::from_readonly(&self.global(), self).RotateAxisAngleSelf(x, y, z, angle) } // https://drafts.fxtf.org/geometry-1/#dom-dommatrixreadonly-skewx fn SkewX(&self, sx: f64) -> Root { - DOMMatrix::from_readonly(&self.global_scope(), self).SkewXSelf(sx) + DOMMatrix::from_readonly(&self.global(), self).SkewXSelf(sx) } // https://drafts.fxtf.org/geometry-1/#dom-dommatrixreadonly-skewy fn SkewY(&self, sy: f64) -> Root { - DOMMatrix::from_readonly(&self.global_scope(), self).SkewYSelf(sy) + DOMMatrix::from_readonly(&self.global(), self).SkewYSelf(sy) } // https://drafts.fxtf.org/geometry-1/#dom-dommatrixreadonly-multiply fn Multiply(&self, other: &DOMMatrixInit) -> Fallible> { - DOMMatrix::from_readonly(&self.global_scope(), self).MultiplySelf(&other) + DOMMatrix::from_readonly(&self.global(), self).MultiplySelf(&other) } // https://drafts.fxtf.org/geometry-1/#dom-dommatrixreadonly-flipx @@ -517,7 +517,7 @@ impl DOMMatrixReadOnlyMethods for DOMMatrixReadOnly { 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0); let matrix = flip.post_mul(&self.matrix.borrow()); - DOMMatrix::new(&self.global_scope(), is2D, matrix) + DOMMatrix::new(&self.global(), is2D, matrix) } // https://drafts.fxtf.org/geometry-1/#dom-dommatrixreadonly-flipy @@ -528,12 +528,12 @@ impl DOMMatrixReadOnlyMethods for DOMMatrixReadOnly { 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0); let matrix = flip.post_mul(&self.matrix.borrow()); - DOMMatrix::new(&self.global_scope(), is2D, matrix) + DOMMatrix::new(&self.global(), is2D, matrix) } // https://drafts.fxtf.org/geometry-1/#dom-dommatrixreadonly-inverse fn Inverse(&self) -> Root { - DOMMatrix::from_readonly(&self.global_scope(), self).InvertSelf() + DOMMatrix::from_readonly(&self.global(), self).InvertSelf() } // https://drafts.fxtf.org/geometry-1/#dom-dommatrixreadonly-transformpoint @@ -541,7 +541,7 @@ impl DOMMatrixReadOnlyMethods for DOMMatrixReadOnly { let matrix = self.matrix.borrow(); let result = matrix.transform_point4d(&Point4D::new(point.x, point.y, point.z, point.w)); DOMPoint::new( - &self.global_scope(), + &self.global(), result.x as f64, result.y as f64, result.z as f64, diff --git a/components/script/dom/domquad.rs b/components/script/dom/domquad.rs index abe30f80bdd..7d80dc9d8fd 100644 --- a/components/script/dom/domquad.rs +++ b/components/script/dom/domquad.rs @@ -107,7 +107,7 @@ impl DOMQuadMethods for DOMQuad { let right = self.p1.X().max(self.p2.X()).max(self.p3.X()).max(self.p4.X()); let bottom = self.p1.Y().max(self.p2.Y()).max(self.p3.Y()).max(self.p4.Y()); - DOMRect::new(&self.global_scope(), + DOMRect::new(&self.global(), left, top, right - left, diff --git a/components/script/dom/eventdispatcher.rs b/components/script/dom/eventdispatcher.rs index 5ed7c5effe1..cb7107e92e5 100644 --- a/components/script/dom/eventdispatcher.rs +++ b/components/script/dom/eventdispatcher.rs @@ -51,7 +51,7 @@ fn dispatch_to_listeners(event: &Event, target: &EventTarget, event_path: &[&Eve assert!(!event.stop_propagation()); assert!(!event.stop_immediate()); - let window = match Root::downcast::(target.global_scope()) { + let window = match Root::downcast::(target.global()) { Some(window) => { if window.need_emit_timeline_marker(TimelineMarkerType::DOMEvent) { Some(window) diff --git a/components/script/dom/eventtarget.rs b/components/script/dom/eventtarget.rs index b86e0991ccf..6d6ea81c7b6 100644 --- a/components/script/dom/eventtarget.rs +++ b/components/script/dom/eventtarget.rs @@ -154,7 +154,7 @@ impl CompiledEventListener { match *handler { CommonEventHandler::ErrorEventHandler(ref handler) => { if let Some(event) = event.downcast::() { - let cx = object.global_scope().get_cx(); + let cx = object.global().get_cx(); rooted!(in(cx) let error = event.Error(cx)); let return_value = handler.Call_(object, EventOrString::String(event.Message()), @@ -200,7 +200,7 @@ impl CompiledEventListener { CommonEventHandler::EventHandler(ref handler) => { if let Ok(value) = handler.Call_(object, event, exception_handle) { - let cx = object.global_scope().get_cx(); + let cx = object.global().get_cx(); rooted!(in(cx) let value = value); let value = value.handle(); @@ -498,7 +498,7 @@ impl EventTarget { bubbles: EventBubbles, cancelable: EventCancelable) -> Root { - let event = Event::new(&self.global_scope(), Atom::from(name), bubbles, cancelable); + let event = Event::new(&self.global(), Atom::from(name), bubbles, cancelable); event.fire(self); diff --git a/components/script/dom/filereader.rs b/components/script/dom/filereader.rs index b6d1e5cf216..296a6461b55 100644 --- a/components/script/dom/filereader.rs +++ b/components/script/dom/filereader.rs @@ -114,7 +114,7 @@ impl FileReader { fr.change_ready_state(FileReaderReadyState::Done); *fr.result.borrow_mut() = None; - let exception = DOMException::new(&fr.global_scope(), error); + let exception = DOMException::new(&fr.global(), error); fr.error.set(Some(&exception)); fr.dispatch_progress_event(atom!("error"), 0, None); @@ -288,7 +288,7 @@ impl FileReaderMethods for FileReader { // Steps 1 & 3 *self.result.borrow_mut() = None; - let exception = DOMException::new(&self.global_scope(), DOMErrorName::AbortError); + let exception = DOMException::new(&self.global(), DOMErrorName::AbortError); self.error.set(Some(&exception)); self.terminate_ongoing_reading(); @@ -316,7 +316,7 @@ impl FileReaderMethods for FileReader { impl FileReader { fn dispatch_progress_event(&self, type_: Atom, loaded: u64, total: Option) { - let progressevent = ProgressEvent::new(&self.global_scope(), + let progressevent = ProgressEvent::new(&self.global(), type_, EventBubbles::DoesNotBubble, EventCancelable::NotCancelable, total.is_some(), loaded, total.unwrap_or(0)); progressevent.upcast::().fire(self.upcast()); @@ -333,7 +333,7 @@ impl FileReader { return Err(Error::InvalidState); } // Step 2 - let global = self.global_scope(); + let global = self.global(); if blob.IsClosed() { let exception = DOMException::new(&global, DOMErrorName::InvalidStateError); self.error.set(Some(&exception)); @@ -355,7 +355,7 @@ impl FileReader { let fr = Trusted::new(self); let gen_id = self.generation_id.get(); - let global = self.global_scope(); + let global = self.global(); let wrapper = global.get_runnable_wrapper(); let task_source = global.file_reading_task_source(); diff --git a/components/script/dom/formdata.rs b/components/script/dom/formdata.rs index 8bbd46833b3..2c8f99b424b 100644 --- a/components/script/dom/formdata.rs +++ b/components/script/dom/formdata.rs @@ -152,7 +152,7 @@ impl FormData { let bytes = blob.get_bytes().unwrap_or(vec![]); - File::new(&self.global_scope(), BlobImpl::new_from_bytes(bytes), name, None, "") + File::new(&self.global(), BlobImpl::new_from_bytes(bytes), name, None, "") } pub fn datums(&self) -> Vec { diff --git a/components/script/dom/htmlformcontrolscollection.rs b/components/script/dom/htmlformcontrolscollection.rs index 5edc19232d4..3986692099c 100644 --- a/components/script/dom/htmlformcontrolscollection.rs +++ b/components/script/dom/htmlformcontrolscollection.rs @@ -65,7 +65,7 @@ impl HTMLFormControlsCollectionMethods for HTMLFormControlsCollection { // Step 4-5 let once = iter::once(Root::upcast::(elem)); let list = once.chain(peekable.map(Root::upcast)); - let global = self.global_scope(); + let global = self.global(); let window = global.as_window(); Some(RadioNodeListOrElement::RadioNodeList(RadioNodeList::new_simple_list(window, list))) } diff --git a/components/script/dom/htmllinkelement.rs b/components/script/dom/htmllinkelement.rs index b387990b68e..937bdc410d4 100644 --- a/components/script/dom/htmllinkelement.rs +++ b/components/script/dom/htmllinkelement.rs @@ -267,7 +267,7 @@ impl HTMLLinkElement { credentials_mode: CredentialsMode::Include, use_url_credentials: true, origin: document.url().clone(), - pipeline_id: Some(self.global_scope().pipeline_id()), + pipeline_id: Some(self.global().pipeline_id()), referrer_url: Some(document.url().clone()), referrer_policy: referrer_policy, .. RequestInit::default() diff --git a/components/script/dom/htmlscriptelement.rs b/components/script/dom/htmlscriptelement.rs index 1bee0c9c32f..fa1604ffc2b 100644 --- a/components/script/dom/htmlscriptelement.rs +++ b/components/script/dom/htmlscriptelement.rs @@ -242,7 +242,7 @@ fn fetch_a_classic_script(script: &HTMLScriptElement, _ => CredentialsMode::Include, }, origin: doc.url().clone(), - pipeline_id: Some(script.global_scope().pipeline_id()), + pipeline_id: Some(script.global().pipeline_id()), referrer_url: Some(doc.url().clone()), referrer_policy: doc.get_referrer_policy(), .. RequestInit::default() diff --git a/components/script/dom/navigator.rs b/components/script/dom/navigator.rs index 51dbf5bbfa7..bea18dfe61b 100644 --- a/components/script/dom/navigator.rs +++ b/components/script/dom/navigator.rs @@ -79,7 +79,7 @@ impl NavigatorMethods for Navigator { // https://webbluetoothcg.github.io/web-bluetooth/#dom-navigator-bluetooth fn Bluetooth(&self) -> Root { - self.bluetooth.or_init(|| Bluetooth::new(&self.global_scope())) + self.bluetooth.or_init(|| Bluetooth::new(&self.global())) } // https://html.spec.whatwg.org/multipage/#navigatorlanguage @@ -89,12 +89,12 @@ impl NavigatorMethods for Navigator { // https://html.spec.whatwg.org/multipage/#dom-navigator-plugins fn Plugins(&self) -> Root { - self.plugins.or_init(|| PluginArray::new(&self.global_scope())) + self.plugins.or_init(|| PluginArray::new(&self.global())) } // https://html.spec.whatwg.org/multipage/#dom-navigator-mimetypes fn MimeTypes(&self) -> Root { - self.mime_types.or_init(|| MimeTypeArray::new(&self.global_scope())) + self.mime_types.or_init(|| MimeTypeArray::new(&self.global())) } // https://html.spec.whatwg.org/multipage/#dom-navigator-javaenabled @@ -105,7 +105,7 @@ impl NavigatorMethods for Navigator { // https://w3c.github.io/ServiceWorker/#navigator-service-worker-attribute fn ServiceWorker(&self) -> Root { self.service_worker.or_init(|| { - ServiceWorkerContainer::new(&self.global_scope()) + ServiceWorkerContainer::new(&self.global()) }) } diff --git a/components/script/dom/promise.rs b/components/script/dom/promise.rs index 9c1feb0154d..c0842dce4fa 100644 --- a/components/script/dom/promise.rs +++ b/components/script/dom/promise.rs @@ -61,7 +61,7 @@ impl PromiseHelper for Rc { impl Drop for Promise { #[allow(unsafe_code)] fn drop(&mut self) { - let cx = self.global_scope().get_cx(); + let cx = self.global().get_cx(); unsafe { RemoveRawValueRoot(cx, self.permanent_js_root.get_unsafe()); } @@ -81,7 +81,7 @@ impl Promise { #[allow(unsafe_code, unrooted_must_root)] pub fn duplicate(&self) -> Rc { - let cx = self.global_scope().get_cx(); + let cx = self.global().get_cx(); unsafe { Promise::new_with_js_promise(self.reflector().get_jsobject(), cx) } @@ -166,7 +166,7 @@ impl Promise { pub fn reject_error(&self, cx: *mut JSContext, error: Error) { rooted!(in(cx) let mut v = UndefinedValue()); unsafe { - error.to_jsval(cx, &self.global_scope(), v.handle_mut()); + error.to_jsval(cx, &self.global(), v.handle_mut()); } self.reject(cx, v.handle()); } @@ -210,7 +210,7 @@ impl Promise { #[allow(unsafe_code)] pub fn append_native_handler(&self, handler: &PromiseNativeHandler) { - let cx = self.global_scope().get_cx(); + let cx = self.global().get_cx(); rooted!(in(cx) let resolve_func = create_native_handler_function(cx, handler.reflector().get_jsobject(), diff --git a/components/script/dom/request.rs b/components/script/dom/request.rs index 623a8037f62..efeafd5e289 100644 --- a/components/script/dom/request.rs +++ b/components/script/dom/request.rs @@ -305,7 +305,7 @@ impl Request { let r = Request::from_net_request(global, false, request); - r.headers.or_init(|| Headers::for_request(&r.global_scope())); + r.headers.or_init(|| Headers::for_request(&r.global())); // Step 27 let mut headers_copy = r.Headers(); @@ -429,7 +429,7 @@ impl Request { let body_used = r.body_used.get(); let mime_type = r.mime_type.borrow().clone(); let headers_guard = r.Headers().get_guard(); - let r_clone = Request::new(&r.global_scope(), url, is_service_worker_global_scope); + let r_clone = Request::new(&r.global(), url, is_service_worker_global_scope); r_clone.request.borrow_mut().pipeline_id.set(req.pipeline_id.get()); { let mut borrowed_r_request = r_clone.request.borrow_mut(); @@ -549,7 +549,7 @@ impl RequestMethods for Request { // https://fetch.spec.whatwg.org/#dom-request-headers fn Headers(&self) -> Root { - self.headers.or_init(|| Headers::new(&self.global_scope())) + self.headers.or_init(|| Headers::new(&self.global())) } // https://fetch.spec.whatwg.org/#dom-request-type diff --git a/components/script/dom/response.rs b/components/script/dom/response.rs index febff29f97b..cabbd567b49 100644 --- a/components/script/dom/response.rs +++ b/components/script/dom/response.rs @@ -292,7 +292,7 @@ impl ResponseMethods for Response { // https://fetch.spec.whatwg.org/#dom-response-headers fn Headers(&self) -> Root { - self.headers_reflector.or_init(|| Headers::for_response(&self.global_scope())) + self.headers_reflector.or_init(|| Headers::for_response(&self.global())) } // https://fetch.spec.whatwg.org/#dom-response-clone @@ -301,7 +301,7 @@ impl ResponseMethods for Response { // TODO: This step relies on body and stream, which are still unimplemented. // Step 2 - let new_response = Response::new(&self.global_scope()); + let new_response = Response::new(&self.global()); new_response.Headers().set_guard(self.Headers().get_guard()); // https://fetch.spec.whatwg.org/#concept-response-clone diff --git a/components/script/dom/serviceworker.rs b/components/script/dom/serviceworker.rs index 3b3cd58eee4..8f3686f0b0c 100644 --- a/components/script/dom/serviceworker.rs +++ b/components/script/dom/serviceworker.rs @@ -90,7 +90,7 @@ impl ServiceWorkerMethods for ServiceWorker { let data = try!(StructuredCloneData::write(cx, message)); let msg_vec = DOMMessage(data.move_to_arraybuffer()); let _ = - self.global_scope() + self.global() .constellation_chan() .send(ScriptMsg::ForwardDOMMessage(msg_vec, self.scope_url.clone())); Ok(()) diff --git a/components/script/dom/serviceworkercontainer.rs b/components/script/dom/serviceworkercontainer.rs index c5d27017f8e..0947b9c0a1f 100644 --- a/components/script/dom/serviceworkercontainer.rs +++ b/components/script/dom/serviceworkercontainer.rs @@ -58,7 +58,7 @@ impl ServiceWorkerContainerMethods for ServiceWorkerContainer { script_url: USVString, options: &RegistrationOptions) -> Fallible> { let USVString(ref script_url) = script_url; - let api_base_url = self.global_scope().api_base_url(); + let api_base_url = self.global().api_base_url(); // Step 3-4 let script_url = match api_base_url.join(script_url) { Ok(url) => url, @@ -96,7 +96,7 @@ impl ServiceWorkerContainerMethods for ServiceWorkerContainer { return Err(Error::Type("Scope URL contains forbidden characters".to_owned())); } - let global = self.global_scope(); + let global = self.global(); let worker_registration = ServiceWorkerRegistration::new(&global, script_url, scope.clone(), diff --git a/components/script/dom/storage.rs b/components/script/dom/storage.rs index 83d9ab4bf61..b8a3865cadd 100644 --- a/components/script/dom/storage.rs +++ b/components/script/dom/storage.rs @@ -40,11 +40,11 @@ impl Storage { } fn get_url(&self) -> Url { - self.global_scope().get_url() + self.global().get_url() } fn get_storage_thread(&self) -> IpcSender { - self.global_scope().resource_threads().sender() + self.global().resource_threads().sender() } } @@ -150,7 +150,7 @@ impl Storage { /// https://html.spec.whatwg.org/multipage/#send-a-storage-notification fn broadcast_change_notification(&self, key: Option, old_value: Option, new_value: Option) { - let global = self.global_scope(); + let global = self.global(); let window = global.as_window(); let task_source = window.dom_manipulation_task_source(); let trusted_storage = Trusted::new(self); @@ -182,7 +182,7 @@ impl Runnable for StorageEventRunnable { let this = *self; let storage_root = this.element.root(); let storage = storage_root.r(); - let global = storage.global_scope(); + let global = storage.global(); let ev_url = storage.get_url(); let storage_event = StorageEvent::new( diff --git a/components/script/dom/testbinding.rs b/components/script/dom/testbinding.rs index b5d77809147..fe76ddccab9 100644 --- a/components/script/dom/testbinding.rs +++ b/components/script/dom/testbinding.rs @@ -113,7 +113,7 @@ impl TestBindingMethods for TestBinding { fn EnumAttribute(&self) -> TestEnum { TestEnum::_empty } fn SetEnumAttribute(&self, _: TestEnum) {} fn InterfaceAttribute(&self) -> Root { - Blob::new(&self.global_scope(), BlobImpl::new_from_bytes(vec![]), "".to_owned()) + Blob::new(&self.global(), BlobImpl::new_from_bytes(vec![]), "".to_owned()) } fn SetInterfaceAttribute(&self, _: &Blob) {} fn UnionAttribute(&self) -> HTMLElementOrLong { HTMLElementOrLong::Long(0) } @@ -209,7 +209,7 @@ impl TestBindingMethods for TestBinding { fn SetAttr_to_automatically_rename(&self, _: DOMString) {} fn GetEnumAttributeNullable(&self) -> Option { Some(TestEnum::_empty) } fn GetInterfaceAttributeNullable(&self) -> Option> { - Some(Blob::new(&self.global_scope(), BlobImpl::new_from_bytes(vec![]), "".to_owned())) + Some(Blob::new(&self.global(), BlobImpl::new_from_bytes(vec![]), "".to_owned())) } fn SetInterfaceAttributeNullable(&self, _: Option<&Blob>) {} fn GetInterfaceAttributeWeak(&self) -> Option> { @@ -264,7 +264,7 @@ impl TestBindingMethods for TestBinding { fn ReceiveByteString(&self) -> ByteString { ByteString::new(vec!()) } fn ReceiveEnum(&self) -> TestEnum { TestEnum::_empty } fn ReceiveInterface(&self) -> Root { - Blob::new(&self.global_scope(), BlobImpl::new_from_bytes(vec![]), "".to_owned()) + Blob::new(&self.global(), BlobImpl::new_from_bytes(vec![]), "".to_owned()) } fn ReceiveAny(&self, _: *mut JSContext) -> JSVal { NullValue() } fn ReceiveObject(&self, cx: *mut JSContext) -> NonZero<*mut JSObject> { @@ -287,7 +287,7 @@ impl TestBindingMethods for TestBinding { } fn ReceiveSequence(&self) -> Vec { vec![1] } fn ReceiveInterfaceSequence(&self) -> Vec> { - vec![Blob::new(&self.global_scope(), BlobImpl::new_from_bytes(vec![]), "".to_owned())] + vec![Blob::new(&self.global(), BlobImpl::new_from_bytes(vec![]), "".to_owned())] } fn ReceiveNullableBoolean(&self) -> Option { Some(false) } @@ -308,7 +308,7 @@ impl TestBindingMethods for TestBinding { fn ReceiveNullableByteString(&self) -> Option { Some(ByteString::new(vec!())) } fn ReceiveNullableEnum(&self) -> Option { Some(TestEnum::_empty) } fn ReceiveNullableInterface(&self) -> Option> { - Some(Blob::new(&self.global_scope(), BlobImpl::new_from_bytes(vec![]), "".to_owned())) + Some(Blob::new(&self.global(), BlobImpl::new_from_bytes(vec![]), "".to_owned())) } fn ReceiveNullableObject(&self, cx: *mut JSContext) -> Option> { self.GetObjectAttributeNullable(cx) @@ -655,12 +655,12 @@ impl TestBindingMethods for TestBinding { #[allow(unrooted_must_root)] fn ReturnResolvedPromise(&self, cx: *mut JSContext, v: HandleValue) -> Fallible> { - Promise::Resolve(&self.global_scope(), cx, v) + Promise::Resolve(&self.global(), cx, v) } #[allow(unrooted_must_root)] fn ReturnRejectedPromise(&self, cx: *mut JSContext, v: HandleValue) -> Fallible> { - Promise::Reject(&self.global_scope(), cx, v) + Promise::Reject(&self.global(), cx, v) } fn PromiseResolveNative(&self, cx: *mut JSContext, p: &Promise, v: HandleValue) { @@ -672,7 +672,7 @@ impl TestBindingMethods for TestBinding { } fn PromiseRejectWithTypeError(&self, p: &Promise, s: USVString) { - p.reject_error(self.global_scope().get_cx(), Error::Type(s.0)); + p.reject_error(self.global().get_cx(), Error::Type(s.0)); } #[allow(unrooted_must_root)] @@ -682,7 +682,7 @@ impl TestBindingMethods for TestBinding { promise: TrustedPromise::new(promise), value: value, }; - let _ = self.global_scope() + let _ = self.global() .schedule_callback( OneshotTimerCallback::TestBindingCallback(cb), MsDuration::new(delay)); @@ -692,7 +692,7 @@ impl TestBindingMethods for TestBinding { fn PromiseNativeHandler(&self, resolve: Option>, reject: Option>) -> Rc { - let global = self.global_scope(); + let global = self.global(); let handler = PromiseNativeHandler::new(&global, resolve.map(SimpleHandler::new), reject.map(SimpleHandler::new)); @@ -721,7 +721,7 @@ impl TestBindingMethods for TestBinding { #[allow(unrooted_must_root)] fn PromiseAttribute(&self) -> Rc { - Promise::new(&self.global_scope()) + Promise::new(&self.global()) } fn AcceptPromise(&self, _promise: &Promise) { @@ -751,7 +751,7 @@ impl TestBindingMethods for TestBinding { } fn AdvanceClock(&self, ms: i32, tick: bool) { - self.global_scope().as_window().advance_animation_clock(ms, tick); + self.global().as_window().advance_animation_clock(ms, tick); } fn Panic(&self) { panic!("explicit panic from script") } @@ -788,7 +788,7 @@ impl TestBindingCallback { #[allow(unrooted_must_root)] pub fn invoke(self) { let p = self.promise.root(); - let cx = p.global_scope().get_cx(); + let cx = p.global().get_cx(); let _ac = JSAutoCompartment::new(cx, p.reflector().get_jsobject().get()); p.resolve_native(cx, &self.value); } diff --git a/components/script/dom/url.rs b/components/script/dom/url.rs index 9ff223a74c6..35dc4d896fa 100644 --- a/components/script/dom/url.rs +++ b/components/script/dom/url.rs @@ -284,7 +284,7 @@ impl URLMethods for URL { // https://url.spec.whatwg.org/#dom-url-searchparams fn SearchParams(&self) -> Root { self.search_params.or_init(|| { - URLSearchParams::new(&self.global_scope(), Some(self)) + URLSearchParams::new(&self.global(), Some(self)) }) } diff --git a/components/script/dom/webglprogram.rs b/components/script/dom/webglprogram.rs index 5c2648de4b9..98139081c3b 100644 --- a/components/script/dom/webglprogram.rs +++ b/components/script/dom/webglprogram.rs @@ -230,7 +230,7 @@ impl WebGLProgram { .unwrap(); receiver.recv().unwrap().map(|(size, ty, name)| - WebGLActiveInfo::new(&self.global_scope(), size, ty, DOMString::from(name))) + WebGLActiveInfo::new(&self.global(), size, ty, DOMString::from(name))) } /// glGetActiveAttrib @@ -244,7 +244,7 @@ impl WebGLProgram { .unwrap(); receiver.recv().unwrap().map(|(size, ty, name)| - WebGLActiveInfo::new(&self.global_scope(), size, ty, DOMString::from(name))) + WebGLActiveInfo::new(&self.global(), size, ty, DOMString::from(name))) } /// glGetAttribLocation diff --git a/components/script/dom/webglrenderingcontext.rs b/components/script/dom/webglrenderingcontext.rs index 0f9e6072a30..312357fd3d2 100644 --- a/components/script/dom/webglrenderingcontext.rs +++ b/components/script/dom/webglrenderingcontext.rs @@ -1153,27 +1153,27 @@ impl WebGLRenderingContextMethods for WebGLRenderingContext { // generated objects, either here or in the webgl thread // https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.5 fn CreateBuffer(&self) -> Option> { - WebGLBuffer::maybe_new(&self.global_scope(), self.ipc_renderer.clone()) + WebGLBuffer::maybe_new(&self.global(), self.ipc_renderer.clone()) } // https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.6 fn CreateFramebuffer(&self) -> Option> { - WebGLFramebuffer::maybe_new(&self.global_scope(), self.ipc_renderer.clone()) + WebGLFramebuffer::maybe_new(&self.global(), self.ipc_renderer.clone()) } // https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.7 fn CreateRenderbuffer(&self) -> Option> { - WebGLRenderbuffer::maybe_new(&self.global_scope(), self.ipc_renderer.clone()) + WebGLRenderbuffer::maybe_new(&self.global(), self.ipc_renderer.clone()) } // https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.8 fn CreateTexture(&self) -> Option> { - WebGLTexture::maybe_new(&self.global_scope(), self.ipc_renderer.clone()) + WebGLTexture::maybe_new(&self.global(), self.ipc_renderer.clone()) } // https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.9 fn CreateProgram(&self) -> Option> { - WebGLProgram::maybe_new(&self.global_scope(), self.ipc_renderer.clone()) + WebGLProgram::maybe_new(&self.global(), self.ipc_renderer.clone()) } // https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.9 @@ -1185,7 +1185,7 @@ impl WebGLRenderingContextMethods for WebGLRenderingContext { return None; } } - WebGLShader::maybe_new(&self.global_scope(), self.ipc_renderer.clone(), shader_type) + WebGLShader::maybe_new(&self.global(), self.ipc_renderer.clone(), shader_type) } // https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.5 @@ -1479,7 +1479,7 @@ impl WebGLRenderingContextMethods for WebGLRenderingContext { name: DOMString) -> Option> { program.and_then(|p| { handle_potential_webgl_error!(self, p.get_uniform_location(name), None) - .map(|location| WebGLUniformLocation::new(&self.global_scope(), location, p.id())) + .map(|location| WebGLUniformLocation::new(&self.global(), location, p.id())) }) } diff --git a/components/script/dom/websocket.rs b/components/script/dom/websocket.rs index eb8b3cebf4f..2582367ec08 100644 --- a/components/script/dom/websocket.rs +++ b/components/script/dom/websocket.rs @@ -328,7 +328,7 @@ impl WebSocket { address: address, }; - self.global_scope() + self.global() .script_chan() .send(CommonScriptMsg::RunnableMsg(WebSocketEvent, task)) .unwrap(); @@ -436,7 +436,7 @@ impl WebSocketMethods for WebSocket { self.ready_state.set(WebSocketRequestState::Closing); let address = Trusted::new(self); - let sender = self.global_scope().networking_task_source(); + let sender = self.global().networking_task_source(); fail_the_websocket_connection(address, sender); } WebSocketRequestState::Open => { @@ -470,7 +470,7 @@ impl Runnable for ConnectionEstablishedTask { // Step 1: Protocols. if !self.protocols.is_empty() && self.headers.get::().is_none() { - let sender = ws.global_scope().networking_task_source(); + let sender = ws.global().networking_task_source(); fail_the_websocket_connection(self.address, sender); return; } @@ -491,7 +491,7 @@ impl Runnable for ConnectionEstablishedTask { if let Some(cookies) = self.headers.get_raw("set-cookie") { for cookie in cookies.iter() { if let Ok(cookie_value) = String::from_utf8(cookie.clone()) { - let _ = ws.global_scope().core_resource_thread().send( + let _ = ws.global().core_resource_thread().send( SetCookiesForUrl(ws.url.clone(), cookie_value, HTTP)); } } @@ -555,7 +555,7 @@ impl Runnable for CloseTask { let clean_close = !self.failed; let code = self.code.unwrap_or(close_code::NO_STATUS); let reason = DOMString::from(self.reason.unwrap_or("".to_owned())); - let close_event = CloseEvent::new(&ws.global_scope(), + let close_event = CloseEvent::new(&ws.global(), atom!("close"), EventBubbles::DoesNotBubble, EventCancelable::NotCancelable, @@ -586,7 +586,7 @@ impl Runnable for MessageReceivedTask { } // Step 2-5. - let global = ws.global_scope(); + let global = ws.global(); // global.get_cx() returns a valid `JSContext` pointer, so this is safe. unsafe { let cx = global.get_cx(); diff --git a/components/script/dom/worker.rs b/components/script/dom/worker.rs index 328471be089..42ba8bb8e08 100644 --- a/components/script/dom/worker.rs +++ b/components/script/dom/worker.rs @@ -128,7 +128,7 @@ impl Worker { return; } - let global = worker.global_scope(); + let global = worker.global(); let target = worker.upcast(); let _ac = JSAutoCompartment::new(global.get_cx(), target.reflector().get_jsobject().get()); rooted!(in(global.get_cx()) let mut message = UndefinedValue()); @@ -143,7 +143,7 @@ impl Worker { #[allow(unsafe_code)] fn dispatch_error(&self, error_info: ErrorInfo) { - let global = self.global_scope(); + let global = self.global(); let event = ErrorEvent::new(&global, atom!("error"), EventBubbles::DoesNotBubble, diff --git a/components/script/dom/xmlhttprequest.rs b/components/script/dom/xmlhttprequest.rs index 9b0cbeeb580..cd2cd37c476 100644 --- a/components/script/dom/xmlhttprequest.rs +++ b/components/script/dom/xmlhttprequest.rs @@ -210,7 +210,7 @@ impl XMLHttpRequest { } fn sync_in_window(&self) -> bool { - self.sync.get() && self.global_scope().is::() + self.sync.get() && self.global().is::() } fn initiate_async_xhr(context: Arc>, @@ -282,7 +282,7 @@ impl LoadOrigin for XMLHttpRequest { } fn pipeline_id(&self) -> Option { - Some(self.global_scope().pipeline_id()) + Some(self.global().pipeline_id()) } } @@ -305,7 +305,7 @@ impl XMLHttpRequestMethods for XMLHttpRequest { fn Open_(&self, method: ByteString, url: USVString, async: bool, username: Option, password: Option) -> ErrorResult { // Step 1 - if let Some(window) = Root::downcast::(self.global_scope()) { + if let Some(window) = Root::downcast::(self.global()) { if !window.Document().r().is_fully_active() { return Err(Error::InvalidState); } @@ -339,7 +339,7 @@ impl XMLHttpRequestMethods for XMLHttpRequest { } // Step 2 - let base = self.global_scope().api_base_url(); + let base = self.global().api_base_url(); // Step 6 let mut parsed_url = match base.join(&url.0) { Ok(parsed) => parsed, @@ -571,7 +571,7 @@ impl XMLHttpRequestMethods for XMLHttpRequest { // preference is enabled, we allow bypassing the CORS check. // This is a temporary measure until we figure out Servo privilege // story. See https://github.com/servo/servo/issues/9582 - if let Some(win) = Root::downcast::(self.global_scope()) { + if let Some(win) = Root::downcast::(self.global()) { let is_root_pipeline = win.parent_info().is_none(); is_root_pipeline && PREFS.is_mozbrowser_enabled() } else { @@ -594,7 +594,7 @@ impl XMLHttpRequestMethods for XMLHttpRequest { use_cors_preflight: has_handlers, credentials_mode: credentials_mode, use_url_credentials: use_url_credentials, - origin: self.global_scope().get_url(), + origin: self.global().get_url(), referrer_url: self.referrer_url.clone(), referrer_policy: self.referrer_policy.clone(), pipeline_id: self.pipeline_id(), @@ -649,7 +649,7 @@ impl XMLHttpRequestMethods for XMLHttpRequest { self.fetch_time.set(time::now().to_timespec().sec); - let rv = self.fetch(request, &self.global_scope()); + let rv = self.fetch(request, &self.global()); // Step 10 if self.sync.get() { return rv; @@ -740,7 +740,7 @@ impl XMLHttpRequestMethods for XMLHttpRequest { // https://xhr.spec.whatwg.org/#the-responsetype-attribute fn SetResponseType(&self, response_type: XMLHttpRequestResponseType) -> ErrorResult { // Step 1 - if self.global_scope().is::() && response_type == XMLHttpRequestResponseType::Document { + if self.global().is::() && response_type == XMLHttpRequestResponseType::Document { return Ok(()); } match self.ready_state.get() { @@ -824,7 +824,7 @@ impl XMLHttpRequestMethods for XMLHttpRequest { fn GetResponseXML(&self) -> Fallible>> { // TODO(#2823): Until [Exposed] is implemented, this attribute needs to return null // explicitly in the worker scope. - if self.global_scope().is::() { + if self.global().is::() { return Ok(None); } @@ -855,7 +855,7 @@ impl XMLHttpRequest { fn change_ready_state(&self, rs: XMLHttpRequestState) { assert!(self.ready_state.get() != rs); self.ready_state.set(rs); - let event = Event::new(&self.global_scope(), + let event = Event::new(&self.global(), atom!("readystatechange"), EventBubbles::DoesNotBubble, EventCancelable::Cancelable); @@ -971,7 +971,7 @@ impl XMLHttpRequest { self.ready_state.set(XMLHttpRequestState::Loading); } let event = Event::new( - &self.global_scope(), + &self.global(), atom!("readystatechange"), EventBubbles::DoesNotBubble, EventCancelable::Cancelable); @@ -1043,7 +1043,7 @@ impl XMLHttpRequest { } fn dispatch_progress_event(&self, upload: bool, type_: Atom, loaded: u64, total: Option) { - let progressevent = ProgressEvent::new(&self.global_scope(), + let progressevent = ProgressEvent::new(&self.global(), type_, EventBubbles::DoesNotBubble, EventCancelable::NotCancelable, @@ -1078,12 +1078,12 @@ impl XMLHttpRequest { }); let duration = Length::new(duration_ms as u64); *self.timeout_cancel.borrow_mut() = - Some(self.global_scope().schedule_callback(callback, duration)); + Some(self.global().schedule_callback(callback, duration)); } fn cancel_timeout(&self) { if let Some(handle) = self.timeout_cancel.borrow_mut().take() { - self.global_scope().unschedule_callback(handle); + self.global().unschedule_callback(handle); } } @@ -1110,7 +1110,7 @@ impl XMLHttpRequest { // Step 3, 4 let bytes = self.response.borrow().to_vec(); - let blob = Blob::new(&self.global_scope(), BlobImpl::new_from_bytes(bytes), mime); + let blob = Blob::new(&self.global(), BlobImpl::new_from_bytes(bytes), mime); self.response_blob.set(Some(blob.r())); blob } @@ -1195,7 +1195,7 @@ impl XMLHttpRequest { fn document_text_html(&self) -> Root{ let charset = self.final_charset().unwrap_or(UTF_8); - let wr = self.global_scope(); + let wr = self.global(); let decoded = charset.decode(&self.response.borrow(), DecoderTrap::Replace).unwrap(); let document = self.new_doc(IsHTMLDocument::HTMLDocument); // TODO: Disable scripting while parsing @@ -1208,7 +1208,7 @@ impl XMLHttpRequest { fn handle_xml(&self) -> Root { let charset = self.final_charset().unwrap_or(UTF_8); - let wr = self.global_scope(); + let wr = self.global(); let decoded = charset.decode(&self.response.borrow(), DecoderTrap::Replace).unwrap(); let document = self.new_doc(IsHTMLDocument::NonHTMLDocument); // TODO: Disable scripting while parsing @@ -1220,7 +1220,7 @@ impl XMLHttpRequest { } fn new_doc(&self, is_html_document: IsHTMLDocument) -> Root { - let wr = self.global_scope(); + let wr = self.global(); let win = wr.as_window(); let doc = win.Document(); let doc = doc.r(); diff --git a/components/script/fetch.rs b/components/script/fetch.rs index 372c0d9ee6c..6db6c5e4202 100644 --- a/components/script/fetch.rs +++ b/components/script/fetch.rs @@ -76,7 +76,7 @@ pub fn Fetch(global: &GlobalScope, input: RequestOrUSVString, init: &RequestInit // Step 2 let request = match Request::Constructor(global, input, init) { Err(e) => { - promise.reject_error(promise.global_scope().get_cx(), e); + promise.reject_error(promise.global().get_cx(), e); return promise; }, Ok(r) => r.get_request(), @@ -124,13 +124,13 @@ impl FetchResponseListener for FetchContext { // JSAutoCompartment needs to be manually made. // Otherwise, Servo will crash. - let promise_cx = promise.global_scope().get_cx(); + let promise_cx = promise.global().get_cx(); let _ac = JSAutoCompartment::new(promise_cx, promise.reflector().get_jsobject().get()); match fetch_metadata { // Step 4.1 Err(_) => { promise.reject_error( - promise.global_scope().get_cx(), + promise.global().get_cx(), Error::Type("Network error occurred".to_string())); self.fetch_promise = Some(TrustedPromise::new(promise)); return; diff --git a/components/script/timers.rs b/components/script/timers.rs index ddfd336cd4f..34ac02b6589 100644 --- a/components/script/timers.rs +++ b/components/script/timers.rs @@ -489,7 +489,7 @@ impl JsTimerTask { // step 4.2 match *&self.callback { InternalTimerCallback::StringTimerCallback(ref code_str) => { - let global = this.global_scope(); + let global = this.global(); let cx = global.get_cx(); rooted!(in(cx) let mut rval = UndefinedValue()); @@ -514,7 +514,7 @@ impl JsTimerTask { // reschedule repeating timers when they were not canceled as part of step 4.2. if self.is_interval == IsInterval::Interval && timers.active_timers.borrow().contains_key(&self.handle) { - timers.initialize_and_schedule(&this.global_scope(), self); + timers.initialize_and_schedule(&this.global(), self); } } }