diff options
author | bors-servo <lbergstrom+bors@mozilla.com> | 2016-10-07 07:52:09 -0500 |
---|---|---|
committer | GitHub <noreply@github.com> | 2016-10-07 07:52:09 -0500 |
commit | a6e4b5bb86ad707a0863acff87344ca4239cfd2c (patch) | |
tree | c820d9f2420c44cdfe29de97f1a710e7dc354bb7 /components | |
parent | e23959a7618e8e7b7ca20300a2afeb1ac77712f3 (diff) | |
parent | d8e92bb271a9f9dd87bf77e38cd820d01f2f0ae4 (diff) | |
download | servo-a6e4b5bb86ad707a0863acff87344ca4239cfd2c.tar.gz servo-a6e4b5bb86ad707a0863acff87344ca4239cfd2c.zip |
Auto merge of #13596 - nox:inline, r=Ms2ger
Get rid of dom::bindings::global
Globals in that PR are now represented by the fake IDL interface `GlobalScope`.
<!-- Reviewable:start -->
---
This change is [<img src="https://reviewable.io/review_button.svg" height="34" align="absmiddle" alt="Reviewable"/>](https://reviewable.io/reviews/servo/servo/13596)
<!-- Reviewable:end -->
Diffstat (limited to 'components')
170 files changed, 1595 insertions, 1742 deletions
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<Option<Vec<u8>>>, // 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<Window>, // TODO: target browsing context pub keep_alive: Cell<bool>, diff --git a/components/script/body.rs b/components/script/body.rs index 276d6425d2f..c5b6008c363 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}; @@ -42,11 +42,11 @@ pub enum FetchedData { // https://fetch.spec.whatwg.org/#concept-body-consume-body #[allow(unrooted_must_root)] pub fn consume_body<T: BodyOperations + Reflectable>(object: &T, body_type: BodyType) -> Rc<Promise> { - let promise = Promise::new(object.global().r()); + let promise = Promise::new(&object.global()); // 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().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<T: BodyOperations + Reflectable>(object: &T, body_type, object.get_mime_type()); - let cx = promise.global().r().get_cx(); + let cx = promise.global().get_cx(); match pkg_data_results { Ok(results) => { match results { @@ -98,13 +98,14 @@ fn run_package_data_algorithm<T: BodyOperations + Reflectable>(object: &T, body_type: BodyType, mime_type: Ref<Vec<u8>>) -> Fallible<FetchedData> { - let cx = object.global().r().get_cx(); + let global = object.global(); + 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(), bytes, mime), - BodyType::FormData => run_form_data_algorithm(object.global().r(), bytes, mime), + BodyType::Blob => run_blob_data_algorithm(&global, bytes, mime), + BodyType::FormData => run_form_data_algorithm(&global, bytes, mime), } } @@ -132,7 +133,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<u8>, mime: &[u8]) -> Fallible<FetchedData> { let mime_string = if let Ok(s) = String::from_utf8(mime.to_vec()) { @@ -144,7 +145,7 @@ fn run_blob_data_algorithm(root: GlobalRef, Ok(FetchedData::BlobData(blob)) } -fn run_form_data_algorithm(root: GlobalRef, bytes: Vec<u8>, mime: &[u8]) -> Fallible<FetchedData> { +fn run_form_data_algorithm(root: &GlobalScope, bytes: Vec<u8>, mime: &[u8]) -> Fallible<FetchedData> { let mime_str = if let Ok(s) = str::from_utf8(mime) { s } else { diff --git a/components/script/devtools.rs b/components/script/devtools.rs index d515d1fb99a..dcaee91c843 100644 --- a/components/script/devtools.rs +++ b/components/script/devtools.rs @@ -13,13 +13,13 @@ 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; 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; @@ -33,7 +33,7 @@ use uuid::Uuid; #[allow(unsafe_code)] -pub fn handle_evaluate_js(global: &GlobalRef, eval: String, reply: IpcSender<EvaluateJSReply>) { +pub fn handle_evaluate_js(global: &GlobalScope, eval: String, reply: IpcSender<EvaluateJSReply>) { // global.get_cx() returns a valid `JSContext` pointer, so this is safe. let result = unsafe { let cx = global.get_cx(); @@ -245,7 +245,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); } @@ -271,7 +271,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::<GlobalScope>().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/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<BeforeUnloadEvent> { + pub fn new_uninitialized(global: &GlobalScope) -> Root<BeforeUnloadEvent> { 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<BeforeUnloadEvent> { diff --git a/components/script/dom/bindings/callback.rs b/components/script/dom/bindings/callback.rs index 7e6bb3534fb..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_root_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,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 { GlobalScope::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 4ea45ef9ded..24826ced714 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 = GlobalScope::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(), error); + throw_dom_exception(cx, &promiseGlobal, error); $*{exceptionCode} } } @@ -1927,10 +1927,12 @@ 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] - if descriptor.interface.parent: - parentName = getIdentifier(descriptor.interface.parent).name + name = getIdentifier(t).name + descriptor = descriptorProvider.getDescriptor(name) + if name != 'GlobalScope': + extras += [descriptor.path] + parentName = descriptor.getParentName() + if parentName: descriptor = descriptorProvider.getDescriptor(parentName) extras += [descriptor.path, descriptor.bindingPath] elif t.isType() and t.isMozMap(): @@ -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, @@ -2754,7 +2757,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 +2811,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)) @@ -3164,16 +3168,15 @@ class CGCallGenerator(CGThing): if isFallible: if static: - glob = "" + glob = "&global" else: - glob = " let global = global_root_from_reflector(this);\n" + glob = "&this.global()" 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))) @@ -3383,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 = GlobalScope::from_object(JS_CALLEE(cx, vp).to_object()); """) return CGList([preamble, self.generate_code()]) @@ -3435,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"], nativeName, True, self.descriptor, self.method) return CGList([setupArgs, call]) @@ -3489,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"], self.attr.type, nativeName, self.descriptor, self.attr) return CGList([setupArgs, call]) @@ -3542,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"], self.attr.type, nativeName, self.descriptor, self.attr) return CGList([checkForArg, call]) @@ -5249,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 = GlobalScope::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()"], nativeName, True, + callGenerator = CGMethodCall(["&global"], nativeName, True, self.descriptor, self.constructor) return CGList([preamble, callGenerator]) @@ -5496,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_root_from_object', - 'dom::bindings::global::global_root_from_object_maybe_wrapped', - 'dom::bindings::global::global_root_from_reflector', 'dom::bindings::interface::ConstructorClassHook', 'dom::bindings::interface::InterfaceConstructorBehavior', 'dom::bindings::interface::NonCallbackInterfaceObjectClass', @@ -5593,6 +5592,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', @@ -5744,33 +5744,38 @@ 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), 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() @@ -6799,7 +6804,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: @@ -6927,7 +6932,7 @@ class GlobalGenRoots(): allprotos.append(CGGeneric("\n")) if downcast: - hierarchy[descriptor.getParentName()].append(name) + hierarchy[descriptor.interface.parent.identifier.name].append(name) typeIdCode = [] topTypeVariants = [ @@ -6959,7 +6964,7 @@ impl Clone for TopTypeId { 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/bindings/error.rs b/components/script/dom/bindings/error.rs index 1c0d49c4976..96ae220ce98 100644 --- a/components/script/dom/bindings/error.rs +++ b/components/script/dom/bindings/error.rs @@ -8,9 +8,9 @@ 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::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 +87,7 @@ pub type Fallible<T> = Result<T, Error>; 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, @@ -245,8 +245,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()); + GlobalScope::from_context(cx) + .report_an_error(error_info, value.handle()); } } } @@ -270,7 +270,7 @@ 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, self); assert!(JS_IsExceptionPending(cx)); diff --git a/components/script/dom/bindings/global.rs b/components/script/dom/bindings/global.rs deleted file mode 100644 index e0341ceeb68..00000000000 --- a/components/script/dom/bindings/global.rs +++ /dev/null @@ -1,398 +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 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::js::Root; -use dom::bindings::reflector::{Reflectable, Reflector}; -use dom::console::TimerSet; -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}; -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::{mem, 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 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)] -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<window::Window>), - /// A root for a `WorkerGlobalScope` object. - Worker(Root<WorkerGlobalScope>), -} - -impl<'a> GlobalRef<'a> { - /// 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(), - } - } - - /// 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 `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 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 { - 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<ConstellationMsg> { - 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<TimerEventRequest> { - match *self { - GlobalRef::Window(window) => window.scheduler_chan(), - GlobalRef::Worker(worker) => worker.scheduler_chan(), - } - } - - /// Get an `IpcSender<ScriptToDevtoolsControlMsg>` to send messages to Devtools - /// thread when available. - pub fn devtools_chan(&self) -> Option<IpcSender<ScriptToDevtoolsControlMsg>> { - 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 { - 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() - } - - /// 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 { - GlobalRef::Window(ref window) => window.get_url(), - GlobalRef::Worker(ref worker) => worker.get_url().clone(), - } - } - - /// 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<ScriptChan + Send> { - 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<ScriptChan + Send> { - 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 { - match *self { - GlobalRef::Window(ref window) => window.file_reading_task_source(), - GlobalRef::Worker(ref worker) => worker.file_reading_task_source(), - } - } - - /// 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<ScriptChan + Send>, Box<ScriptPort + Send>) { - 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) { - match *self { - GlobalRef::Window(_) => ScriptThread::process_event(msg), - GlobalRef::Worker(ref worker) => worker.process_event(msg), - } - } - - /// 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.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<u16> = 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); - } - } - ) - } - - /// 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, - 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 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 { - 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 { - GlobalRef::Window(_) => ScriptThread::enqueue_promise_job(job, *self), - 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(), - } - } - - /// 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> { - 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 object of the realm that the given DOM object's reflector was created in. -pub fn global_root_from_reflector<T: Reflectable>(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 { - 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(_) => (), - } - - match root_from_object(global) { - Ok(worker) => return GlobalRoot::Worker(worker), - Err(_) => (), - } - - panic!("found DOM global that doesn't unwrap to Window or WorkerGlobalScope") -} - -/// 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 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_root_from_object_maybe_wrapped(mut obj: *mut JSObject) -> GlobalRoot { - if IsWrapper(obj) { - obj = UnwrapObject(obj, /* stopAtWindowProxy = */ 0); - assert!(!obj.is_null()); - } - global_root_from_object(obj) -} diff --git a/components/script/dom/bindings/iterable.rs b/components/script/dom/bindings/iterable.rs index 84381b52655..3e6febeeb5d 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<T: Reflectable + JSTraceable + Iterable> IterableIterator<T> { /// Create a new iterator instance for the provided iterable DOM interface. pub fn new(iterable: &T, type_: IteratorType, - wrap: fn(*mut JSContext, GlobalRef, Box<IterableIterator<T>>) + wrap: fn(*mut JSContext, &GlobalScope, Box<IterableIterator<T>>) -> Root<Self>) -> Root<Self> { let iterator = box IterableIterator { reflector: Reflector::new(), @@ -93,8 +93,7 @@ impl<T: Reflectable + JSTraceable + Iterable> IterableIterator<T> { iterable: JS::from_ref(iterable), index: Cell::new(0), }; - let global = iterable.global(); - reflect_dom_object(iterator, global.r(), wrap) + reflect_dom_object(iterator, &*iterable.global(), wrap) } /// Return the next value from the iterable object. diff --git a/components/script/dom/bindings/mod.rs b/components/script/dom/bindings/mod.rs index 013484a47b9..27504efda7c 100644 --- a/components/script/dom/bindings/mod.rs +++ b/components/script/dom/bindings/mod.rs @@ -43,8 +43,9 @@ //! [`Fallible<T>`](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). @@ -133,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 d5280712a03..737268bf7d0 100644 --- a/components/script/dom/bindings/reflector.rs +++ b/components/script/dom/bindings/reflector.rs @@ -4,19 +4,24 @@ //! The `Reflector` struct. -use dom::bindings::global::{GlobalRef, GlobalRoot, global_root_from_reflector}; +use dom::bindings::conversions::DerivedFrom; 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<T: Reflectable>(obj: Box<T>, - global: GlobalRef, - wrap_fn: fn(*mut JSContext, GlobalRef, Box<T>) -> Root<T>) - -> Root<T> { - wrap_fn(global.get_cx(), global, obj) +pub fn reflect_dom_object<T, U>( + obj: Box<T>, + global: &U, + wrap_fn: fn(*mut JSContext, &GlobalScope, Box<T>) -> Root<T>) + -> Root<T> + where T: Reflectable, U: DerivedFrom<GlobalScope> +{ + 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. @@ -74,9 +79,9 @@ pub trait Reflectable { /// Returns the receiver's reflector. fn reflector(&self) -> &Reflector; - /// 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) + /// Returns the global scope of the realm that the Reflectable was created in. + fn global(&self) -> Root<GlobalScope> where Self: Sized { + GlobalScope::from_reflector(self) } } 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/blob.rs b/components/script/dom/blob.rs index aef31efd687..a2ceed8b046 100644 --- a/components/script/dom/blob.rs +++ b/components/script/dom/blob.rs @@ -7,10 +7,10 @@ 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; +use dom::globalscope::GlobalScope; use encoding::all::UTF_8; use encoding::types::{EncoderTrap, Encoding}; use ipc_channel::ipc; @@ -79,7 +79,9 @@ pub struct Blob { impl Blob { #[allow(unrooted_must_root)] - pub fn new(global: GlobalRef, blob_impl: BlobImpl, typeString: String) -> Root<Blob> { + pub fn new( + global: &GlobalScope, blob_impl: BlobImpl, typeString: String) + -> Root<Blob> { let boxed_blob = box Blob::new_inherited(blob_impl, typeString); reflect_dom_object(boxed_blob, global, BlobBinding::Wrap) } @@ -99,7 +101,6 @@ impl Blob { #[allow(unrooted_must_root)] fn new_sliced(parent: &Blob, rel_pos: RelativePos, relative_content_type: DOMString) -> Root<Blob> { - let global = parent.global(); let blob_impl = match *parent.blob_impl.borrow() { BlobImpl::File(_) => { // Create new parent node @@ -115,11 +116,11 @@ impl Blob { } }; - Blob::new(global.r(), blob_impl, relative_content_type.into()) + Blob::new(&parent.global(), blob_impl, relative_content_type.into()) } // https://w3c.github.io/FileAPI/#constructorBlob - pub fn Constructor(global: GlobalRef, + pub fn Constructor(global: &GlobalScope, blobParts: Option<Vec<BlobOrString>>, blobPropertyBag: &BlobBinding::BlobPropertyBag) -> Fallible<Root<Blob>> { @@ -142,8 +143,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(), f.id.clone())?; (bytes, true) } }; @@ -188,6 +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().get_url(); match *self.blob_impl.borrow_mut() { BlobImpl::Sliced(_, _) => { @@ -197,8 +198,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()); @@ -217,8 +217,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, @@ -249,9 +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 global = self.global(); - - let origin = get_blob_origin(&global.r().get_url()); + let origin = get_blob_origin(&self.global().get_url()); let (tx, rx) = ipc::channel().unwrap(); let msg = FileManagerThreadMsg::AddSlicedURLEntry(parent_id.clone(), @@ -280,8 +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 global = self.global(); - let origin = get_blob_origin(&global.r().get_url()); + let origin = get_blob_origin(&self.global().get_url()); let (tx, rx) = ipc::channel().unwrap(); @@ -293,7 +289,7 @@ impl Blob { fn send_to_file_manager(&self, msg: FileManagerThreadMsg) { let global = self.global(); - let resource_threads = global.r().resource_threads(); + let resource_threads = global.resource_threads(); let _ = resource_threads.send(CoreResourceMsg::ToFileManager(msg)); } } @@ -306,7 +302,7 @@ impl Drop for Blob { } } -fn read_file(global: GlobalRef, id: Uuid) -> Result<Vec<u8>, ()> { +fn read_file(global: &GlobalScope, id: Uuid) -> Result<Vec<u8>, ()> { let resource_threads = global.resource_threads(); let (chan, recv) = ipc::channel().map_err(|_|())?; let origin = get_blob_origin(&global.get_url()); diff --git a/components/script/dom/bluetooth.rs b/components/script/dom/bluetooth.rs index 42ad4c2730a..863d75bfec4 100644 --- a/components/script/dom/bluetooth.rs +++ b/components/script/dom/bluetooth.rs @@ -8,13 +8,13 @@ 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; 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,16 +52,14 @@ impl Bluetooth { } } - pub fn new(global: GlobalRef) -> Root<Bluetooth> { + pub fn new(global: &GlobalScope) -> Root<Bluetooth> { reflect_dom_object(box Bluetooth::new_inherited(), global, BluetoothBinding::Wrap) } fn get_bluetooth_thread(&self) -> IpcSender<BluetoothMethodMsg> { - let global_root = self.global(); - let global_ref = global_root.r(); - global_ref.as_window().bluetooth_thread() + self.global().as_window().bluetooth_thread() } fn request_device(&self, option: &RequestDeviceOptions) -> Fallible<Root<BluetoothDevice>> { @@ -105,11 +103,12 @@ impl Bluetooth { // Step 12-13. match device { Ok(device) => { - let ad_data = BluetoothAdvertisingData::new(self.global().r(), + let global = self.global(); + 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)) @@ -271,13 +270,13 @@ fn canonicalize_filter(filter: &BluetoothRequestDeviceFilter) -> Fallible<Blueto } #[allow(unrooted_must_root)] -pub fn result_to_promise<T: ToJSValConvertible>(global_ref: GlobalRef, +pub fn result_to_promise<T: ToJSValConvertible>(global: &GlobalScope, bluetooth_result: Fallible<T>) -> Rc<Promise> { - let p = Promise::new(global_ref); + 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().get_cx(), &v), + Err(e) => p.reject_error(p.global().get_cx(), e), } p } @@ -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<Promise> { - result_to_promise(self.global().r(), self.request_device(option)) + result_to_promise(&self.global(), self.request_device(option)) } } 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<u16>, txPower: Option<i8>, rssi: Option<i8>) 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..f4348465108 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<DOMString>, adData: &BluetoothAdvertisingData) @@ -66,6 +66,8 @@ impl BluetoothDeviceMethods for BluetoothDevice { // https://webbluetoothcg.github.io/web-bluetooth/#dom-bluetoothdevice-gatt fn Gatt(&self) -> Root<BluetoothRemoteGATTServer> { - self.gatt.or_init(|| BluetoothRemoteGATTServer::new(self.global().r(), self)) + self.gatt.or_init(|| { + BluetoothRemoteGATTServer::new(&self.global(), self) + }) } } diff --git a/components/script/dom/bluetoothremotegattcharacteristic.rs b/components/script/dom/bluetoothremotegattcharacteristic.rs index 6b7ba1dcfad..95b26ff66c1 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, @@ -74,9 +74,7 @@ impl BluetoothRemoteGATTCharacteristic { } fn get_bluetooth_thread(&self) -> IpcSender<BluetoothMethodMsg> { - let global_root = self.global(); - let global_ref = global_root.r(); - global_ref.as_window().bluetooth_thread() + self.global().as_window().bluetooth_thread() } fn get_instance_id(&self) -> String { @@ -95,7 +93,7 @@ impl BluetoothRemoteGATTCharacteristic { let descriptor = receiver.recv().unwrap(); match descriptor { Ok(descriptor) => { - Ok(BluetoothRemoteGATTDescriptor::new(self.global().r(), + Ok(BluetoothRemoteGATTDescriptor::new(&self.global(), self, DOMString::from(descriptor.uuid), descriptor.instance_id)) @@ -126,7 +124,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(), self, DOMString::from(desc.uuid), desc.instance_id)) @@ -214,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<Promise> { - result_to_promise(self.global().r(), self.get_descriptor(descriptor)) + result_to_promise(&self.global(), self.get_descriptor(descriptor)) } #[allow(unrooted_must_root)] @@ -222,7 +220,7 @@ impl BluetoothRemoteGATTCharacteristicMethods for BluetoothRemoteGATTCharacteris fn GetDescriptors(&self, descriptor: Option<BluetoothDescriptorUUID>) -> Rc<Promise> { - result_to_promise(self.global().r(), self.get_descriptors(descriptor)) + result_to_promise(&self.global(), self.get_descriptors(descriptor)) } // https://webbluetoothcg.github.io/web-bluetooth/#dom-bluetoothremotegattcharacteristic-value @@ -233,12 +231,12 @@ impl BluetoothRemoteGATTCharacteristicMethods for BluetoothRemoteGATTCharacteris #[allow(unrooted_must_root)] // https://webbluetoothcg.github.io/web-bluetooth/#dom-bluetoothremotegattcharacteristic-readvalue fn ReadValue(&self) -> Rc<Promise> { - result_to_promise(self.global().r(), 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<u8>) -> Rc<Promise> { - result_to_promise(self.global().r(), 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 d036f8bd9ea..f066bb9d22a 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) @@ -61,9 +61,7 @@ impl BluetoothRemoteGATTDescriptor { } fn get_bluetooth_thread(&self) -> IpcSender<BluetoothMethodMsg> { - let global_root = self.global(); - let global_ref = global_root.r(); - global_ref.as_window().bluetooth_thread() + self.global().as_window().bluetooth_thread() } fn get_instance_id(&self) -> String { @@ -137,12 +135,12 @@ impl BluetoothRemoteGATTDescriptorMethods for BluetoothRemoteGATTDescriptor { #[allow(unrooted_must_root)] // https://webbluetoothcg.github.io/web-bluetooth/#dom-bluetoothremotegattdescriptor-readvalue fn ReadValue(&self) -> Rc<Promise> { - result_to_promise(self.global().r(), 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<u8>) -> Rc<Promise> { - result_to_promise(self.global().r(), 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 3439ba53350..fe19651ebf4 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,16 +39,14 @@ impl BluetoothRemoteGATTServer { } } - pub fn new(global: GlobalRef, device: &BluetoothDevice) -> Root<BluetoothRemoteGATTServer> { + pub fn new(global: &GlobalScope, device: &BluetoothDevice) -> Root<BluetoothRemoteGATTServer> { reflect_dom_object(box BluetoothRemoteGATTServer::new_inherited(device), - global, - BluetoothRemoteGATTServerBinding::Wrap) + global, + BluetoothRemoteGATTServerBinding::Wrap) } fn get_bluetooth_thread(&self) -> IpcSender<BluetoothMethodMsg> { - let global_root = self.global(); - let global_ref = global_root.r(); - global_ref.as_window().bluetooth_thread() + self.global().as_window().bluetooth_thread() } // https://webbluetoothcg.github.io/web-bluetooth/#dom-bluetoothremotegattserver-connect @@ -80,7 +78,7 @@ impl BluetoothRemoteGATTServer { let service = receiver.recv().unwrap(); match service { Ok(service) => { - Ok(BluetoothRemoteGATTService::new(self.global().r(), + Ok(BluetoothRemoteGATTService::new(&self.global(), &self.device.get(), DOMString::from(service.uuid), service.is_primary, @@ -112,7 +110,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(), &self.device.get(), DOMString::from(service.uuid), service.is_primary, @@ -140,7 +138,7 @@ impl BluetoothRemoteGATTServerMethods for BluetoothRemoteGATTServer { #[allow(unrooted_must_root)] // https://webbluetoothcg.github.io/web-bluetooth/#dom-bluetoothremotegattserver-connect fn Connect(&self) -> Rc<Promise> { - result_to_promise(self.global().r(), self.connect()) + result_to_promise(&self.global(), self.connect()) } // https://webbluetoothcg.github.io/web-bluetooth/#dom-bluetoothremotegattserver-disconnect @@ -163,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<Promise> { - result_to_promise(self.global().r(), self.get_primary_service(service)) + result_to_promise(&self.global(), self.get_primary_service(service)) } #[allow(unrooted_must_root)] @@ -171,6 +169,6 @@ impl BluetoothRemoteGATTServerMethods for BluetoothRemoteGATTServer { fn GetPrimaryServices(&self, service: Option<BluetoothServiceUUID>) -> Rc<Promise> { - result_to_promise(self.global().r(), 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 3ece2507cd3..bce51131649 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, @@ -61,9 +61,7 @@ impl BluetoothRemoteGATTService { } fn get_bluetooth_thread(&self) -> IpcSender<BluetoothMethodMsg> { - let global_root = self.global(); - let global_ref = global_root.r(); - global_ref.as_window().bluetooth_thread() + self.global().as_window().bluetooth_thread() } fn get_instance_id(&self) -> String { @@ -84,7 +82,8 @@ impl BluetoothRemoteGATTService { let characteristic = receiver.recv().unwrap(); match characteristic { Ok(characteristic) => { - let properties = BluetoothCharacteristicProperties::new(self.global().r(), + let global = self.global(); + let properties = BluetoothCharacteristicProperties::new(&global, characteristic.broadcast, characteristic.read, characteristic.write_without_response, @@ -94,7 +93,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 +126,8 @@ 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 properties = BluetoothCharacteristicProperties::new(&global, characteristic.broadcast, characteristic.read, characteristic.write_without_response, @@ -137,7 +137,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 +167,7 @@ impl BluetoothRemoteGATTService { let service = receiver.recv().unwrap(); match service { Ok(service) => { - Ok(BluetoothRemoteGATTService::new(self.global().r(), + 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().r(), + .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<Promise> { - result_to_promise(self.global().r(), 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<BluetoothCharacteristicUUID>) -> Rc<Promise> { - result_to_promise(self.global().r(), 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<Promise> { - result_to_promise(self.global().r(), 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<BluetoothServiceUUID>) -> Rc<Promise> { - result_to_promise(self.global().r(), self.get_included_services(service)) + result_to_promise(&self.global(), self.get_included_services(service)) } } 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<UUID> { + pub fn GetService(_: &GlobalScope, name: BluetoothServiceUUID) -> Fallible<UUID> { Self::service(name) } // https://webbluetoothcg.github.io/web-bluetooth/#dom-bluetoothuuid-getcharacteristic - pub fn GetCharacteristic(_: GlobalRef, name: BluetoothCharacteristicUUID) -> Fallible<UUID> { + pub fn GetCharacteristic(_: &GlobalScope, name: BluetoothCharacteristicUUID) -> Fallible<UUID> { Self::characteristic(name) } // https://webbluetoothcg.github.io/web-bluetooth/#dom-bluetoothuuid-getdescriptor - pub fn GetDescriptor(_: GlobalRef, name: BluetoothDescriptorUUID) -> Fallible<UUID> { + pub fn GetDescriptor(_: &GlobalScope, name: BluetoothDescriptorUUID) -> Fallible<UUID> { Self::descriptor(name) } } 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<Root<Window>> { self.children.borrow().iter().find(|context| { let window = context.active_window(); - window.pipeline_id() == pipeline_id + window.upcast::<GlobalScope>().pipeline_id() == pipeline_id }).map(|context| context.active_window()) } 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<CanvasGradient> { + pub fn new(global: &GlobalScope, style: CanvasGradientStyle) -> Root<CanvasGradient> { 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<u8>, surface_size: Size2D<i32>, repeat: RepetitionStyle, diff --git a/components/script/dom/canvasrenderingcontext2d.rs b/components/script/dom/canvasrenderingcontext2d.rs index 4b598407829..f2436f73419 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,7 +117,7 @@ impl CanvasContextState { } impl CanvasRenderingContext2D { - fn new_inherited(global: GlobalRef, + fn new_inherited(global: &GlobalScope, canvas: &HTMLCanvasElement, size: Size2D<i32>) -> CanvasRenderingContext2D { @@ -135,7 +135,7 @@ impl CanvasRenderingContext2D { } } - pub fn new(global: GlobalRef, + pub fn new(global: &GlobalScope, canvas: &HTMLCanvasElement, size: Size2D<i32>) -> Root<CanvasRenderingContext2D> { @@ -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(), sw, sh, None)) } // https://html.spec.whatwg.org/multipage/#dom-context-2d-createimagedata fn CreateImageData_(&self, imagedata: &ImageData) -> Fallible<Root<ImageData>> { - Ok(ImageData::new(self.global().r(), + 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().r(), 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<f64>, y1: Finite<f64>) -> Root<CanvasGradient> { - CanvasGradient::new(self.global().r(), + 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().r(), + 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().r(), + Ok(CanvasPattern::new(&self.global(), 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<Client> { - 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..a66af7bd75f 100644 --- a/components/script/dom/closeevent.rs +++ b/components/script/dom/closeevent.rs @@ -6,12 +6,12 @@ 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; use dom::bindings::str::DOMString; use dom::event::{Event, EventBubbles, EventCancelable}; +use dom::globalscope::GlobalScope; use string_cache::Atom; #[dom_struct] @@ -32,13 +32,13 @@ impl CloseEvent { } } - pub fn new_uninitialized(global: GlobalRef) -> Root<CloseEvent> { + pub fn new_uninitialized(global: &GlobalScope) -> Root<CloseEvent> { 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, @@ -57,7 +57,7 @@ impl CloseEvent { ev } - pub fn Constructor(global: GlobalRef, + pub fn Constructor(global: &GlobalScope, type_: DOMString, init: &CloseEventBinding::CloseEventInit) -> Fallible<Root<CloseEvent>> { diff --git a/components/script/dom/comment.rs b/components/script/dom/comment.rs index 43115e1dd51..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,7 +31,7 @@ impl Comment { CommentBinding::Wrap) } - pub fn Constructor(global: GlobalRef, data: DOMString) -> Fallible<Root<Comment>> { + pub fn Constructor(global: &GlobalScope, data: DOMString) -> Fallible<Root<Comment>> { 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 ad28c585248..d9df56ebef0 100644 --- a/components/script/dom/console.rs +++ b/components/script/dom/console.rs @@ -3,25 +3,21 @@ * 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::inheritance::Castable; use dom::bindings::str::DOMString; -use std::collections::HashMap; -use std::collections::hash_map::Entry; -use time::{Timespec, get_time}; +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) { + 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::<WorkerGlobalScope>().map(|worker| { + worker.get_worker_id() + }); let devtools_message = ScriptToDevtoolsControlMsg::ConsoleAPI( global.pipeline_id(), console_message, @@ -33,7 +29,7 @@ impl Console { impl Console { // https://developer.mozilla.org/en-US/docs/Web/API/Console/log - pub fn Log(global: GlobalRef, messages: Vec<DOMString>) { + pub fn Log(global: &GlobalScope, messages: Vec<DOMString>) { for message in messages { println!("{}", message); Self::send_to_devtools(global, LogLevel::Log, message); @@ -41,7 +37,7 @@ impl Console { } // https://developer.mozilla.org/en-US/docs/Web/API/Console - pub fn Debug(global: GlobalRef, messages: Vec<DOMString>) { + pub fn Debug(global: &GlobalScope, messages: Vec<DOMString>) { for message in messages { println!("{}", message); Self::send_to_devtools(global, LogLevel::Debug, message); @@ -49,7 +45,7 @@ impl Console { } // https://developer.mozilla.org/en-US/docs/Web/API/Console/info - pub fn Info(global: GlobalRef, messages: Vec<DOMString>) { + pub fn Info(global: &GlobalScope, messages: Vec<DOMString>) { for message in messages { println!("{}", message); Self::send_to_devtools(global, LogLevel::Info, message); @@ -57,7 +53,7 @@ impl Console { } // https://developer.mozilla.org/en-US/docs/Web/API/Console/warn - pub fn Warn(global: GlobalRef, messages: Vec<DOMString>) { + pub fn Warn(global: &GlobalScope, messages: Vec<DOMString>) { for message in messages { println!("{}", message); Self::send_to_devtools(global, LogLevel::Warn, message); @@ -65,7 +61,7 @@ impl Console { } // https://developer.mozilla.org/en-US/docs/Web/API/Console/error - pub fn Error(global: GlobalRef, messages: Vec<DOMString>) { + pub fn Error(global: &GlobalScope, messages: Vec<DOMString>) { for message in messages { println!("{}", message); Self::send_to_devtools(global, LogLevel::Error, message); @@ -73,7 +69,7 @@ impl Console { } // https://developer.mozilla.org/en-US/docs/Web/API/Console/assert - pub fn Assert(global: GlobalRef, condition: bool, message: Option<DOMString>) { + pub fn Assert(global: &GlobalScope, condition: bool, message: Option<DOMString>) { if !condition { let message = message.unwrap_or_else(|| DOMString::from("no message")); println!("Assertion failed: {}", message); @@ -82,8 +78,8 @@ 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()) { + 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, LogLevel::Log, message); @@ -91,8 +87,8 @@ 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) { + pub fn TimeEnd(global: &GlobalScope, label: DOMString) { + if let Ok(delta) = global.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<HashMap<DOMString, u64>>); - -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<u64, ()> { - self.0.borrow_mut().remove(label).ok_or(()).map(|start| { - timestamp_in_ms(get_time()) - start - }) - } -} 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<Crypto> { + pub fn new(global: &GlobalScope) -> Root<Crypto> { reflect_dom_object(box Crypto::new_inherited(), global, CryptoBinding::Wrap) } } 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<DOMString> { + pub fn Escape(_: &GlobalScope, ident: DOMString) -> Fallible<DOMString> { let mut escaped = String::new(); serialize_identifier(&ident, &mut escaped).unwrap(); Ok(DOMString::from(escaped)) 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..d7e026d69bc 100644 --- a/components/script/dom/customevent.rs +++ b/components/script/dom/customevent.rs @@ -6,12 +6,12 @@ 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; 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 +32,12 @@ impl CustomEvent { } } - pub fn new_uninitialized(global: GlobalRef) -> Root<CustomEvent> { + pub fn new_uninitialized(global: &GlobalScope) -> Root<CustomEvent> { 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, @@ -47,8 +47,9 @@ 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<Root<CustomEvent>> { diff --git a/components/script/dom/dedicatedworkerglobalscope.rs b/components/script/dom/dedicatedworkerglobalscope.rs index 49a46b88575..fb818be3797 100644 --- a/components/script/dom/dedicatedworkerglobalscope.rs +++ b/components/script/dom/dedicatedworkerglobalscope.rs @@ -11,12 +11,12 @@ 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::inheritance::Castable; 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 +212,7 @@ impl DedicatedWorkerGlobalScope { } let reporter_name = format!("dedicated-worker-reporter-{}", random::<u64>()); - scope.mem_profiler_chan().run_with_memory_reporting(|| { + scope.upcast::<GlobalScope>().mem_profiler_chan().run_with_memory_reporting(|| { while let Ok(event) = global.receive_event() { if scope.is_closing() { break; @@ -281,8 +281,8 @@ 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()); - MessageEvent::dispatch_jsval(target, GlobalRef::Worker(scope), message.handle()); + data.read(scope.upcast(), message.handle_mut()); + MessageEvent::dispatch_jsval(target, scope.upcast(), message.handle()); }, WorkerScriptMsg::Common(CommonScriptMsg::RunnableMsg(_, runnable)) => { runnable.handler() @@ -300,14 +300,13 @@ 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) => - 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!"), } }, @@ -342,11 +341,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::<WorkerGlobalScope>(GlobalScope::from_context(cx)) + .expect("global is not a worker scope"); assert!(worker.is::<DedicatedWorkerGlobalScope>()); // A false response causes the script to terminate diff --git a/components/script/dom/document.rs b/components/script/dom/document.rs index 5e834ef52cd..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; @@ -45,6 +44,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; @@ -650,8 +650,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.constellation_chan().send(event).unwrap(); + let global_scope = self.window.upcast::<GlobalScope>(); + let event = ConstellationMsg::Focus(global_scope.pipeline_id()); + global_scope.constellation_chan().send(event).unwrap(); } } } @@ -669,8 +670,10 @@ impl Document { /// Sends this document's title to the compositor. pub fn send_title_to_compositor(&self) { let window = self.window(); - window.constellation_chan() - .send(ConstellationMsg::SetTitle(window.pipeline_id(), + let global_scope = window.upcast::<GlobalScope>(); + global_scope + .constellation_chan() + .send(ConstellationMsg::SetTitle(global_scope.pipeline_id(), Some(String::from(self.Title())))) .unwrap(); } @@ -723,7 +726,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::<GlobalScope>().constellation_chan().send(event).unwrap(); } return; } @@ -961,7 +964,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::<GlobalScope>().constellation_chan().send(event).unwrap(); } return; } @@ -1356,10 +1359,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::<GlobalScope>(); let event = ConstellationMsg::MozBrowserEvent(parent_pipeline_id, - Some(self.window.pipeline_id()), + Some(global_scope.pipeline_id()), event); - self.window.constellation_chan().send(event).unwrap(); + global_scope.constellation_chan().send(event).unwrap(); } } } @@ -1379,10 +1383,11 @@ impl Document { // // TODO: Should tick animation only when document is visible if !self.running_animation_callbacks.get() { + let global_scope = self.window.upcast::<GlobalScope>(); let event = ConstellationMsg::ChangeRunningAnimationsState( - self.window.pipeline_id(), + global_scope.pipeline_id(), AnimationState::AnimationCallbacksPresent); - self.window.constellation_chan().send(event).unwrap(); + global_scope.constellation_chan().send(event).unwrap(); } ident @@ -1418,9 +1423,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::<GlobalScope>(); + let event = ConstellationMsg::ChangeRunningAnimationsState(global_scope.pipeline_id(), AnimationState::NoAnimationCallbacksPresent); - self.window.constellation_chan().send(event).unwrap(); + global_scope.constellation_chan().send(event).unwrap(); } self.running_animation_callbacks.set(false); @@ -1478,7 +1484,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::<GlobalScope>().pipeline_id()); win.main_thread_script_chan().send(msg).unwrap(); } } @@ -1576,9 +1583,10 @@ impl Document { } pub fn notify_constellation_load(&self) { - let pipeline_id = self.window.pipeline_id(); + let global_scope = self.window.upcast::<GlobalScope>(); + let pipeline_id = global_scope.pipeline_id(); let load_event = ConstellationMsg::LoadComplete(pipeline_id); - self.window.constellation_chan().send(load_event).unwrap(); + global_scope.constellation_chan().send(load_event).unwrap(); } pub fn set_current_parser(&self, script: Option<ParserRef>) { @@ -1810,7 +1818,7 @@ impl Document { } // https://dom.spec.whatwg.org/#dom-document - pub fn Constructor(global: GlobalRef) -> Fallible<Root<Document>> { + pub fn Constructor(global: &GlobalScope) -> Fallible<Root<Document>> { let win = global.as_window(); let doc = win.Document(); let doc = doc.r(); @@ -1848,7 +1856,7 @@ impl Document { doc_loader, referrer, referrer_policy), - GlobalRef::Window(window), + window, DocumentBinding::Wrap); { let node = document.upcast::<Node>(); @@ -2325,13 +2333,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 +2349,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), } @@ -2719,7 +2727,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::<GlobalScope>() + .resource_threads() + .send(GetCookiesForUrl((*url).clone(), tx, NonHTTP)); let cookies = rx.recv().unwrap(); Ok(cookies.map_or(DOMString::new(), DOMString::from)) } @@ -2736,6 +2747,7 @@ impl DocumentMethods for Document { let url = self.url(); let _ = self.window + .upcast::<GlobalScope>() .resource_threads() .send(SetCookiesForUrl((*url).clone(), String::from(cookie), NonHTTP)); Ok(()) @@ -2993,7 +3005,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/documentfragment.rs b/components/script/dom/documentfragment.rs index 0fba19d5aff..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,7 +38,7 @@ impl DocumentFragment { DocumentFragmentBinding::Wrap) } - pub fn Constructor(global: GlobalRef) -> Fallible<Root<DocumentFragment>> { + pub fn Constructor(global: &GlobalScope) -> Fallible<Root<DocumentFragment>> { let document = global.as_window().Document(); Ok(DocumentFragment::new(document.r())) 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<DOMException> { + pub fn new(global: &GlobalScope, code: DOMErrorName) -> Root<DOMException> { 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<DOMImplementation> { 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..dbe7a27516c 100644 --- a/components/script/dom/dommatrix.rs +++ b/components/script/dom/dommatrix.rs @@ -5,11 +5,11 @@ 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; use dom::dommatrixreadonly::{dommatrixinit_to_matrix, DOMMatrixReadOnly, entries_to_matrix}; +use dom::globalscope::GlobalScope; use euclid::Matrix4D; @@ -20,7 +20,7 @@ pub struct DOMMatrix { impl DOMMatrix { #[allow(unrooted_must_root)] - pub fn new(global: GlobalRef, is2D: bool, matrix: Matrix4D<f64>) -> Root<Self> { + pub fn new(global: &GlobalScope, is2D: bool, matrix: Matrix4D<f64>) -> Root<Self> { let dommatrix = Self::new_inherited(is2D, matrix); reflect_dom_object(box dommatrix, global, Wrap) } @@ -32,12 +32,12 @@ impl DOMMatrix { } // https://drafts.fxtf.org/geometry-1/#dom-dommatrix-dommatrix - pub fn Constructor(global: GlobalRef) -> Fallible<Root<Self>> { + pub fn Constructor(global: &GlobalScope) -> Fallible<Root<Self>> { 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<f64>) -> Fallible<Root<Self>> { + pub fn Constructor_(global: &GlobalScope, entries: Vec<f64>) -> Fallible<Root<Self>> { entries_to_matrix(&entries[..]) .map(|(is2D, matrix)| { Self::new(global, is2D, matrix) @@ -45,14 +45,14 @@ impl DOMMatrix { } // https://drafts.fxtf.org/geometry-1/#dom-dommatrix-frommatrix - pub fn FromMatrix(global: GlobalRef, other: &DOMMatrixInit) -> Fallible<Root<Self>> { + pub fn FromMatrix(global: &GlobalScope, other: &DOMMatrixInit) -> Fallible<Root<Self>> { dommatrixinit_to_matrix(&other) .map(|(is2D, matrix)| { Self::new(global, is2D, matrix) }) } - pub fn from_readonly(global: GlobalRef, ro: &DOMMatrixReadOnly) -> Root<Self> { + pub fn from_readonly(global: &GlobalScope, ro: &DOMMatrixReadOnly) -> Root<Self> { 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..fa7c819a1ba 100644 --- a/components/script/dom/dommatrixreadonly.rs +++ b/components/script/dom/dommatrixreadonly.rs @@ -8,11 +8,11 @@ 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; use dom::dompoint::DOMPoint; +use dom::globalscope::GlobalScope; use euclid::{Matrix4D, Point4D, Radians}; use std::cell::{Cell, Ref}; use std::f64; @@ -26,7 +26,7 @@ pub struct DOMMatrixReadOnly { impl DOMMatrixReadOnly { #[allow(unrooted_must_root)] - pub fn new(global: GlobalRef, is2D: bool, matrix: Matrix4D<f64>) -> Root<Self> { + pub fn new(global: &GlobalScope, is2D: bool, matrix: Matrix4D<f64>) -> Root<Self> { let dommatrix = Self::new_inherited(is2D, matrix); reflect_dom_object(box dommatrix, global, Wrap) } @@ -40,12 +40,12 @@ impl DOMMatrixReadOnly { } // https://drafts.fxtf.org/geometry-1/#dom-dommatrixreadonly-dommatrixreadonly - pub fn Constructor(global: GlobalRef) -> Fallible<Root<Self>> { + pub fn Constructor(global: &GlobalScope) -> Fallible<Root<Self>> { Ok(Self::new(global, true, Matrix4D::identity())) } // https://drafts.fxtf.org/geometry-1/#dom-dommatrixreadonly-dommatrixreadonly-numbersequence - pub fn Constructor_(global: GlobalRef, entries: Vec<f64>) -> Fallible<Root<Self>> { + pub fn Constructor_(global: &GlobalScope, entries: Vec<f64>) -> Fallible<Root<Self>> { entries_to_matrix(&entries[..]) .map(|(is2D, matrix)| { Self::new(global, is2D, matrix) @@ -53,7 +53,7 @@ impl DOMMatrixReadOnly { } // https://drafts.fxtf.org/geometry-1/#dom-dommatrixreadonly-frommatrix - pub fn FromMatrix(global: GlobalRef, other: &DOMMatrixInit) -> Fallible<Root<Self>> { + pub fn FromMatrix(global: &GlobalScope, other: &DOMMatrixInit) -> Fallible<Root<Self>> { dommatrixinit_to_matrix(&other) .map(|(is2D, matrix)| { Self::new(global, is2D, matrix) @@ -463,48 +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> { - DOMMatrix::from_readonly(self.global().r(), 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<f64>, scaleZ: f64, originX: f64, originY: f64, originZ: f64) -> Root<DOMMatrix> { - DOMMatrix::from_readonly(self.global().r(), self).ScaleSelf(scaleX, scaleY, scaleZ, originX, originY, originZ) + 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> { - DOMMatrix::from_readonly(self.global().r(), self).Scale3dSelf(scale, originX, originY, originZ) + 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<f64>, rotZ: Option<f64>) -> Root<DOMMatrix> { - DOMMatrix::from_readonly(self.global().r(), 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> { - DOMMatrix::from_readonly(self.global().r(), 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> { - DOMMatrix::from_readonly(self.global().r(), 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> { - DOMMatrix::from_readonly(self.global().r(), 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> { - DOMMatrix::from_readonly(self.global().r(), 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<Root<DOMMatrix>> { - DOMMatrix::from_readonly(self.global().r(), self).MultiplySelf(&other) + DOMMatrix::from_readonly(&self.global(), self).MultiplySelf(&other) } // https://drafts.fxtf.org/geometry-1/#dom-dommatrixreadonly-flipx @@ -515,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().r(), is2D, matrix) + DOMMatrix::new(&self.global(), is2D, matrix) } // https://drafts.fxtf.org/geometry-1/#dom-dommatrixreadonly-flipy @@ -526,19 +528,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(), is2D, matrix) } // https://drafts.fxtf.org/geometry-1/#dom-dommatrixreadonly-inverse fn Inverse(&self) -> Root<DOMMatrix> { - DOMMatrix::from_readonly(self.global().r(), self).InvertSelf() + DOMMatrix::from_readonly(&self.global(), self).InvertSelf() } // https://drafts.fxtf.org/geometry-1/#dom-dommatrixreadonly-transformpoint fn TransformPoint(&self, point: &DOMPointInit) -> Root<DOMPoint> { 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(), + 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..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}; @@ -38,11 +38,11 @@ impl DOMParser { pub fn new(window: &Window) -> Root<DOMParser> { reflect_dom_object(box DOMParser::new_inherited(window), - GlobalRef::Window(window), + window, DOMParserBinding::Wrap) } - pub fn Constructor(global: GlobalRef) -> Fallible<Root<DOMParser>> { + pub fn Constructor(global: &GlobalScope) -> Fallible<Root<DOMParser>> { Ok(DOMParser::new(global.as_window())) } } diff --git a/components/script/dom/dompoint.rs b/components/script/dom/dompoint.rs index 906a30ea617..2f77f77c2c1 100644 --- a/components/script/dom/dompoint.rs +++ b/components/script/dom/dompoint.rs @@ -5,10 +5,10 @@ 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}; +use dom::globalscope::GlobalScope; // http://dev.w3.org/fxtf/geometry/Overview.html#dompoint #[dom_struct] @@ -23,11 +23,11 @@ impl DOMPoint { } } - pub fn new(global: GlobalRef, x: f64, y: f64, z: f64, w: f64) -> Root<DOMPoint> { + pub fn new(global: &GlobalScope, x: f64, y: f64, z: f64, w: f64) -> Root<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, @@ -36,7 +36,7 @@ impl DOMPoint { Ok(DOMPoint::new(global, x, y, z, w)) } - pub fn new_from_init(global: GlobalRef, p: &DOMPointInit) -> Root<DOMPoint> { + pub fn new_from_init(global: &GlobalScope, p: &DOMPointInit) -> Root<DOMPoint> { 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..9da4e27a984 100644 --- a/components/script/dom/dompointreadonly.rs +++ b/components/script/dom/dompointreadonly.rs @@ -4,9 +4,9 @@ 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; use std::cell::Cell; // http://dev.w3.org/fxtf/geometry/Overview.html#dompointreadonly @@ -30,13 +30,13 @@ impl DOMPointReadOnly { } } - pub fn new(global: GlobalRef, x: f64, y: f64, z: f64, w: f64) -> Root<DOMPointReadOnly> { + pub fn new(global: &GlobalScope, x: f64, y: f64, z: f64, w: f64) -> Root<DOMPointReadOnly> { reflect_dom_object(box DOMPointReadOnly::new_inherited(x, y, z, w), global, Wrap) } - pub fn Constructor(global: GlobalRef, + pub fn Constructor(global: &GlobalScope, x: f64, y: f64, z: f64, diff --git a/components/script/dom/domquad.rs b/components/script/dom/domquad.rs index a9af14d3d69..7d80dc9d8fd 100644 --- a/components/script/dom/domquad.rs +++ b/components/script/dom/domquad.rs @@ -6,11 +6,11 @@ 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; use dom::domrect::DOMRect; +use dom::globalscope::GlobalScope; // https://drafts.fxtf.org/geometry/#DOMQuad #[dom_struct] @@ -37,7 +37,7 @@ impl DOMQuad { } } - pub fn new(global: GlobalRef, + pub fn new(global: &GlobalScope, p1: &DOMPoint, p2: &DOMPoint, p3: &DOMPoint, @@ -47,7 +47,7 @@ impl DOMQuad { Wrap) } - pub fn Constructor(global: GlobalRef, + pub fn Constructor(global: &GlobalScope, p1: &DOMPointInit, p2: &DOMPointInit, p3: &DOMPointInit, @@ -61,7 +61,7 @@ impl DOMQuad { } // https://drafts.fxtf.org/geometry/#dom-domquad-fromrect - pub fn FromRect(global: GlobalRef, other: &DOMRectInit) -> Root<DOMQuad> { + pub fn FromRect(global: &GlobalScope, other: &DOMRectInit) -> Root<DOMQuad> { DOMQuad::new(global, &*DOMPoint::new(global, other.x, other.y, 0f64, 1f64), &*DOMPoint::new(global, other.x + other.width, other.y, 0f64, 1f64), @@ -70,7 +70,7 @@ impl DOMQuad { } // https://drafts.fxtf.org/geometry/#dom-domquad-fromquad - pub fn FromQuad(global: GlobalRef, other: &DOMQuadInit) -> Root<DOMQuad> { + pub fn FromQuad(global: &GlobalScope, other: &DOMQuadInit) -> Root<DOMQuad> { DOMQuad::new(global, &DOMPoint::new_from_init(global, &other.p1), &DOMPoint::new_from_init(global, &other.p2), @@ -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().r(), + DOMRect::new(&self.global(), left, top, right - left, diff --git a/components/script/dom/domrect.rs b/components/script/dom/domrect.rs index 086e21882c6..78e1b2db22e 100644 --- a/components/script/dom/domrect.rs +++ b/components/script/dom/domrect.rs @@ -6,10 +6,10 @@ 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; +use dom::globalscope::GlobalScope; #[dom_struct] pub struct DOMRect { @@ -23,13 +23,13 @@ impl DOMRect { } } - pub fn new(global: GlobalRef, x: f64, y: f64, width: f64, height: f64) -> Root<DOMRect> { + pub fn new(global: &GlobalScope, x: f64, y: f64, width: f64, height: f64) -> Root<DOMRect> { reflect_dom_object(box DOMRect::new_inherited(x, y, width, height), global, DOMRectBinding::Wrap) } - pub fn Constructor(global: GlobalRef, + pub fn Constructor(global: &GlobalScope, x: f64, y: f64, width: f64, 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<Item = Root<DOMRect>> { 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..ef0c7ce2c67 100644 --- a/components/script/dom/domrectreadonly.rs +++ b/components/script/dom/domrectreadonly.rs @@ -4,9 +4,9 @@ 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; use std::cell::Cell; #[dom_struct] @@ -29,7 +29,7 @@ impl DOMRectReadOnly { } } - pub fn new(global: GlobalRef, + pub fn new(global: &GlobalScope, x: f64, y: f64, width: f64, @@ -40,7 +40,7 @@ impl DOMRectReadOnly { Wrap) } - pub fn Constructor(global: GlobalRef, + pub fn Constructor(global: &GlobalScope, x: f64, y: f64, width: 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<DOMStringMap> { 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<DOMTokenList> { 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::<Node>().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<DOMRect> { let win = window_from_node(self); let rect = self.upcast::<Node>().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..edf1118b58c 100644 --- a/components/script/dom/errorevent.rs +++ b/components/script/dom/errorevent.rs @@ -7,12 +7,12 @@ 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; 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 +41,13 @@ impl ErrorEvent { } } - pub fn new_uninitialized(global: GlobalRef) -> Root<ErrorEvent> { + pub fn new_uninitialized(global: &GlobalScope) -> Root<ErrorEvent> { 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, @@ -70,7 +70,7 @@ impl ErrorEvent { ev } - pub fn Constructor(global: GlobalRef, + pub fn Constructor(global: &GlobalScope, type_: DOMString, init: &ErrorEventBinding::ErrorEventInit) -> Fallible<Root<ErrorEvent>>{ let msg = match init.message.as_ref() { @@ -94,11 +94,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, + 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..cdbfdafec2e 100644 --- a/components/script/dom/event.rs +++ b/components/script/dom/event.rs @@ -6,13 +6,13 @@ 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}; 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 +115,13 @@ impl Event { } } - pub fn new_uninitialized(global: GlobalRef) -> Root<Event> { + pub fn new_uninitialized(global: &GlobalScope) -> Root<Event> { 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<Event> { @@ -130,7 +130,7 @@ impl Event { event } - pub fn Constructor(global: GlobalRef, + pub fn Constructor(global: &GlobalScope, type_: DOMString, init: &EventBinding::EventInit) -> Fallible<Root<Event>> { let bubbles = EventBubbles::from(init.bubbles); diff --git a/components/script/dom/eventdispatcher.rs b/components/script/dom/eventdispatcher.rs index 28ea0b42b31..cb7107e92e5 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::<Window>(target.global()) { + Some(window) => { if window.need_emit_timeline_marker(TimelineMarkerType::DOMEvent) { Some(window) } else { diff --git a/components/script/dom/eventsource.rs b/components/script/dom/eventsource.rs index 4007e391852..f05e73beafa 100644 --- a/components/script/dom/eventsource.rs +++ b/components/script/dom/eventsource.rs @@ -6,11 +6,11 @@ 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; use dom::eventtarget::EventTarget; +use dom::globalscope::GlobalScope; use std::cell::Cell; use url::Url; @@ -42,11 +42,13 @@ impl EventSource { } } - fn new(global: GlobalRef, url: Url, with_credentials: bool) -> Root<EventSource> { - reflect_dom_object(box EventSource::new_inherited(url, with_credentials), global, Wrap) + fn new(global: &GlobalScope, url: Url, with_credentials: bool) -> Root<EventSource> { + reflect_dom_object(box EventSource::new_inherited(url, with_credentials), + global, + Wrap) } - pub fn Constructor(global: GlobalRef, + pub fn Constructor(global: &GlobalScope, url_str: DOMString, event_source_init: &EventSourceInit) -> Fallible<Root<EventSource>> { // Steps 1-2 diff --git a/components/script/dom/eventtarget.rs b/components/script/dom/eventtarget.rs index 9bdaac20288..6d6ea81c7b6 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::<ErrorEvent>() { - let global = object.global(); - let cx = global.r().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()), @@ -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().get_cx(); rooted!(in(cx) let value = value); let value = value.handle(); @@ -500,8 +498,7 @@ impl EventTarget { bubbles: EventBubbles, cancelable: EventCancelable) -> Root<Event> { - let global = self.global(); - let event = Event::new(global.r(), 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/extendableevent.rs b/components/script/dom/extendableevent.rs index ffb6c3baad2..d859d8f4724 100644 --- a/components/script/dom/extendableevent.rs +++ b/components/script/dom/extendableevent.rs @@ -5,12 +5,12 @@ 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; use dom::bindings::str::DOMString; use dom::event::Event; +use dom::globalscope::GlobalScope; use js::jsapi::{HandleValue, JSContext}; use string_cache::Atom; @@ -28,7 +28,7 @@ impl ExtendableEvent { extensions_allowed: true } } - pub fn new(global: GlobalRef, + pub fn new(global: &GlobalScope, type_: Atom, bubbles: bool, cancelable: bool) @@ -41,7 +41,7 @@ impl ExtendableEvent { ev } - pub fn Constructor(global: GlobalRef, + pub fn Constructor(global: &GlobalScope, type_: DOMString, init: &ExtendableEventBinding::ExtendableEventInit) -> Fallible<Root<ExtendableEvent>> { Ok(ExtendableEvent::new(global, diff --git a/components/script/dom/extendablemessageevent.rs b/components/script/dom/extendablemessageevent.rs index 202c81c0416..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; @@ -13,6 +12,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 +27,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<ExtendableMessageEvent> { @@ -46,12 +46,13 @@ impl ExtendableMessageEvent { ev } - pub fn Constructor(global: GlobalRef, + pub fn Constructor(global: &GlobalScope, type_: DOMString, init: &ExtendableMessageEventBinding::ExtendableMessageEventInit) -> Fallible<Root<ExtendableMessageEvent>> { rooted!(in(global.get_cx()) let data = init.data); - let ev = ExtendableMessageEvent::new(global, Atom::from(type_), + let ev = ExtendableMessageEvent::new(global, + Atom::from(type_), init.parent.parent.bubbles, init.parent.parent.cancelable, data.handle(), @@ -63,7 +64,7 @@ impl ExtendableMessageEvent { impl ExtendableMessageEvent { pub fn dispatch_jsval(target: &EventTarget, - scope: GlobalRef, + scope: &GlobalScope, message: HandleValue) { let Extendablemessageevent = ExtendableMessageEvent::new( scope, atom!("message"), false, false, message, diff --git a/components/script/dom/file.rs b/components/script/dom/file.rs index 8b4abaaed80..dba94a85e50 100644 --- a/components/script/dom/file.rs +++ b/components/script/dom/file.rs @@ -6,11 +6,12 @@ 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; 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 +42,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<i64>, typeString: &str) -> Root<File> { reflect_dom_object(box File::new_inherited(blob_impl, name, modified, typeString), global, @@ -52,14 +53,12 @@ impl File { pub fn new_from_selected(window: &Window, selected: SelectedFile) -> Root<File> { 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) } // https://w3c.github.io/FileAPI/#file-constructor - pub fn Constructor(global: GlobalRef, + pub fn Constructor(global: &GlobalScope, fileBits: Vec<BlobOrString>, filename: DOMString, filePropertyBag: &FileBinding::FilePropertyBag) @@ -76,7 +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, 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/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<File>>) -> Root<FileList> { 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..296a6461b55 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; @@ -17,6 +16,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,12 +88,12 @@ impl FileReader { } } - pub fn new(global: GlobalRef) -> Root<FileReader> { + pub fn new(global: &GlobalScope) -> Root<FileReader> { reflect_dom_object(box FileReader::new_inherited(), global, FileReaderBinding::Wrap) } - pub fn Constructor(global: GlobalRef) -> Fallible<Root<FileReader>> { + pub fn Constructor(global: &GlobalScope) -> Fallible<Root<FileReader>> { Ok(FileReader::new(global)) } @@ -114,8 +114,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(), error); + let exception = DOMException::new(&fr.global(), error); fr.error.set(Some(&exception)); fr.dispatch_progress_event(atom!("error"), 0, None); @@ -289,8 +288,7 @@ impl FileReaderMethods for FileReader { // Steps 1 & 3 *self.result.borrow_mut() = None; - let global = self.global(); - let exception = DOMException::new(global.r(), DOMErrorName::AbortError); + let exception = DOMException::new(&self.global(), DOMErrorName::AbortError); self.error.set(Some(&exception)); self.terminate_ongoing_reading(); @@ -318,8 +316,7 @@ impl FileReaderMethods for FileReader { impl FileReader { fn dispatch_progress_event(&self, type_: Atom, loaded: u64, total: Option<u64>) { - let global = self.global(); - let progressevent = ProgressEvent::new(global.r(), + let progressevent = ProgressEvent::new(&self.global(), type_, EventBubbles::DoesNotBubble, EventCancelable::NotCancelable, total.is_some(), loaded, total.unwrap_or(0)); progressevent.upcast::<Event>().fire(self.upcast()); @@ -336,9 +333,9 @@ impl FileReader { return Err(Error::InvalidState); } // Step 2 + let global = self.global(); if blob.IsClosed() { - let global = self.global(); - let exception = DOMException::new(global.r(), DOMErrorName::InvalidStateError); + let exception = DOMException::new(&global, DOMErrorName::InvalidStateError); self.error.set(Some(&exception)); self.dispatch_progress_event(atom!("error"), 0, None); @@ -358,8 +355,9 @@ impl FileReader { let fr = Trusted::new(self); let gen_id = self.generation_id.get(); - let wrapper = self.global().r().get_runnable_wrapper(); - let task_source = self.global().r().file_reading_task_source(); + let global = self.global(); + 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/filereadersync.rs b/components/script/dom/filereadersync.rs index b248848edad..875843ea0c6 100644 --- a/components/script/dom/filereadersync.rs +++ b/components/script/dom/filereadersync.rs @@ -4,12 +4,10 @@ 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; - - +use dom::globalscope::GlobalScope; #[dom_struct] pub struct FileReaderSync { @@ -23,12 +21,12 @@ impl FileReaderSync { } } - pub fn new(global: GlobalRef) -> Root<FileReaderSync> { + pub fn new(global: &GlobalScope) -> Root<FileReaderSync> { reflect_dom_object(box FileReaderSync::new_inherited(), global, FileReaderSyncBinding::Wrap) } - pub fn Constructor(global: GlobalRef) -> Fallible<Root<FileReaderSync>> { + pub fn Constructor(global: &GlobalScope) -> Fallible<Root<FileReaderSync>> { Ok(FileReaderSync::new(global)) } } diff --git a/components/script/dom/focusevent.rs b/components/script/dom/focusevent.rs index dd5e41e8426..d06b725286d 100644 --- a/components/script/dom/focusevent.rs +++ b/components/script/dom/focusevent.rs @@ -6,13 +6,13 @@ 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; 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 +31,7 @@ impl FocusEvent { } } - pub fn new_uninitialized(global: GlobalRef) -> Root<FocusEvent> { + pub fn new_uninitialized(global: &GlobalScope) -> Root<FocusEvent> { reflect_dom_object(box FocusEvent::new_inherited(), global, FocusEventBinding::Wrap) @@ -44,8 +44,7 @@ impl FocusEvent { view: Option<&Window>, detail: i32, related_target: Option<&EventTarget>) -> Root<FocusEvent> { - 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::<UIEvent>().InitUIEvent(type_, bool::from(can_bubble), bool::from(cancelable), @@ -54,12 +53,13 @@ impl FocusEvent { ev } - pub fn Constructor(global: GlobalRef, + pub fn Constructor(global: &GlobalScope, type_: DOMString, init: &FocusEventBinding::FocusEventInit) -> Fallible<Root<FocusEvent>> { 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_window(), + type_, bubbles, cancelable, init.parent.view.r(), 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<ForceTouchEvent> { 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::<UIEvent>().InitUIEvent(type_, true, true, Some(window), 0); ev } diff --git a/components/script/dom/formdata.rs b/components/script/dom/formdata.rs index 542b44e804e..2c8f99b424b 100644 --- a/components/script/dom/formdata.rs +++ b/components/script/dom/formdata.rs @@ -7,13 +7,13 @@ 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}; 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,12 +45,12 @@ impl FormData { } } - pub fn new(form: Option<&HTMLFormElement>, global: GlobalRef) -> Root<FormData> { + pub fn new(form: Option<&HTMLFormElement>, global: &GlobalScope) -> Root<FormData> { reflect_dom_object(box FormData::new_inherited(form), global, FormDataWrap) } - pub fn Constructor(global: GlobalRef, form: Option<&HTMLFormElement>) -> Fallible<Root<FormData>> { + pub fn Constructor(global: &GlobalScope, form: Option<&HTMLFormElement>) -> Fallible<Root<FormData>> { // TODO: Construct form data set for form if it is supplied Ok(FormData::new(form, global)) } @@ -145,8 +145,6 @@ impl FormDataMethods for FormData { impl FormData { fn get_file(&self, blob: &Blob, opt_filename: Option<USVString>) -> Root<File> { - let global = self.global(); - let name = match opt_filename { Some(filename) => DOMString::from(filename.0), None => DOMString::from(""), @@ -154,7 +152,7 @@ impl FormData { let bytes = blob.get_bytes().unwrap_or(vec![]); - File::new(global.r(), BlobImpl::new_from_bytes(bytes), name, None, "") + File::new(&self.global(), BlobImpl::new_from_bytes(bytes), name, None, "") } pub fn datums(&self) -> Vec<FormDatum> { diff --git a/components/script/dom/globalscope.rs b/components/script/dom/globalscope.rs new file mode 100644 index 00000000000..fc160675df5 --- /dev/null +++ b/components/script/dom/globalscope.rs @@ -0,0 +1,524 @@ +/* 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 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}; +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::{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; +use net_traits::{CoreResourceThread, ResourceThreads, IpcSend}; +use profile_traits::{mem, 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, 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 task_source::file_reading::FileReadingTaskSource; +use time::{Timespec, get_time}; +use timers::{IsInterval, OneshotTimerCallback, OneshotTimerHandle}; +use timers::{OneshotTimers, TimerCallback}; +use url::Url; + +#[dom_struct] +pub struct GlobalScope { + eventtarget: EventTarget, + crypto: MutNullableHeap<JS<Crypto>>, + next_worker_id: Cell<WorkerId>, + + /// 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<bool>, + + /// Timers used by the Console API. + console_timers: DOMRefCell<HashMap<DOMString, u64>>, + + /// For providing instructions to an optional devtools server. + #[ignore_heap_size_of = "channels are hard"] + devtools_chan: Option<IpcSender<ScriptToDevtoolsControlMsg>>, + + /// 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, + + /// A handle for communicating messages to the constellation thread. + #[ignore_heap_size_of = "channels are hard"] + constellation_chan: IpcSender<ConstellationMsg>, + + #[ignore_heap_size_of = "channels are hard"] + scheduler_chan: IpcSender<TimerEventRequest>, + + /// https://html.spec.whatwg.org/multipage/#in-error-reporting-mode + in_error_reporting_mode: Cell<bool>, + + /// 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 { + pub fn new_inherited( + pipeline_id: PipelineId, + devtools_chan: Option<IpcSender<ScriptToDevtoolsControlMsg>>, + mem_profiler_chan: mem::ProfilerChan, + time_profiler_chan: time::ProfilerChan, + constellation_chan: IpcSender<ConstellationMsg>, + scheduler_chan: IpcSender<TimerEventRequest>, + resource_threads: ResourceThreads, + timer_event_chan: IpcSender<TimerEvent>) + -> Self { + 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, + mem_profiler_chan: mem_profiler_chan, + time_profiler_chan: time_profiler_chan, + constellation_chan: constellation_chan, + scheduler_chan: scheduler_chan.clone(), + in_error_reporting_mode: Default::default(), + resource_threads: resource_threads, + timers: OneshotTimers::new(timer_event_chan, scheduler_chan), + } + } + + /// Returns the global scope of the realm that the given DOM object's reflector + /// was created in. + #[allow(unsafe_code)] + pub fn from_reflector<T: Reflectable>(reflector: &T) -> Root<Self> { + 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<Self> { + 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<Self> { + 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<Self> { + 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 { + let runtime = JS_GetObjectRuntime( + self.reflector().get_jsobject().get()); + assert!(!runtime.is_null()); + let context = JS_GetContext(runtime); + assert!(!context.is_null()); + context + } + } + + pub fn crypto(&self) -> Root<Crypto> { + 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 + } + + 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); + } + + 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<u64, ()> { + self.console_timers.borrow_mut().remove(label).ok_or(()).map(|start| { + timestamp_in_ms(get_time()) - start + }) + } + + /// Get an `&IpcSender<ScriptToDevtoolsControlMsg>` to send messages + /// to the devtools thread when available. + pub fn devtools_chan(&self) -> Option<&IpcSender<ScriptToDevtoolsControlMsg>> { + 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 + } + + /// Get a sender to the time profiler thread. + 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<ConstellationMsg> { + &self.constellation_chan + } + + pub fn scheduler_chan(&self) -> &IpcSender<TimerEventRequest> { + &self.scheduler_chan + } + + /// Get the `PipelineId` for this global scope. + 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::<Window>() { + // 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::<WorkerGlobalScope>() { + // https://html.spec.whatwg.org/multipage/#script-settings-for-workers:api-base-url + return worker.get_url().clone(); + } + unreachable!(); + } + + /// Get the URL for this global scope. + pub fn get_url(&self) -> Url { + if let Some(window) = self.downcast::<Window>() { + return window.get_url(); + } + if let Some(worker) = self.downcast::<WorkerGlobalScope>() { + return worker.get_url().clone(); + } + unreachable!(); + } + + /// Extract a `Window`, panic if the global object is not a `Window`. + pub fn as_window(&self) -> &Window { + self.downcast::<Window>().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::<Event>().fire(self.upcast::<EventTarget>()); + + // Step 15 + if event_status == EventStatus::NotCanceled { + if let Some(dedicated) = self.downcast::<DedicatedWorkerGlobalScope>() { + dedicated.forward_error_to_worker_object(error_info); + } + } + + // 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 + } + + /// Get the `CoreResourceThread` for this global scope. + 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<ScriptChan + Send> { + if let Some(window) = self.downcast::<Window>() { + return MainThreadScriptChan(window.main_thread_script_chan().clone()).clone(); + } + if let Some(worker) = self.downcast::<WorkerGlobalScope>() { + return worker.script_chan(); + } + unreachable!(); + } + + /// `ScriptChan` to send messages to the networking task source of + /// this of this global scope. + pub fn networking_task_source(&self) -> Box<ScriptChan + Send> { + if let Some(window) = self.downcast::<Window>() { + return window.networking_task_source(); + } + if let Some(worker) = self.downcast::<WorkerGlobalScope>() { + return worker.script_chan(); + } + 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<u16> = 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); + } + } + ) + } + + 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<HandleValue>, + 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::<Window>() { + return TimerSource::FromWindow(self.pipeline_id()); + } + if self.is::<WorkerGlobalScope>() { + return TimerSource::FromWorker; + } + 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::<Window>() { + return window.get_runnable_wrapper(); + } + if let Some(worker) = self.downcast::<WorkerGlobalScope>() { + return worker.get_runnable_wrapper(); + } + 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::<Window>() { + return ScriptThread::flush_promise_jobs(self); + } + if let Some(worker) = self.downcast::<WorkerGlobalScope>() { + return worker.flush_promise_jobs(); + } + unreachable!(); + } + + /// Enqueue a promise callback for subsequent execution. + pub fn enqueue_promise_job(&self, job: EnqueuedPromiseCallback) { + if self.is::<Window>() { + return ScriptThread::enqueue_promise_job(job, self); + } + if let Some(worker) = self.downcast::<WorkerGlobalScope>() { + return worker.enqueue_promise_job(job); + } + 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<ScriptChan + Send>, Box<ScriptPort + Send>) { + if let Some(window) = self.downcast::<Window>() { + return window.new_script_pair(); + } + if let Some(worker) = self.downcast::<WorkerGlobalScope>() { + return worker.new_script_pair(); + } + 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::<Window>() { + return ScriptThread::process_event(msg); + } + if let Some(worker) = self.downcast::<WorkerGlobalScope>() { + return worker.process_event(msg); + } + 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::<Window>() { + return window.file_reading_task_source(); + } + if let Some(worker) = self.downcast::<WorkerGlobalScope>() { + return worker.file_reading_task_source(); + } + unreachable!(); + } +} + +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<GlobalScope> { + 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/hashchangeevent.rs b/components/script/dom/hashchangeevent.rs index 33562123ac6..0fd753c433c 100644 --- a/components/script/dom/hashchangeevent.rs +++ b/components/script/dom/hashchangeevent.rs @@ -6,12 +6,12 @@ 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; 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 +31,13 @@ impl HashChangeEvent { } } - pub fn new_uninitialized(global: GlobalRef) - -> Root<HashChangeEvent> { + pub fn new_uninitialized(global: &GlobalScope) -> Root<HashChangeEvent> { 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, @@ -55,7 +54,7 @@ impl HashChangeEvent { ev } - pub fn Constructor(global: GlobalRef, + pub fn Constructor(global: &GlobalScope, type_: DOMString, init: &HashChangeEventBinding::HashChangeEventInit) -> Fallible<Root<HashChangeEvent>> { diff --git a/components/script/dom/headers.rs b/components/script/dom/headers.rs index 7f43dd6b07a..02262dbb475 100644 --- a/components/script/dom/headers.rs +++ b/components/script/dom/headers.rs @@ -5,11 +5,11 @@ 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}; 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,12 +43,12 @@ impl Headers { } } - pub fn new(global: GlobalRef) -> Root<Headers> { + pub fn new(global: &GlobalScope) -> Root<Headers> { reflect_dom_object(box Headers::new_inherited(), global, HeadersWrap) } // https://fetch.spec.whatwg.org/#dom-headers - pub fn Constructor(global: GlobalRef, init: Option<HeadersInit>) + pub fn Constructor(global: &GlobalScope, init: Option<HeadersInit>) -> Fallible<Root<Headers>> { let dom_headers_new = Headers::new(global); try!(dom_headers_new.fill(init)); @@ -205,13 +205,13 @@ impl Headers { } } - pub fn for_request(global: GlobalRef) -> Root<Headers> { + pub fn for_request(global: &GlobalScope) -> Root<Headers> { let headers_for_request = Headers::new(global); headers_for_request.guard.set(Guard::Request); headers_for_request } - pub fn for_response(global: GlobalRef) -> Root<Headers> { + pub fn for_response(global: &GlobalScope) -> Root<Headers> { 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..1a971eae009 100644 --- a/components/script/dom/history.rs +++ b/components/script/dom/history.rs @@ -6,9 +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::global::GlobalRef; +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; @@ -31,26 +32,28 @@ impl History { pub fn new(window: &Window) -> Root<History> { reflect_dom_object(box History::new_inherited(window), - GlobalRef::Window(window), + window, HistoryBinding::Wrap) } } impl History { fn traverse_history(&self, direction: TraversalDirection) { - let pipeline = self.window.pipeline_id(); + let global_scope = self.window.upcast::<GlobalScope>(); + let pipeline = global_scope.pipeline_id(); let msg = ConstellationMsg::TraverseHistory(Some(pipeline), direction); - let _ = self.window.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::<GlobalScope>(); + 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.constellation_chan().send(msg); + let _ = global_scope.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::<GlobalScope>().constellation_chan().send(event).unwrap(); } fn parse_plain_attribute(&self, name: &Atom, value: DOMString) -> AttrValue { diff --git a/components/script/dom/htmlcanvaselement.rs b/components/script/dom/htmlcanvaselement.rs index f4a13836eb1..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; @@ -20,6 +19,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 +142,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::<GlobalScope>(), self, size); *self.context.borrow_mut() = Some(CanvasContext::Context2d(JS::from_ref(&*context))); } @@ -177,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/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<CollectionFilter + 'static>) -> Root<HTMLCollection> { 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/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/htmlformcontrolscollection.rs b/components/script/dom/htmlformcontrolscollection.rs index e52a541225f..3986692099c 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<HTMLFormControlsCollection> { reflect_dom_object(box HTMLFormControlsCollection::new_inherited(root, filter), - GlobalRef::Window(window), + window, HTMLFormControlsCollectionBinding::Wrap) } @@ -67,7 +66,6 @@ impl HTMLFormControlsCollectionMethods for HTMLFormControlsCollection { let once = iter::once(Root::upcast::<Node>(elem)); let list = once.chain(peekable.map(Root::upcast)); let global = self.global(); - let global = global.r(); let window = global.as_window(); Some(RadioNodeListOrElement::RadioNodeList(RadioNodeList::new_simple_list(window, list))) } diff --git a/components/script/dom/htmlformelement.rs b/components/script/dom/htmlformelement.rs index 8759fbafe5e..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; @@ -24,6 +23,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,14 +436,14 @@ impl HTMLFormElement { // Step 2 let nav = box PlannedNavigation { load_data: load_data, - pipeline_id: window.pipeline_id(), + pipeline_id: window.upcast::<GlobalScope>().pipeline_id(), script_chan: window.main_thread_script_chan().clone(), generation_id: self.generation_id.get(), form: Trusted::new(self) }; // 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/htmliframeelement.rs b/components/script/dom/htmliframeelement.rs index 1503ff28e06..75d828e73c9 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; @@ -30,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; @@ -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::<GlobalScope>(); 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,8 @@ impl HTMLIFrameElement { frame_type: frame_type, replace: replace, }; - window.constellation_chan() + global_scope + .constellation_chan() .send(ConstellationMsg::ScriptLoadedURLInIFrame(load_info)) .unwrap(); @@ -217,7 +219,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::<GlobalScope>().constellation_chan().send(msg).unwrap(); } } @@ -316,7 +318,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, @@ -408,7 +410,7 @@ pub fn Navigate(iframe: &HTMLIFrameElement, direction: TraversalDirection) -> Er if iframe.upcast::<Node>().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::<GlobalScope>().constellation_chan().send(msg).unwrap(); } Ok(()) @@ -642,7 +644,7 @@ impl VirtualMethods for HTMLIFrameElement { (Some(sender), Some(receiver)) }; let msg = ConstellationMsg::RemoveIFrame(pipeline_id, sender); - window.constellation_chan().send(msg).unwrap(); + window.upcast::<GlobalScope>().constellation_chan().send(msg).unwrap(); if let Some(receiver) = receiver { receiver.recv().unwrap() } diff --git a/components/script/dom/htmlimageelement.rs b/components/script/dom/htmlimageelement.rs index c6652913c42..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; @@ -17,6 +16,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; @@ -191,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()); } } } @@ -225,7 +225,7 @@ impl HTMLImageElement { HTMLImageElementBinding::Wrap) } - pub fn Image(global: GlobalRef, + pub fn Image(global: &GlobalScope, width: Option<u32>, height: Option<u32>) -> Fallible<Root<HTMLImageElement>> { let document = global.as_window().Document(); diff --git a/components/script/dom/htmlinputelement.rs b/components/script/dom/htmlinputelement.rs index d9cda98b284..ab184463bb2 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<DOMString>, document: &Document) -> HTMLInputElement { - let chan = document.window().constellation_chan().clone(); + let chan = document.window().upcast::<GlobalScope>().constellation_chan().clone(); HTMLInputElement { htmlelement: HTMLElement::new_inherited_with_state(IN_ENABLED_STATE | IN_READ_WRITE_STATE, @@ -794,7 +795,7 @@ impl HTMLInputElement { fn select_files(&self, opt_test_paths: Option<Vec<DOMString>>) { 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::<GlobalScope>().resource_threads(); let mut files: Vec<Root<File>> = vec![]; let mut error = None; diff --git a/components/script/dom/htmllinkelement.rs b/components/script/dom/htmllinkelement.rs index b02aa0ad6a7..937bdc410d4 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; @@ -266,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().pipeline_id()), referrer_url: Some(document.url().clone()), referrer_policy: referrer_policy, .. RequestInit::default() @@ -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::<GlobalScope>().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/htmlmediaelement.rs b/components/script/dom/htmlmediaelement.rs index 5bbdd738079..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,18 +299,18 @@ 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) { 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); @@ -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/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<HTMLOptionsCollection> { 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..fa1604ffc2b 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}; @@ -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().pipeline_id()), referrer_url: Some(doc.url().clone()), referrer_policy: doc.get_referrer_policy(), .. RequestInit::default() @@ -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::<GlobalScope>().evaluate_script_on_global_with_result( &script.text, script.url.as_str(), rval.handle_mut()); // Step 6. @@ -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/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<DOMString>, document: &Document) -> HTMLTextAreaElement { - let chan = document.window().constellation_chan().clone(); + let chan = document.window().upcast::<GlobalScope>().constellation_chan().clone(); HTMLTextAreaElement { htmlelement: HTMLElement::new_inherited_with_state(IN_ENABLED_STATE | IN_READ_WRITE_STATE, 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<Vec<u8>>) -> Root<ImageData> { + pub fn new(global: &GlobalScope, width: u32, height: u32, data: Option<Vec<u8>>) -> Root<ImageData> { 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..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; @@ -62,7 +62,7 @@ impl KeyboardEvent { pub fn new_uninitialized(window: &Window) -> Root<KeyboardEvent> { reflect_dom_object(box KeyboardEvent::new_inherited(), - GlobalRef::Window(window), + window, KeyboardEventBinding::Wrap) } @@ -101,10 +101,11 @@ impl KeyboardEvent { ev } - pub fn Constructor(global: GlobalRef, + pub fn Constructor(global: &GlobalScope, type_: DOMString, init: &KeyboardEventBinding::KeyboardEventInit) -> Fallible<Root<KeyboardEvent>> { - let event = KeyboardEvent::new(global.as_window(), type_, + let event = KeyboardEvent::new(global.as_window(), + type_, init.parent.parent.parent.bubbles, init.parent.parent.parent.cancelable, init.parent.parent.view.r(), 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<Location> { 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<MediaError> { 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..53143711cf0 100644 --- a/components/script/dom/messageevent.rs +++ b/components/script/dom/messageevent.rs @@ -6,13 +6,13 @@ 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; 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 +27,14 @@ pub struct MessageEvent { } impl MessageEvent { - pub fn new_uninitialized(global: GlobalRef) -> Root<MessageEvent> { + pub fn new_uninitialized(global: &GlobalScope) -> Root<MessageEvent> { 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<MessageEvent> { @@ -48,7 +48,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<MessageEvent> { @@ -60,27 +60,36 @@ impl MessageEvent { ev } - pub fn Constructor(global: GlobalRef, + pub fn Constructor(global: &GlobalScope, type_: DOMString, init: &MessageEventBinding::MessageEventInit) -> Fallible<Root<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, + 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) } } impl MessageEvent { pub fn dispatch_jsval(target: &EventTarget, - scope: GlobalRef, + scope: &GlobalScope, message: HandleValue) { let messageevent = MessageEvent::new( - scope, atom!("message"), false, false, message, - DOMString::new(), DOMString::new()); + scope, + atom!("message"), + false, + false, + message, + DOMString::new(), + DOMString::new()); messageevent.upcast::<Event>().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<MimeTypeArray> { + pub fn new(global: &GlobalScope) -> Root<MimeTypeArray> { reflect_dom_object(box MimeTypeArray::new_inherited(), global, MimeTypeArrayBinding::Wrap) 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/mouseevent.rs b/components/script/dom/mouseevent.rs index 659a28226b7..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; @@ -53,7 +53,7 @@ impl MouseEvent { pub fn new_uninitialized(window: &Window) -> Root<MouseEvent> { reflect_dom_object(box MouseEvent::new_inherited(), - GlobalRef::Window(window), + window, MouseEventBinding::Wrap) } @@ -82,12 +82,13 @@ impl MouseEvent { ev } - pub fn Constructor(global: GlobalRef, + pub fn Constructor(global: &GlobalScope, type_: DOMString, init: &MouseEventBinding::MouseEventInit) -> Fallible<Root<MouseEvent>> { 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_window(), + type_, bubbles, cancelable, init.parent.parent.view.r(), 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<NamedNodeMap> { 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..bea18dfe61b 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<Navigator> { 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<Bluetooth> { - self.bluetooth.or_init(|| Bluetooth::new(self.global().r())) + self.bluetooth.or_init(|| Bluetooth::new(&self.global())) } // 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<PluginArray> { - self.plugins.or_init(|| PluginArray::new(self.global().r())) + self.plugins.or_init(|| PluginArray::new(&self.global())) } // https://html.spec.whatwg.org/multipage/#dom-navigator-mimetypes fn MimeTypes(&self) -> Root<MimeTypeArray> { - self.mime_types.or_init(|| MimeTypeArray::new(self.global().r())) + self.mime_types.or_init(|| MimeTypeArray::new(&self.global())) } // 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<ServiceWorkerContainer> { - self.service_worker.or_init(|| ServiceWorkerContainer::new(self.global().r())) + self.service_worker.or_init(|| { + ServiceWorkerContainer::new(&self.global()) + }) } // 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: &T) -> uintptr_t { t as *const T as uintptr_t } impl Node { - pub fn reflect_node<N: DerivedFrom<Node> + Reflectable> - (node: Box<N>, - document: &Document, - wrap_fn: extern "Rust" fn(*mut JSContext, GlobalRef, Box<N>) -> Root<N>) - -> Root<N> { + pub fn reflect_node<N>( + node: Box<N>, + document: &Document, + wrap_fn: extern "Rust" fn(*mut JSContext, &GlobalScope, Box<N>) -> Root<N>) + -> Root<N> + where N: DerivedFrom<Node> + 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<NodeIterator> { 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<NodeList> { reflect_dom_object(box NodeList::new_inherited(list_type), - GlobalRef::Window(window), NodeListBinding::Wrap) + window, + NodeListBinding::Wrap) } pub fn new_simple_list<T>(window: &Window, iter: T) -> Root<NodeList> diff --git a/components/script/dom/pagetransitionevent.rs b/components/script/dom/pagetransitionevent.rs index 7c6b7b6f555..883f3319394 100644 --- a/components/script/dom/pagetransitionevent.rs +++ b/components/script/dom/pagetransitionevent.rs @@ -6,12 +6,12 @@ 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; use dom::bindings::str::DOMString; use dom::event::Event; +use dom::globalscope::GlobalScope; use std::cell::Cell; use string_cache::Atom; @@ -30,13 +30,13 @@ impl PageTransitionEvent { } } - pub fn new_uninitialized(global: GlobalRef) -> Root<PageTransitionEvent> { + pub fn new_uninitialized(global: &GlobalScope) -> Root<PageTransitionEvent> { 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, @@ -51,7 +51,7 @@ impl PageTransitionEvent { ev } - pub fn Constructor(global: GlobalRef, + pub fn Constructor(global: &GlobalScope, type_: DOMString, init: &PageTransitionEventBinding::PageTransitionEventInit) -> Fallible<Root<PageTransitionEvent>> { 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<PluginArray> { + pub fn new(global: &GlobalScope) -> Root<PluginArray> { 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..7b7af62a6fe 100644 --- a/components/script/dom/popstateevent.rs +++ b/components/script/dom/popstateevent.rs @@ -6,12 +6,12 @@ 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; 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 +32,13 @@ impl PopStateEvent { } } - pub fn new_uninitialized(global: GlobalRef) -> Root<PopStateEvent> { + pub fn new_uninitialized(global: &GlobalScope) -> Root<PopStateEvent> { 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, @@ -54,7 +54,7 @@ impl PopStateEvent { } #[allow(unsafe_code)] - pub fn Constructor(global: GlobalRef, + pub fn Constructor(global: &GlobalScope, type_: DOMString, init: &PopStateEventBinding::PopStateEventInit) -> Fallible<Root<PopStateEvent>> { diff --git a/components/script/dom/progressevent.rs b/components/script/dom/progressevent.rs index f0d2b5c400a..189f65412fe 100644 --- a/components/script/dom/progressevent.rs +++ b/components/script/dom/progressevent.rs @@ -6,13 +6,12 @@ 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; 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 +31,12 @@ impl ProgressEvent { total: total } } - pub fn new_uninitialized(window: &Window) -> Root<ProgressEvent> { + pub fn new_uninitialized(global: &GlobalScope) -> Root<ProgressEvent> { 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<ProgressEvent> { let ev = reflect_dom_object(box ProgressEvent::new_inherited(length_computable, loaded, total), @@ -49,7 +48,7 @@ impl ProgressEvent { } ev } - pub fn Constructor(global: GlobalRef, + pub fn Constructor(global: &GlobalScope, type_: DOMString, init: &ProgressEventBinding::ProgressEventInit) -> Fallible<Root<ProgressEvent>> { diff --git a/components/script/dom/promise.rs b/components/script/dom/promise.rs index 5fd1ef6f85e..c0842dce4fa 100644 --- a/components/script/dom/promise.rs +++ b/components/script/dom/promise.rs @@ -15,9 +15,9 @@ 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; use dom::promisenativehandler::PromiseNativeHandler; use js::conversions::ToJSValConvertible; use js::jsapi::{CallOriginalPromiseResolve, CallOriginalPromiseReject, CallOriginalPromiseThen}; @@ -61,7 +61,7 @@ impl PromiseHelper for Rc<Promise> { impl Drop for Promise { #[allow(unsafe_code)] fn drop(&mut self) { - let cx = self.global().r().get_cx(); + let cx = self.global().get_cx(); unsafe { RemoveRawValueRoot(cx, self.permanent_js_root.get_unsafe()); } @@ -70,7 +70,7 @@ impl Drop for Promise { impl Promise { #[allow(unsafe_code)] - pub fn new(global: GlobalRef) -> Rc<Promise> { + pub fn new(global: &GlobalScope) -> Rc<Promise> { let cx = global.get_cx(); rooted!(in(cx) let mut obj = ptr::null_mut()); unsafe { @@ -81,7 +81,7 @@ impl Promise { #[allow(unsafe_code, unrooted_must_root)] pub fn duplicate(&self) -> Rc<Promise> { - let cx = self.global().r().get_cx(); + let cx = self.global().get_cx(); unsafe { Promise::new_with_js_promise(self.reflector().get_jsobject(), cx) } @@ -112,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<Rc<Promise>> { let _ac = JSAutoCompartment::new(cx, global.reflector().get_jsobject().get()); @@ -124,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<Rc<Promise>> { let _ac = JSAutoCompartment::new(cx, global.reflector().get_jsobject().get()); @@ -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().r(), v.handle_mut()); + error.to_jsval(cx, &self.global(), v.handle_mut()); } self.reject(cx, v.handle()); } @@ -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().get_cx(); rooted!(in(cx) let resolve_func = create_native_handler_function(cx, handler.reflector().get_jsobject(), 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<Box<Callback>>, reject: Option<Box<Callback>>) -> Root<PromiseNativeHandler> { 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<RadioNodeList> { 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..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}; @@ -60,7 +60,7 @@ impl Range { -> Root<Range> { 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 { @@ -70,7 +70,7 @@ impl Range { } // https://dom.spec.whatwg.org/#dom-range - pub fn Constructor(global: GlobalRef) -> Fallible<Root<Range>> { + pub fn Constructor(global: &GlobalScope) -> Fallible<Root<Range>> { 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 fa665679c0d..efeafd5e289 100644 --- a/components/script/dom/request.rs +++ b/components/script/dom/request.rs @@ -17,10 +17,10 @@ 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}; +use dom::globalscope::GlobalScope; use dom::headers::{Guard, Headers}; use dom::promise::Promise; use dom::xmlhttprequest::Extractable; @@ -51,7 +51,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,7 +67,7 @@ impl Request { } } - pub fn new(global: GlobalRef, + pub fn new(global: &GlobalScope, url: Url, is_service_worker_global_scope: bool) -> Root<Request> { reflect_dom_object(box Request::new_inherited(global, @@ -77,7 +77,7 @@ impl Request { } // https://fetch.spec.whatwg.org/#dom-request - pub fn Constructor(global: GlobalRef, + pub fn Constructor(global: &GlobalScope, input: RequestInfo, init: &RequestInit) -> Fallible<Root<Request>> { @@ -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; @@ -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())); // Step 27 let mut headers_copy = r.Headers(); @@ -412,7 +412,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<Request> { let r = Request::new(global, @@ -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(), 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(); @@ -451,7 +447,7 @@ 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 origin = Origin::Origin(global.get_url().origin()); @@ -553,7 +549,7 @@ impl RequestMethods for Request { // https://fetch.spec.whatwg.org/#dom-request-headers fn Headers(&self) -> Root<Headers> { - self.headers.or_init(|| Headers::new(self.global().r())) + 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 2287bb181b4..cabbd567b49 100644 --- a/components/script/dom/response.rs +++ b/components/script/dom/response.rs @@ -10,10 +10,10 @@ 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}; +use dom::globalscope::GlobalScope; use dom::headers::{Headers, Guard}; use dom::headers::{is_vchar, is_obs_text}; use dom::promise::Promise; @@ -66,11 +66,11 @@ impl Response { } // https://fetch.spec.whatwg.org/#dom-response - pub fn new(global: GlobalRef) -> Root<Response> { + pub fn new(global: &GlobalScope) -> Root<Response> { reflect_dom_object(box Response::new_inherited(), global, ResponseBinding::Wrap) } - pub fn Constructor(global: GlobalRef, body: Option<BodyInit>, init: &ResponseBinding::ResponseInit) + pub fn Constructor(global: &GlobalScope, body: Option<BodyInit>, init: &ResponseBinding::ResponseInit) -> Fallible<Root<Response>> { // Step 1 if init.status < 200 || init.status > 599 { @@ -138,7 +138,7 @@ impl Response { } // https://fetch.spec.whatwg.org/#dom-response-error - pub fn Error(global: GlobalRef) -> Root<Response> { + pub fn Error(global: &GlobalScope) -> Root<Response> { let r = Response::new(global); *r.response_type.borrow_mut() = DOMResponseType::Error; r.Headers().set_guard(Guard::Immutable); @@ -147,7 +147,7 @@ impl Response { } // https://fetch.spec.whatwg.org/#dom-response-redirect - pub fn Redirect(global: GlobalRef, url: USVString, status: u16) -> Fallible<Root<Response>> { + pub fn Redirect(global: &GlobalScope, url: USVString, status: u16) -> Fallible<Root<Response>> { // Step 1 // TODO: `entry settings object` is not implemented in Servo yet. let base_url = global.get_url(); @@ -292,7 +292,7 @@ impl ResponseMethods for Response { // https://fetch.spec.whatwg.org/#dom-response-headers fn Headers(&self) -> Root<Headers> { - self.headers_reflector.or_init(|| Headers::for_response(self.global().r())) + 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().r()); + 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/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<Screen> { 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..8f3686f0b0c 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<ServiceWorker> { @@ -89,8 +89,10 @@ 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() + .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 abeb69f2ea3..0947b9c0a1f 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<ServiceWorkerContainer> { + pub fn new(global: &GlobalScope) -> Root<ServiceWorkerContainer> { reflect_dom_object(box ServiceWorkerContainer::new_inherited(), global, Wrap) } } @@ -58,8 +58,9 @@ impl ServiceWorkerContainerMethods for ServiceWorkerContainer { script_url: USVString, options: &RegistrationOptions) -> Fallible<Root<ServiceWorkerRegistration>> { let USVString(ref script_url) = script_url; + let api_base_url = self.global().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())) } @@ -95,11 +96,12 @@ impl ServiceWorkerContainerMethods for ServiceWorkerContainer { return Err(Error::Type("Scope URL contains forbidden characters".to_owned())); } - let worker_registration = ServiceWorkerRegistration::new(self.global().r(), + let global = self.global(); + let worker_registration = ServiceWorkerRegistration::new(&global, script_url, scope.clone(), self); - ScriptThread::set_registration(scope, &*worker_registration, self.global().r().pipeline_id()); + ScriptThread::set_registration(scope, &*worker_registration, global.pipeline_id()); Ok(worker_registration) } } diff --git a/components/script/dom/serviceworkerglobalscope.rs b/components/script/dom/serviceworkerglobalscope.rs index 6efd555c909..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::{GlobalRef, global_root_from_context}; use dom::bindings::inheritance::Castable; use dom::bindings::js::{Root, RootCollection}; use dom::bindings::reflector::Reflectable; @@ -17,6 +16,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 +192,7 @@ impl ServiceWorkerGlobalScope { global.dispatch_activate(); let reporter_name = format!("service-worker-reporter-{}", random::<u64>()); - scope.mem_profiler_chan().run_with_memory_reporting(|| { + scope.upcast::<GlobalScope>().mem_profiler_chan().run_with_memory_reporting(|| { while let Ok(event) = global.receive_event() { if !global.handle_event(event) { break; @@ -205,14 +205,13 @@ 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) => - 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 @@ -237,8 +236,8 @@ 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()); - ExtendableMessageEvent::dispatch_jsval(target, GlobalRef::Worker(scope), message.handle()); + data.read(scope.upcast(), message.handle_mut()); + ExtendableMessageEvent::dispatch_jsval(target, scope.upcast(), message.handle()); }, CommonWorker(WorkerScriptMsg::Common(CommonScriptMsg::RunnableMsg(_, runnable))) => { runnable.handler() @@ -302,8 +301,7 @@ impl ServiceWorkerGlobalScope { } fn dispatch_activate(&self) { - let global = GlobalRef::Worker(self.upcast::<WorkerGlobalScope>()); - let event = ExtendableEvent::new(global, atom!("activate"), false, false); + let event = ExtendableEvent::new(self.upcast(), atom!("activate"), false, false); let event = (&*event).upcast::<Event>(); self.upcast::<EventTarget>().dispatch_event(event); } @@ -311,11 +309,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::<WorkerGlobalScope>(GlobalScope::from_context(cx)) + .expect("global is not a worker scope"); assert!(worker.is::<ServiceWorkerGlobalScope>()); // A false response causes the script to terminate diff --git a/components/script/dom/serviceworkerregistration.rs b/components/script/dom/serviceworkerregistration.rs index f7c47b8ecec..c3a08e514e4 100644 --- a/components/script/dom/serviceworkerregistration.rs +++ b/components/script/dom/serviceworkerregistration.rs @@ -4,11 +4,11 @@ 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; use dom::eventtarget::EventTarget; +use dom::globalscope::GlobalScope; use dom::serviceworker::ServiceWorker; use dom::serviceworkercontainer::Controllable; use dom::workerglobalscope::prepare_workerscope_init; @@ -35,7 +35,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<ServiceWorkerRegistration> { @@ -49,7 +49,7 @@ impl ServiceWorkerRegistration { self.active.as_ref().unwrap() } - pub fn create_scope_things(global: GlobalRef, script_url: Url) -> ScopeThings { + pub fn create_scope_things(global: &GlobalScope, script_url: Url) -> ScopeThings { let worker_load_origin = WorkerScriptLoadOrigin { referrer_url: None, referrer_policy: None, @@ -57,12 +57,13 @@ impl ServiceWorkerRegistration { }; 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, 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/servohtmlparser.rs b/components/script/dom/servohtmlparser.rs index 24a22be75dd..a65d9e84a6d 100644 --- a/components/script/dom/servohtmlparser.rs +++ b/components/script/dom/servohtmlparser.rs @@ -11,13 +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::global::GlobalRef; +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; @@ -277,8 +278,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 +314,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] @@ -346,7 +345,7 @@ impl ServoHTMLParser { }; profile(ProfilerCategory::ScriptParseHTML, Some(metadata), - self.document.window().time_profiler_chan().clone(), + self.document.window().upcast::<GlobalScope>().time_profiler_chan().clone(), || self.do_parse_sync()) } 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..b8a3865cadd 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,20 +35,16 @@ impl Storage { } } - pub fn new(global: &GlobalRef, storage_type: StorageType) -> Root<Storage> { - reflect_dom_object(box Storage::new_inherited(storage_type), *global, StorageBinding::Wrap) + pub fn new(global: &GlobalScope, storage_type: StorageType) -> Root<Storage> { + reflect_dom_object(box Storage::new_inherited(storage_type), global, StorageBinding::Wrap) } fn get_url(&self) -> Url { - let global_root = self.global(); - let global_ref = global_root.r(); - global_ref.get_url() + self.global().get_url() } fn get_storage_thread(&self) -> IpcSender<StorageThreadMsg> { - let global_root = self.global(); - let global_ref = global_root.r(); - global_ref.as_window().resource_threads().sender() + self.global().resource_threads().sender() } } @@ -154,13 +150,14 @@ impl Storage { /// https://html.spec.whatwg.org/multipage/#send-a-storage-notification fn broadcast_change_notification(&self, key: Option<String>, old_value: Option<String>, new_value: Option<String>) { - let global_root = self.global(); - let global_ref = global_root.r(); - let window = global_ref.as_window(); + let global = self.global(); + 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(); } } @@ -185,13 +182,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(); let ev_url = storage.get_url(); let storage_event = StorageEvent::new( - global_ref, + &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 +201,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 global.pipeline_id() != it_window.upcast::<GlobalScope>().pipeline_id() { storage_event.upcast::<Event>().fire(it_window.upcast()); } } diff --git a/components/script/dom/storageevent.rs b/components/script/dom/storageevent.rs index 69fe7c257d5..21c16f1db78 100644 --- a/components/script/dom/storageevent.rs +++ b/components/script/dom/storageevent.rs @@ -6,12 +6,12 @@ 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; 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 +46,11 @@ impl StorageEvent { pub fn new_uninitialized(window: &Window, url: DOMString) -> Root<StorageEvent> { 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, @@ -70,7 +70,7 @@ impl StorageEvent { ev } - pub fn Constructor(global: GlobalRef, + pub fn Constructor(global: &GlobalScope, type_: DOMString, init: &StorageEventBinding::StorageEventInit) -> Fallible<Root<StorageEvent>> { let key = init.key.clone(); 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<DOMString>, title: Option<DOMString>) -> Root<StyleSheet> { 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<Document>) -> Root<StyleSheetList> { 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..fe76ddccab9 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::{GlobalRef, global_root_from_context}; use dom::bindings::js::Root; use dom::bindings::mozmap::MozMap; use dom::bindings::num::Finite; @@ -30,6 +29,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,22 +57,22 @@ impl TestBinding { } } - pub fn new(global: GlobalRef) -> Root<TestBinding> { + pub fn new(global: &GlobalScope) -> Root<TestBinding> { reflect_dom_object(box TestBinding::new_inherited(), global, TestBindingBinding::Wrap) } - pub fn Constructor(global: GlobalRef) -> Fallible<Root<TestBinding>> { + pub fn Constructor(global: &GlobalScope) -> Fallible<Root<TestBinding>> { Ok(TestBinding::new(global)) } #[allow(unused_variables)] - pub fn Constructor_(global: GlobalRef, nums: Vec<f64>) -> Fallible<Root<TestBinding>> { + pub fn Constructor_(global: &GlobalScope, nums: Vec<f64>) -> Fallible<Root<TestBinding>> { Ok(TestBinding::new(global)) } #[allow(unused_variables)] - pub fn Constructor__(global: GlobalRef, num: f64) -> Fallible<Root<TestBinding>> { + pub fn Constructor__(global: &GlobalScope, num: f64) -> Fallible<Root<TestBinding>> { Ok(TestBinding::new(global)) } } @@ -113,7 +113,7 @@ impl TestBindingMethods for TestBinding { fn EnumAttribute(&self) -> TestEnum { TestEnum::_empty } fn SetEnumAttribute(&self, _: TestEnum) {} fn InterfaceAttribute(&self) -> Root<Blob> { - Blob::new(self.global().r(), 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<TestEnum> { Some(TestEnum::_empty) } fn GetInterfaceAttributeNullable(&self) -> Option<Root<Blob>> { - Some(Blob::new(self.global().r(), 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<Root<URL>> { @@ -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> { - Blob::new(self.global().r(), 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<i32> { vec![1] } fn ReceiveInterfaceSequence(&self) -> Vec<Root<Blob>> { - vec![Blob::new(self.global().r(), BlobImpl::new_from_bytes(vec![]), "".to_owned())] + vec![Blob::new(&self.global(), BlobImpl::new_from_bytes(vec![]), "".to_owned())] } fn ReceiveNullableBoolean(&self) -> Option<bool> { Some(false) } @@ -308,7 +308,7 @@ impl TestBindingMethods for TestBinding { fn ReceiveNullableByteString(&self) -> Option<ByteString> { Some(ByteString::new(vec!())) } fn ReceiveNullableEnum(&self) -> Option<TestEnum> { Some(TestEnum::_empty) } fn ReceiveNullableInterface(&self) -> Option<Root<Blob>> { - Some(Blob::new(self.global().r(), 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<NonZero<*mut JSObject>> { self.GetObjectAttributeNullable(cx) @@ -655,12 +655,12 @@ impl TestBindingMethods for TestBinding { #[allow(unrooted_must_root)] fn ReturnResolvedPromise(&self, cx: *mut JSContext, v: HandleValue) -> Fallible<Rc<Promise>> { - Promise::Resolve(self.global().r(), cx, v) + Promise::Resolve(&self.global(), cx, v) } #[allow(unrooted_must_root)] fn ReturnRejectedPromise(&self, cx: *mut JSContext, v: HandleValue) -> Fallible<Rc<Promise>> { - Promise::Reject(self.global().r(), 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().r().get_cx(), Error::Type(s.0)); + p.reject_error(self.global().get_cx(), Error::Type(s.0)); } #[allow(unrooted_must_root)] @@ -682,8 +682,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() + .schedule_callback( + OneshotTimerCallback::TestBindingCallback(cb), + MsDuration::new(delay)); } #[allow(unrooted_must_root)] @@ -691,10 +693,10 @@ impl TestBindingMethods for TestBinding { resolve: Option<Rc<SimpleCallback>>, reject: Option<Rc<SimpleCallback>>) -> Rc<Promise> { let global = self.global(); - let handler = PromiseNativeHandler::new(global.r(), + 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; @@ -711,15 +713,15 @@ 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 { GlobalScope::from_context(cx) }; + let _ = self.handler.Call_(&*global, v, ExceptionHandling::Report); } } } #[allow(unrooted_must_root)] fn PromiseAttribute(&self) -> Rc<Promise> { - Promise::new(self.global().r()) + Promise::new(&self.global()) } fn AcceptPromise(&self, _promise: &Promise) { @@ -749,24 +751,24 @@ impl TestBindingMethods for TestBinding { } fn AdvanceClock(&self, ms: i32, tick: bool) { - self.global().r().as_window().advance_animation_clock(ms, tick); + self.global().as_window().advance_animation_clock(ms, tick); } fn Panic(&self) { panic!("explicit panic from script") } } 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)] @@ -786,7 +788,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().get_cx(); let _ac = JSAutoCompartment::new(cx, p.reflector().get_jsobject().get()); p.resolve_native(cx, &self.value); } diff --git a/components/script/dom/testbindingiterable.rs b/components/script/dom/testbindingiterable.rs index 2ad0df6dbb6..10045705192 100644 --- a/components/script/dom/testbindingiterable.rs +++ b/components/script/dom/testbindingiterable.rs @@ -7,10 +7,10 @@ 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; +use dom::globalscope::GlobalScope; #[dom_struct] pub struct TestBindingIterable { @@ -19,14 +19,14 @@ pub struct TestBindingIterable { } impl TestBindingIterable { - fn new(global: GlobalRef) -> Root<TestBindingIterable> { + fn new(global: &GlobalScope) -> Root<TestBindingIterable> { reflect_dom_object(box TestBindingIterable { reflector: Reflector::new(), vals: DOMRefCell::new(vec![]), }, global, TestBindingIterableBinding::Wrap) } - pub fn Constructor(global: GlobalRef) -> Fallible<Root<TestBindingIterable>> { + pub fn Constructor(global: &GlobalScope) -> Fallible<Root<TestBindingIterable>> { Ok(TestBindingIterable::new(global)) } } diff --git a/components/script/dom/testbindingpairiterable.rs b/components/script/dom/testbindingpairiterable.rs index 9bceedd4980..f536459c1e9 100644 --- a/components/script/dom/testbindingpairiterable.rs +++ b/components/script/dom/testbindingpairiterable.rs @@ -8,11 +8,11 @@ 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}; use dom::bindings::str::DOMString; +use dom::globalscope::GlobalScope; #[dom_struct] pub struct TestBindingPairIterable { @@ -35,14 +35,14 @@ impl Iterable for TestBindingPairIterable { } impl TestBindingPairIterable { - fn new(global: GlobalRef) -> Root<TestBindingPairIterable> { + fn new(global: &GlobalScope) -> Root<TestBindingPairIterable> { reflect_dom_object(box TestBindingPairIterable { reflector: Reflector::new(), map: DOMRefCell::new(vec![]), }, global, TestBindingPairIterableBinding::TestBindingPairIterableWrap) } - pub fn Constructor(global: GlobalRef) -> Fallible<Root<TestBindingPairIterable>> { + pub fn Constructor(global: &GlobalScope) -> Fallible<Root<TestBindingPairIterable>> { Ok(TestBindingPairIterable::new(global)) } } diff --git a/components/script/dom/text.rs b/components/script/dom/text.rs index 5d377e1e05d..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,7 +35,7 @@ impl Text { document, TextBinding::Wrap) } - pub fn Constructor(global: GlobalRef, text: DOMString) -> Fallible<Root<Text>> { + pub fn Constructor(global: &GlobalScope, text: DOMString) -> Fallible<Root<Text>> { 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 fae78342a73..db18d9a5be4 100644 --- a/components/script/dom/textdecoder.rs +++ b/components/script/dom/textdecoder.rs @@ -6,10 +6,10 @@ 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}; +use dom::globalscope::GlobalScope; use encoding::label::encoding_from_whatwg_label; use encoding::types::{DecoderTrap, EncodingRef}; use js::jsapi::{JSContext, JSObject}; @@ -36,14 +36,14 @@ impl TextDecoder { Err(Error::Range("The given encoding is not supported.".to_owned())) } - pub fn new(global: GlobalRef, encoding: EncodingRef, fatal: bool) -> Root<TextDecoder> { + pub fn new(global: &GlobalScope, encoding: EncodingRef, fatal: bool) -> Root<TextDecoder> { reflect_dom_object(box TextDecoder::new_inherited(encoding, fatal), global, TextDecoderBinding::Wrap) } /// https://encoding.spec.whatwg.org/#dom-textdecoder - pub fn Constructor(global: GlobalRef, + pub fn Constructor(global: &GlobalScope, label: DOMString, options: &TextDecoderBinding::TextDecoderOptions) -> Fallible<Root<TextDecoder>> { diff --git a/components/script/dom/textencoder.rs b/components/script/dom/textencoder.rs index 996e5d28e98..9c8ad647080 100644 --- a/components/script/dom/textencoder.rs +++ b/components/script/dom/textencoder.rs @@ -6,10 +6,10 @@ 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}; +use dom::globalscope::GlobalScope; use encoding::EncoderTrap; use encoding::Encoding; use encoding::all::UTF_8; @@ -30,14 +30,14 @@ impl TextEncoder { } } - pub fn new(global: GlobalRef) -> Root<TextEncoder> { + pub fn new(global: &GlobalScope) -> Root<TextEncoder> { reflect_dom_object(box TextEncoder::new_inherited(), global, TextEncoderBinding::Wrap) } // https://encoding.spec.whatwg.org/#dom-textencoder - pub fn Constructor(global: GlobalRef) -> Fallible<Root<TextEncoder>> { + pub fn Constructor(global: &GlobalScope) -> Fallible<Root<TextEncoder>> { Ok(TextEncoder::new(global)) } } 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<TouchEvent> { 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<TouchList> { 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<TreeWalker> { 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..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; @@ -37,7 +37,7 @@ impl UIEvent { pub fn new_uninitialized(window: &Window) -> Root<UIEvent> { reflect_dom_object(box UIEvent::new_inherited(), - GlobalRef::Window(window), + window, UIEventBinding::Wrap) } @@ -52,12 +52,13 @@ impl UIEvent { ev } - pub fn Constructor(global: GlobalRef, + pub fn Constructor(global: &GlobalScope, type_: DOMString, init: &UIEventBinding::UIEventInit) -> Fallible<Root<UIEvent>> { 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_window(), + type_, bubbles, cancelable, init.view.r(), init.detail); Ok(event) diff --git a/components/script/dom/url.rs b/components/script/dom/url.rs index bc686d23cc4..35dc4d896fa 100644 --- a/components/script/dom/url.rs +++ b/components/script/dom/url.rs @@ -6,11 +6,11 @@ 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}; use dom::blob::Blob; +use dom::globalscope::GlobalScope; use dom::urlhelper::UrlHelper; use dom::urlsearchparams::URLSearchParams; use ipc_channel::ipc; @@ -44,7 +44,7 @@ impl URL { } } - pub fn new(global: GlobalRef, url: Url) -> Root<URL> { + pub fn new(global: &GlobalScope, url: Url) -> Root<URL> { reflect_dom_object(box URL::new_inherited(url), global, URLBinding::Wrap) } @@ -61,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<USVString>) -> Fallible<Root<URL>> { let parsed_base = match base { @@ -97,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 { @@ -109,12 +109,12 @@ 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.get_url()); @@ -131,7 +131,7 @@ impl URL { } // https://w3c.github.io/FileAPI/#dfn-revokeObjectURL - pub fn RevokeObjectURL(global: GlobalRef, url: DOMString) { + 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 @@ -283,7 +283,9 @@ impl URLMethods for URL { // https://url.spec.whatwg.org/#dom-url-searchparams fn SearchParams(&self) -> Root<URLSearchParams> { - self.search_params.or_init(|| URLSearchParams::new(self.global().r(), Some(self))) + self.search_params.or_init(|| { + URLSearchParams::new(&self.global(), 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..2718f278dc3 100644 --- a/components/script/dom/urlsearchparams.rs +++ b/components/script/dom/urlsearchparams.rs @@ -7,11 +7,11 @@ 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}; use dom::bindings::weakref::MutableWeakRef; +use dom::globalscope::GlobalScope; use dom::url::URL; use encoding::types::EncodingRef; use url::form_urlencoded; @@ -35,13 +35,13 @@ impl URLSearchParams { } } - pub fn new(global: GlobalRef, url: Option<&URL>) -> Root<URLSearchParams> { + pub fn new(global: &GlobalScope, url: Option<&URL>) -> Root<URLSearchParams> { reflect_dom_object(box URLSearchParams::new_inherited(url), global, URLSearchParamsBinding::Wrap) } // https://url.spec.whatwg.org/#dom-urlsearchparams-urlsearchparams - pub fn Constructor(global: GlobalRef, init: Option<USVStringOrURLSearchParams>) -> + pub fn Constructor(global: &GlobalScope, init: Option<USVStringOrURLSearchParams>) -> Fallible<Root<URLSearchParams>> { // Step 1. let query = URLSearchParams::new(global, None); 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<ValidityState> { 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<WebGLActiveInfo> { + pub fn new(global: &GlobalScope, size: i32, ty: u32, name: DOMString) -> Root<WebGLActiveInfo> { 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<CanvasMsg>) + pub fn maybe_new(global: &GlobalScope, renderer: IpcSender<CanvasMsg>) -> Option<Root<WebGLBuffer>> { 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<CanvasMsg>, id: WebGLBufferId) -> Root<WebGLBuffer> { diff --git a/components/script/dom/webglcontextevent.rs b/components/script/dom/webglcontextevent.rs index 9c73a9f6b65..079218ab3ae 100644 --- a/components/script/dom/webglcontextevent.rs +++ b/components/script/dom/webglcontextevent.rs @@ -7,12 +7,12 @@ 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; use dom::bindings::str::DOMString; use dom::event::{Event, EventBubbles, EventCancelable}; +use dom::globalscope::GlobalScope; use string_cache::Atom; #[dom_struct] @@ -41,7 +41,7 @@ impl WebGLContextEvent { } } - pub fn new_uninitialized(global_ref: GlobalRef) -> Root<WebGLContextEvent> { + pub fn new_uninitialized(global_ref: &GlobalScope) -> Root<WebGLContextEvent> { // 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 +52,7 @@ impl WebGLContextEvent { WebGLContextEventBinding::Wrap) } - pub fn new(global: GlobalRef, + pub fn new(global: &GlobalScope, type_: Atom, bubbles: EventBubbles, cancelable: EventCancelable, @@ -70,7 +70,7 @@ impl WebGLContextEvent { event } - pub fn Constructor(global: GlobalRef, + pub fn Constructor(global: &GlobalScope, type_: DOMString, init: &WebGLContextEventInit) -> Fallible<Root<WebGLContextEvent>> { let status_message = match init.statusMessage.as_ref() { @@ -82,7 +82,8 @@ impl WebGLContextEvent { let cancelable = EventCancelable::from(init.parent.cancelable); - Ok(WebGLContextEvent::new(global, Atom::from(type_), + Ok(WebGLContextEvent::new(global, + 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<CanvasMsg>) + pub fn maybe_new(global: &GlobalScope, renderer: IpcSender<CanvasMsg>) -> Option<Root<WebGLFramebuffer>> { 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<CanvasMsg>, id: WebGLFramebufferId) -> Root<WebGLFramebuffer> { 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<WebGLObject> { + pub fn new(global: &GlobalScope) -> Root<WebGLObject> { 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..98139081c3b 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<CanvasMsg>) + pub fn maybe_new(global: &GlobalScope, renderer: IpcSender<CanvasMsg>) -> Option<Root<WebGLProgram>> { 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<CanvasMsg>, id: WebGLProgramId) -> Root<WebGLProgram> { @@ -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(), 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(), 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<CanvasMsg>) + pub fn maybe_new(global: &GlobalScope, renderer: IpcSender<CanvasMsg>) -> Option<Root<WebGLRenderbuffer>> { 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<CanvasMsg>, id: WebGLRenderbufferId) -> Root<WebGLRenderbuffer> { diff --git a/components/script/dom/webglrenderingcontext.rs b/components/script/dom/webglrenderingcontext.rs index b69f11146fd..312357fd3d2 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,7 +127,7 @@ pub struct WebGLRenderingContext { } impl WebGLRenderingContext { - fn new_inherited(global: GlobalRef, + fn new_inherited(global: &GlobalScope, canvas: &HTMLCanvasElement, size: Size2D<i32>, attrs: GLContextAttributes) @@ -159,11 +159,10 @@ impl WebGLRenderingContext { } #[allow(unrooted_must_root)] - pub fn new(global: GlobalRef, canvas: &HTMLCanvasElement, size: Size2D<i32>, attrs: GLContextAttributes) + pub fn new(global: &GlobalScope, canvas: &HTMLCanvasElement, size: Size2D<i32>, attrs: GLContextAttributes) -> Option<Root<WebGLRenderingContext>> { match WebGLRenderingContext::new_inherited(global, canvas, size, attrs) { - Ok(ctx) => Some(reflect_dom_object(box ctx, global, - 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, @@ -1154,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<Root<WebGLBuffer>> { - WebGLBuffer::maybe_new(self.global().r(), 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<Root<WebGLFramebuffer>> { - WebGLFramebuffer::maybe_new(self.global().r(), 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<Root<WebGLRenderbuffer>> { - WebGLRenderbuffer::maybe_new(self.global().r(), 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<Root<WebGLTexture>> { - WebGLTexture::maybe_new(self.global().r(), 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<Root<WebGLProgram>> { - WebGLProgram::maybe_new(self.global().r(), 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 @@ -1186,7 +1185,7 @@ impl WebGLRenderingContextMethods for WebGLRenderingContext { return None; } } - WebGLShader::maybe_new(self.global().r(), 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 @@ -1480,7 +1479,7 @@ impl WebGLRenderingContextMethods for WebGLRenderingContext { name: DOMString) -> Option<Root<WebGLUniformLocation>> { 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(), 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<CanvasMsg>, shader_type: u32) -> Option<Root<WebGLShader>> { 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<CanvasMsg>, 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<WebGLShaderPrecisionFormat> { 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<CanvasMsg>) + pub fn maybe_new(global: &GlobalScope, renderer: IpcSender<CanvasMsg>) -> Option<Root<WebGLTexture>> { 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<CanvasMsg>, id: WebGLTextureId) -> Root<WebGLTexture> { 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<WebGLUniformLocation> { 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/websocket.rs b/components/script/dom/websocket.rs index df9c2e5ed34..2582367ec08 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; @@ -20,6 +19,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,12 +190,12 @@ impl WebSocket { } } - fn new(global: GlobalRef, url: Url) -> Root<WebSocket> { + fn new(global: &GlobalScope, url: Url) -> Root<WebSocket> { reflect_dom_object(box WebSocket::new_inherited(url), global, WebSocketBinding::Wrap) } - pub fn Constructor(global: GlobalRef, + pub fn Constructor(global: &GlobalScope, url: DOMString, protocols: Option<StringOrStringSequence>) -> Fallible<Root<WebSocket>> { @@ -328,8 +328,10 @@ impl WebSocket { address: address, }; - let global = self.global(); - global.r().script_chan().send(CommonScriptMsg::RunnableMsg(WebSocketEvent, task)).unwrap(); + self.global() + .script_chan() + .send(CommonScriptMsg::RunnableMsg(WebSocketEvent, task)) + .unwrap(); } Ok(true) @@ -434,7 +436,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().networking_task_source(); fail_the_websocket_connection(address, sender); } WebSocketRequestState::Open => { @@ -465,11 +467,10 @@ impl Runnable for ConnectionEstablishedTask { fn handler(self: Box<Self>) { let ws = self.address.root(); - let global = ws.r().global(); // Step 1: Protocols. if !self.protocols.is_empty() && self.headers.get::<WebSocketProtocol>().is_none() { - let sender = global.r().networking_task_source(); + let sender = ws.global().networking_task_source(); fail_the_websocket_connection(self.address, sender); return; } @@ -490,9 +491,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().core_resource_thread().send( + SetCookiesForUrl(ws.url.clone(), cookie_value, HTTP)); } } } @@ -534,8 +534,6 @@ impl Runnable for CloseTask { fn handler(self: Box<Self>) { 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. @@ -557,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(global.r(), + let close_event = CloseEvent::new(&ws.global(), atom!("close"), EventBubbles::DoesNotBubble, EventCancelable::NotCancelable, @@ -588,10 +586,10 @@ impl Runnable for MessageReceivedTask { } // Step 2-5. - let global = ws.r().global(); + let global = ws.global(); // 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 { @@ -599,7 +597,7 @@ 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, BlobImpl::new_from_bytes(data), "".to_owned()); blob.to_jsval(cx, message.handle_mut()); } BinaryType::Arraybuffer => { @@ -615,7 +613,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 3ac5c4e37f9..9bb813a2946 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}; @@ -16,8 +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::global::{GlobalRef, global_root_from_object}; +use dom::bindings::error::{Error, ErrorResult, Fallible}; use dom::bindings::inheritance::Castable; use dom::bindings::js::{JS, MutNullableHeap, Root}; use dom::bindings::num::Finite; @@ -27,14 +26,12 @@ 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; 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; use dom::location::Location; @@ -73,8 +70,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; @@ -99,7 +96,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; @@ -143,7 +140,7 @@ pub type ScrollPoint = Point2D<Au>; #[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"] @@ -156,7 +153,6 @@ pub struct Window { history_traversal_task_source: HistoryTraversalTaskSource, #[ignore_heap_size_of = "task sources are hard"] file_reading_task_source: FileReadingTaskSource, - crypto: MutNullableHeap<JS<Crypto>>, navigator: MutNullableHeap<JS<Navigator>>, #[ignore_heap_size_of = "channels are hard"] image_cache_thread: ImageCacheThread, @@ -171,39 +167,16 @@ pub struct Window { session_storage: MutNullableHeap<JS<Storage>>, local_storage: MutNullableHeap<JS<Storage>>, status: DOMRefCell<DOMString>, - #[ignore_heap_size_of = "channels are hard"] - scheduler_chan: IpcSender<TimerEventRequest>, - timers: OneshotTimers, - - next_worker_id: Cell<WorkerId>, - - /// 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, - - /// For providing instructions to an optional devtools server. - #[ignore_heap_size_of = "channels are hard"] - devtools_chan: Option<IpcSender<ScriptToDevtoolsControlMsg>>, /// For sending timeline markers. Will be ignored if /// no devtools server devtools_markers: DOMRefCell<HashSet<TimelineMarkerType>>, #[ignore_heap_size_of = "channels are hard"] devtools_marker_sender: DOMRefCell<Option<IpcSender<TimelineMarker>>>, - /// A flag to indicate whether the developer tools have requested live updates of - /// page changes. - devtools_wants_updates: Cell<bool>, - /// Pending resize event, if any. resize_event: Cell<Option<(WindowSizeData, WindowSizeType)>>, - /// Pipeline id associated with this page. - id: PipelineId, - /// Parent id associated with this page, if any. parent_info: Option<(PipelineId, FrameType)>, @@ -225,18 +198,10 @@ pub struct Window { /// The current size of the window, in pixels. window_size: Cell<Option<WindowSizeData>>, - /// 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<BluetoothMethodMsg>, - /// A handle for communicating messages to the constellation thread. - #[ignore_heap_size_of = "channels are hard"] - constellation_chan: IpcSender<ConstellationMsg>, - /// Pending scroll to fragment event, if any fragment_name: DOMRefCell<Option<String>>, @@ -269,12 +234,6 @@ pub struct Window { /// A list of scroll offsets for each scrollable element. scroll_offsets: DOMRefCell<HashMap<UntrustedNodeAddress, Point2D<f32>>>, - - /// https://html.spec.whatwg.org/multipage/#in-error-reporting-mode - in_error_reporting_mode: Cell<bool>, - - /// Timers used by the Console API. - console_timers: TimerSet, } impl Window { @@ -320,17 +279,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 - } - pub fn parent_info(&self) -> Option<(PipelineId, FrameType)> { self.parent_info } @@ -464,7 +412,11 @@ impl WindowMethods for Window { } let (sender, receiver) = ipc::channel().unwrap(); - self.constellation_chan().send(ConstellationMsg::Alert(self.pipeline_id(), s.to_string(), sender)).unwrap(); + let global_scope = self.upcast::<GlobalScope>(); + global_scope + .constellation_chan() + .send(ConstellationMsg::Alert(global_scope.pipeline_id(), s.to_string(), sender)) + .unwrap(); let should_display_alert_dialog = receiver.recv().unwrap(); if should_display_alert_dialog { @@ -474,7 +426,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::<GlobalScope>().pipeline_id())) + .unwrap(); } // https://html.spec.whatwg.org/multipage/#dom-document-2 @@ -494,17 +448,17 @@ impl WindowMethods for Window { // https://html.spec.whatwg.org/multipage/#dom-sessionstorage fn SessionStorage(&self) -> Root<Storage> { - 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<Storage> { - 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<Crypto> { - self.crypto.or_init(|| Crypto::new(GlobalRef::Window(self))) + self.upcast::<GlobalScope>().crypto() } // https://html.spec.whatwg.org/multipage/#dom-frameelement @@ -519,47 +473,43 @@ impl WindowMethods for Window { // https://html.spec.whatwg.org/multipage/#dom-windowtimers-settimeout fn SetTimeout(&self, _cx: *mut JSContext, callback: Rc<Function>, timeout: i32, args: Vec<HandleValue>) -> i32 { - self.timers.set_timeout_or_interval(GlobalRef::Window(self), - TimerCallback::FunctionTimerCallback(callback), - args, - timeout, - IsInterval::NonInterval, - TimerSource::FromWindow(self.id.clone())) + self.upcast::<GlobalScope>().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<HandleValue>) -> i32 { - self.timers.set_timeout_or_interval(GlobalRef::Window(self), - TimerCallback::StringTimerCallback(callback), - args, - timeout, - IsInterval::NonInterval, - TimerSource::FromWindow(self.id.clone())) + self.upcast::<GlobalScope>().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::<GlobalScope>().clear_timeout_or_interval(handle); } // https://html.spec.whatwg.org/multipage/#dom-windowtimers-setinterval fn SetInterval(&self, _cx: *mut JSContext, callback: Rc<Function>, timeout: i32, args: Vec<HandleValue>) -> i32 { - self.timers.set_timeout_or_interval(GlobalRef::Window(self), - TimerCallback::FunctionTimerCallback(callback), - args, - timeout, - IsInterval::Interval, - TimerSource::FromWindow(self.id.clone())) + self.upcast::<GlobalScope>().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<HandleValue>) -> i32 { - self.timers.set_timeout_or_interval(GlobalRef::Window(self), - TimerCallback::StringTimerCallback(callback), - args, - timeout, - IsInterval::Interval, - TimerSource::FromWindow(self.id.clone())) + self.upcast::<GlobalScope>().set_timeout_or_interval( + TimerCallback::StringTimerCallback(callback), + args, + timeout, + IsInterval::Interval) } // https://html.spec.whatwg.org/multipage/#dom-windowtimers-clearinterval @@ -825,7 +775,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::<GlobalScope>() + .constellation_chan() + .send(ConstellationMsg::ResizeTo(size)) + .unwrap() } // https://drafts.csswg.org/cssom-view/#dom-window-resizeby @@ -840,7 +793,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::<GlobalScope>() + .constellation_chan() + .send(ConstellationMsg::MoveTo(point)) + .unwrap() } // https://drafts.csswg.org/cssom-view/#dom-window-moveby @@ -904,14 +860,14 @@ impl WindowMethods for Window { #[allow(unrooted_must_root)] // https://fetch.spec.whatwg.org/#fetch-method fn Fetch(&self, input: RequestOrUSVString, init: &RequestInit) -> Rc<Promise> { - fetch::Fetch(self.global().r(), input, init) + fetch::Fetch(&self.upcast(), input, init) } } 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()), } } @@ -1001,8 +957,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.constellation_chan.send(message).unwrap(); + let global_scope = self.upcast::<GlobalScope>(); + 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) { @@ -1013,7 +971,10 @@ impl Window { pub fn client_window(&self) -> (Size2D<u32>, Point2D<i32>) { let (send, recv) = ipc::channel::<(Size2D<u32>, Point2D<i32>)>().unwrap(); - self.constellation_chan.send(ConstellationMsg::GetClientWindow(send)).unwrap(); + self.upcast::<GlobalScope>() + .constellation_chan() + .send(ConstellationMsg::GetClientWindow(send)) + .unwrap(); recv.recv().unwrap_or((Size2D::zero(), Point2D::zero())) } @@ -1054,7 +1015,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::<GlobalScope>().pipeline_id(), goal, reason); return false; } @@ -1071,7 +1032,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::<GlobalScope>().pipeline_id(), &goal, &query_type, &reason); } let document = self.Document(); @@ -1176,8 +1137,9 @@ impl Window { let ready_state = document.ReadyState(); if ready_state == DocumentReadyState::Complete && !reftest_wait { - let event = ConstellationMsg::SetDocumentState(self.id, DocumentState::Idle); - self.constellation_chan().send(event).unwrap(); + let global_scope = self.upcast::<GlobalScope>(); + let event = ConstellationMsg::SetDocumentState(global_scope.pipeline_id(), DocumentState::Idle); + global_scope.constellation_chan().send(event).unwrap(); } } @@ -1286,10 +1248,13 @@ impl Window { } let layer_id = self.layout_rpc.node_layer_id().layer_id; - let pipeline_id = self.id; let (send, recv) = ipc::channel::<Point2D<f32>>().unwrap(); - self.constellation_chan.send(ConstellationMsg::GetScrollOffset(pipeline_id, layer_id, send)).unwrap(); + let global_scope = self.upcast::<GlobalScope>(); + global_scope + .constellation_chan() + .send(ConstellationMsg::GetScrollOffset(global_scope.pipeline_id(), layer_id, send)) + .unwrap(); recv.recv().unwrap_or(Point2D::zero()) } @@ -1364,13 +1329,13 @@ 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::<GlobalScope>().pipeline_id(), LoadData::new(url, referrer_policy, Some(doc.url().clone())), replace)).unwrap(); } pub fn handle_fire_timer(&self, timer_id: TimerEventId) { - self.timers.fire_timer(timer_id, self); + self.upcast::<GlobalScope>().fire_timer(timer_id); self.reflow(ReflowGoal::ForDisplay, ReflowQueryType::NoQuery, ReflowReason::Timer); @@ -1396,44 +1361,10 @@ impl Window { (*self.Document().url()).clone() } - pub fn resource_threads(&self) -> &ResourceThreads { - &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 - } - - pub fn devtools_chan(&self) -> Option<IpcSender<ScriptToDevtoolsControlMsg>> { - self.devtools_chan.clone() - } - pub fn layout_chan(&self) -> &Sender<Msg> { &self.layout_chan } - pub fn constellation_chan(&self) -> &IpcSender<ConstellationMsg> { - &self.constellation_chan - } - - pub fn scheduler_chan(&self) -> &IpcSender<TimerEventRequest> { - &self.scheduler_chan - } - - pub fn schedule_callback(&self, callback: OneshotTimerCallback, duration: MsDuration) -> OneshotTimerHandle { - self.timers.schedule_callback(callback, - duration, - TimerSource::FromWindow(self.id.clone())) - } - - 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) } @@ -1483,35 +1414,19 @@ 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<Root<Window>> { None } pub fn thaw(&self) { - self.timers.resume(); + self.upcast::<GlobalScope>().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) @@ -1580,10 +1495,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, - } + GlobalScope::from_object(obj.get()) + .downcast::<Window>() + .map_or(false, |window| window.is_mozbrowser()) } #[allow(unsafe_code)] @@ -1629,7 +1543,16 @@ impl Window { }; let current_time = time::get_time(); let win = box Window { - eventtarget: EventTarget::new_inherited(), + globalscope: + GlobalScope::new_inherited( + id, + devtools_chan, + mem_profiler_chan, + time_profiler_chan, + constellation_chan, + 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, @@ -1637,12 +1560,8 @@ 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, - time_profiler_chan: time_profiler_chan, - devtools_chan: devtools_chan, history: Default::default(), browsing_context: Default::default(), performance: Default::default(), @@ -1652,16 +1571,10 @@ 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), - next_worker_id: Cell::new(WorkerId(0)), - id: id, parent_info: parent_info, dom_static: GlobalStaticData::new(), 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), @@ -1675,54 +1588,14 @@ 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, 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 - } - - 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. - 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(GlobalRef::Window(self), - 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::<Event>().fire(self.upcast::<EventTarget>()); - - // Step 14. - self.in_error_reporting_mode.set(false); - } } fn should_move_clip_rect(clip_rect: Rect<Au>, new_viewport: Rect<f32>) -> bool { @@ -1826,12 +1699,12 @@ 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. 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 fb6b170ab1d..42ba8bb8e08 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; @@ -21,6 +20,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 +61,7 @@ impl Worker { } } - pub fn new(global: GlobalRef, + pub fn new(global: &GlobalScope, sender: Sender<(TrustedWorkerAddress, WorkerScriptMsg)>, closing: Arc<AtomicBool>) -> Root<Worker> { reflect_dom_object(box Worker::new_inherited(sender, closing), @@ -71,7 +71,7 @@ impl Worker { // https://html.spec.whatwg.org/multipage/#dom-worker #[allow(unsafe_code)] - pub fn Constructor(global: GlobalRef, script_url: DOMString) -> Fallible<Root<Worker>> { + pub fn Constructor(global: &GlobalScope, script_url: DOMString) -> Fallible<Root<Worker>> { // Step 2-4. let worker_url = match global.api_base_url().join(&script_url) { Ok(url) => url, @@ -128,12 +128,12 @@ impl Worker { return; } - let global = worker.r().global(); + let global = worker.global(); 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()); - 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) { @@ -144,7 +144,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, atom!("error"), EventBubbles::DoesNotBubble, EventCancelable::Cancelable, @@ -159,7 +159,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 9b976c5a31d..8cd09b3fdbe 100644 --- a/components/script/dom/workerglobalscope.rs +++ b/components/script/dom/workerglobalscope.rs @@ -2,26 +2,21 @@ * 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; 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::global::{GlobalRef, GlobalRoot}; +use dom::bindings::error::{Error, ErrorResult, Fallible, report_pending_exception}; use dom::bindings::inheritance::Castable; 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; -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}; @@ -34,15 +29,12 @@ 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 profile_traits::{mem, time}; +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, TimerEventRequest, TimerSource}; -use script_traits::ScriptMsg as ConstellationMsg; +use script_traits::{TimerEvent, TimerEventId}; use script_traits::WorkerGlobalScopeInit; -use std::cell::Cell; use std::default::Default; use std::panic; use std::rc::Rc; @@ -50,26 +42,20 @@ 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; -#[derive(Copy, Clone, PartialEq)] -pub enum WorkerGlobalScopeTypeId { - DedicatedWorkerGlobalScope, -} - -pub fn prepare_workerscope_init(global: GlobalRef, +pub fn prepare_workerscope_init(global: &GlobalScope, devtools_sender: Option<IpcSender<DevtoolScriptControlMsg>>) -> WorkerGlobalScopeInit { - let worker_id = global.get_next_worker_id(); let init = WorkerGlobalScopeInit { - resource_threads: global.resource_threads(), + resource_threads: global.resource_threads().clone(), mem_profiler_chan: global.mem_profiler_chan().clone(), - to_devtools_sender: global.devtools_chan(), + to_devtools_sender: global.devtools_chan().cloned(), time_profiler_chan: global.time_profiler_chan().clone(), from_devtools_sender: devtools_sender, constellation_chan: global.constellation_chan().clone(), scheduler_chan: global.scheduler_chan().clone(), - worker_id: worker_id, + worker_id: global.get_next_worker_id(), pipeline_id: global.pipeline_id(), }; @@ -79,28 +65,16 @@ 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, #[ignore_heap_size_of = "Arc"] closing: Option<Arc<AtomicBool>>, #[ignore_heap_size_of = "Defined in js"] runtime: Runtime, - next_worker_id: Cell<WorkerId>, - #[ignore_heap_size_of = "Defined in std"] - resource_threads: ResourceThreads, location: MutNullableHeap<JS<WorkerLocation>>, navigator: MutNullableHeap<JS<WorkerNavigator>>, - crypto: MutNullableHeap<JS<Crypto>>, - 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, - #[ignore_heap_size_of = "Defined in ipc-channel"] - to_devtools_sender: Option<IpcSender<ScriptToDevtoolsControlMsg>>, #[ignore_heap_size_of = "Defined in ipc-channel"] /// Optional `IpcSender` for sending the `DevtoolScriptControlMsg` @@ -112,23 +86,7 @@ pub struct WorkerGlobalScope { /// `IpcSender` doesn't exist from_devtools_receiver: Receiver<DevtoolScriptControlMsg>, - /// A flag to indicate whether the developer tools has requested live updates - /// from the worker - devtools_wants_updates: Cell<bool>, - - #[ignore_heap_size_of = "Defined in std"] - constellation_chan: IpcSender<ConstellationMsg>, - - #[ignore_heap_size_of = "Defined in std"] - scheduler_chan: IpcSender<TimerEventRequest>, - - /// Timers used by the Console API. - console_timers: TimerSet, - promise_job_queue: PromiseJobQueue, - - /// https://html.spec.whatwg.org/multipage/#in-error-reporting-mode - in_error_reporting_mode: Cell<bool> } impl WorkerGlobalScope { @@ -140,48 +98,28 @@ impl WorkerGlobalScope { closing: Option<Arc<AtomicBool>>) -> WorkerGlobalScope { WorkerGlobalScope { - eventtarget: EventTarget::new_inherited(), - next_worker_id: Cell::new(WorkerId(0)), + 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, + init.resource_threads, + timer_event_chan), worker_id: init.worker_id, - pipeline_id: init.pipeline_id, worker_url: worker_url, closing: closing, runtime: runtime, - 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, - 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(), 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 - } - - pub fn time_profiler_chan(&self) -> &time::ProfilerChan { - &self.time_profiler_chan - } - - pub fn devtools_chan(&self) -> Option<IpcSender<ScriptToDevtoolsControlMsg>> { - self.to_devtools_sender.clone() - } - pub fn from_devtools_sender(&self) -> Option<IpcSender<DevtoolScriptControlMsg>> { self.from_devtools_sender.clone() } @@ -190,24 +128,6 @@ impl WorkerGlobalScope { &self.from_devtools_receiver } - pub fn constellation_chan(&self) -> &IpcSender<ConstellationMsg> { - &self.constellation_chan - } - - pub fn scheduler_chan(&self) -> &IpcSender<TimerEventRequest> { - &self.scheduler_chan - } - - 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() } @@ -224,10 +144,6 @@ impl WorkerGlobalScope { } } - pub fn resource_threads(&self) -> &ResourceThreads { - &self.resource_threads - } - pub fn get_url(&self) -> &Url { &self.worker_url } @@ -236,21 +152,14 @@ 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(), + cancelled: self.closing.clone(), } } 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) { @@ -263,8 +172,9 @@ impl WorkerGlobalScope { fn do_flush_promise_jobs(&self) { self.promise_job_queue.flush_promise_jobs(|id| { - assert_eq!(self.pipeline_id(), id); - Some(GlobalRoot::Worker(Root::from_ref(self))) + let global = self.upcast::<GlobalScope>(); + assert_eq!(global.pipeline_id(), id); + Some(Root::from_ref(global)) }); } } @@ -277,7 +187,7 @@ impl LoadOrigin for WorkerGlobalScope { None } fn pipeline_id(&self) -> Option<PipelineId> { - Some(self.pipeline_id()) + Some(self.upcast::<GlobalScope>().pipeline_id()) } } @@ -310,8 +220,9 @@ impl WorkerGlobalScopeMethods for WorkerGlobalScope { rooted!(in(self.runtime.cx()) let mut rval = UndefinedValue()); for url in urls { + let global_scope = self.upcast::<GlobalScope>(); 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), @@ -346,7 +257,7 @@ impl WorkerGlobalScopeMethods for WorkerGlobalScope { // https://html.spec.whatwg.org/multipage/#dfn-Crypto fn Crypto(&self) -> Root<Crypto> { - self.crypto.or_init(|| Crypto::new(GlobalRef::Worker(self))) + self.upcast::<GlobalScope>().crypto() } // https://html.spec.whatwg.org/multipage/#dom-windowbase64-btoa @@ -359,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<Function>, timeout: i32, args: Vec<HandleValue>) -> i32 { - self.timers.set_timeout_or_interval(GlobalRef::Worker(self), - TimerCallback::FunctionTimerCallback(callback), - args, - timeout, - IsInterval::NonInterval, - TimerSource::FromWorker) + self.upcast::<GlobalScope>().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<HandleValue>) -> i32 { - self.timers.set_timeout_or_interval(GlobalRef::Worker(self), - TimerCallback::StringTimerCallback(callback), - args, - timeout, - IsInterval::NonInterval, - TimerSource::FromWorker) + self.upcast::<GlobalScope>().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::<GlobalScope>().clear_timeout_or_interval(handle); } // https://html.spec.whatwg.org/multipage/#dom-windowtimers-setinterval fn SetInterval(&self, _cx: *mut JSContext, callback: Rc<Function>, timeout: i32, args: Vec<HandleValue>) -> i32 { - self.timers.set_timeout_or_interval(GlobalRef::Worker(self), - TimerCallback::FunctionTimerCallback(callback), - args, - timeout, - IsInterval::Interval, - TimerSource::FromWorker) + self.upcast::<GlobalScope>().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<HandleValue>) -> i32 { - self.timers.set_timeout_or_interval(GlobalRef::Worker(self), - TimerCallback::StringTimerCallback(callback), - args, - timeout, - IsInterval::Interval, - TimerSource::FromWorker) + self.upcast::<GlobalScope>().set_timeout_or_interval( + TimerCallback::StringTimerCallback(callback), + args, + timeout, + IsInterval::Interval) } // https://html.spec.whatwg.org/multipage/#dom-windowtimers-clearinterval @@ -412,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<Promise> { - fetch::Fetch(self.global().r(), input, init) + fetch::Fetch(self.upcast(), input, init) } } @@ -457,10 +364,6 @@ impl WorkerGlobalScope { FileReadingTaskSource(self.script_chan()) } - pub fn pipeline_id(&self) -> PipelineId { - self.pipeline_id - } - pub fn new_script_pair(&self) -> (Box<ScriptChan + Send>, Box<ScriptPort + Send>) { let dedicated = self.downcast::<DedicatedWorkerGlobalScope>(); if let Some(dedicated) = dedicated { @@ -483,11 +386,7 @@ impl WorkerGlobalScope { } pub fn handle_fire_timer(&self, timer_id: TimerEventId) { - self.timers.fire_timer(timer_id, self); - } - - pub fn set_devtools_wants_updates(&self, value: bool) { - self.devtools_wants_updates.set(value); + self.upcast::<GlobalScope>().fire_timer(timer_id); } pub fn close(&self) { @@ -495,42 +394,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(GlobalRef::Worker(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::<Event>().fire(self.upcast::<EventTarget>()); - - // Step 15 - if event_status == EventStatus::NotCanceled { - if let Some(dedicated) = self.downcast::<DedicatedWorkerGlobalScope>() { - dedicated.forward_error_to_worker_object(error_info); - } - } - - // Step 14 - self.in_error_reporting_mode.set(false); - } } struct FlushPromiseJobs { 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<WorkerLocation> { 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<WorkerNavigator> { 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::<Node>(); diff --git a/components/script/dom/xmlhttprequest.rs b/components/script/dom/xmlhttprequest.rs index caebbddd09e..cd2cd37c476 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, GlobalRoot}; use dom::bindings::inheritance::Castable; use dom::bindings::js::{JS, MutHeapJSVal, MutNullableHeap}; use dom::bindings::js::{Root, RootedReference}; @@ -25,9 +24,12 @@ 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::workerglobalscope::WorkerGlobalScope; 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::<Window>() { let document = window.Document(); (Some(document.url().clone()), document.get_referrer_policy()) } else { @@ -196,22 +198,19 @@ impl XMLHttpRequest { referrer_policy: referrer_policy, } } - pub fn new(global: GlobalRef) -> Root<XMLHttpRequest> { + pub fn new(global: &GlobalScope) -> Root<XMLHttpRequest> { reflect_dom_object(box XMLHttpRequest::new_inherited(global), global, XMLHttpRequestBinding::Wrap) } // https://xhr.spec.whatwg.org/#constructors - pub fn Constructor(global: GlobalRef) -> Fallible<Root<XMLHttpRequest>> { + pub fn Constructor(global: &GlobalScope) -> Fallible<Root<XMLHttpRequest>> { Ok(XMLHttpRequest::new(global)) } fn sync_in_window(&self) -> bool { - match self.global() { - GlobalRoot::Window(_) if self.sync.get() => true, - _ => false - } + self.sync.get() && self.global().is::<Window>() } fn initiate_async_xhr(context: Arc<Mutex<XHRContext>>, @@ -283,8 +282,7 @@ impl LoadOrigin for XMLHttpRequest { } fn pipeline_id(&self) -> Option<PipelineId> { - let global = self.global(); - Some(global.r().pipeline_id()) + Some(self.global().pipeline_id()) } } @@ -307,11 +305,10 @@ impl XMLHttpRequestMethods for XMLHttpRequest { fn Open_(&self, method: ByteString, url: USVString, async: bool, username: Option<USVString>, password: Option<USVString>) -> 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::<Window>(self.global()) { + if !window.Document().r().is_fully_active() { + return Err(Error::InvalidState); } - _ => {} } // Step 5 @@ -342,7 +339,7 @@ impl XMLHttpRequestMethods for XMLHttpRequest { } // Step 2 - let base = self.global().r().api_base_url(); + let base = self.global().api_base_url(); // Step 6 let mut parsed_url = match base.join(&url.0) { Ok(parsed) => parsed, @@ -574,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 GlobalRoot::Window(win) = self.global() { + if let Some(win) = Root::downcast::<Window>(self.global()) { let is_root_pipeline = win.parent_info().is_none(); is_root_pipeline && PREFS.is_mozbrowser_enabled() } else { @@ -597,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().r().get_url(), + origin: self.global().get_url(), referrer_url: self.referrer_url.clone(), referrer_policy: self.referrer_policy.clone(), pipeline_id: self.pipeline_id(), @@ -652,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()); // Step 10 if self.sync.get() { return rv; @@ -743,9 +740,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().is::<WorkerGlobalScope>() && response_type == XMLHttpRequestResponseType::Document { + return Ok(()); } match self.ready_state.get() { // Step 2 @@ -828,7 +824,7 @@ impl XMLHttpRequestMethods for XMLHttpRequest { fn GetResponseXML(&self) -> Fallible<Option<Root<Document>>> { // 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().is::<WorkerGlobalScope>() { return Ok(None); } @@ -859,8 +855,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(), + let event = Event::new(&self.global(), atom!("readystatechange"), EventBubbles::DoesNotBubble, EventCancelable::Cancelable); @@ -975,9 +970,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(), + &self.global(), atom!("readystatechange"), EventBubbles::DoesNotBubble, EventCancelable::Cancelable); @@ -1049,8 +1043,7 @@ impl XMLHttpRequest { } fn dispatch_progress_event(&self, upload: bool, type_: Atom, loaded: u64, total: Option<u64>) { - let global = self.global(); - let progressevent = ProgressEvent::new(global.r(), + let progressevent = ProgressEvent::new(&self.global(), type_, EventBubbles::DoesNotBubble, EventCancelable::NotCancelable, @@ -1083,15 +1076,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().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().unschedule_callback(handle); } } @@ -1118,7 +1110,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(), BlobImpl::new_from_bytes(bytes), mime); self.response_blob.set(Some(blob.r())); blob } @@ -1204,18 +1196,19 @@ impl XMLHttpRequest { fn document_text_html(&self) -> Root<Document>{ let charset = self.final_charset().unwrap_or(UTF_8); let wr = self.global(); - let wr = wr.r(); 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.pipeline_id()))); document } fn handle_xml(&self) -> Root<Document> { let charset = self.final_charset().unwrap_or(UTF_8); let wr = self.global(); - let wr = wr.r(); let decoded = charset.decode(&self.response.borrow(), DecoderTrap::Replace).unwrap(); let document = self.new_doc(IsHTMLDocument::NonHTMLDocument); // TODO: Disable scripting while parsing @@ -1228,12 +1221,11 @@ impl XMLHttpRequest { fn new_doc(&self, is_html_document: IsHTMLDocument) -> Root<Document> { let wr = self.global(); - let wr = wr.r(); let win = wr.as_window(); let doc = win.Document(); let doc = doc.r(); let docloader = DocumentLoader::new(&*doc.loader()); - let base = self.global().r().get_url(); + let base = wr.get_url(); let parsed_url = match base.join(&self.ResponseURL().0) { Ok(parsed) => Some(parsed), Err(_) => None // Step 7 @@ -1292,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 { 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<XMLHttpRequestUpload> { + pub fn new(global: &GlobalScope) -> Root<XMLHttpRequestUpload> { reflect_dom_object(box XMLHttpRequestUpload::new_inherited(), global, XMLHttpRequestUploadBinding::Wrap) diff --git a/components/script/fetch.rs b/components/script/fetch.rs index 634439c7c7d..6db6c5e4202 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,7 +66,7 @@ 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<Promise> { +pub fn Fetch(global: &GlobalScope, input: RequestOrUSVString, init: &RequestInit) -> Rc<Promise> { let core_resource_thread = global.core_resource_thread(); // Step 1 @@ -76,7 +76,7 @@ pub fn Fetch(global: GlobalRef, input: RequestOrUSVString, init: &RequestInit) - // Step 2 let request = match Request::Constructor(global, input, init) { Err(e) => { - promise.reject_error(promise.global().r().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().r().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().r().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/script_runtime.rs b/components/script/script_runtime.rs index 658ace4c46a..603e24a1468 100644 --- a/components/script/script_runtime.rs +++ b/components/script/script_runtime.rs @@ -8,11 +8,11 @@ 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::js::{RootCollection, RootCollectionPtr, trace_roots}; +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; +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,7 +138,7 @@ 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); @@ -149,7 +149,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<F>(&self, target_provider: F) - where F: Fn(PipelineId) -> Option<GlobalRoot> + where F: Fn(PipelineId) -> Option<Root<GlobalScope>> { self.pending_promise_job_runnable.set(false); { @@ -161,7 +161,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(); @@ -177,9 +177,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().pipeline_id(); - global.r().enqueue_promise_job(EnqueuedPromiseCallback { + let global = GlobalScope::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 61ecacda815..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::{GlobalRef, GlobalRoot}; use dom::bindings::inheritance::Castable; use dom::bindings::js::{JS, MutNullableHeap, Root, RootCollection}; use dom::bindings::js::{RootCollectionPtr, RootedReference}; @@ -40,6 +39,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; @@ -169,7 +169,7 @@ impl InProgressLoad { /// Encapsulated state required to create cancellable runnables from non-script threads. pub struct RunnableWrapper { - pub cancelled: Arc<AtomicBool>, + pub cancelled: Option<Arc<AtomicBool>>, } impl RunnableWrapper { @@ -183,7 +183,7 @@ impl RunnableWrapper { /// A runnable that can be discarded by toggling a shared flag. pub struct CancellableRunnable<T: Runnable + Send> { - cancelled: Arc<AtomicBool>, + cancelled: Option<Arc<AtomicBool>>, inner: Box<T>, } @@ -191,7 +191,9 @@ impl<T: Runnable + Send> Runnable for CancellableRunnable<T> { 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<CancellableRunnable<T>>, script_thread: &ScriptThread) { @@ -649,7 +651,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::<GlobalScope>().pipeline_id(), size)), None => () } } @@ -984,8 +986,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), @@ -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), @@ -1191,7 +1191,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); @@ -1245,9 +1245,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::<GlobalScope>().speed_up_timers(); } else { - window.slow_down_timers(); + window.upcast::<GlobalScope>().slow_down_timers(); } return true; } @@ -1292,7 +1292,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::<GlobalScope>().suspend(); return; } } @@ -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); @@ -1501,7 +1500,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::<GlobalScope>().pipeline_id() == id { debug!("shutting down layout for root context {:?}", id); shut_down_layout(&context); let _ = self.constellation_chan.send(ConstellationMsg::PipelineExited(id)); @@ -1768,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::<GlobalScope>().evaluate_js_on_global_with_result( &script_source, jsval.handle_mut()); let strval = DOMString::from_jsval(self.get_cx(), jsval.handle(), @@ -1807,7 +1806,7 @@ impl ScriptThread { } if incomplete.is_frozen { - window.freeze(); + window.upcast::<GlobalScope>().suspend(); } if !incomplete.is_visible { @@ -2153,7 +2152,7 @@ impl ScriptThread { }; let window = context.active_window(); - if window.live_devtools_updates() { + if window.upcast::<GlobalScope>().live_devtools_updates() { let css_error = CSSError { filename: filename, line: line, @@ -2173,23 +2172,26 @@ 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); }); } - 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); + let _ = script_thread.dom_manipulation_task_source.queue( + box FlushPromiseJobs, global); }) } 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()) + }) }); } } 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 cb607c57acb..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<T: Runnable + Send + 'static>(&self, msg: Box<T>, global: GlobalRef) -> Result<(), ()> { + fn queue<T: Runnable + Send + 'static>(&self, msg: Box<T>, 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()); } } diff --git a/components/script/timers.rs b/components/script/timers.rs index 601755c6fc4..34ac02b6589 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<T: Reflectable>(&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<HandleValue>, 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<HandleValue>, 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(); @@ -490,10 +490,10 @@ impl JsTimerTask { match *&self.callback { InternalTimerCallback::StringTimerCallback(ref code_str) => { let global = this.global(); - let cx = global.r().get_cx(); + 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) => { @@ -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(), self); } } } diff --git a/components/script/webdriver_handlers.rs b/components/script/webdriver_handlers.rs index 03281464765..bcb0186d8e6 100644 --- a/components/script/webdriver_handlers.rs +++ b/components/script/webdriver_handlers.rs @@ -13,12 +13,12 @@ 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; use dom::browsingcontext::BrowsingContext; use dom::element::Element; +use dom::globalscope::GlobalScope; use dom::htmlelement::HTMLElement; use dom::htmliframeelement::HTMLIFrameElement; use dom::htmlinputelement::HTMLInputElement; @@ -92,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::<GlobalScope>().evaluate_js_on_global_with_result( &eval, rval.handle_mut()); jsval_to_webdriver(cx, rval.handle()) }; @@ -112,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::<GlobalScope>().evaluate_js_on_global_with_result( &eval, rval.handle_mut()); } @@ -142,7 +142,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::<GlobalScope>().pipeline_id())); reply.send(frame_id).unwrap() } @@ -208,7 +208,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::<GlobalScope>().resource_threads().send( GetCookiesDataForUrl(url.clone(), sender, NonHTTP) ); let cookies = receiver.recv().unwrap(); @@ -223,7 +223,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::<GlobalScope>().resource_threads().send( GetCookiesDataForUrl(url.clone(), sender, NonHTTP) ); let cookies = receiver.recv().unwrap(); @@ -245,13 +245,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::<GlobalScope>().resource_threads().send( SetCookiesForUrlWithData(url.clone(), cookie, method) ); Ok(()) }, (false, None) => { - let _ = document.window().resource_threads().send( + let _ = document.window().upcast::<GlobalScope>().resource_threads().send( SetCookiesForUrlWithData(url.clone(), cookie, method) ); Ok(()) |