Auto merge of #18635 - servo:RENAME-ALL-THE-THINGS, r=emilio

Rename JS<T> to Dom<T>, Root<T> to DomRoot<T>, and other things

<!-- 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/18635)
<!-- Reviewable:end -->
This commit is contained in:
bors-servo 2017-09-26 03:20:05 -05:00 committed by GitHub
commit 1282e0d808
308 changed files with 2886 additions and 2895 deletions

View file

@ -12,7 +12,7 @@
//! //!
//! 1. Layout is not allowed to mutate the DOM. //! 1. Layout is not allowed to mutate the DOM.
//! //!
//! 2. Layout is not allowed to see anything with `LayoutJS` in the name, because it could hang //! 2. Layout is not allowed to see anything with `LayoutDom` in the name, because it could hang
//! onto these objects and cause use-after-free. //! onto these objects and cause use-after-free.
//! //!
//! When implementing wrapper functions, be careful that you do not touch the borrow flags, or you //! When implementing wrapper functions, be careful that you do not touch the borrow flags, or you

View file

@ -12,7 +12,7 @@
//! //!
//! 1. Layout is not allowed to mutate the DOM. //! 1. Layout is not allowed to mutate the DOM.
//! //!
//! 2. Layout is not allowed to see anything with `LayoutJS` in the name, because it could hang //! 2. Layout is not allowed to see anything with `LayoutDom` in the name, because it could hang
//! onto these objects and cause use-after-free. //! onto these objects and cause use-after-free.
//! //!
//! When implementing wrapper functions, be careful that you do not touch the borrow flags, or you //! When implementing wrapper functions, be careful that you do not touch the borrow flags, or you
@ -44,7 +44,7 @@ use script::layout_exports::{Document, Element, Node, Text};
use script::layout_exports::{HANDLED_SNAPSHOT, HAS_SNAPSHOT}; use script::layout_exports::{HANDLED_SNAPSHOT, HAS_SNAPSHOT};
use script::layout_exports::{LayoutCharacterDataHelpers, LayoutDocumentHelpers}; use script::layout_exports::{LayoutCharacterDataHelpers, LayoutDocumentHelpers};
use script::layout_exports::{LayoutElementHelpers, LayoutNodeHelpers, RawLayoutElementHelpers}; use script::layout_exports::{LayoutElementHelpers, LayoutNodeHelpers, RawLayoutElementHelpers};
use script::layout_exports::LayoutJS; use script::layout_exports::LayoutDom;
use script::layout_exports::PendingRestyle; use script::layout_exports::PendingRestyle;
use script_layout_interface::{HTMLCanvasData, LayoutNodeType, SVGSVGData, TrustedNodeAddress}; use script_layout_interface::{HTMLCanvasData, LayoutNodeType, SVGSVGData, TrustedNodeAddress};
use script_layout_interface::{OpaqueStyleAndLayoutData, StyleData}; use script_layout_interface::{OpaqueStyleAndLayoutData, StyleData};
@ -87,7 +87,7 @@ pub unsafe fn drop_style_and_layout_data(data: OpaqueStyleAndLayoutData) {
#[derive(Clone, Copy)] #[derive(Clone, Copy)]
pub struct ServoLayoutNode<'a> { pub struct ServoLayoutNode<'a> {
/// The wrapped node. /// The wrapped node.
node: LayoutJS<Node>, node: LayoutDom<Node>,
/// Being chained to a PhantomData prevents `LayoutNode`s from escaping. /// Being chained to a PhantomData prevents `LayoutNode`s from escaping.
chain: PhantomData<&'a ()>, chain: PhantomData<&'a ()>,
@ -115,7 +115,7 @@ impl<'a> PartialEq for ServoLayoutNode<'a> {
} }
impl<'ln> ServoLayoutNode<'ln> { impl<'ln> ServoLayoutNode<'ln> {
fn from_layout_js(n: LayoutJS<Node>) -> ServoLayoutNode<'ln> { fn from_layout_js(n: LayoutDom<Node>) -> ServoLayoutNode<'ln> {
ServoLayoutNode { ServoLayoutNode {
node: n, node: n,
chain: PhantomData, chain: PhantomData,
@ -123,11 +123,11 @@ impl<'ln> ServoLayoutNode<'ln> {
} }
pub unsafe fn new(address: &TrustedNodeAddress) -> ServoLayoutNode { pub unsafe fn new(address: &TrustedNodeAddress) -> ServoLayoutNode {
ServoLayoutNode::from_layout_js(LayoutJS::from_trusted_node_address(*address)) ServoLayoutNode::from_layout_js(LayoutDom::from_trusted_node_address(*address))
} }
/// Creates a new layout node with the same lifetime as this layout node. /// Creates a new layout node with the same lifetime as this layout node.
pub unsafe fn new_with_this_lifetime(&self, node: &LayoutJS<Node>) -> ServoLayoutNode<'ln> { pub unsafe fn new_with_this_lifetime(&self, node: &LayoutDom<Node>) -> ServoLayoutNode<'ln> {
ServoLayoutNode { ServoLayoutNode {
node: *node, node: *node,
chain: self.chain, chain: self.chain,
@ -301,9 +301,9 @@ impl<'le> GetLayoutData for ServoThreadSafeLayoutElement<'le> {
} }
impl<'ln> ServoLayoutNode<'ln> { impl<'ln> ServoLayoutNode<'ln> {
/// Returns the interior of this node as a `LayoutJS`. This is highly unsafe for layout to /// Returns the interior of this node as a `LayoutDom`. This is highly unsafe for layout to
/// call and as such is marked `unsafe`. /// call and as such is marked `unsafe`.
pub unsafe fn get_jsmanaged(&self) -> &LayoutJS<Node> { pub unsafe fn get_jsmanaged(&self) -> &LayoutDom<Node> {
&self.node &self.node
} }
} }
@ -311,7 +311,7 @@ impl<'ln> ServoLayoutNode<'ln> {
// A wrapper around documents that ensures ayout can only ever access safe properties. // A wrapper around documents that ensures ayout can only ever access safe properties.
#[derive(Clone, Copy)] #[derive(Clone, Copy)]
pub struct ServoLayoutDocument<'ld> { pub struct ServoLayoutDocument<'ld> {
document: LayoutJS<Document>, document: LayoutDom<Document>,
chain: PhantomData<&'ld ()>, chain: PhantomData<&'ld ()>,
} }
@ -341,7 +341,7 @@ impl<'ld> ServoLayoutDocument<'ld> {
unsafe { self.document.style_shared_lock() } unsafe { self.document.style_shared_lock() }
} }
pub fn from_layout_js(doc: LayoutJS<Document>) -> ServoLayoutDocument<'ld> { pub fn from_layout_js(doc: LayoutDom<Document>) -> ServoLayoutDocument<'ld> {
ServoLayoutDocument { ServoLayoutDocument {
document: doc, document: doc,
chain: PhantomData, chain: PhantomData,
@ -352,7 +352,7 @@ impl<'ld> ServoLayoutDocument<'ld> {
/// A wrapper around elements that ensures layout can only ever access safe properties. /// A wrapper around elements that ensures layout can only ever access safe properties.
#[derive(Clone, Copy)] #[derive(Clone, Copy)]
pub struct ServoLayoutElement<'le> { pub struct ServoLayoutElement<'le> {
element: LayoutJS<Element>, element: LayoutDom<Element>,
chain: PhantomData<&'le ()>, chain: PhantomData<&'le ()>,
} }
@ -560,7 +560,7 @@ impl<'le> Hash for ServoLayoutElement<'le> {
impl<'le> Eq for ServoLayoutElement<'le> {} impl<'le> Eq for ServoLayoutElement<'le> {}
impl<'le> ServoLayoutElement<'le> { impl<'le> ServoLayoutElement<'le> {
fn from_layout_js(el: LayoutJS<Element>) -> ServoLayoutElement<'le> { fn from_layout_js(el: LayoutDom<Element>) -> ServoLayoutElement<'le> {
ServoLayoutElement { ServoLayoutElement {
element: el, element: el,
chain: PhantomData, chain: PhantomData,
@ -611,7 +611,7 @@ impl<'le> ServoLayoutElement<'le> {
} }
} }
fn as_element<'le>(node: LayoutJS<Node>) -> Option<ServoLayoutElement<'le>> { fn as_element<'le>(node: LayoutDom<Node>) -> Option<ServoLayoutElement<'le>> {
node.downcast().map(ServoLayoutElement::from_layout_js) node.downcast().map(ServoLayoutElement::from_layout_js)
} }
@ -828,7 +828,7 @@ impl<'ln> DangerousThreadSafeLayoutNode for ServoThreadSafeLayoutNode<'ln> {
impl<'ln> ServoThreadSafeLayoutNode<'ln> { impl<'ln> ServoThreadSafeLayoutNode<'ln> {
/// Creates a new layout node with the same lifetime as this layout node. /// Creates a new layout node with the same lifetime as this layout node.
pub unsafe fn new_with_this_lifetime(&self, node: &LayoutJS<Node>) -> ServoThreadSafeLayoutNode<'ln> { pub unsafe fn new_with_this_lifetime(&self, node: &LayoutDom<Node>) -> ServoThreadSafeLayoutNode<'ln> {
ServoThreadSafeLayoutNode { ServoThreadSafeLayoutNode {
node: self.node.new_with_this_lifetime(node), node: self.node.new_with_this_lifetime(node),
pseudo: PseudoElementType::Normal, pseudo: PseudoElementType::Normal,
@ -843,9 +843,9 @@ impl<'ln> ServoThreadSafeLayoutNode<'ln> {
} }
} }
/// Returns the interior of this node as a `LayoutJS`. This is highly unsafe for layout to /// Returns the interior of this node as a `LayoutDom`. This is highly unsafe for layout to
/// call and as such is marked `unsafe`. /// call and as such is marked `unsafe`.
unsafe fn get_jsmanaged(&self) -> &LayoutJS<Node> { unsafe fn get_jsmanaged(&self) -> &LayoutDom<Node> {
self.node.get_jsmanaged() self.node.get_jsmanaged()
} }
} }
@ -915,7 +915,7 @@ impl<'ln> ThreadSafeLayoutNode for ServoThreadSafeLayoutNode<'ln> {
fn is_ignorable_whitespace(&self, context: &SharedStyleContext) -> bool { fn is_ignorable_whitespace(&self, context: &SharedStyleContext) -> bool {
unsafe { unsafe {
let text: LayoutJS<Text> = match self.get_jsmanaged().downcast() { let text: LayoutDom<Text> = match self.get_jsmanaged().downcast() {
Some(text) => text, Some(text) => text,
None => return false None => return false
}; };

View file

@ -4,8 +4,8 @@
use dom::bindings::codegen::Bindings::FormDataBinding::FormDataMethods; use dom::bindings::codegen::Bindings::FormDataBinding::FormDataMethods;
use dom::bindings::error::{Error, Fallible}; use dom::bindings::error::{Error, Fallible};
use dom::bindings::js::Root;
use dom::bindings::reflector::DomObject; use dom::bindings::reflector::DomObject;
use dom::bindings::root::DomRoot;
use dom::bindings::str::USVString; use dom::bindings::str::USVString;
use dom::blob::{Blob, BlobImpl}; use dom::blob::{Blob, BlobImpl};
use dom::formdata::FormData; use dom::formdata::FormData;
@ -33,8 +33,8 @@ pub enum BodyType {
pub enum FetchedData { pub enum FetchedData {
Text(String), Text(String),
Json(JSValue), Json(JSValue),
BlobData(Root<Blob>), BlobData(DomRoot<Blob>),
FormData(Root<FormData>), FormData(DomRoot<FormData>),
} }
// https://fetch.spec.whatwg.org/#concept-body-consume-body // https://fetch.spec.whatwg.org/#concept-body-consume-body

View file

@ -13,8 +13,8 @@ use dom::bindings::codegen::Bindings::ElementBinding::ElementMethods;
use dom::bindings::codegen::Bindings::WindowBinding::WindowMethods; use dom::bindings::codegen::Bindings::WindowBinding::WindowMethods;
use dom::bindings::conversions::{ConversionResult, FromJSValConvertible, jsstring_to_str}; use dom::bindings::conversions::{ConversionResult, FromJSValConvertible, jsstring_to_str};
use dom::bindings::inheritance::Castable; use dom::bindings::inheritance::Castable;
use dom::bindings::js::Root;
use dom::bindings::reflector::DomObject; use dom::bindings::reflector::DomObject;
use dom::bindings::root::DomRoot;
use dom::bindings::str::DOMString; use dom::bindings::str::DOMString;
use dom::document::AnimationFrameCallback; use dom::document::AnimationFrameCallback;
use dom::element::Element; use dom::element::Element;
@ -90,7 +90,7 @@ pub fn handle_get_document_element(documents: &Documents,
fn find_node_by_unique_id(documents: &Documents, fn find_node_by_unique_id(documents: &Documents,
pipeline: PipelineId, pipeline: PipelineId,
node_id: &str) node_id: &str)
-> Option<Root<Node>> { -> Option<DomRoot<Node>> {
documents.find_document(pipeline).and_then(|document| documents.find_document(pipeline).and_then(|document|
document.upcast::<Node>().traverse_preorder().find(|candidate| candidate.unique_id() == node_id) document.upcast::<Node>().traverse_preorder().find(|candidate| candidate.unique_id() == node_id)
) )

View file

@ -143,7 +143,7 @@ use dom_struct::dom_struct;
#[dom_struct] #[dom_struct]
pub struct Document { pub struct Document {
node: Node, node: Node,
window: JS<Window>, window: Dom<Window>,
is_html_document: bool, is_html_document: bool,
... ...
} }
@ -164,11 +164,11 @@ relationship. The `Document` just has a pointer to a `Window`, one of many
pointers to that object, which can live in native DOM data structures or in pointers to that object, which can live in native DOM data structures or in
JavaScript objects. These are precisely the pointers we need to tell the JavaScript objects. These are precisely the pointers we need to tell the
garbage collector about. We do this with a garbage collector about. We do this with a
[custom type for traced pointers: `JS<T>`][js] (for example, the `JS<Window>` [custom type for traced pointers: `Dom<T>`][dom] (for example, the `Dom<Window>`
above). The implementation of `trace` for `JS<T>` is not auto-generated; this above). The implementation of `trace` for `Dom<T>` is not auto-generated; this
is where we actually call the SpiderMonkey trace hooks: is where we actually call the SpiderMonkey trace hooks:
[js]: http://doc.servo.org/script/dom/bindings/js/struct.JS.html [dom]: http://doc.servo.org/script/dom/bindings/root/struct.Dom.html
```rust ```rust
pub fn trace_reflector(tracer: *mut JSTracer, description: &str, reflector: &Reflector) { pub fn trace_reflector(tracer: *mut JSTracer, description: &str, reflector: &Reflector) {
@ -183,7 +183,7 @@ pub fn trace_reflector(tracer: *mut JSTracer, description: &str, reflector: &Ref
} }
} }
impl<T: DomObject> JSTraceable for JS<T> { impl<T: DomObject> JSTraceable for Dom<T> {
unsafe fn trace(&self, trc: *mut JSTracer) { unsafe fn trace(&self, trc: *mut JSTracer) {
trace_reflector(trc, "", unsafe { (**self.ptr).reflector() }); trace_reflector(trc, "", unsafe { (**self.ptr).reflector() });
} }
@ -222,22 +222,22 @@ objects.
[gc-root]: https://en.wikipedia.org/wiki/Tracing_garbage_collection#Reachability_of_an_object [gc-root]: https://en.wikipedia.org/wiki/Tracing_garbage_collection#Reachability_of_an_object
Another common situation is creating a stack-local root manually. For this Another common situation is creating a stack-local root manually. For this
purpose, we have a [`Root<T>`][root] struct. When the `Root<T>` is destroyed, purpose, we have a [`DomRoot<T>`][root] struct. When the `DomRoot<T>` is destroyed,
typically at the end of the function (or block) where it was created, its typically at the end of the function (or block) where it was created, its
destructor will un-root the DOM object. This is an example of the destructor will un-root the DOM object. This is an example of the
[RAII idiom][raii], which Rust inherits from C++. [RAII idiom][raii], which Rust inherits from C++.
`Root<T>` structs are primarily returned from [`T::new` functions][new] when `DomRoot<T>` structs are primarily returned from [`T::new` functions][new] when
creating a new DOM object. creating a new DOM object.
In some cases, we need to use a DOM object longer than the reference we In some cases, we need to use a DOM object longer than the reference we
received allows us to; the [`Root::from_ref` associated function][from-ref] received allows us to; the [`DomRoot::from_ref` associated function][from-ref]
allows creating a new `Root<T>` struct in that case. allows creating a new `DomRoot<T>` struct in that case.
[root]: http://doc.servo.org/script/dom/bindings/js/struct.Root.html [root]: http://doc.servo.org/script/dom/bindings/root/struct.DomRoot.html
[raii]: https://en.wikipedia.org/wiki/Resource_Acquisition_Is_Initialization [raii]: https://en.wikipedia.org/wiki/Resource_Acquisition_Is_Initialization
[new]: http://doc.servo.org/script/dom/index.html#construction [new]: http://doc.servo.org/script/dom/index.html#construction
[from-ref]: http://doc.servo.org/script/dom/bindings/js/struct.Root.html#method.from_ref [from-ref]: http://doc.servo.org/script/dom/bindings/root/struct.DomRoot.html#method.from_ref
We can then obtain a reference from the `Root<T>` through Rust's built-in We can then obtain a reference from the `DomRoot<T>` through Rust's built-in
[`Deref` trait][deref], which exposes a method `deref` with the following [`Deref` trait][deref], which exposes a method `deref` with the following
signature: signature:
@ -249,19 +249,19 @@ pub fn deref<'a>(&'a self) -> &'a T {
What this syntax means is: What this syntax means is:
- **`<'a>`**: 'for any lifetime `'a`', - **`<'a>`**: 'for any lifetime `'a`',
- **`(&'a self)`**: 'take a reference to a `Root` which is valid over lifetime `'a`', - **`(&'a self)`**: 'take a reference to a `DomRoot` which is valid over lifetime `'a`',
- **`-> &'a T`**: 'return a reference whose lifetime is limited to `'a`'. - **`-> &'a T`**: 'return a reference whose lifetime is limited to `'a`'.
This allows us to call methods and access fields of the underlying type `T` This allows us to call methods and access fields of the underlying type `T`
through a `Root<T>`. through a `DomRoot<T>`.
[deref]: https://doc.rust-lang.org/std/ops/trait.Deref.html [deref]: https://doc.rust-lang.org/std/ops/trait.Deref.html
A third way to obtain a reference is from the `JS<T>` struct we encountered A third way to obtain a reference is from the `Dom<T>` struct we encountered
earlier. Whenever we have a reference to a `JS<T>`, we know that the DOM struct earlier. Whenever we have a reference to a `Dom<T>`, we know that the DOM struct
that contains it is already rooted, and thus that the garbage collector is that contains it is already rooted, and thus that the garbage collector is
aware of the `JS<T>`, and will keep the DOM object it points to alive. aware of the `Dom<T>`, and will keep the DOM object it points to alive.
This allows us to implement the `Deref` trait on `JS<T>` as well. This allows us to implement the `Deref` trait on `Dom<T>` as well.
The correctness of these APIs is heavily dependent on the fact that the The correctness of these APIs is heavily dependent on the fact that the
reference cannot outlive the smart pointer it was retrieved from, and the fact reference cannot outlive the smart pointer it was retrieved from, and the fact
@ -282,10 +282,10 @@ use-after-free and other dangerous bugs.
[lifetimes]: https://doc.rust-lang.org/book/lifetimes.html [lifetimes]: https://doc.rust-lang.org/book/lifetimes.html
[ti]: https://en.wikipedia.org/wiki/Type_inference [ti]: https://en.wikipedia.org/wiki/Type_inference
You can check out the [`js` module's documentation][js-docs] for more details You can check out the [`root` module's documentation][root-docs] for more details
that didn't make it into this document. that didn't make it into this document.
[js-docs]: http://doc.servo.org/script/dom/bindings/js/index.html [root-docs]: http://doc.servo.org/script/dom/bindings/root/index.html
Custom static analysis Custom static analysis
====================== ======================
@ -294,14 +294,14 @@ To recapitulate, the safety of our system depends on two major parts:
- The auto-generated `trace` methods ensure that SpiderMonkey's garbage - The auto-generated `trace` methods ensure that SpiderMonkey's garbage
collector can see all of the references between DOM objects. collector can see all of the references between DOM objects.
- The implementation of `Root<T>` guarantees that we can't use a DOM object - The implementation of `DomRoot<T>` guarantees that we can't use a DOM object
from Rust without telling SpiderMonkey about our temporary reference. from Rust without telling SpiderMonkey about our temporary reference.
But there's a hole in this scheme. We could copy an unrooted pointer — a But there's a hole in this scheme. We could copy an unrooted pointer — a
`JS<T>` — to a local variable on the stack, and then at some later point, root `Dom<T>` — to a local variable on the stack, and then at some later point, root
it and use the DOM object. In the meantime, SpiderMonkey's garbage collector it and use the DOM object. In the meantime, SpiderMonkey's garbage collector
won't know about that `JS<T>` on the stack, so it might free the DOM object. won't know about that `Dom<T>` on the stack, so it might free the DOM object.
To really be safe, we need to make sure that `JS<T>` *only* appears in places To really be safe, we need to make sure that `Dom<T>` *only* appears in places
where it will be traced, such as DOM structs, and never in local variables, where it will be traced, such as DOM structs, and never in local variables,
function arguments, and so forth. function arguments, and so forth.
@ -315,10 +315,10 @@ Developing the Servo Web Browser Engine using Rust</cite>][lints].
[lints]: http://arxiv.org/pdf/1505.07383v1.pdf [lints]: http://arxiv.org/pdf/1505.07383v1.pdf
We have already [implemented a plugin][js-lint] which effectively forbids We have already [implemented a plugin][js-lint] which effectively forbids
`JS<T>` from appearing on the [stack][stack]. Because lint plugins are part of `Dom<T>` from appearing on the [stack][stack]. Because lint plugins are part of
the usual [warnings infrastructure][warnings], we can use the `allow` attribute the usual [warnings infrastructure][warnings], we can use the `allow` attribute
in places where it's okay to use `JS<T>`, like DOM struct definitions and the in places where it's okay to use `Dom<T>`, like DOM struct definitions and the
implementation of `JS<T>` itself. implementation of `Dom<T>` itself.
[js-lint]: http://doc.servo.org/plugins/lints/unrooted_must_root/struct.UnrootedPass.html [js-lint]: http://doc.servo.org/plugins/lints/unrooted_must_root/struct.UnrootedPass.html
[stack]: https://en.wikipedia.org/wiki/Stack-based_memory_allocation [stack]: https://en.wikipedia.org/wiki/Stack-based_memory_allocation

View file

@ -5,7 +5,7 @@
//! Tracking of pending loads in a document. //! Tracking of pending loads in a document.
//! https://html.spec.whatwg.org/multipage/#the-end //! https://html.spec.whatwg.org/multipage/#the-end
use dom::bindings::js::JS; use dom::bindings::root::Dom;
use dom::document::Document; use dom::document::Document;
use ipc_channel::ipc::IpcSender; use ipc_channel::ipc::IpcSender;
use net_traits::{CoreResourceMsg, FetchResponseMsg, ResourceThreads, IpcSend}; use net_traits::{CoreResourceMsg, FetchResponseMsg, ResourceThreads, IpcSend};
@ -43,7 +43,7 @@ impl LoadType {
#[must_root] #[must_root]
pub struct LoadBlocker { pub struct LoadBlocker {
/// The document whose load event is blocked by this object existing. /// The document whose load event is blocked by this object existing.
doc: JS<Document>, doc: Dom<Document>,
/// The load that is blocking the document's load event. /// The load that is blocking the document's load event.
load: Option<LoadType>, load: Option<LoadType>,
} }
@ -53,7 +53,7 @@ impl LoadBlocker {
pub fn new(doc: &Document, load: LoadType) -> LoadBlocker { pub fn new(doc: &Document, load: LoadType) -> LoadBlocker {
doc.loader_mut().add_blocking_load(load.clone()); doc.loader_mut().add_blocking_load(load.clone());
LoadBlocker { LoadBlocker {
doc: JS::from_ref(doc), doc: Dom::from_ref(doc),
load: Some(load), load: Some(load),
} }
} }

View file

@ -3,11 +3,11 @@
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use devtools_traits::AttrInfo; use devtools_traits::AttrInfo;
use dom::bindings::cell::DOMRefCell; use dom::bindings::cell::DomRefCell;
use dom::bindings::codegen::Bindings::AttrBinding::{self, AttrMethods}; use dom::bindings::codegen::Bindings::AttrBinding::{self, AttrMethods};
use dom::bindings::inheritance::Castable; use dom::bindings::inheritance::Castable;
use dom::bindings::js::{LayoutJS, MutNullableJS, Root, RootedReference};
use dom::bindings::reflector::{Reflector, reflect_dom_object}; use dom::bindings::reflector::{Reflector, reflect_dom_object};
use dom::bindings::root::{DomRoot, LayoutDom, MutNullableDom, RootedReference};
use dom::bindings::str::DOMString; use dom::bindings::str::DOMString;
use dom::customelementregistry::CallbackReaction; use dom::customelementregistry::CallbackReaction;
use dom::element::{AttributeMutation, Element}; use dom::element::{AttributeMutation, Element};
@ -29,10 +29,10 @@ use style::attr::{AttrIdentifier, AttrValue};
pub struct Attr { pub struct Attr {
reflector_: Reflector, reflector_: Reflector,
identifier: AttrIdentifier, identifier: AttrIdentifier,
value: DOMRefCell<AttrValue>, value: DomRefCell<AttrValue>,
/// the element that owns this attribute. /// the element that owns this attribute.
owner: MutNullableJS<Element>, owner: MutNullableDom<Element>,
} }
impl Attr { impl Attr {
@ -51,8 +51,8 @@ impl Attr {
namespace: namespace, namespace: namespace,
prefix: prefix, prefix: prefix,
}, },
value: DOMRefCell::new(value), value: DomRefCell::new(value),
owner: MutNullableJS::new(owner), owner: MutNullableDom::new(owner),
} }
} }
@ -63,7 +63,7 @@ impl Attr {
namespace: Namespace, namespace: Namespace,
prefix: Option<Prefix>, prefix: Option<Prefix>,
owner: Option<&Element>) owner: Option<&Element>)
-> Root<Attr> { -> DomRoot<Attr> {
reflect_dom_object(box Attr::new_inherited(local_name, reflect_dom_object(box Attr::new_inherited(local_name,
value, value,
name, name,
@ -161,7 +161,7 @@ impl AttrMethods for Attr {
} }
// https://dom.spec.whatwg.org/#dom-attr-ownerelement // https://dom.spec.whatwg.org/#dom-attr-ownerelement
fn GetOwnerElement(&self) -> Option<Root<Element>> { fn GetOwnerElement(&self) -> Option<DomRoot<Element>> {
self.owner() self.owner()
} }
@ -232,7 +232,7 @@ impl Attr {
self.owner.set(owner); self.owner.set(owner);
} }
pub fn owner(&self) -> Option<Root<Element>> { pub fn owner(&self) -> Option<DomRoot<Element>> {
self.owner.get() self.owner.get()
} }
@ -256,7 +256,7 @@ pub trait AttrHelpersForLayout {
} }
#[allow(unsafe_code)] #[allow(unsafe_code)]
impl AttrHelpersForLayout for LayoutJS<Attr> { impl AttrHelpersForLayout for LayoutDom<Attr> {
#[inline] #[inline]
unsafe fn value_forever(&self) -> &'static AttrValue { unsafe fn value_forever(&self) -> &'static AttrValue {
// This transmute is used to cheat the lifetime restriction. // This transmute is used to cheat the lifetime restriction.

View file

@ -4,13 +4,13 @@
#![allow(dead_code)] #![allow(dead_code)]
use dom::bindings::cell::DOMRefCell; use dom::bindings::cell::DomRefCell;
use dom::bindings::codegen::Bindings::BeforeUnloadEventBinding; use dom::bindings::codegen::Bindings::BeforeUnloadEventBinding;
use dom::bindings::codegen::Bindings::BeforeUnloadEventBinding::BeforeUnloadEventMethods; use dom::bindings::codegen::Bindings::BeforeUnloadEventBinding::BeforeUnloadEventMethods;
use dom::bindings::codegen::Bindings::EventBinding::EventMethods; use dom::bindings::codegen::Bindings::EventBinding::EventMethods;
use dom::bindings::inheritance::Castable; use dom::bindings::inheritance::Castable;
use dom::bindings::js::Root;
use dom::bindings::reflector::reflect_dom_object; use dom::bindings::reflector::reflect_dom_object;
use dom::bindings::root::DomRoot;
use dom::bindings::str::DOMString; use dom::bindings::str::DOMString;
use dom::event::{Event, EventBubbles, EventCancelable}; use dom::event::{Event, EventBubbles, EventCancelable};
use dom::window::Window; use dom::window::Window;
@ -21,18 +21,18 @@ use servo_atoms::Atom;
#[dom_struct] #[dom_struct]
pub struct BeforeUnloadEvent { pub struct BeforeUnloadEvent {
event: Event, event: Event,
return_value: DOMRefCell<DOMString>, return_value: DomRefCell<DOMString>,
} }
impl BeforeUnloadEvent { impl BeforeUnloadEvent {
fn new_inherited() -> BeforeUnloadEvent { fn new_inherited() -> BeforeUnloadEvent {
BeforeUnloadEvent { BeforeUnloadEvent {
event: Event::new_inherited(), event: Event::new_inherited(),
return_value: DOMRefCell::new(DOMString::new()), return_value: DomRefCell::new(DOMString::new()),
} }
} }
pub fn new_uninitialized(window: &Window) -> Root<BeforeUnloadEvent> { pub fn new_uninitialized(window: &Window) -> DomRoot<BeforeUnloadEvent> {
reflect_dom_object(box BeforeUnloadEvent::new_inherited(), reflect_dom_object(box BeforeUnloadEvent::new_inherited(),
window, window,
BeforeUnloadEventBinding::Wrap) BeforeUnloadEventBinding::Wrap)
@ -41,7 +41,7 @@ impl BeforeUnloadEvent {
pub fn new(window: &Window, pub fn new(window: &Window,
type_: Atom, type_: Atom,
bubbles: EventBubbles, bubbles: EventBubbles,
cancelable: EventCancelable) -> Root<BeforeUnloadEvent> { cancelable: EventCancelable) -> DomRoot<BeforeUnloadEvent> {
let ev = BeforeUnloadEvent::new_uninitialized(window); let ev = BeforeUnloadEvent::new_uninitialized(window);
{ {
let event = ev.upcast::<Event>(); let event = ev.upcast::<Event>();

View file

@ -5,8 +5,8 @@
//! Base classes to work with IDL callbacks. //! Base classes to work with IDL callbacks.
use dom::bindings::error::{Error, Fallible, report_pending_exception}; use dom::bindings::error::{Error, Fallible, report_pending_exception};
use dom::bindings::js::{JS, Root};
use dom::bindings::reflector::DomObject; use dom::bindings::reflector::DomObject;
use dom::bindings::root::{Dom, DomRoot};
use dom::bindings::settings_stack::{AutoEntryScript, AutoIncumbentScript}; use dom::bindings::settings_stack::{AutoEntryScript, AutoIncumbentScript};
use dom::bindings::utils::AsCCharPtrPtr; use dom::bindings::utils::AsCCharPtrPtr;
use dom::globalscope::GlobalScope; use dom::globalscope::GlobalScope;
@ -53,7 +53,7 @@ pub struct CallbackObject {
/// ///
/// ["callback context"]: https://heycam.github.io/webidl/#dfn-callback-context /// ["callback context"]: https://heycam.github.io/webidl/#dfn-callback-context
/// [sometimes]: https://github.com/whatwg/html/issues/2248 /// [sometimes]: https://github.com/whatwg/html/issues/2248
incumbent: Option<JS<GlobalScope>> incumbent: Option<Dom<GlobalScope>>
} }
impl Default for CallbackObject { impl Default for CallbackObject {
@ -69,7 +69,7 @@ impl CallbackObject {
CallbackObject { CallbackObject {
callback: Heap::default(), callback: Heap::default(),
permanent_js_root: Heap::default(), permanent_js_root: Heap::default(),
incumbent: GlobalScope::incumbent().map(|i| JS::from_ref(&*i)), incumbent: GlobalScope::incumbent().map(|i| Dom::from_ref(&*i)),
} }
} }
@ -120,7 +120,7 @@ pub trait CallbackContainer {
/// ///
/// ["callback context"]: https://heycam.github.io/webidl/#dfn-callback-context /// ["callback context"]: https://heycam.github.io/webidl/#dfn-callback-context
fn incumbent(&self) -> Option<&GlobalScope> { fn incumbent(&self) -> Option<&GlobalScope> {
self.callback_holder().incumbent.as_ref().map(JS::deref) self.callback_holder().incumbent.as_ref().map(Dom::deref)
} }
} }
@ -223,7 +223,7 @@ pub fn wrap_call_this_object<T: DomObject>(cx: *mut JSContext,
pub struct CallSetup { pub struct CallSetup {
/// The global for reporting exceptions. This is the global object of the /// The global for reporting exceptions. This is the global object of the
/// (possibly wrapped) callback object. /// (possibly wrapped) callback object.
exception_global: Root<GlobalScope>, exception_global: DomRoot<GlobalScope>,
/// The `JSContext` used for the call. /// The `JSContext` used for the call.
cx: *mut JSContext, cx: *mut JSContext,
/// The compartment we were in before the call. /// The compartment we were in before the call.

View file

@ -12,14 +12,14 @@ use style::thread_state;
/// This extends the API of `core::cell::RefCell` to allow unsafe access in /// This extends the API of `core::cell::RefCell` to allow unsafe access in
/// certain situations, with dynamic checking in debug builds. /// certain situations, with dynamic checking in debug builds.
#[derive(Clone, Debug, Default, HeapSizeOf, PartialEq)] #[derive(Clone, Debug, Default, HeapSizeOf, PartialEq)]
pub struct DOMRefCell<T> { pub struct DomRefCell<T> {
value: RefCell<T>, value: RefCell<T>,
} }
// Functionality specific to Servo's `DOMRefCell` type // Functionality specific to Servo's `DomRefCell` type
// =================================================== // ===================================================
impl<T> DOMRefCell<T> { impl<T> DomRefCell<T> {
/// Return a reference to the contents. /// Return a reference to the contents.
/// ///
/// For use in the layout thread only. /// For use in the layout thread only.
@ -59,10 +59,10 @@ impl<T> DOMRefCell<T> {
// Functionality duplicated with `core::cell::RefCell` // Functionality duplicated with `core::cell::RefCell`
// =================================================== // ===================================================
impl<T> DOMRefCell<T> { impl<T> DomRefCell<T> {
/// Create a new `DOMRefCell` containing `value`. /// Create a new `DomRefCell` containing `value`.
pub fn new(value: T) -> DOMRefCell<T> { pub fn new(value: T) -> DomRefCell<T> {
DOMRefCell { DomRefCell {
value: RefCell::new(value), value: RefCell::new(value),
} }
} }
@ -79,7 +79,7 @@ impl<T> DOMRefCell<T> {
/// ///
/// Panics if the value is currently mutably borrowed. /// Panics if the value is currently mutably borrowed.
pub fn borrow(&self) -> Ref<T> { pub fn borrow(&self) -> Ref<T> {
self.try_borrow().expect("DOMRefCell<T> already mutably borrowed") self.try_borrow().expect("DomRefCell<T> already mutably borrowed")
} }
/// Mutably borrows the wrapped value. /// Mutably borrows the wrapped value.
@ -93,7 +93,7 @@ impl<T> DOMRefCell<T> {
/// ///
/// Panics if the value is currently borrowed. /// Panics if the value is currently borrowed.
pub fn borrow_mut(&self) -> RefMut<T> { pub fn borrow_mut(&self) -> RefMut<T> {
self.try_borrow_mut().expect("DOMRefCell<T> already borrowed") self.try_borrow_mut().expect("DomRefCell<T> already borrowed")
} }
/// Attempts to immutably borrow the wrapped value. /// Attempts to immutably borrow the wrapped value.

View file

@ -1272,7 +1272,7 @@ class CGArgumentConverter(CGThing):
arg = "arg%d" % index arg = "arg%d" % index
if argument.type.isGeckoInterface(): if argument.type.isGeckoInterface():
init = "rooted_vec!(let mut %s)" % arg init = "rooted_vec!(let mut %s)" % arg
innerConverter.append(CGGeneric("%s.push(JS::from_ref(&*slot));" % arg)) innerConverter.append(CGGeneric("%s.push(Dom::from_ref(&*slot));" % arg))
else: else:
init = "let mut %s = vec![]" % arg init = "let mut %s = vec![]" % arg
innerConverter.append(CGGeneric("%s.push(slot);" % arg)) innerConverter.append(CGGeneric("%s.push(slot);" % arg))
@ -2253,8 +2253,8 @@ def UnionTypes(descriptors, dictionaries, callbacks, typedefs, config):
'dom::bindings::conversions::StringificationBehavior', 'dom::bindings::conversions::StringificationBehavior',
'dom::bindings::conversions::root_from_handlevalue', 'dom::bindings::conversions::root_from_handlevalue',
'dom::bindings::error::throw_not_in_union', 'dom::bindings::error::throw_not_in_union',
'dom::bindings::js::Root',
'dom::bindings::mozmap::MozMap', 'dom::bindings::mozmap::MozMap',
'dom::bindings::root::DomRoot',
'dom::bindings::str::ByteString', 'dom::bindings::str::ByteString',
'dom::bindings::str::DOMString', 'dom::bindings::str::DOMString',
'dom::bindings::str::USVString', 'dom::bindings::str::USVString',
@ -2558,7 +2558,7 @@ class CGWrapMethod(CGAbstractMethod):
args = [Argument('*mut JSContext', 'cx'), args = [Argument('*mut JSContext', 'cx'),
Argument('&GlobalScope', 'scope'), Argument('&GlobalScope', 'scope'),
Argument("Box<%s>" % descriptor.concreteType, 'object')] Argument("Box<%s>" % descriptor.concreteType, 'object')]
retval = 'Root<%s>' % descriptor.concreteType retval = 'DomRoot<%s>' % descriptor.concreteType
CGAbstractMethod.__init__(self, descriptor, 'Wrap', retval, args, CGAbstractMethod.__init__(self, descriptor, 'Wrap', retval, args,
pub=True, unsafe=True) pub=True, unsafe=True)
@ -2580,7 +2580,7 @@ assert!(!proto.is_null());
%(copyUnforgeable)s %(copyUnforgeable)s
(*raw).init_reflector(obj.get()); (*raw).init_reflector(obj.get());
Root::from_ref(&*raw)""" % {'copyUnforgeable': unforgeable, 'createObject': create}) DomRoot::from_ref(&*raw)""" % {'copyUnforgeable': unforgeable, 'createObject': create})
class CGWrapGlobalMethod(CGAbstractMethod): class CGWrapGlobalMethod(CGAbstractMethod):
@ -2592,7 +2592,7 @@ class CGWrapGlobalMethod(CGAbstractMethod):
assert descriptor.isGlobal() assert descriptor.isGlobal()
args = [Argument('*mut JSContext', 'cx'), args = [Argument('*mut JSContext', 'cx'),
Argument("Box<%s>" % descriptor.concreteType, 'object')] Argument("Box<%s>" % descriptor.concreteType, 'object')]
retval = 'Root<%s>' % descriptor.concreteType retval = 'DomRoot<%s>' % descriptor.concreteType
CGAbstractMethod.__init__(self, descriptor, 'Wrap', retval, args, CGAbstractMethod.__init__(self, descriptor, 'Wrap', retval, args,
pub=True, unsafe=True) pub=True, unsafe=True)
self.properties = properties self.properties = properties
@ -2638,7 +2638,7 @@ assert!(immutable);
%(unforgeable)s %(unforgeable)s
Root::from_ref(&*raw)\ DomRoot::from_ref(&*raw)\
""" % values) """ % values)
@ -3421,7 +3421,9 @@ class CGAbstractStaticBindingMethod(CGAbstractMethod):
def definition_body(self): def definition_body(self):
preamble = "let global = GlobalScope::from_object(JS_CALLEE(cx, vp).to_object());\n" preamble = "let global = GlobalScope::from_object(JS_CALLEE(cx, vp).to_object());\n"
if len(self.exposureSet) == 1: if len(self.exposureSet) == 1:
preamble += "let global = Root::downcast::<dom::types::%s>(global).unwrap();\n" % list(self.exposureSet)[0] preamble += """
let global = DomRoot::downcast::<dom::types::%s>(global).unwrap();
""" % list(self.exposureSet)[0]
return CGList([CGGeneric(preamble), self.generate_code()]) return CGList([CGGeneric(preamble), self.generate_code()])
def generate_code(self): def generate_code(self):
@ -5352,7 +5354,9 @@ class CGClassConstructHook(CGAbstractExternMethod):
def definition_body(self): def definition_body(self):
preamble = """let global = GlobalScope::from_object(JS_CALLEE(cx, vp).to_object());\n""" preamble = """let global = GlobalScope::from_object(JS_CALLEE(cx, vp).to_object());\n"""
if len(self.exposureSet) == 1: if len(self.exposureSet) == 1:
preamble += "let global = Root::downcast::<dom::types::%s>(global).unwrap();\n" % list(self.exposureSet)[0] preamble += """\
let global = DomRoot::downcast::<dom::types::%s>(global).unwrap();
""" % list(self.exposureSet)[0]
preamble += """let args = CallArgs::from_vp(vp, argc);\n""" preamble += """let args = CallArgs::from_vp(vp, argc);\n"""
preamble = CGGeneric(preamble) preamble = CGGeneric(preamble)
if self.constructor.isHTMLConstructor(): if self.constructor.isHTMLConstructor():
@ -5408,7 +5412,7 @@ if !JS_WrapObject(cx, prototype.handle_mut()) {
return false; return false;
} }
let result: Result<Root<%s>, Error> = html_constructor(&global, &args); let result: Result<DomRoot<%s>, Error> = html_constructor(&global, &args);
let result = match result { let result = match result {
Ok(result) => result, Ok(result) => result,
Err(e) => { Err(e) => {
@ -5708,14 +5712,14 @@ def generate_imports(config, cgthings, descriptors, callbacks=None, dictionaries
'dom::bindings::interface::push_new_element_queue', 'dom::bindings::interface::push_new_element_queue',
'dom::bindings::iterable::Iterable', 'dom::bindings::iterable::Iterable',
'dom::bindings::iterable::IteratorType', 'dom::bindings::iterable::IteratorType',
'dom::bindings::js::JS',
'dom::bindings::js::OptionalHeapSetter',
'dom::bindings::js::Root',
'dom::bindings::js::RootedReference',
'dom::bindings::namespace::NamespaceObjectClass', 'dom::bindings::namespace::NamespaceObjectClass',
'dom::bindings::namespace::create_namespace_object', 'dom::bindings::namespace::create_namespace_object',
'dom::bindings::reflector::MutDomObject', 'dom::bindings::reflector::MutDomObject',
'dom::bindings::reflector::DomObject', 'dom::bindings::reflector::DomObject',
'dom::bindings::root::Dom',
'dom::bindings::root::DomRoot',
'dom::bindings::root::OptionalHeapSetter',
'dom::bindings::root::RootedReference',
'dom::bindings::utils::AsVoidPtr', 'dom::bindings::utils::AsVoidPtr',
'dom::bindings::utils::DOMClass', 'dom::bindings::utils::DOMClass',
'dom::bindings::utils::DOMJSClass', 'dom::bindings::utils::DOMJSClass',
@ -6281,7 +6285,7 @@ class CGRegisterProxyHandlers(CGThing):
class CGBindingRoot(CGThing): class CGBindingRoot(CGThing):
""" """
Root codegen class for binding generation. Instantiate the class, and call DomRoot codegen class for binding generation. Instantiate the class, and call
declare or define to generate header or cpp code (respectively). declare or define to generate header or cpp code (respectively).
""" """
def __init__(self, config, prefix, webIDLFile): def __init__(self, config, prefix, webIDLFile):
@ -6961,7 +6965,7 @@ class CallbackGetter(CallbackMember):
needThisHandling=False) needThisHandling=False)
def getRvalDecl(self): def getRvalDecl(self):
return "JS::Rooted<JS::Value> rval(cx, JS::UndefinedValue());\n" return "Dom::Rooted<Dom::Value> rval(cx, JS::UndefinedValue());\n"
def getCall(self): def getCall(self):
replacements = { replacements = {
@ -7195,7 +7199,7 @@ class GlobalGenRoots():
imports = [CGGeneric("use dom::types::*;\n"), imports = [CGGeneric("use dom::types::*;\n"),
CGGeneric("use dom::bindings::conversions::{DerivedFrom, get_dom_class};\n"), CGGeneric("use dom::bindings::conversions::{DerivedFrom, get_dom_class};\n"),
CGGeneric("use dom::bindings::inheritance::Castable;\n"), CGGeneric("use dom::bindings::inheritance::Castable;\n"),
CGGeneric("use dom::bindings::js::{JS, LayoutJS, Root};\n"), CGGeneric("use dom::bindings::root::{Dom, DomRoot, LayoutDom};\n"),
CGGeneric("use dom::bindings::trace::JSTraceable;\n"), CGGeneric("use dom::bindings::trace::JSTraceable;\n"),
CGGeneric("use dom::bindings::reflector::DomObject;\n"), CGGeneric("use dom::bindings::reflector::DomObject;\n"),
CGGeneric("use js::jsapi::JSTracer;\n\n"), CGGeneric("use js::jsapi::JSTracer;\n\n"),

View file

@ -212,7 +212,7 @@ class Descriptor(DescriptorProvider):
self.argumentType = "???" self.argumentType = "???"
self.nativeType = ty self.nativeType = ty
else: else:
self.returnType = "Root<%s>" % typeName self.returnType = "DomRoot<%s>" % typeName
self.argumentType = "&%s" % typeName self.argumentType = "&%s" % typeName
self.nativeType = "*const %s" % typeName self.nativeType = "*const %s" % typeName
if self.interface.isIteratorInterface(): if self.interface.isIteratorInterface():

View file

@ -24,7 +24,7 @@
//! | USVString | `USVString` | //! | USVString | `USVString` |
//! | ByteString | `ByteString` | //! | ByteString | `ByteString` |
//! | object | `*mut JSObject` | //! | object | `*mut JSObject` |
//! | interface types | `&T` | `Root<T>` | //! | interface types | `&T` | `DomRoot<T>` |
//! | dictionary types | `&T` | *unsupported* | //! | dictionary types | `&T` | *unsupported* |
//! | enumeration types | `T` | //! | enumeration types | `T` |
//! | callback function types | `Rc<T>` | //! | callback function types | `Rc<T>` |
@ -34,9 +34,9 @@
use dom::bindings::error::{Error, Fallible}; use dom::bindings::error::{Error, Fallible};
use dom::bindings::inheritance::Castable; use dom::bindings::inheritance::Castable;
use dom::bindings::js::Root;
use dom::bindings::num::Finite; use dom::bindings::num::Finite;
use dom::bindings::reflector::{DomObject, Reflector}; use dom::bindings::reflector::{DomObject, Reflector};
use dom::bindings::root::DomRoot;
use dom::bindings::str::{ByteString, DOMString, USVString}; use dom::bindings::str::{ByteString, DOMString, USVString};
use dom::bindings::trace::{JSTraceable, RootedTraceableBox}; use dom::bindings::trace::{JSTraceable, RootedTraceableBox};
use dom::bindings::utils::DOMClass; use dom::bindings::utils::DOMClass;
@ -102,13 +102,13 @@ impl<T: Float + FromJSValConvertible<Config=()>> FromJSValConvertible for Finite
} }
} }
impl <T: DomObject + IDLInterface> FromJSValConvertible for Root<T> { impl <T: DomObject + IDLInterface> FromJSValConvertible for DomRoot<T> {
type Config = (); type Config = ();
unsafe fn from_jsval(_cx: *mut JSContext, unsafe fn from_jsval(_cx: *mut JSContext,
value: HandleValue, value: HandleValue,
_config: Self::Config) _config: Self::Config)
-> Result<ConversionResult<Root<T>>, ()> { -> Result<ConversionResult<DomRoot<T>>, ()> {
Ok(match root_from_handlevalue(value) { Ok(match root_from_handlevalue(value) {
Ok(result) => ConversionResult::Success(result), Ok(result) => ConversionResult::Success(result),
Err(()) => ConversionResult::Failure("value is not an object".into()), Err(()) => ConversionResult::Failure("value is not an object".into()),
@ -405,16 +405,16 @@ pub fn native_from_object<T>(obj: *mut JSObject) -> Result<*const T, ()>
} }
} }
/// Get a `Root<T>` for the given DOM object, unwrapping any wrapper /// Get a `DomRoot<T>` for the given DOM object, unwrapping any wrapper
/// around it first, and checking if the object is of the correct type. /// around it first, and checking if the object is of the correct type.
/// ///
/// Returns Err(()) if `obj` is an opaque security wrapper or if the object is /// Returns Err(()) if `obj` is an opaque security wrapper or if the object is
/// not a reflector for a DOM object of the given type (as defined by the /// not a reflector for a DOM object of the given type (as defined by the
/// proto_id and proto_depth). /// proto_id and proto_depth).
pub fn root_from_object<T>(obj: *mut JSObject) -> Result<Root<T>, ()> pub fn root_from_object<T>(obj: *mut JSObject) -> Result<DomRoot<T>, ()>
where T: DomObject + IDLInterface where T: DomObject + IDLInterface
{ {
native_from_object(obj).map(|ptr| unsafe { Root::from_ref(&*ptr) }) native_from_object(obj).map(|ptr| unsafe { DomRoot::from_ref(&*ptr) })
} }
/// Get a `*const T` for a DOM object accessible from a `HandleValue`. /// Get a `*const T` for a DOM object accessible from a `HandleValue`.
@ -428,9 +428,9 @@ pub fn native_from_handlevalue<T>(v: HandleValue) -> Result<*const T, ()>
native_from_object(v.get().to_object()) native_from_object(v.get().to_object())
} }
/// Get a `Root<T>` for a DOM object accessible from a `HandleValue`. /// Get a `DomRoot<T>` for a DOM object accessible from a `HandleValue`.
/// Caller is responsible for throwing a JS exception if needed in case of error. /// Caller is responsible for throwing a JS exception if needed in case of error.
pub fn root_from_handlevalue<T>(v: HandleValue) -> Result<Root<T>, ()> pub fn root_from_handlevalue<T>(v: HandleValue) -> Result<DomRoot<T>, ()>
where T: DomObject + IDLInterface where T: DomObject + IDLInterface
{ {
if !v.get().is_object() { if !v.get().is_object() {
@ -439,14 +439,14 @@ pub fn root_from_handlevalue<T>(v: HandleValue) -> Result<Root<T>, ()>
root_from_object(v.get().to_object()) root_from_object(v.get().to_object())
} }
/// Get a `Root<T>` for a DOM object accessible from a `HandleObject`. /// Get a `DomRoot<T>` for a DOM object accessible from a `HandleObject`.
pub fn root_from_handleobject<T>(obj: HandleObject) -> Result<Root<T>, ()> pub fn root_from_handleobject<T>(obj: HandleObject) -> Result<DomRoot<T>, ()>
where T: DomObject + IDLInterface where T: DomObject + IDLInterface
{ {
root_from_object(obj.get()) root_from_object(obj.get())
} }
impl<T: DomObject> ToJSValConvertible for Root<T> { impl<T: DomObject> ToJSValConvertible for DomRoot<T> {
unsafe fn to_jsval(&self, cx: *mut JSContext, rval: MutableHandleValue) { unsafe fn to_jsval(&self, cx: *mut JSContext, rval: MutableHandleValue) {
self.reflector().to_jsval(cx, rval); self.reflector().to_jsval(cx, rval);
} }

View file

@ -77,7 +77,7 @@ use dom::bindings::constant::{ConstantSpec, define_constants};
use dom::bindings::conversions::{DOM_OBJECT_SLOT, DerivedFrom, get_dom_class}; use dom::bindings::conversions::{DOM_OBJECT_SLOT, DerivedFrom, get_dom_class};
use dom::bindings::error::{Error, Fallible}; use dom::bindings::error::{Error, Fallible};
use dom::bindings::guard::Guard; use dom::bindings::guard::Guard;
use dom::bindings::js::Root; use dom::bindings::root::DomRoot;
use dom::bindings::utils::{DOM_PROTOTYPE_SLOT, ProtoOrIfaceArray, get_proto_or_iface_array}; use dom::bindings::utils::{DOM_PROTOTYPE_SLOT, ProtoOrIfaceArray, get_proto_or_iface_array};
use dom::create::create_native_html_element; use dom::create::create_native_html_element;
use dom::customelementregistry::ConstructionStackEntry; use dom::customelementregistry::ConstructionStackEntry;
@ -236,7 +236,7 @@ pub unsafe fn create_global_object(
} }
// https://html.spec.whatwg.org/multipage/#htmlconstructor // https://html.spec.whatwg.org/multipage/#htmlconstructor
pub unsafe fn html_constructor<T>(window: &Window, call_args: &CallArgs) -> Fallible<Root<T>> pub unsafe fn html_constructor<T>(window: &Window, call_args: &CallArgs) -> Fallible<DomRoot<T>>
where T: DerivedFrom<Element> { where T: DerivedFrom<Element> {
let document = window.Document(); let document = window.Document();
@ -289,7 +289,7 @@ pub unsafe fn html_constructor<T>(window: &Window, call_args: &CallArgs) -> Fall
// Step 8.1 // Step 8.1
let name = QualName::new(None, ns!(html), definition.local_name.clone()); let name = QualName::new(None, ns!(html), definition.local_name.clone());
let element = if definition.is_autonomous() { let element = if definition.is_autonomous() {
Root::upcast(HTMLElement::new(name.local, None, &*document)) DomRoot::upcast(HTMLElement::new(name.local, None, &*document))
} else { } else {
create_native_html_element(name, None, &*document, ElementCreator::ScriptCreated) create_native_html_element(name, None, &*document, ElementCreator::ScriptCreated)
}; };
@ -303,7 +303,7 @@ pub unsafe fn html_constructor<T>(window: &Window, call_args: &CallArgs) -> Fall
element.set_custom_element_definition(definition.clone()); element.set_custom_element_definition(definition.clone());
// Step 8.5 // Step 8.5
Root::downcast(element).ok_or(Error::InvalidState) DomRoot::downcast(element).ok_or(Error::InvalidState)
}, },
// Step 9 // Step 9
Some(ConstructionStackEntry::Element(element)) => { Some(ConstructionStackEntry::Element(element)) => {
@ -315,7 +315,7 @@ pub unsafe fn html_constructor<T>(window: &Window, call_args: &CallArgs) -> Fall
construction_stack.push(ConstructionStackEntry::AlreadyConstructedMarker); construction_stack.push(ConstructionStackEntry::AlreadyConstructedMarker);
// Step 13 // Step 13
Root::downcast(element).ok_or(Error::InvalidState) DomRoot::downcast(element).ok_or(Error::InvalidState)
}, },
// Step 10 // Step 10
Some(ConstructionStackEntry::AlreadyConstructedMarker) => Err(Error::InvalidState), Some(ConstructionStackEntry::AlreadyConstructedMarker) => Err(Error::InvalidState),

View file

@ -10,8 +10,8 @@ use core::nonzero::NonZero;
use dom::bindings::codegen::Bindings::IterableIteratorBinding::IterableKeyAndValueResult; use dom::bindings::codegen::Bindings::IterableIteratorBinding::IterableKeyAndValueResult;
use dom::bindings::codegen::Bindings::IterableIteratorBinding::IterableKeyOrValueResult; use dom::bindings::codegen::Bindings::IterableIteratorBinding::IterableKeyOrValueResult;
use dom::bindings::error::Fallible; use dom::bindings::error::Fallible;
use dom::bindings::js::{JS, Root};
use dom::bindings::reflector::{DomObject, Reflector, reflect_dom_object}; use dom::bindings::reflector::{DomObject, Reflector, reflect_dom_object};
use dom::bindings::root::{Dom, DomRoot};
use dom::bindings::trace::JSTraceable; use dom::bindings::trace::JSTraceable;
use dom::globalscope::GlobalScope; use dom::globalscope::GlobalScope;
use dom_struct::dom_struct; use dom_struct::dom_struct;
@ -51,7 +51,7 @@ pub trait Iterable {
#[dom_struct] #[dom_struct]
pub struct IterableIterator<T: DomObject + JSTraceable + Iterable> { pub struct IterableIterator<T: DomObject + JSTraceable + Iterable> {
reflector: Reflector, reflector: Reflector,
iterable: JS<T>, iterable: Dom<T>,
type_: IteratorType, type_: IteratorType,
index: Cell<u32>, index: Cell<u32>,
} }
@ -61,11 +61,11 @@ impl<T: DomObject + JSTraceable + Iterable> IterableIterator<T> {
pub fn new(iterable: &T, pub fn new(iterable: &T,
type_: IteratorType, type_: IteratorType,
wrap: unsafe fn(*mut JSContext, &GlobalScope, Box<IterableIterator<T>>) wrap: unsafe fn(*mut JSContext, &GlobalScope, Box<IterableIterator<T>>)
-> Root<Self>) -> Root<Self> { -> DomRoot<Self>) -> DomRoot<Self> {
let iterator = box IterableIterator { let iterator = box IterableIterator {
reflector: Reflector::new(), reflector: Reflector::new(),
type_: type_, type_: type_,
iterable: JS::from_ref(iterable), iterable: Dom::from_ref(iterable),
index: Cell::new(0), index: Cell::new(0),
}; };
reflect_dom_object(iterator, &*iterable.global(), wrap) reflect_dom_object(iterator, &*iterable.global(), wrap)

View file

@ -142,13 +142,13 @@ pub mod guard;
pub mod inheritance; pub mod inheritance;
pub mod interface; pub mod interface;
pub mod iterable; pub mod iterable;
pub mod js;
pub mod mozmap; pub mod mozmap;
pub mod namespace; pub mod namespace;
pub mod num; pub mod num;
pub mod proxyhandler; pub mod proxyhandler;
pub mod refcounted; pub mod refcounted;
pub mod reflector; pub mod reflector;
pub mod root;
pub mod settings_stack; pub mod settings_stack;
pub mod str; pub mod str;
pub mod structuredclone; pub mod structuredclone;

View file

@ -25,8 +25,8 @@
use core::nonzero::NonZero; use core::nonzero::NonZero;
use dom::bindings::conversions::ToJSValConvertible; use dom::bindings::conversions::ToJSValConvertible;
use dom::bindings::error::Error; use dom::bindings::error::Error;
use dom::bindings::js::Root;
use dom::bindings::reflector::{DomObject, Reflector}; use dom::bindings::reflector::{DomObject, Reflector};
use dom::bindings::root::DomRoot;
use dom::bindings::trace::trace_reflector; use dom::bindings::trace::trace_reflector;
use dom::promise::Promise; use dom::promise::Promise;
use js::jsapi::JSTracer; use js::jsapi::JSTracer;
@ -178,14 +178,14 @@ impl<T: DomObject> Trusted<T> {
/// Obtain a usable DOM pointer from a pinned `Trusted<T>` value. Fails if used on /// Obtain a usable DOM pointer from a pinned `Trusted<T>` value. Fails if used on
/// a different thread than the original value from which this `Trusted<T>` was /// a different thread than the original value from which this `Trusted<T>` was
/// obtained. /// obtained.
pub fn root(&self) -> Root<T> { pub fn root(&self) -> DomRoot<T> {
assert!(LIVE_REFERENCES.with(|ref r| { assert!(LIVE_REFERENCES.with(|ref r| {
let r = r.borrow(); let r = r.borrow();
let live_references = r.as_ref().unwrap(); let live_references = r.as_ref().unwrap();
self.owner_thread == (&*live_references) as *const _ as *const libc::c_void self.owner_thread == (&*live_references) as *const _ as *const libc::c_void
})); }));
unsafe { unsafe {
Root::new(NonZero::new_unchecked(self.refcount.0 as *const T)) DomRoot::new(NonZero::new_unchecked(self.refcount.0 as *const T))
} }
} }
} }

View file

@ -5,7 +5,7 @@
//! The `Reflector` struct. //! The `Reflector` struct.
use dom::bindings::conversions::DerivedFrom; use dom::bindings::conversions::DerivedFrom;
use dom::bindings::js::Root; use dom::bindings::root::DomRoot;
use dom::globalscope::GlobalScope; use dom::globalscope::GlobalScope;
use js::jsapi::{HandleObject, JSContext, JSObject, Heap}; use js::jsapi::{HandleObject, JSContext, JSObject, Heap};
use std::default::Default; use std::default::Default;
@ -15,8 +15,8 @@ use std::default::Default;
pub fn reflect_dom_object<T, U>( pub fn reflect_dom_object<T, U>(
obj: Box<T>, obj: Box<T>,
global: &U, global: &U,
wrap_fn: unsafe fn(*mut JSContext, &GlobalScope, Box<T>) -> Root<T>) wrap_fn: unsafe fn(*mut JSContext, &GlobalScope, Box<T>) -> DomRoot<T>)
-> Root<T> -> DomRoot<T>
where T: DomObject, U: DerivedFrom<GlobalScope> where T: DomObject, U: DerivedFrom<GlobalScope>
{ {
let global_scope = global.upcast(); let global_scope = global.upcast();
@ -77,7 +77,7 @@ pub trait DomObject {
fn reflector(&self) -> &Reflector; fn reflector(&self) -> &Reflector;
/// Returns the global scope of the realm that the DomObject was created in. /// Returns the global scope of the realm that the DomObject was created in.
fn global(&self) -> Root<GlobalScope> where Self: Sized { fn global(&self) -> DomRoot<GlobalScope> where Self: Sized {
GlobalScope::from_reflector(self) GlobalScope::from_reflector(self)
} }
} }

View file

@ -11,16 +11,16 @@
//! //!
//! Here is a brief overview of the important types: //! Here is a brief overview of the important types:
//! //!
//! - `Root<T>`: a stack-based reference to a rooted DOM object. //! - `DomRoot<T>`: a stack-based reference to a rooted DOM object.
//! - `JS<T>`: a reference to a DOM object that can automatically be traced by //! - `Dom<T>`: a reference to a DOM object that can automatically be traced by
//! the GC when encountered as a field of a Rust structure. //! the GC when encountered as a field of a Rust structure.
//! //!
//! `JS<T>` does not allow access to their inner value without explicitly //! `Dom<T>` does not allow access to their inner value without explicitly
//! creating a stack-based root via the `root` method. This returns a `Root<T>`, //! creating a stack-based root via the `root` method. This returns a `DomRoot<T>`,
//! which causes the JS-owned value to be uncollectable for the duration of the //! which causes the JS-owned value to be uncollectable for the duration of the
//! `Root` object's lifetime. A reference to the object can then be obtained //! `Root` object's lifetime. A reference to the object can then be obtained
//! from the `Root` object. These references are not allowed to outlive their //! from the `Root` object. These references are not allowed to outlive their
//! originating `Root<T>`. //! originating `DomRoot<T>`.
//! //!
use core::nonzero::NonZero; use core::nonzero::NonZero;
@ -50,63 +50,63 @@ use style::thread_state;
/// A traced reference to a DOM object /// A traced reference to a DOM object
/// ///
/// This type is critical to making garbage collection work with the DOM, /// This type is critical to making garbage collection work with the DOM,
/// but it is very dangerous; if garbage collection happens with a `JS<T>` /// but it is very dangerous; if garbage collection happens with a `Dom<T>`
/// on the stack, the `JS<T>` can point to freed memory. /// on the stack, the `Dom<T>` can point to freed memory.
/// ///
/// This should only be used as a field in other DOM objects. /// This should only be used as a field in other DOM objects.
#[must_root] #[must_root]
pub struct JS<T> { pub struct Dom<T> {
ptr: NonZero<*const T>, ptr: NonZero<*const T>,
} }
// JS<T> is similar to Rc<T>, in that it's not always clear how to avoid double-counting. // Dom<T> is similar to Rc<T>, in that it's not always clear how to avoid double-counting.
// For now, we choose not to follow any such pointers. // For now, we choose not to follow any such pointers.
impl<T> HeapSizeOf for JS<T> { impl<T> HeapSizeOf for Dom<T> {
fn heap_size_of_children(&self) -> usize { fn heap_size_of_children(&self) -> usize {
0 0
} }
} }
impl<T> JS<T> { impl<T> Dom<T> {
/// Returns `LayoutJS<T>` containing the same pointer. /// Returns `LayoutDom<T>` containing the same pointer.
pub unsafe fn to_layout(&self) -> LayoutJS<T> { pub unsafe fn to_layout(&self) -> LayoutDom<T> {
debug_assert!(thread_state::get().is_layout()); debug_assert!(thread_state::get().is_layout());
LayoutJS { LayoutDom {
ptr: self.ptr.clone(), ptr: self.ptr.clone(),
} }
} }
} }
impl<T: DomObject> JS<T> { impl<T: DomObject> Dom<T> {
/// Create a JS<T> from a &T /// Create a Dom<T> from a &T
#[allow(unrooted_must_root)] #[allow(unrooted_must_root)]
pub fn from_ref(obj: &T) -> JS<T> { pub fn from_ref(obj: &T) -> Dom<T> {
debug_assert!(thread_state::get().is_script()); debug_assert!(thread_state::get().is_script());
JS { Dom {
ptr: unsafe { NonZero::new_unchecked(&*obj) }, ptr: unsafe { NonZero::new_unchecked(&*obj) },
} }
} }
} }
impl<'root, T: DomObject + 'root> RootedReference<'root> for JS<T> { impl<'root, T: DomObject + 'root> RootedReference<'root> for Dom<T> {
type Ref = &'root T; type Ref = &'root T;
fn r(&'root self) -> &'root T { fn r(&'root self) -> &'root T {
&self &self
} }
} }
impl<T: DomObject> Deref for JS<T> { impl<T: DomObject> Deref for Dom<T> {
type Target = T; type Target = T;
fn deref(&self) -> &T { fn deref(&self) -> &T {
debug_assert!(thread_state::get().is_script()); debug_assert!(thread_state::get().is_script());
// We can only have &JS<T> from a rooted thing, so it's safe to deref // We can only have &Dom<T> from a rooted thing, so it's safe to deref
// it to &T. // it to &T.
unsafe { &*self.ptr.get() } unsafe { &*self.ptr.get() }
} }
} }
unsafe impl<T: DomObject> JSTraceable for JS<T> { unsafe impl<T: DomObject> JSTraceable for Dom<T> {
unsafe fn trace(&self, trc: *mut JSTracer) { unsafe fn trace(&self, trc: *mut JSTracer) {
#[cfg(debug_assertions)] #[cfg(debug_assertions)]
let trace_str = format!("for {} on heap", type_name::<T>()); let trace_str = format!("for {} on heap", type_name::<T>());
@ -124,32 +124,32 @@ unsafe impl<T: DomObject> JSTraceable for JS<T> {
/// An unrooted reference to a DOM object for use in layout. `Layout*Helpers` /// An unrooted reference to a DOM object for use in layout. `Layout*Helpers`
/// traits must be implemented on this. /// traits must be implemented on this.
#[allow_unrooted_interior] #[allow_unrooted_interior]
pub struct LayoutJS<T> { pub struct LayoutDom<T> {
ptr: NonZero<*const T>, ptr: NonZero<*const T>,
} }
impl<T: Castable> LayoutJS<T> { impl<T: Castable> LayoutDom<T> {
/// Cast a DOM object root upwards to one of the interfaces it derives from. /// Cast a DOM object root upwards to one of the interfaces it derives from.
pub fn upcast<U>(&self) -> LayoutJS<U> pub fn upcast<U>(&self) -> LayoutDom<U>
where U: Castable, where U: Castable,
T: DerivedFrom<U> T: DerivedFrom<U>
{ {
debug_assert!(thread_state::get().is_layout()); debug_assert!(thread_state::get().is_layout());
let ptr: *const T = self.ptr.get(); let ptr: *const T = self.ptr.get();
LayoutJS { LayoutDom {
ptr: unsafe { NonZero::new_unchecked(ptr as *const U) }, ptr: unsafe { NonZero::new_unchecked(ptr as *const U) },
} }
} }
/// Cast a DOM object downwards to one of the interfaces it might implement. /// Cast a DOM object downwards to one of the interfaces it might implement.
pub fn downcast<U>(&self) -> Option<LayoutJS<U>> pub fn downcast<U>(&self) -> Option<LayoutDom<U>>
where U: DerivedFrom<T> where U: DerivedFrom<T>
{ {
debug_assert!(thread_state::get().is_layout()); debug_assert!(thread_state::get().is_layout());
unsafe { unsafe {
if (*self.unsafe_get()).is::<U>() { if (*self.unsafe_get()).is::<U>() {
let ptr: *const T = self.ptr.get(); let ptr: *const T = self.ptr.get();
Some(LayoutJS { Some(LayoutDom {
ptr: NonZero::new_unchecked(ptr as *const U), ptr: NonZero::new_unchecked(ptr as *const U),
}) })
} else { } else {
@ -159,7 +159,7 @@ impl<T: Castable> LayoutJS<T> {
} }
} }
impl<T: DomObject> LayoutJS<T> { impl<T: DomObject> LayoutDom<T> {
/// Get the reflector. /// Get the reflector.
pub unsafe fn get_jsobject(&self) -> *mut JSObject { pub unsafe fn get_jsobject(&self) -> *mut JSObject {
debug_assert!(thread_state::get().is_layout()); debug_assert!(thread_state::get().is_layout());
@ -167,114 +167,114 @@ impl<T: DomObject> LayoutJS<T> {
} }
} }
impl<T> Copy for LayoutJS<T> {} impl<T> Copy for LayoutDom<T> {}
impl<T> PartialEq for JS<T> { impl<T> PartialEq for Dom<T> {
fn eq(&self, other: &JS<T>) -> bool { fn eq(&self, other: &Dom<T>) -> bool {
self.ptr == other.ptr self.ptr == other.ptr
} }
} }
impl<T> Eq for JS<T> {} impl<T> Eq for Dom<T> {}
impl<T> PartialEq for LayoutJS<T> { impl<T> PartialEq for LayoutDom<T> {
fn eq(&self, other: &LayoutJS<T>) -> bool { fn eq(&self, other: &LayoutDom<T>) -> bool {
self.ptr == other.ptr self.ptr == other.ptr
} }
} }
impl<T> Eq for LayoutJS<T> {} impl<T> Eq for LayoutDom<T> {}
impl<T> Hash for JS<T> { impl<T> Hash for Dom<T> {
fn hash<H: Hasher>(&self, state: &mut H) { fn hash<H: Hasher>(&self, state: &mut H) {
self.ptr.hash(state) self.ptr.hash(state)
} }
} }
impl<T> Hash for LayoutJS<T> { impl<T> Hash for LayoutDom<T> {
fn hash<H: Hasher>(&self, state: &mut H) { fn hash<H: Hasher>(&self, state: &mut H) {
self.ptr.hash(state) self.ptr.hash(state)
} }
} }
impl <T> Clone for JS<T> { impl <T> Clone for Dom<T> {
#[inline] #[inline]
#[allow(unrooted_must_root)] #[allow(unrooted_must_root)]
fn clone(&self) -> JS<T> { fn clone(&self) -> Dom<T> {
debug_assert!(thread_state::get().is_script()); debug_assert!(thread_state::get().is_script());
JS { Dom {
ptr: self.ptr.clone(), ptr: self.ptr.clone(),
} }
} }
} }
impl <T> Clone for LayoutJS<T> { impl <T> Clone for LayoutDom<T> {
#[inline] #[inline]
fn clone(&self) -> LayoutJS<T> { fn clone(&self) -> LayoutDom<T> {
debug_assert!(thread_state::get().is_layout()); debug_assert!(thread_state::get().is_layout());
LayoutJS { LayoutDom {
ptr: self.ptr.clone(), ptr: self.ptr.clone(),
} }
} }
} }
impl LayoutJS<Node> { impl LayoutDom<Node> {
/// Create a new JS-owned value wrapped from an address known to be a /// Create a new JS-owned value wrapped from an address known to be a
/// `Node` pointer. /// `Node` pointer.
pub unsafe fn from_trusted_node_address(inner: TrustedNodeAddress) -> LayoutJS<Node> { pub unsafe fn from_trusted_node_address(inner: TrustedNodeAddress) -> LayoutDom<Node> {
debug_assert!(thread_state::get().is_layout()); debug_assert!(thread_state::get().is_layout());
let TrustedNodeAddress(addr) = inner; let TrustedNodeAddress(addr) = inner;
LayoutJS { LayoutDom {
ptr: NonZero::new_unchecked(addr as *const Node), ptr: NonZero::new_unchecked(addr as *const Node),
} }
} }
} }
/// A holder that provides interior mutability for GC-managed values such as /// A holder that provides interior mutability for GC-managed values such as
/// `JS<T>`. Essentially a `Cell<JS<T>>`, but safer. /// `Dom<T>`. Essentially a `Cell<Dom<T>>`, but safer.
/// ///
/// This should only be used as a field in other DOM objects; see warning /// This should only be used as a field in other DOM objects; see warning
/// on `JS<T>`. /// on `Dom<T>`.
#[must_root] #[must_root]
#[derive(JSTraceable)] #[derive(JSTraceable)]
pub struct MutJS<T: DomObject> { pub struct MutDom<T: DomObject> {
val: UnsafeCell<JS<T>>, val: UnsafeCell<Dom<T>>,
} }
impl<T: DomObject> MutJS<T> { impl<T: DomObject> MutDom<T> {
/// Create a new `MutJS`. /// Create a new `MutDom`.
pub fn new(initial: &T) -> MutJS<T> { pub fn new(initial: &T) -> MutDom<T> {
debug_assert!(thread_state::get().is_script()); debug_assert!(thread_state::get().is_script());
MutJS { MutDom {
val: UnsafeCell::new(JS::from_ref(initial)), val: UnsafeCell::new(Dom::from_ref(initial)),
} }
} }
/// Set this `MutJS` to the given value. /// Set this `MutDom` to the given value.
pub fn set(&self, val: &T) { pub fn set(&self, val: &T) {
debug_assert!(thread_state::get().is_script()); debug_assert!(thread_state::get().is_script());
unsafe { unsafe {
*self.val.get() = JS::from_ref(val); *self.val.get() = Dom::from_ref(val);
} }
} }
/// Get the value in this `MutJS`. /// Get the value in this `MutDom`.
pub fn get(&self) -> Root<T> { pub fn get(&self) -> DomRoot<T> {
debug_assert!(thread_state::get().is_script()); debug_assert!(thread_state::get().is_script());
unsafe { unsafe {
Root::from_ref(&*ptr::read(self.val.get())) DomRoot::from_ref(&*ptr::read(self.val.get()))
} }
} }
} }
impl<T: DomObject> HeapSizeOf for MutJS<T> { impl<T: DomObject> HeapSizeOf for MutDom<T> {
fn heap_size_of_children(&self) -> usize { fn heap_size_of_children(&self) -> usize {
// See comment on HeapSizeOf for JS<T>. // See comment on HeapSizeOf for Dom<T>.
0 0
} }
} }
impl<T: DomObject> PartialEq for MutJS<T> { impl<T: DomObject> PartialEq for MutDom<T> {
fn eq(&self, other: &Self) -> bool { fn eq(&self, other: &Self) -> bool {
unsafe { unsafe {
*self.val.get() == *other.val.get() *self.val.get() == *other.val.get()
@ -282,7 +282,7 @@ impl<T: DomObject> PartialEq for MutJS<T> {
} }
} }
impl<T: DomObject + PartialEq> PartialEq<T> for MutJS<T> { impl<T: DomObject + PartialEq> PartialEq<T> for MutDom<T> {
fn eq(&self, other: &T) -> bool { fn eq(&self, other: &T) -> bool {
unsafe { unsafe {
**self.val.get() == *other **self.val.get() == *other
@ -291,30 +291,30 @@ impl<T: DomObject + PartialEq> PartialEq<T> for MutJS<T> {
} }
/// A holder that provides interior mutability for GC-managed values such as /// A holder that provides interior mutability for GC-managed values such as
/// `JS<T>`, with nullability represented by an enclosing Option wrapper. /// `Dom<T>`, with nullability represented by an enclosing Option wrapper.
/// Essentially a `Cell<Option<JS<T>>>`, but safer. /// Essentially a `Cell<Option<Dom<T>>>`, but safer.
/// ///
/// This should only be used as a field in other DOM objects; see warning /// This should only be used as a field in other DOM objects; see warning
/// on `JS<T>`. /// on `Dom<T>`.
#[must_root] #[must_root]
#[derive(JSTraceable)] #[derive(JSTraceable)]
pub struct MutNullableJS<T: DomObject> { pub struct MutNullableDom<T: DomObject> {
ptr: UnsafeCell<Option<JS<T>>>, ptr: UnsafeCell<Option<Dom<T>>>,
} }
impl<T: DomObject> MutNullableJS<T> { impl<T: DomObject> MutNullableDom<T> {
/// Create a new `MutNullableJS`. /// Create a new `MutNullableDom`.
pub fn new(initial: Option<&T>) -> MutNullableJS<T> { pub fn new(initial: Option<&T>) -> MutNullableDom<T> {
debug_assert!(thread_state::get().is_script()); debug_assert!(thread_state::get().is_script());
MutNullableJS { MutNullableDom {
ptr: UnsafeCell::new(initial.map(JS::from_ref)), ptr: UnsafeCell::new(initial.map(Dom::from_ref)),
} }
} }
/// Retrieve a copy of the current inner value. If it is `None`, it is /// Retrieve a copy of the current inner value. If it is `None`, it is
/// initialized with the result of `cb` first. /// initialized with the result of `cb` first.
pub fn or_init<F>(&self, cb: F) -> Root<T> pub fn or_init<F>(&self, cb: F) -> DomRoot<T>
where F: FnOnce() -> Root<T> where F: FnOnce() -> DomRoot<T>
{ {
debug_assert!(thread_state::get().is_script()); debug_assert!(thread_state::get().is_script());
match self.get() { match self.get() {
@ -327,40 +327,40 @@ impl<T: DomObject> MutNullableJS<T> {
} }
} }
/// Retrieve a copy of the inner optional `JS<T>` as `LayoutJS<T>`. /// Retrieve a copy of the inner optional `Dom<T>` as `LayoutDom<T>`.
/// For use by layout, which can't use safe types like Temporary. /// For use by layout, which can't use safe types like Temporary.
#[allow(unrooted_must_root)] #[allow(unrooted_must_root)]
pub unsafe fn get_inner_as_layout(&self) -> Option<LayoutJS<T>> { pub unsafe fn get_inner_as_layout(&self) -> Option<LayoutDom<T>> {
debug_assert!(thread_state::get().is_layout()); debug_assert!(thread_state::get().is_layout());
ptr::read(self.ptr.get()).map(|js| js.to_layout()) ptr::read(self.ptr.get()).map(|js| js.to_layout())
} }
/// Get a rooted value out of this object /// Get a rooted value out of this object
#[allow(unrooted_must_root)] #[allow(unrooted_must_root)]
pub fn get(&self) -> Option<Root<T>> { pub fn get(&self) -> Option<DomRoot<T>> {
debug_assert!(thread_state::get().is_script()); debug_assert!(thread_state::get().is_script());
unsafe { unsafe {
ptr::read(self.ptr.get()).map(|o| Root::from_ref(&*o)) ptr::read(self.ptr.get()).map(|o| DomRoot::from_ref(&*o))
} }
} }
/// Set this `MutNullableJS` to the given value. /// Set this `MutNullableDom` to the given value.
pub fn set(&self, val: Option<&T>) { pub fn set(&self, val: Option<&T>) {
debug_assert!(thread_state::get().is_script()); debug_assert!(thread_state::get().is_script());
unsafe { unsafe {
*self.ptr.get() = val.map(|p| JS::from_ref(p)); *self.ptr.get() = val.map(|p| Dom::from_ref(p));
} }
} }
/// Gets the current value out of this object and sets it to `None`. /// Gets the current value out of this object and sets it to `None`.
pub fn take(&self) -> Option<Root<T>> { pub fn take(&self) -> Option<DomRoot<T>> {
let value = self.get(); let value = self.get();
self.set(None); self.set(None);
value value
} }
} }
impl<T: DomObject> PartialEq for MutNullableJS<T> { impl<T: DomObject> PartialEq for MutNullableDom<T> {
fn eq(&self, other: &Self) -> bool { fn eq(&self, other: &Self) -> bool {
unsafe { unsafe {
*self.ptr.get() == *other.ptr.get() *self.ptr.get() == *other.ptr.get()
@ -368,73 +368,73 @@ impl<T: DomObject> PartialEq for MutNullableJS<T> {
} }
} }
impl<'a, T: DomObject> PartialEq<Option<&'a T>> for MutNullableJS<T> { impl<'a, T: DomObject> PartialEq<Option<&'a T>> for MutNullableDom<T> {
fn eq(&self, other: &Option<&T>) -> bool { fn eq(&self, other: &Option<&T>) -> bool {
unsafe { unsafe {
*self.ptr.get() == other.map(JS::from_ref) *self.ptr.get() == other.map(Dom::from_ref)
} }
} }
} }
impl<T: DomObject> Default for MutNullableJS<T> { impl<T: DomObject> Default for MutNullableDom<T> {
#[allow(unrooted_must_root)] #[allow(unrooted_must_root)]
fn default() -> MutNullableJS<T> { fn default() -> MutNullableDom<T> {
debug_assert!(thread_state::get().is_script()); debug_assert!(thread_state::get().is_script());
MutNullableJS { MutNullableDom {
ptr: UnsafeCell::new(None), ptr: UnsafeCell::new(None),
} }
} }
} }
impl<T: DomObject> HeapSizeOf for MutNullableJS<T> { impl<T: DomObject> HeapSizeOf for MutNullableDom<T> {
fn heap_size_of_children(&self) -> usize { fn heap_size_of_children(&self) -> usize {
// See comment on HeapSizeOf for JS<T>. // See comment on HeapSizeOf for Dom<T>.
0 0
} }
} }
/// A holder that allows to lazily initialize the value only once /// A holder that allows to lazily initialize the value only once
/// `JS<T>`, using OnceCell /// `Dom<T>`, using OnceCell
/// Essentially a `OnceCell<JS<T>>`. /// Essentially a `OnceCell<Dom<T>>`.
/// ///
/// This should only be used as a field in other DOM objects; see warning /// This should only be used as a field in other DOM objects; see warning
/// on `JS<T>`. /// on `Dom<T>`.
#[must_root] #[must_root]
pub struct OnceCellJS<T: DomObject> { pub struct DomOnceCell<T: DomObject> {
ptr: OnceCell<JS<T>>, ptr: OnceCell<Dom<T>>,
} }
impl<T: DomObject> OnceCellJS<T> { impl<T: DomObject> DomOnceCell<T> {
/// Retrieve a copy of the current inner value. If it is `None`, it is /// Retrieve a copy of the current inner value. If it is `None`, it is
/// initialized with the result of `cb` first. /// initialized with the result of `cb` first.
#[allow(unrooted_must_root)] #[allow(unrooted_must_root)]
pub fn init_once<F>(&self, cb: F) -> &T pub fn init_once<F>(&self, cb: F) -> &T
where F: FnOnce() -> Root<T> where F: FnOnce() -> DomRoot<T>
{ {
debug_assert!(thread_state::get().is_script()); debug_assert!(thread_state::get().is_script());
&self.ptr.init_once(|| JS::from_ref(&cb())) &self.ptr.init_once(|| Dom::from_ref(&cb()))
} }
} }
impl<T: DomObject> Default for OnceCellJS<T> { impl<T: DomObject> Default for DomOnceCell<T> {
#[allow(unrooted_must_root)] #[allow(unrooted_must_root)]
fn default() -> OnceCellJS<T> { fn default() -> DomOnceCell<T> {
debug_assert!(thread_state::get().is_script()); debug_assert!(thread_state::get().is_script());
OnceCellJS { DomOnceCell {
ptr: OnceCell::new(), ptr: OnceCell::new(),
} }
} }
} }
impl<T: DomObject> HeapSizeOf for OnceCellJS<T> { impl<T: DomObject> HeapSizeOf for DomOnceCell<T> {
fn heap_size_of_children(&self) -> usize { fn heap_size_of_children(&self) -> usize {
// See comment on HeapSizeOf for JS<T>. // See comment on HeapSizeOf for Dom<T>.
0 0
} }
} }
#[allow(unrooted_must_root)] #[allow(unrooted_must_root)]
unsafe impl<T: DomObject> JSTraceable for OnceCellJS<T> { unsafe impl<T: DomObject> JSTraceable for DomOnceCell<T> {
unsafe fn trace(&self, trc: *mut JSTracer) { unsafe fn trace(&self, trc: *mut JSTracer) {
if let Some(ptr) = self.ptr.as_ref() { if let Some(ptr) = self.ptr.as_ref() {
ptr.trace(trc); ptr.trace(trc);
@ -442,7 +442,7 @@ unsafe impl<T: DomObject> JSTraceable for OnceCellJS<T> {
} }
} }
impl<T: DomObject> LayoutJS<T> { impl<T: DomObject> LayoutDom<T> {
/// Returns an unsafe pointer to the interior of this JS object. This is /// Returns an unsafe pointer to the interior of this JS object. This is
/// the only method that be safely accessed from layout. (The fact that /// the only method that be safely accessed from layout. (The fact that
/// this is unsafe is what necessitates the layout wrappers.) /// this is unsafe is what necessitates the layout wrappers.)
@ -468,7 +468,7 @@ pub trait RootedReference<'root> {
fn r(&'root self) -> Self::Ref; fn r(&'root self) -> Self::Ref;
} }
impl<'root, T: JSTraceable + DomObject + 'root> RootedReference<'root> for [JS<T>] { impl<'root, T: JSTraceable + DomObject + 'root> RootedReference<'root> for [Dom<T>] {
type Ref = &'root [&'root T]; type Ref = &'root [&'root T];
fn r(&'root self) -> &'root [&'root T] { fn r(&'root self) -> &'root [&'root T] {
unsafe { mem::transmute(self) } unsafe { mem::transmute(self) }
@ -559,16 +559,16 @@ pub unsafe fn trace_roots(tracer: *mut JSTracer) {
/// for the same JS value. `Root`s cannot outlive the associated /// for the same JS value. `Root`s cannot outlive the associated
/// `RootCollection` object. /// `RootCollection` object.
#[allow_unrooted_interior] #[allow_unrooted_interior]
pub struct Root<T: DomObject> { pub struct DomRoot<T: DomObject> {
/// Reference to rooted value that must not outlive this container /// Reference to rooted value that must not outlive this container
ptr: NonZero<*const T>, ptr: NonZero<*const T>,
/// List that ensures correct dynamic root ordering /// List that ensures correct dynamic root ordering
root_list: *const RootCollection, root_list: *const RootCollection,
} }
impl<T: Castable> Root<T> { impl<T: Castable> DomRoot<T> {
/// Cast a DOM object root upwards to one of the interfaces it derives from. /// Cast a DOM object root upwards to one of the interfaces it derives from.
pub fn upcast<U>(root: Root<T>) -> Root<U> pub fn upcast<U>(root: DomRoot<T>) -> DomRoot<U>
where U: Castable, where U: Castable,
T: DerivedFrom<U> T: DerivedFrom<U>
{ {
@ -576,7 +576,7 @@ impl<T: Castable> Root<T> {
} }
/// Cast a DOM object root downwards to one of the interfaces it might implement. /// Cast a DOM object root downwards to one of the interfaces it might implement.
pub fn downcast<U>(root: Root<T>) -> Option<Root<U>> pub fn downcast<U>(root: DomRoot<T>) -> Option<DomRoot<U>>
where U: DerivedFrom<T> where U: DerivedFrom<T>
{ {
if root.is::<U>() { if root.is::<U>() {
@ -587,16 +587,16 @@ impl<T: Castable> Root<T> {
} }
} }
impl<T: DomObject> Root<T> { impl<T: DomObject> DomRoot<T> {
/// Create a new stack-bounded root for the provided JS-owned value. /// Create a new stack-bounded root for the provided JS-owned value.
/// It cannot outlive its associated `RootCollection`, and it gives /// It cannot outlive its associated `RootCollection`, and it gives
/// out references which cannot outlive this new `Root`. /// out references which cannot outlive this new `Root`.
pub fn new(unrooted: NonZero<*const T>) -> Root<T> { pub fn new(unrooted: NonZero<*const T>) -> DomRoot<T> {
debug_assert!(thread_state::get().is_script()); debug_assert!(thread_state::get().is_script());
STACK_ROOTS.with(|ref collection| { STACK_ROOTS.with(|ref collection| {
let RootCollectionPtr(collection) = collection.get().unwrap(); let RootCollectionPtr(collection) = collection.get().unwrap();
unsafe { (*collection).root(&*(*unrooted.get()).reflector()) } unsafe { (*collection).root(&*(*unrooted.get()).reflector()) }
Root { DomRoot {
ptr: unrooted, ptr: unrooted,
root_list: collection, root_list: collection,
} }
@ -604,19 +604,19 @@ impl<T: DomObject> Root<T> {
} }
/// Generate a new root from a reference /// Generate a new root from a reference
pub fn from_ref(unrooted: &T) -> Root<T> { pub fn from_ref(unrooted: &T) -> DomRoot<T> {
Root::new(unsafe { NonZero::new_unchecked(unrooted) }) DomRoot::new(unsafe { NonZero::new_unchecked(unrooted) })
} }
} }
impl<'root, T: DomObject + 'root> RootedReference<'root> for Root<T> { impl<'root, T: DomObject + 'root> RootedReference<'root> for DomRoot<T> {
type Ref = &'root T; type Ref = &'root T;
fn r(&'root self) -> &'root T { fn r(&'root self) -> &'root T {
self self
} }
} }
impl<T: DomObject> Deref for Root<T> { impl<T: DomObject> Deref for DomRoot<T> {
type Target = T; type Target = T;
fn deref(&self) -> &T { fn deref(&self) -> &T {
debug_assert!(thread_state::get().is_script()); debug_assert!(thread_state::get().is_script());
@ -624,25 +624,25 @@ impl<T: DomObject> Deref for Root<T> {
} }
} }
impl<T: DomObject + HeapSizeOf> HeapSizeOf for Root<T> { impl<T: DomObject + HeapSizeOf> HeapSizeOf for DomRoot<T> {
fn heap_size_of_children(&self) -> usize { fn heap_size_of_children(&self) -> usize {
(**self).heap_size_of_children() (**self).heap_size_of_children()
} }
} }
impl<T: DomObject> PartialEq for Root<T> { impl<T: DomObject> PartialEq for DomRoot<T> {
fn eq(&self, other: &Self) -> bool { fn eq(&self, other: &Self) -> bool {
self.ptr == other.ptr self.ptr == other.ptr
} }
} }
impl<T: DomObject> Clone for Root<T> { impl<T: DomObject> Clone for DomRoot<T> {
fn clone(&self) -> Root<T> { fn clone(&self) -> DomRoot<T> {
Root::from_ref(&*self) DomRoot::from_ref(&*self)
} }
} }
impl<T: DomObject> Drop for Root<T> { impl<T: DomObject> Drop for DomRoot<T> {
fn drop(&mut self) { fn drop(&mut self) {
unsafe { unsafe {
(*self.root_list).unroot(self.reflector()); (*self.root_list).unroot(self.reflector());
@ -650,7 +650,7 @@ impl<T: DomObject> Drop for Root<T> {
} }
} }
unsafe impl<T: DomObject> JSTraceable for Root<T> { unsafe impl<T: DomObject> JSTraceable for DomRoot<T> {
unsafe fn trace(&self, _: *mut JSTracer) { unsafe fn trace(&self, _: *mut JSTracer) {
// Already traced. // Already traced.
} }

View file

@ -2,7 +2,7 @@
* License, v. 2.0. If a copy of the MPL was not distributed with this * 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/. */ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use dom::bindings::js::{JS, Root}; use dom::bindings::root::{Dom, DomRoot};
use dom::bindings::trace::JSTraceable; use dom::bindings::trace::JSTraceable;
use dom::globalscope::GlobalScope; use dom::globalscope::GlobalScope;
use js::jsapi::GetScriptedCallerGlobal; use js::jsapi::GetScriptedCallerGlobal;
@ -24,7 +24,7 @@ enum StackEntryKind {
#[allow(unrooted_must_root)] #[allow(unrooted_must_root)]
#[derive(JSTraceable)] #[derive(JSTraceable)]
struct StackEntry { struct StackEntry {
global: JS<GlobalScope>, global: Dom<GlobalScope>,
kind: StackEntryKind, kind: StackEntryKind,
} }
@ -37,7 +37,7 @@ pub unsafe fn trace(tracer: *mut JSTracer) {
/// RAII struct that pushes and pops entries from the script settings stack. /// RAII struct that pushes and pops entries from the script settings stack.
pub struct AutoEntryScript { pub struct AutoEntryScript {
global: Root<GlobalScope>, global: DomRoot<GlobalScope>,
} }
impl AutoEntryScript { impl AutoEntryScript {
@ -47,11 +47,11 @@ impl AutoEntryScript {
trace!("Prepare to run script with {:p}", global); trace!("Prepare to run script with {:p}", global);
let mut stack = stack.borrow_mut(); let mut stack = stack.borrow_mut();
stack.push(StackEntry { stack.push(StackEntry {
global: JS::from_ref(global), global: Dom::from_ref(global),
kind: StackEntryKind::Entry, kind: StackEntryKind::Entry,
}); });
AutoEntryScript { AutoEntryScript {
global: Root::from_ref(global), global: DomRoot::from_ref(global),
} }
}) })
} }
@ -80,13 +80,13 @@ impl Drop for AutoEntryScript {
/// Returns the ["entry"] global object. /// Returns the ["entry"] global object.
/// ///
/// ["entry"]: https://html.spec.whatwg.org/multipage/#entry /// ["entry"]: https://html.spec.whatwg.org/multipage/#entry
pub fn entry_global() -> Root<GlobalScope> { pub fn entry_global() -> DomRoot<GlobalScope> {
STACK.with(|stack| { STACK.with(|stack| {
stack.borrow() stack.borrow()
.iter() .iter()
.rev() .rev()
.find(|entry| entry.kind == StackEntryKind::Entry) .find(|entry| entry.kind == StackEntryKind::Entry)
.map(|entry| Root::from_ref(&*entry.global)) .map(|entry| DomRoot::from_ref(&*entry.global))
}).unwrap() }).unwrap()
} }
@ -109,7 +109,7 @@ impl AutoIncumbentScript {
// Step 1. // Step 1.
let mut stack = stack.borrow_mut(); let mut stack = stack.borrow_mut();
stack.push(StackEntry { stack.push(StackEntry {
global: JS::from_ref(global), global: Dom::from_ref(global),
kind: StackEntryKind::Incumbent, kind: StackEntryKind::Incumbent,
}); });
AutoIncumbentScript { AutoIncumbentScript {
@ -145,7 +145,7 @@ impl Drop for AutoIncumbentScript {
/// Returns the ["incumbent"] global object. /// Returns the ["incumbent"] global object.
/// ///
/// ["incumbent"]: https://html.spec.whatwg.org/multipage/#incumbent /// ["incumbent"]: https://html.spec.whatwg.org/multipage/#incumbent
pub fn incumbent_global() -> Option<Root<GlobalScope>> { pub fn incumbent_global() -> Option<DomRoot<GlobalScope>> {
// https://html.spec.whatwg.org/multipage/#incumbent-settings-object // https://html.spec.whatwg.org/multipage/#incumbent-settings-object
// Step 1, 3: See what the JS engine has to say. If we've got a scripted // Step 1, 3: See what the JS engine has to say. If we've got a scripted
@ -165,6 +165,6 @@ pub fn incumbent_global() -> Option<Root<GlobalScope>> {
STACK.with(|stack| { STACK.with(|stack| {
stack.borrow() stack.borrow()
.last() .last()
.map(|entry| Root::from_ref(&*entry.global)) .map(|entry| DomRoot::from_ref(&*entry.global))
}) })
} }

View file

@ -7,8 +7,8 @@
use dom::bindings::conversions::root_from_handleobject; use dom::bindings::conversions::root_from_handleobject;
use dom::bindings::error::{Error, Fallible}; use dom::bindings::error::{Error, Fallible};
use dom::bindings::js::Root;
use dom::bindings::reflector::DomObject; use dom::bindings::reflector::DomObject;
use dom::bindings::root::DomRoot;
use dom::blob::{Blob, BlobImpl}; use dom::blob::{Blob, BlobImpl};
use dom::globalscope::GlobalScope; use dom::globalscope::GlobalScope;
use js::jsapi::{Handle, HandleObject, HandleValue, MutableHandleValue, JSAutoCompartment, JSContext}; use js::jsapi::{Handle, HandleObject, HandleValue, MutableHandleValue, JSAutoCompartment, JSContext};
@ -110,7 +110,7 @@ unsafe fn read_blob(cx: *mut JSContext,
return blob.reflector().get_jsobject().get() return blob.reflector().get_jsobject().get()
} }
unsafe fn write_blob(blob: Root<Blob>, unsafe fn write_blob(blob: DomRoot<Blob>,
w: *mut JSStructuredCloneWriter) w: *mut JSStructuredCloneWriter)
-> Result<(), ()> { -> Result<(), ()> {
let structured_writer = StructuredCloneWriter { w: w }; let structured_writer = StructuredCloneWriter { w: w };

View file

@ -18,9 +18,9 @@
//! achieved via `unsafe_no_jsmanaged_fields!` or similar. //! achieved via `unsafe_no_jsmanaged_fields!` or similar.
//! 3. For all fields, `Foo::trace()` //! 3. For all fields, `Foo::trace()`
//! calls `trace()` on the field. //! calls `trace()` on the field.
//! For example, for fields of type `JS<T>`, `JS<T>::trace()` calls //! For example, for fields of type `Dom<T>`, `Dom<T>::trace()` calls
//! `trace_reflector()`. //! `trace_reflector()`.
//! 4. `trace_reflector()` calls `JS::TraceEdge()` with a //! 4. `trace_reflector()` calls `Dom::TraceEdge()` with a
//! pointer to the `JSObject` for the reflector. This notifies the GC, which //! pointer to the `JSObject` for the reflector. This notifies the GC, which
//! will add the object to the graph, and will trace that object as well. //! will add the object to the graph, and will trace that object as well.
//! 5. When the GC finishes tracing, it [`finalizes`](../index.html#destruction) //! 5. When the GC finishes tracing, it [`finalizes`](../index.html#destruction)
@ -38,11 +38,11 @@ use canvas_traits::webgl::{WebGLReceiver, WebGLSender, WebGLShaderId, WebGLTextu
use cssparser::RGBA; use cssparser::RGBA;
use devtools_traits::{CSSError, TimelineMarkerType, WorkerId}; use devtools_traits::{CSSError, TimelineMarkerType, WorkerId};
use dom::abstractworker::SharedRt; use dom::abstractworker::SharedRt;
use dom::bindings::cell::DOMRefCell; use dom::bindings::cell::DomRefCell;
use dom::bindings::error::Error; use dom::bindings::error::Error;
use dom::bindings::js::{JS, Root};
use dom::bindings::refcounted::{Trusted, TrustedPromise}; use dom::bindings::refcounted::{Trusted, TrustedPromise};
use dom::bindings::reflector::{DomObject, Reflector}; use dom::bindings::reflector::{DomObject, Reflector};
use dom::bindings::root::{Dom, DomRoot};
use dom::bindings::str::{DOMString, USVString}; use dom::bindings::str::{DOMString, USVString};
use dom::bindings::utils::WindowProxyHandler; use dom::bindings::utils::WindowProxyHandler;
use dom::document::PendingRestyle; use dom::document::PendingRestyle;
@ -202,7 +202,7 @@ unsafe impl<T: JSTraceable> JSTraceable for UnsafeCell<T> {
} }
} }
unsafe impl<T: JSTraceable> JSTraceable for DOMRefCell<T> { unsafe impl<T: JSTraceable> JSTraceable for DomRefCell<T> {
unsafe fn trace(&self, trc: *mut JSTracer) { unsafe fn trace(&self, trc: *mut JSTracer) {
(*self).borrow_for_gc_trace().trace(trc) (*self).borrow_for_gc_trace().trace(trc)
} }
@ -710,7 +710,7 @@ impl RootedTraceableSet {
/// Roots any JSTraceable thing /// Roots any JSTraceable thing
/// ///
/// If you have a valid DomObject, use Root. /// If you have a valid DomObject, use DomRoot.
/// If you have GC things like *mut JSObject or JSVal, use rooted!. /// If you have GC things like *mut JSObject or JSVal, use rooted!.
/// If you have an arbitrary number of DomObjects to root, use rooted_vec!. /// If you have an arbitrary number of DomObjects to root, use rooted_vec!.
/// If you know what you're doing, use this. /// If you know what you're doing, use this.
@ -720,7 +720,7 @@ pub struct RootedTraceable<'a, T: 'static + JSTraceable> {
} }
impl<'a, T: JSTraceable + 'static> RootedTraceable<'a, T> { impl<'a, T: JSTraceable + 'static> RootedTraceable<'a, T> {
/// Root a JSTraceable thing for the life of this RootedTraceable /// DomRoot a JSTraceable thing for the life of this RootedTraceable
pub fn new(traceable: &'a T) -> RootedTraceable<'a, T> { pub fn new(traceable: &'a T) -> RootedTraceable<'a, T> {
unsafe { unsafe {
RootedTraceableSet::add(traceable); RootedTraceableSet::add(traceable);
@ -741,7 +741,7 @@ impl<'a, T: JSTraceable + 'static> Drop for RootedTraceable<'a, T> {
/// Roots any JSTraceable thing /// Roots any JSTraceable thing
/// ///
/// If you have a valid DomObject, use Root. /// If you have a valid DomObject, use DomRoot.
/// If you have GC things like *mut JSObject or JSVal, use rooted!. /// If you have GC things like *mut JSObject or JSVal, use rooted!.
/// If you have an arbitrary number of DomObjects to root, use rooted_vec!. /// If you have an arbitrary number of DomObjects to root, use rooted_vec!.
/// If you know what you're doing, use this. /// If you know what you're doing, use this.
@ -757,7 +757,7 @@ unsafe impl<T: JSTraceable + 'static> JSTraceable for RootedTraceableBox<T> {
} }
impl<T: JSTraceable + 'static> RootedTraceableBox<T> { impl<T: JSTraceable + 'static> RootedTraceableBox<T> {
/// Root a JSTraceable thing for the life of this RootedTraceable /// DomRoot a JSTraceable thing for the life of this RootedTraceable
pub fn new(traceable: T) -> RootedTraceableBox<T> { pub fn new(traceable: T) -> RootedTraceableBox<T> {
let traceable = Box::into_raw(box traceable); let traceable = Box::into_raw(box traceable);
unsafe { unsafe {
@ -804,7 +804,7 @@ impl<T: JSTraceable + 'static> Drop for RootedTraceableBox<T> {
/// A vector of items to be rooted with `RootedVec`. /// A vector of items to be rooted with `RootedVec`.
/// Guaranteed to be empty when not rooted. /// Guaranteed to be empty when not rooted.
/// Usage: `rooted_vec!(let mut v);` or if you have an /// Usage: `rooted_vec!(let mut v);` or if you have an
/// iterator of `Root`s, `rooted_vec!(let v <- iterator);`. /// iterator of `DomRoot`s, `rooted_vec!(let v <- iterator);`.
#[allow(unrooted_must_root)] #[allow(unrooted_must_root)]
#[derive(JSTraceable)] #[derive(JSTraceable)]
#[allow_unrooted_interior] #[allow_unrooted_interior]
@ -840,16 +840,16 @@ impl<'a, T: 'static + JSTraceable> RootedVec<'a, T> {
} }
} }
impl<'a, T: 'static + JSTraceable + DomObject> RootedVec<'a, JS<T>> { impl<'a, T: 'static + JSTraceable + DomObject> RootedVec<'a, Dom<T>> {
/// Create a vector of items of type JS<T> that is rooted for /// Create a vector of items of type Dom<T> that is rooted for
/// the lifetime of this struct /// the lifetime of this struct
pub fn from_iter<I>(root: &'a mut RootableVec<JS<T>>, iter: I) -> Self pub fn from_iter<I>(root: &'a mut RootableVec<Dom<T>>, iter: I) -> Self
where I: Iterator<Item = Root<T>> where I: Iterator<Item = DomRoot<T>>
{ {
unsafe { unsafe {
RootedTraceableSet::add(root); RootedTraceableSet::add(root);
} }
root.v.extend(iter.map(|item| JS::from_ref(&*item))); root.v.extend(iter.map(|item| Dom::from_ref(&*item)));
RootedVec { RootedVec {
root: root, root: root,
} }

View file

@ -12,8 +12,8 @@
//! `WeakBox` itself is dropped too. //! `WeakBox` itself is dropped too.
use core::nonzero::NonZero; use core::nonzero::NonZero;
use dom::bindings::js::Root;
use dom::bindings::reflector::DomObject; use dom::bindings::reflector::DomObject;
use dom::bindings::root::DomRoot;
use dom::bindings::trace::JSTraceable; use dom::bindings::trace::JSTraceable;
use heapsize::HeapSizeOf; use heapsize::HeapSizeOf;
use js::jsapi::{JSTracer, JS_GetReservedSlot, JS_SetReservedSlot}; use js::jsapi::{JSTracer, JS_GetReservedSlot, JS_SetReservedSlot};
@ -84,9 +84,9 @@ impl<T: WeakReferenceable> WeakRef<T> {
value.downgrade() value.downgrade()
} }
/// Root a weak reference. Returns `None` if the object was already collected. /// DomRoot a weak reference. Returns `None` if the object was already collected.
pub fn root(&self) -> Option<Root<T>> { pub fn root(&self) -> Option<DomRoot<T>> {
unsafe { &*self.ptr.get() }.value.get().map(Root::new) unsafe { &*self.ptr.get() }.value.get().map(DomRoot::new)
} }
/// Return whether the weakly-referenced object is still alive. /// Return whether the weakly-referenced object is still alive.
@ -179,9 +179,9 @@ impl<T: WeakReferenceable> MutableWeakRef<T> {
} }
} }
/// Root a mutable weak reference. Returns `None` if the object /// DomRoot a mutable weak reference. Returns `None` if the object
/// was already collected. /// was already collected.
pub fn root(&self) -> Option<Root<T>> { pub fn root(&self) -> Option<DomRoot<T>> {
unsafe { &*self.cell.get() }.as_ref().and_then(WeakRef::root) unsafe { &*self.cell.get() }.as_ref().and_then(WeakRef::root)
} }
} }

View file

@ -2,13 +2,13 @@
* License, v. 2.0. If a copy of the MPL was not distributed with this * 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/. */ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use dom::bindings::cell::DOMRefCell; use dom::bindings::cell::DomRefCell;
use dom::bindings::codegen::Bindings::BlobBinding; use dom::bindings::codegen::Bindings::BlobBinding;
use dom::bindings::codegen::Bindings::BlobBinding::BlobMethods; use dom::bindings::codegen::Bindings::BlobBinding::BlobMethods;
use dom::bindings::codegen::UnionTypes::BlobOrString; use dom::bindings::codegen::UnionTypes::BlobOrString;
use dom::bindings::error::{Error, Fallible}; use dom::bindings::error::{Error, Fallible};
use dom::bindings::js::{JS, Root};
use dom::bindings::reflector::{DomObject, Reflector, reflect_dom_object}; use dom::bindings::reflector::{DomObject, Reflector, reflect_dom_object};
use dom::bindings::root::{Dom, DomRoot};
use dom::bindings::str::DOMString; use dom::bindings::str::DOMString;
use dom::globalscope::GlobalScope; use dom::globalscope::GlobalScope;
use dom_struct::dom_struct; use dom_struct::dom_struct;
@ -27,7 +27,7 @@ use uuid::Uuid;
pub struct FileBlob { pub struct FileBlob {
id: Uuid, id: Uuid,
name: Option<PathBuf>, name: Option<PathBuf>,
cache: DOMRefCell<Option<Vec<u8>>>, cache: DomRefCell<Option<Vec<u8>>>,
size: u64, size: u64,
} }
@ -44,7 +44,7 @@ pub enum BlobImpl {
/// relative positions of current slicing range, /// relative positions of current slicing range,
/// IMPORTANT: The depth of tree is only two, i.e. the parent Blob must be /// IMPORTANT: The depth of tree is only two, i.e. the parent Blob must be
/// either File-based or Memory-based /// either File-based or Memory-based
Sliced(JS<Blob>, RelativePos), Sliced(Dom<Blob>, RelativePos),
} }
impl BlobImpl { impl BlobImpl {
@ -59,7 +59,7 @@ impl BlobImpl {
BlobImpl::File(FileBlob { BlobImpl::File(FileBlob {
id: file_id, id: file_id,
name: Some(name), name: Some(name),
cache: DOMRefCell::new(None), cache: DomRefCell::new(None),
size: size, size: size,
}) })
} }
@ -70,7 +70,7 @@ impl BlobImpl {
pub struct Blob { pub struct Blob {
reflector_: Reflector, reflector_: Reflector,
#[ignore_heap_size_of = "No clear owner"] #[ignore_heap_size_of = "No clear owner"]
blob_impl: DOMRefCell<BlobImpl>, blob_impl: DomRefCell<BlobImpl>,
/// content-type string /// content-type string
type_string: String, type_string: String,
} }
@ -79,7 +79,7 @@ impl Blob {
#[allow(unrooted_must_root)] #[allow(unrooted_must_root)]
pub fn new( pub fn new(
global: &GlobalScope, blob_impl: BlobImpl, typeString: String) global: &GlobalScope, blob_impl: BlobImpl, typeString: String)
-> Root<Blob> { -> DomRoot<Blob> {
let boxed_blob = box Blob::new_inherited(blob_impl, typeString); let boxed_blob = box Blob::new_inherited(blob_impl, typeString);
reflect_dom_object(boxed_blob, global, BlobBinding::Wrap) reflect_dom_object(boxed_blob, global, BlobBinding::Wrap)
} }
@ -88,7 +88,7 @@ impl Blob {
pub fn new_inherited(blob_impl: BlobImpl, type_string: String) -> Blob { pub fn new_inherited(blob_impl: BlobImpl, type_string: String) -> Blob {
Blob { Blob {
reflector_: Reflector::new(), reflector_: Reflector::new(),
blob_impl: DOMRefCell::new(blob_impl), blob_impl: DomRefCell::new(blob_impl),
// NOTE: Guarding the format correctness here, // NOTE: Guarding the format correctness here,
// https://w3c.github.io/FileAPI/#dfn-type // https://w3c.github.io/FileAPI/#dfn-type
type_string: normalize_type_string(&type_string), type_string: normalize_type_string(&type_string),
@ -97,15 +97,15 @@ impl Blob {
#[allow(unrooted_must_root)] #[allow(unrooted_must_root)]
fn new_sliced(parent: &Blob, rel_pos: RelativePos, fn new_sliced(parent: &Blob, rel_pos: RelativePos,
relative_content_type: DOMString) -> Root<Blob> { relative_content_type: DOMString) -> DomRoot<Blob> {
let blob_impl = match *parent.blob_impl.borrow() { let blob_impl = match *parent.blob_impl.borrow() {
BlobImpl::File(_) => { BlobImpl::File(_) => {
// Create new parent node // Create new parent node
BlobImpl::Sliced(JS::from_ref(parent), rel_pos) BlobImpl::Sliced(Dom::from_ref(parent), rel_pos)
} }
BlobImpl::Memory(_) => { BlobImpl::Memory(_) => {
// Create new parent node // Create new parent node
BlobImpl::Sliced(JS::from_ref(parent), rel_pos) BlobImpl::Sliced(Dom::from_ref(parent), rel_pos)
} }
BlobImpl::Sliced(ref grandparent, ref old_rel_pos) => { BlobImpl::Sliced(ref grandparent, ref old_rel_pos) => {
// Adjust the slicing position, using same parent // Adjust the slicing position, using same parent
@ -120,7 +120,7 @@ impl Blob {
pub fn Constructor(global: &GlobalScope, pub fn Constructor(global: &GlobalScope,
blobParts: Option<Vec<BlobOrString>>, blobParts: Option<Vec<BlobOrString>>,
blobPropertyBag: &BlobBinding::BlobPropertyBag) blobPropertyBag: &BlobBinding::BlobPropertyBag)
-> Fallible<Root<Blob>> { -> Fallible<DomRoot<Blob>> {
// TODO: accept other blobParts types - ArrayBuffer or ArrayBufferView // TODO: accept other blobParts types - ArrayBuffer or ArrayBufferView
let bytes: Vec<u8> = match blobParts { let bytes: Vec<u8> = match blobParts {
None => Vec::new(), None => Vec::new(),
@ -237,7 +237,7 @@ impl Blob {
*self.blob_impl.borrow_mut() = BlobImpl::File(FileBlob { *self.blob_impl.borrow_mut() = BlobImpl::File(FileBlob {
id: id.clone(), id: id.clone(),
name: None, name: None,
cache: DOMRefCell::new(Some(bytes.to_vec())), cache: DomRefCell::new(Some(bytes.to_vec())),
size: bytes.len() as u64, size: bytes.len() as u64,
}); });
id id
@ -262,7 +262,7 @@ impl Blob {
*self.blob_impl.borrow_mut() = BlobImpl::File(FileBlob { *self.blob_impl.borrow_mut() = BlobImpl::File(FileBlob {
id: new_id.clone(), id: new_id.clone(),
name: None, name: None,
cache: DOMRefCell::new(None), cache: DomRefCell::new(None),
size: rel_pos.to_abs_range(parent_len as usize).len() as u64, size: rel_pos.to_abs_range(parent_len as usize).len() as u64,
}); });
@ -369,7 +369,7 @@ impl BlobMethods for Blob {
start: Option<i64>, start: Option<i64>,
end: Option<i64>, end: Option<i64>,
content_type: Option<DOMString>) content_type: Option<DOMString>)
-> Root<Blob> { -> DomRoot<Blob> {
let rel_pos = RelativePos::from_opts(start, end); let rel_pos = RelativePos::from_opts(start, end);
Blob::new_sliced(self, rel_pos, content_type.unwrap_or(DOMString::from(""))) Blob::new_sliced(self, rel_pos, content_type.unwrap_or(DOMString::from("")))
} }

View file

@ -8,7 +8,7 @@ use bluetooth_traits::blocklist::{Blocklist, uuid_is_blocklisted};
use bluetooth_traits::scanfilter::{BluetoothScanfilter, BluetoothScanfilterSequence}; use bluetooth_traits::scanfilter::{BluetoothScanfilter, BluetoothScanfilterSequence};
use bluetooth_traits::scanfilter::{RequestDeviceoptions, ServiceUUIDSequence}; use bluetooth_traits::scanfilter::{RequestDeviceoptions, ServiceUUIDSequence};
use core::clone::Clone; use core::clone::Clone;
use dom::bindings::cell::DOMRefCell; use dom::bindings::cell::DomRefCell;
use dom::bindings::codegen::Bindings::BluetoothBinding::{self, BluetoothDataFilterInit, BluetoothLEScanFilterInit}; use dom::bindings::codegen::Bindings::BluetoothBinding::{self, BluetoothDataFilterInit, BluetoothLEScanFilterInit};
use dom::bindings::codegen::Bindings::BluetoothBinding::{BluetoothMethods, RequestDeviceOptions}; use dom::bindings::codegen::Bindings::BluetoothBinding::{BluetoothMethods, RequestDeviceOptions};
use dom::bindings::codegen::Bindings::BluetoothPermissionResultBinding::BluetoothPermissionDescriptor; use dom::bindings::codegen::Bindings::BluetoothPermissionResultBinding::BluetoothPermissionDescriptor;
@ -18,9 +18,9 @@ use dom::bindings::codegen::Bindings::PermissionStatusBinding::{PermissionName,
use dom::bindings::codegen::UnionTypes::StringOrUnsignedLong; use dom::bindings::codegen::UnionTypes::StringOrUnsignedLong;
use dom::bindings::error::Error::{self, Network, Security, Type}; use dom::bindings::error::Error::{self, Network, Security, Type};
use dom::bindings::error::Fallible; use dom::bindings::error::Fallible;
use dom::bindings::js::{JS, Root};
use dom::bindings::refcounted::{Trusted, TrustedPromise}; use dom::bindings::refcounted::{Trusted, TrustedPromise};
use dom::bindings::reflector::{DomObject, reflect_dom_object}; use dom::bindings::reflector::{DomObject, reflect_dom_object};
use dom::bindings::root::{Dom, DomRoot};
use dom::bindings::str::DOMString; use dom::bindings::str::DOMString;
use dom::bluetoothdevice::BluetoothDevice; use dom::bluetoothdevice::BluetoothDevice;
use dom::bluetoothpermissionresult::BluetoothPermissionResult; use dom::bluetoothpermissionresult::BluetoothPermissionResult;
@ -65,13 +65,13 @@ pub struct AllowedBluetoothDevice {
#[derive(HeapSizeOf, JSTraceable)] #[derive(HeapSizeOf, JSTraceable)]
pub struct BluetoothExtraPermissionData { pub struct BluetoothExtraPermissionData {
allowed_devices: DOMRefCell<Vec<AllowedBluetoothDevice>>, allowed_devices: DomRefCell<Vec<AllowedBluetoothDevice>>,
} }
impl BluetoothExtraPermissionData { impl BluetoothExtraPermissionData {
pub fn new() -> BluetoothExtraPermissionData { pub fn new() -> BluetoothExtraPermissionData {
BluetoothExtraPermissionData { BluetoothExtraPermissionData {
allowed_devices: DOMRefCell::new(Vec::new()), allowed_devices: DomRefCell::new(Vec::new()),
} }
} }
@ -120,18 +120,18 @@ where
#[dom_struct] #[dom_struct]
pub struct Bluetooth { pub struct Bluetooth {
eventtarget: EventTarget, eventtarget: EventTarget,
device_instance_map: DOMRefCell<HashMap<String, JS<BluetoothDevice>>>, device_instance_map: DomRefCell<HashMap<String, Dom<BluetoothDevice>>>,
} }
impl Bluetooth { impl Bluetooth {
pub fn new_inherited() -> Bluetooth { pub fn new_inherited() -> Bluetooth {
Bluetooth { Bluetooth {
eventtarget: EventTarget::new_inherited(), eventtarget: EventTarget::new_inherited(),
device_instance_map: DOMRefCell::new(HashMap::new()), device_instance_map: DomRefCell::new(HashMap::new()),
} }
} }
pub fn new(global: &GlobalScope) -> Root<Bluetooth> { pub fn new(global: &GlobalScope) -> DomRoot<Bluetooth> {
reflect_dom_object(box Bluetooth::new_inherited(), reflect_dom_object(box Bluetooth::new_inherited(),
global, global,
BluetoothBinding::Wrap) BluetoothBinding::Wrap)
@ -141,7 +141,7 @@ impl Bluetooth {
self.global().as_window().bluetooth_thread() self.global().as_window().bluetooth_thread()
} }
pub fn get_device_map(&self) -> &DOMRefCell<HashMap<String, JS<BluetoothDevice>>> { pub fn get_device_map(&self) -> &DomRefCell<HashMap<String, Dom<BluetoothDevice>>> {
&self.device_instance_map &self.device_instance_map
} }
@ -520,7 +520,7 @@ impl AsyncBluetoothListener for Bluetooth {
DOMString::from(device.id.clone()), DOMString::from(device.id.clone()),
device.name.map(DOMString::from), device.name.map(DOMString::from),
&self); &self);
device_instance_map.insert(device.id.clone(), JS::from_ref(&bt_device)); device_instance_map.insert(device.id.clone(), Dom::from_ref(&bt_device));
self.global().as_window().bluetooth_extra_permission_data().add_new_allowed_device( self.global().as_window().bluetooth_extra_permission_data().add_new_allowed_device(
AllowedBluetoothDevice { AllowedBluetoothDevice {
@ -631,7 +631,7 @@ impl PermissionAlgorithm for Bluetooth {
// TODO: Implement this correctly, not just using device ids here. // TODO: Implement this correctly, not just using device ids here.
// https://webbluetoothcg.github.io/web-bluetooth/#get-the-bluetoothdevice-representing // https://webbluetoothcg.github.io/web-bluetooth/#get-the-bluetoothdevice-representing
if let Some(device) = device_map.get(&device_id) { if let Some(device) = device_map.get(&device_id) {
matching_devices.push(JS::from_ref(&**device)); matching_devices.push(Dom::from_ref(&**device));
} }
} }

View file

@ -7,8 +7,8 @@ use dom::bindings::codegen::Bindings::BluetoothAdvertisingEventBinding::Bluetoot
use dom::bindings::codegen::Bindings::EventBinding::EventBinding::EventMethods; use dom::bindings::codegen::Bindings::EventBinding::EventBinding::EventMethods;
use dom::bindings::error::Fallible; use dom::bindings::error::Fallible;
use dom::bindings::inheritance::Castable; use dom::bindings::inheritance::Castable;
use dom::bindings::js::{JS, Root, RootedReference};
use dom::bindings::reflector::reflect_dom_object; use dom::bindings::reflector::reflect_dom_object;
use dom::bindings::root::{Dom, DomRoot, RootedReference};
use dom::bindings::str::DOMString; use dom::bindings::str::DOMString;
use dom::bluetoothdevice::BluetoothDevice; use dom::bluetoothdevice::BluetoothDevice;
use dom::event::{Event, EventBubbles, EventCancelable}; use dom::event::{Event, EventBubbles, EventCancelable};
@ -21,7 +21,7 @@ use servo_atoms::Atom;
#[dom_struct] #[dom_struct]
pub struct BluetoothAdvertisingEvent { pub struct BluetoothAdvertisingEvent {
event: Event, event: Event,
device: JS<BluetoothDevice>, device: Dom<BluetoothDevice>,
name: Option<DOMString>, name: Option<DOMString>,
appearance: Option<u16>, appearance: Option<u16>,
tx_power: Option<i8>, tx_power: Option<i8>,
@ -37,7 +37,7 @@ impl BluetoothAdvertisingEvent {
-> BluetoothAdvertisingEvent { -> BluetoothAdvertisingEvent {
BluetoothAdvertisingEvent { BluetoothAdvertisingEvent {
event: Event::new_inherited(), event: Event::new_inherited(),
device: JS::from_ref(device), device: Dom::from_ref(device),
name: name, name: name,
appearance: appearance, appearance: appearance,
tx_power: tx_power, tx_power: tx_power,
@ -54,7 +54,7 @@ impl BluetoothAdvertisingEvent {
appearance: Option<u16>, appearance: Option<u16>,
txPower: Option<i8>, txPower: Option<i8>,
rssi: Option<i8>) rssi: Option<i8>)
-> Root<BluetoothAdvertisingEvent> { -> DomRoot<BluetoothAdvertisingEvent> {
let ev = reflect_dom_object(box BluetoothAdvertisingEvent::new_inherited(device, let ev = reflect_dom_object(box BluetoothAdvertisingEvent::new_inherited(device,
name, name,
appearance, appearance,
@ -73,7 +73,7 @@ impl BluetoothAdvertisingEvent {
pub fn Constructor(window: &Window, pub fn Constructor(window: &Window,
type_: DOMString, type_: DOMString,
init: &BluetoothAdvertisingEventInit) init: &BluetoothAdvertisingEventInit)
-> Fallible<Root<BluetoothAdvertisingEvent>> { -> Fallible<DomRoot<BluetoothAdvertisingEvent>> {
let global = window.upcast::<GlobalScope>(); let global = window.upcast::<GlobalScope>();
let device = init.device.r(); let device = init.device.r();
let name = init.name.clone(); let name = init.name.clone();
@ -96,8 +96,8 @@ impl BluetoothAdvertisingEvent {
impl BluetoothAdvertisingEventMethods for BluetoothAdvertisingEvent { impl BluetoothAdvertisingEventMethods for BluetoothAdvertisingEvent {
// https://webbluetoothcg.github.io/web-bluetooth/#dom-bluetoothadvertisingevent-device // https://webbluetoothcg.github.io/web-bluetooth/#dom-bluetoothadvertisingevent-device
fn Device(&self) -> Root<BluetoothDevice> { fn Device(&self) -> DomRoot<BluetoothDevice> {
Root::from_ref(&*self.device) DomRoot::from_ref(&*self.device)
} }
// https://webbluetoothcg.github.io/web-bluetooth/#dom-bluetoothadvertisingevent-name // https://webbluetoothcg.github.io/web-bluetooth/#dom-bluetoothadvertisingevent-name

View file

@ -5,8 +5,8 @@
use dom::bindings::codegen::Bindings::BluetoothCharacteristicPropertiesBinding; use dom::bindings::codegen::Bindings::BluetoothCharacteristicPropertiesBinding;
use dom::bindings::codegen::Bindings::BluetoothCharacteristicPropertiesBinding:: use dom::bindings::codegen::Bindings::BluetoothCharacteristicPropertiesBinding::
BluetoothCharacteristicPropertiesMethods; BluetoothCharacteristicPropertiesMethods;
use dom::bindings::js::Root;
use dom::bindings::reflector::{Reflector, reflect_dom_object}; use dom::bindings::reflector::{Reflector, reflect_dom_object};
use dom::bindings::root::DomRoot;
use dom::globalscope::GlobalScope; use dom::globalscope::GlobalScope;
use dom_struct::dom_struct; use dom_struct::dom_struct;
@ -60,7 +60,7 @@ impl BluetoothCharacteristicProperties {
authenticatedSignedWrites: bool, authenticatedSignedWrites: bool,
reliableWrite: bool, reliableWrite: bool,
writableAuxiliaries: bool) writableAuxiliaries: bool)
-> Root<BluetoothCharacteristicProperties> { -> DomRoot<BluetoothCharacteristicProperties> {
reflect_dom_object(box BluetoothCharacteristicProperties::new_inherited(broadcast, reflect_dom_object(box BluetoothCharacteristicProperties::new_inherited(broadcast,
read, read,
writeWithoutResponse, writeWithoutResponse,

View file

@ -4,15 +4,15 @@
use bluetooth_traits::{BluetoothCharacteristicMsg, BluetoothDescriptorMsg}; use bluetooth_traits::{BluetoothCharacteristicMsg, BluetoothDescriptorMsg};
use bluetooth_traits::{BluetoothRequest, BluetoothResponse, BluetoothServiceMsg}; use bluetooth_traits::{BluetoothRequest, BluetoothResponse, BluetoothServiceMsg};
use dom::bindings::cell::DOMRefCell; use dom::bindings::cell::DomRefCell;
use dom::bindings::codegen::Bindings::BluetoothDeviceBinding; use dom::bindings::codegen::Bindings::BluetoothDeviceBinding;
use dom::bindings::codegen::Bindings::BluetoothDeviceBinding::BluetoothDeviceMethods; use dom::bindings::codegen::Bindings::BluetoothDeviceBinding::BluetoothDeviceMethods;
use dom::bindings::codegen::Bindings::BluetoothRemoteGATTServerBinding::BluetoothRemoteGATTServerMethods; use dom::bindings::codegen::Bindings::BluetoothRemoteGATTServerBinding::BluetoothRemoteGATTServerMethods;
use dom::bindings::error::Error; use dom::bindings::error::Error;
use dom::bindings::error::ErrorResult; use dom::bindings::error::ErrorResult;
use dom::bindings::inheritance::Castable; use dom::bindings::inheritance::Castable;
use dom::bindings::js::{JS, MutNullableJS, Root};
use dom::bindings::reflector::{DomObject, reflect_dom_object}; use dom::bindings::reflector::{DomObject, reflect_dom_object};
use dom::bindings::root::{Dom, DomRoot, MutNullableDom};
use dom::bindings::str::DOMString; use dom::bindings::str::DOMString;
use dom::bluetooth::{AsyncBluetoothListener, Bluetooth, response_async}; use dom::bluetooth::{AsyncBluetoothListener, Bluetooth, response_async};
use dom::bluetoothcharacteristicproperties::BluetoothCharacteristicProperties; use dom::bluetoothcharacteristicproperties::BluetoothCharacteristicProperties;
@ -35,11 +35,11 @@ pub struct BluetoothDevice {
eventtarget: EventTarget, eventtarget: EventTarget,
id: DOMString, id: DOMString,
name: Option<DOMString>, name: Option<DOMString>,
gatt: MutNullableJS<BluetoothRemoteGATTServer>, gatt: MutNullableDom<BluetoothRemoteGATTServer>,
context: JS<Bluetooth>, context: Dom<Bluetooth>,
attribute_instance_map: (DOMRefCell<HashMap<String, JS<BluetoothRemoteGATTService>>>, attribute_instance_map: (DomRefCell<HashMap<String, Dom<BluetoothRemoteGATTService>>>,
DOMRefCell<HashMap<String, JS<BluetoothRemoteGATTCharacteristic>>>, DomRefCell<HashMap<String, Dom<BluetoothRemoteGATTCharacteristic>>>,
DOMRefCell<HashMap<String, JS<BluetoothRemoteGATTDescriptor>>>), DomRefCell<HashMap<String, Dom<BluetoothRemoteGATTDescriptor>>>),
watching_advertisements: Cell<bool>, watching_advertisements: Cell<bool>,
} }
@ -53,10 +53,10 @@ impl BluetoothDevice {
id: id, id: id,
name: name, name: name,
gatt: Default::default(), gatt: Default::default(),
context: JS::from_ref(context), context: Dom::from_ref(context),
attribute_instance_map: (DOMRefCell::new(HashMap::new()), attribute_instance_map: (DomRefCell::new(HashMap::new()),
DOMRefCell::new(HashMap::new()), DomRefCell::new(HashMap::new()),
DOMRefCell::new(HashMap::new())), DomRefCell::new(HashMap::new())),
watching_advertisements: Cell::new(false), watching_advertisements: Cell::new(false),
} }
} }
@ -65,7 +65,7 @@ impl BluetoothDevice {
id: DOMString, id: DOMString,
name: Option<DOMString>, name: Option<DOMString>,
context: &Bluetooth) context: &Bluetooth)
-> Root<BluetoothDevice> { -> DomRoot<BluetoothDevice> {
reflect_dom_object(box BluetoothDevice::new_inherited(id, reflect_dom_object(box BluetoothDevice::new_inherited(id,
name, name,
context), context),
@ -73,42 +73,42 @@ impl BluetoothDevice {
BluetoothDeviceBinding::Wrap) BluetoothDeviceBinding::Wrap)
} }
pub fn get_gatt(&self) -> Root<BluetoothRemoteGATTServer> { pub fn get_gatt(&self) -> DomRoot<BluetoothRemoteGATTServer> {
self.gatt.or_init(|| { self.gatt.or_init(|| {
BluetoothRemoteGATTServer::new(&self.global(), self) BluetoothRemoteGATTServer::new(&self.global(), self)
}) })
} }
fn get_context(&self) -> Root<Bluetooth> { fn get_context(&self) -> DomRoot<Bluetooth> {
Root::from_ref(&self.context) DomRoot::from_ref(&self.context)
} }
pub fn get_or_create_service(&self, pub fn get_or_create_service(&self,
service: &BluetoothServiceMsg, service: &BluetoothServiceMsg,
server: &BluetoothRemoteGATTServer) server: &BluetoothRemoteGATTServer)
-> Root<BluetoothRemoteGATTService> { -> DomRoot<BluetoothRemoteGATTService> {
let (ref service_map_ref, _, _) = self.attribute_instance_map; let (ref service_map_ref, _, _) = self.attribute_instance_map;
let mut service_map = service_map_ref.borrow_mut(); let mut service_map = service_map_ref.borrow_mut();
if let Some(existing_service) = service_map.get(&service.instance_id) { if let Some(existing_service) = service_map.get(&service.instance_id) {
return Root::from_ref(&existing_service); return DomRoot::from_ref(&existing_service);
} }
let bt_service = BluetoothRemoteGATTService::new(&server.global(), let bt_service = BluetoothRemoteGATTService::new(&server.global(),
&server.Device(), &server.Device(),
DOMString::from(service.uuid.clone()), DOMString::from(service.uuid.clone()),
service.is_primary, service.is_primary,
service.instance_id.clone()); service.instance_id.clone());
service_map.insert(service.instance_id.clone(), JS::from_ref(&bt_service)); service_map.insert(service.instance_id.clone(), Dom::from_ref(&bt_service));
return bt_service; return bt_service;
} }
pub fn get_or_create_characteristic(&self, pub fn get_or_create_characteristic(&self,
characteristic: &BluetoothCharacteristicMsg, characteristic: &BluetoothCharacteristicMsg,
service: &BluetoothRemoteGATTService) service: &BluetoothRemoteGATTService)
-> Root<BluetoothRemoteGATTCharacteristic> { -> DomRoot<BluetoothRemoteGATTCharacteristic> {
let (_, ref characteristic_map_ref, _) = self.attribute_instance_map; let (_, ref characteristic_map_ref, _) = self.attribute_instance_map;
let mut characteristic_map = characteristic_map_ref.borrow_mut(); let mut characteristic_map = characteristic_map_ref.borrow_mut();
if let Some(existing_characteristic) = characteristic_map.get(&characteristic.instance_id) { if let Some(existing_characteristic) = characteristic_map.get(&characteristic.instance_id) {
return Root::from_ref(&existing_characteristic); return DomRoot::from_ref(&existing_characteristic);
} }
let properties = let properties =
BluetoothCharacteristicProperties::new(&service.global(), BluetoothCharacteristicProperties::new(&service.global(),
@ -126,7 +126,7 @@ impl BluetoothDevice {
DOMString::from(characteristic.uuid.clone()), DOMString::from(characteristic.uuid.clone()),
&properties, &properties,
characteristic.instance_id.clone()); characteristic.instance_id.clone());
characteristic_map.insert(characteristic.instance_id.clone(), JS::from_ref(&bt_characteristic)); characteristic_map.insert(characteristic.instance_id.clone(), Dom::from_ref(&bt_characteristic));
return bt_characteristic; return bt_characteristic;
} }
@ -140,17 +140,17 @@ impl BluetoothDevice {
pub fn get_or_create_descriptor(&self, pub fn get_or_create_descriptor(&self,
descriptor: &BluetoothDescriptorMsg, descriptor: &BluetoothDescriptorMsg,
characteristic: &BluetoothRemoteGATTCharacteristic) characteristic: &BluetoothRemoteGATTCharacteristic)
-> Root<BluetoothRemoteGATTDescriptor> { -> DomRoot<BluetoothRemoteGATTDescriptor> {
let (_, _, ref descriptor_map_ref) = self.attribute_instance_map; let (_, _, ref descriptor_map_ref) = self.attribute_instance_map;
let mut descriptor_map = descriptor_map_ref.borrow_mut(); let mut descriptor_map = descriptor_map_ref.borrow_mut();
if let Some(existing_descriptor) = descriptor_map.get(&descriptor.instance_id) { if let Some(existing_descriptor) = descriptor_map.get(&descriptor.instance_id) {
return Root::from_ref(&existing_descriptor); return DomRoot::from_ref(&existing_descriptor);
} }
let bt_descriptor = BluetoothRemoteGATTDescriptor::new(&characteristic.global(), let bt_descriptor = BluetoothRemoteGATTDescriptor::new(&characteristic.global(),
characteristic, characteristic,
DOMString::from(descriptor.uuid.clone()), DOMString::from(descriptor.uuid.clone()),
descriptor.instance_id.clone()); descriptor.instance_id.clone());
descriptor_map.insert(descriptor.instance_id.clone(), JS::from_ref(&bt_descriptor)); descriptor_map.insert(descriptor.instance_id.clone(), Dom::from_ref(&bt_descriptor));
return bt_descriptor; return bt_descriptor;
} }
@ -225,7 +225,7 @@ impl BluetoothDeviceMethods for BluetoothDevice {
} }
// https://webbluetoothcg.github.io/web-bluetooth/#dom-bluetoothdevice-gatt // https://webbluetoothcg.github.io/web-bluetooth/#dom-bluetoothdevice-gatt
fn GetGatt(&self) -> Option<Root<BluetoothRemoteGATTServer>> { fn GetGatt(&self) -> Option<DomRoot<BluetoothRemoteGATTServer>> {
// Step 1. // Step 1.
if self.global().as_window().bluetooth_extra_permission_data() if self.global().as_window().bluetooth_extra_permission_data()
.allowed_devices_contains_id(self.id.clone()) && !self.is_represented_device_null() { .allowed_devices_contains_id(self.id.clone()) && !self.is_represented_device_null() {

View file

@ -3,15 +3,15 @@
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use bluetooth_traits::{BluetoothRequest, BluetoothResponse}; use bluetooth_traits::{BluetoothRequest, BluetoothResponse};
use dom::bindings::cell::DOMRefCell; use dom::bindings::cell::DomRefCell;
use dom::bindings::codegen::Bindings::BluetoothPermissionResultBinding::{self, BluetoothPermissionResultMethods}; use dom::bindings::codegen::Bindings::BluetoothPermissionResultBinding::{self, BluetoothPermissionResultMethods};
use dom::bindings::codegen::Bindings::NavigatorBinding::NavigatorBinding::NavigatorMethods; use dom::bindings::codegen::Bindings::NavigatorBinding::NavigatorBinding::NavigatorMethods;
use dom::bindings::codegen::Bindings::PermissionStatusBinding::{PermissionName, PermissionState}; use dom::bindings::codegen::Bindings::PermissionStatusBinding::{PermissionName, PermissionState};
use dom::bindings::codegen::Bindings::PermissionStatusBinding::PermissionStatusBinding::PermissionStatusMethods; use dom::bindings::codegen::Bindings::PermissionStatusBinding::PermissionStatusBinding::PermissionStatusMethods;
use dom::bindings::codegen::Bindings::WindowBinding::WindowBinding::WindowMethods; use dom::bindings::codegen::Bindings::WindowBinding::WindowBinding::WindowMethods;
use dom::bindings::error::Error; use dom::bindings::error::Error;
use dom::bindings::js::{JS, Root};
use dom::bindings::reflector::{DomObject, reflect_dom_object}; use dom::bindings::reflector::{DomObject, reflect_dom_object};
use dom::bindings::root::{Dom, DomRoot};
use dom::bindings::str::DOMString; use dom::bindings::str::DOMString;
use dom::bluetooth::{AsyncBluetoothListener, Bluetooth, AllowedBluetoothDevice}; use dom::bluetooth::{AsyncBluetoothListener, Bluetooth, AllowedBluetoothDevice};
use dom::bluetoothdevice::BluetoothDevice; use dom::bluetoothdevice::BluetoothDevice;
@ -26,7 +26,7 @@ use std::rc::Rc;
#[dom_struct] #[dom_struct]
pub struct BluetoothPermissionResult { pub struct BluetoothPermissionResult {
status: PermissionStatus, status: PermissionStatus,
devices: DOMRefCell<Vec<JS<BluetoothDevice>>>, devices: DomRefCell<Vec<Dom<BluetoothDevice>>>,
} }
impl BluetoothPermissionResult { impl BluetoothPermissionResult {
@ -34,19 +34,19 @@ impl BluetoothPermissionResult {
fn new_inherited(status: &PermissionStatus) -> BluetoothPermissionResult { fn new_inherited(status: &PermissionStatus) -> BluetoothPermissionResult {
let result = BluetoothPermissionResult { let result = BluetoothPermissionResult {
status: PermissionStatus::new_inherited(status.get_query()), status: PermissionStatus::new_inherited(status.get_query()),
devices: DOMRefCell::new(Vec::new()), devices: DomRefCell::new(Vec::new()),
}; };
result.status.set_state(status.State()); result.status.set_state(status.State());
result result
} }
pub fn new(global: &GlobalScope, status: &PermissionStatus) -> Root<BluetoothPermissionResult> { pub fn new(global: &GlobalScope, status: &PermissionStatus) -> DomRoot<BluetoothPermissionResult> {
reflect_dom_object(box BluetoothPermissionResult::new_inherited(status), reflect_dom_object(box BluetoothPermissionResult::new_inherited(status),
global, global,
BluetoothPermissionResultBinding::Wrap) BluetoothPermissionResultBinding::Wrap)
} }
pub fn get_bluetooth(&self) -> Root<Bluetooth> { pub fn get_bluetooth(&self) -> DomRoot<Bluetooth> {
self.global().as_window().Navigator().Bluetooth() self.global().as_window().Navigator().Bluetooth()
} }
@ -67,16 +67,16 @@ impl BluetoothPermissionResult {
} }
#[allow(unrooted_must_root)] #[allow(unrooted_must_root)]
pub fn set_devices(&self, devices: Vec<JS<BluetoothDevice>>) { pub fn set_devices(&self, devices: Vec<Dom<BluetoothDevice>>) {
*self.devices.borrow_mut() = devices; *self.devices.borrow_mut() = devices;
} }
} }
impl BluetoothPermissionResultMethods for BluetoothPermissionResult { impl BluetoothPermissionResultMethods for BluetoothPermissionResult {
// https://webbluetoothcg.github.io/web-bluetooth/#dom-bluetoothpermissionresult-devices // https://webbluetoothcg.github.io/web-bluetooth/#dom-bluetoothpermissionresult-devices
fn Devices(&self) -> Vec<Root<BluetoothDevice>> { fn Devices(&self) -> Vec<DomRoot<BluetoothDevice>> {
let device_vec: Vec<Root<BluetoothDevice>> = let device_vec: Vec<DomRoot<BluetoothDevice>> =
self.devices.borrow().iter().map(|d| Root::from_ref(&**d)).collect(); self.devices.borrow().iter().map(|d| DomRoot::from_ref(&**d)).collect();
device_vec device_vec
} }
} }
@ -93,7 +93,7 @@ impl AsyncBluetoothListener for BluetoothPermissionResult {
if let Some(ref existing_device) = device_instance_map.get(&device.id) { if let Some(ref existing_device) = device_instance_map.get(&device.id) {
// https://webbluetoothcg.github.io/web-bluetooth/#request-the-bluetooth-permission // https://webbluetoothcg.github.io/web-bluetooth/#request-the-bluetooth-permission
// Step 3. // Step 3.
self.set_devices(vec!(JS::from_ref(&*existing_device))); self.set_devices(vec!(Dom::from_ref(&*existing_device)));
// https://w3c.github.io/permissions/#dom-permissions-request // https://w3c.github.io/permissions/#dom-permissions-request
// Step 8. // Step 8.
@ -103,7 +103,7 @@ impl AsyncBluetoothListener for BluetoothPermissionResult {
DOMString::from(device.id.clone()), DOMString::from(device.id.clone()),
device.name.map(DOMString::from), device.name.map(DOMString::from),
&bluetooth); &bluetooth);
device_instance_map.insert(device.id.clone(), JS::from_ref(&bt_device)); device_instance_map.insert(device.id.clone(), Dom::from_ref(&bt_device));
self.global().as_window().bluetooth_extra_permission_data().add_new_allowed_device( self.global().as_window().bluetooth_extra_permission_data().add_new_allowed_device(
AllowedBluetoothDevice { AllowedBluetoothDevice {
deviceId: DOMString::from(device.id), deviceId: DOMString::from(device.id),
@ -112,7 +112,7 @@ impl AsyncBluetoothListener for BluetoothPermissionResult {
); );
// https://webbluetoothcg.github.io/web-bluetooth/#request-the-bluetooth-permission // https://webbluetoothcg.github.io/web-bluetooth/#request-the-bluetooth-permission
// Step 3. // Step 3.
self.set_devices(vec!(JS::from_ref(&bt_device))); self.set_devices(vec!(Dom::from_ref(&bt_device)));
// https://w3c.github.io/permissions/#dom-permissions-request // https://w3c.github.io/permissions/#dom-permissions-request
// Step 8. // Step 8.

View file

@ -4,7 +4,7 @@
use bluetooth_traits::{BluetoothRequest, BluetoothResponse, GATTType}; use bluetooth_traits::{BluetoothRequest, BluetoothResponse, GATTType};
use bluetooth_traits::blocklist::{Blocklist, uuid_is_blocklisted}; use bluetooth_traits::blocklist::{Blocklist, uuid_is_blocklisted};
use dom::bindings::cell::DOMRefCell; use dom::bindings::cell::DomRefCell;
use dom::bindings::codegen::Bindings::BluetoothCharacteristicPropertiesBinding:: use dom::bindings::codegen::Bindings::BluetoothCharacteristicPropertiesBinding::
BluetoothCharacteristicPropertiesMethods; BluetoothCharacteristicPropertiesMethods;
use dom::bindings::codegen::Bindings::BluetoothRemoteGATTCharacteristicBinding; use dom::bindings::codegen::Bindings::BluetoothRemoteGATTCharacteristicBinding;
@ -14,8 +14,8 @@ use dom::bindings::codegen::Bindings::BluetoothRemoteGATTServerBinding::Bluetoot
use dom::bindings::codegen::Bindings::BluetoothRemoteGATTServiceBinding::BluetoothRemoteGATTServiceMethods; use dom::bindings::codegen::Bindings::BluetoothRemoteGATTServiceBinding::BluetoothRemoteGATTServiceMethods;
use dom::bindings::error::Error::{self, InvalidModification, Network, NotSupported, Security}; use dom::bindings::error::Error::{self, InvalidModification, Network, NotSupported, Security};
use dom::bindings::inheritance::Castable; use dom::bindings::inheritance::Castable;
use dom::bindings::js::{JS, Root};
use dom::bindings::reflector::{DomObject, reflect_dom_object}; use dom::bindings::reflector::{DomObject, reflect_dom_object};
use dom::bindings::root::{Dom, DomRoot};
use dom::bindings::str::{ByteString, DOMString}; use dom::bindings::str::{ByteString, DOMString};
use dom::bluetooth::{AsyncBluetoothListener, get_gatt_children, response_async}; use dom::bluetooth::{AsyncBluetoothListener, get_gatt_children, response_async};
use dom::bluetoothcharacteristicproperties::BluetoothCharacteristicProperties; use dom::bluetoothcharacteristicproperties::BluetoothCharacteristicProperties;
@ -36,10 +36,10 @@ pub const MAXIMUM_ATTRIBUTE_LENGTH: usize = 512;
#[dom_struct] #[dom_struct]
pub struct BluetoothRemoteGATTCharacteristic { pub struct BluetoothRemoteGATTCharacteristic {
eventtarget: EventTarget, eventtarget: EventTarget,
service: JS<BluetoothRemoteGATTService>, service: Dom<BluetoothRemoteGATTService>,
uuid: DOMString, uuid: DOMString,
properties: JS<BluetoothCharacteristicProperties>, properties: Dom<BluetoothCharacteristicProperties>,
value: DOMRefCell<Option<ByteString>>, value: DomRefCell<Option<ByteString>>,
instance_id: String, instance_id: String,
} }
@ -51,10 +51,10 @@ impl BluetoothRemoteGATTCharacteristic {
-> BluetoothRemoteGATTCharacteristic { -> BluetoothRemoteGATTCharacteristic {
BluetoothRemoteGATTCharacteristic { BluetoothRemoteGATTCharacteristic {
eventtarget: EventTarget::new_inherited(), eventtarget: EventTarget::new_inherited(),
service: JS::from_ref(service), service: Dom::from_ref(service),
uuid: uuid, uuid: uuid,
properties: JS::from_ref(properties), properties: Dom::from_ref(properties),
value: DOMRefCell::new(None), value: DomRefCell::new(None),
instance_id: instance_id, instance_id: instance_id,
} }
} }
@ -64,7 +64,7 @@ impl BluetoothRemoteGATTCharacteristic {
uuid: DOMString, uuid: DOMString,
properties: &BluetoothCharacteristicProperties, properties: &BluetoothCharacteristicProperties,
instanceID: String) instanceID: String)
-> Root<BluetoothRemoteGATTCharacteristic> { -> DomRoot<BluetoothRemoteGATTCharacteristic> {
reflect_dom_object(box BluetoothRemoteGATTCharacteristic::new_inherited(service, reflect_dom_object(box BluetoothRemoteGATTCharacteristic::new_inherited(service,
uuid, uuid,
properties, properties,
@ -84,13 +84,13 @@ impl BluetoothRemoteGATTCharacteristic {
impl BluetoothRemoteGATTCharacteristicMethods for BluetoothRemoteGATTCharacteristic { impl BluetoothRemoteGATTCharacteristicMethods for BluetoothRemoteGATTCharacteristic {
// https://webbluetoothcg.github.io/web-bluetooth/#dom-bluetoothremotegattcharacteristic-properties // https://webbluetoothcg.github.io/web-bluetooth/#dom-bluetoothremotegattcharacteristic-properties
fn Properties(&self) -> Root<BluetoothCharacteristicProperties> { fn Properties(&self) -> DomRoot<BluetoothCharacteristicProperties> {
Root::from_ref(&self.properties) DomRoot::from_ref(&self.properties)
} }
// https://webbluetoothcg.github.io/web-bluetooth/#dom-bluetoothremotegattcharacteristic-service // https://webbluetoothcg.github.io/web-bluetooth/#dom-bluetoothremotegattcharacteristic-service
fn Service(&self) -> Root<BluetoothRemoteGATTService> { fn Service(&self) -> DomRoot<BluetoothRemoteGATTService> {
Root::from_ref(&self.service) DomRoot::from_ref(&self.service)
} }
// https://webbluetoothcg.github.io/web-bluetooth/#dom-bluetoothremotegattcharacteristic-uuid // https://webbluetoothcg.github.io/web-bluetooth/#dom-bluetoothremotegattcharacteristic-uuid

View file

@ -4,7 +4,7 @@
use bluetooth_traits::{BluetoothRequest, BluetoothResponse}; use bluetooth_traits::{BluetoothRequest, BluetoothResponse};
use bluetooth_traits::blocklist::{Blocklist, uuid_is_blocklisted}; use bluetooth_traits::blocklist::{Blocklist, uuid_is_blocklisted};
use dom::bindings::cell::DOMRefCell; use dom::bindings::cell::DomRefCell;
use dom::bindings::codegen::Bindings::BluetoothRemoteGATTCharacteristicBinding:: use dom::bindings::codegen::Bindings::BluetoothRemoteGATTCharacteristicBinding::
BluetoothRemoteGATTCharacteristicMethods; BluetoothRemoteGATTCharacteristicMethods;
use dom::bindings::codegen::Bindings::BluetoothRemoteGATTDescriptorBinding; use dom::bindings::codegen::Bindings::BluetoothRemoteGATTDescriptorBinding;
@ -12,8 +12,8 @@ use dom::bindings::codegen::Bindings::BluetoothRemoteGATTDescriptorBinding::Blue
use dom::bindings::codegen::Bindings::BluetoothRemoteGATTServerBinding::BluetoothRemoteGATTServerMethods; use dom::bindings::codegen::Bindings::BluetoothRemoteGATTServerBinding::BluetoothRemoteGATTServerMethods;
use dom::bindings::codegen::Bindings::BluetoothRemoteGATTServiceBinding::BluetoothRemoteGATTServiceMethods; use dom::bindings::codegen::Bindings::BluetoothRemoteGATTServiceBinding::BluetoothRemoteGATTServiceMethods;
use dom::bindings::error::Error::{self, InvalidModification, Network, Security}; use dom::bindings::error::Error::{self, InvalidModification, Network, Security};
use dom::bindings::js::{JS, Root};
use dom::bindings::reflector::{DomObject, Reflector, reflect_dom_object}; use dom::bindings::reflector::{DomObject, Reflector, reflect_dom_object};
use dom::bindings::root::{Dom, DomRoot};
use dom::bindings::str::{ByteString, DOMString}; use dom::bindings::str::{ByteString, DOMString};
use dom::bluetooth::{AsyncBluetoothListener, response_async}; use dom::bluetooth::{AsyncBluetoothListener, response_async};
use dom::bluetoothremotegattcharacteristic::{BluetoothRemoteGATTCharacteristic, MAXIMUM_ATTRIBUTE_LENGTH}; use dom::bluetoothremotegattcharacteristic::{BluetoothRemoteGATTCharacteristic, MAXIMUM_ATTRIBUTE_LENGTH};
@ -27,9 +27,9 @@ use std::rc::Rc;
#[dom_struct] #[dom_struct]
pub struct BluetoothRemoteGATTDescriptor { pub struct BluetoothRemoteGATTDescriptor {
reflector_: Reflector, reflector_: Reflector,
characteristic: JS<BluetoothRemoteGATTCharacteristic>, characteristic: Dom<BluetoothRemoteGATTCharacteristic>,
uuid: DOMString, uuid: DOMString,
value: DOMRefCell<Option<ByteString>>, value: DomRefCell<Option<ByteString>>,
instance_id: String, instance_id: String,
} }
@ -40,9 +40,9 @@ impl BluetoothRemoteGATTDescriptor {
-> BluetoothRemoteGATTDescriptor { -> BluetoothRemoteGATTDescriptor {
BluetoothRemoteGATTDescriptor { BluetoothRemoteGATTDescriptor {
reflector_: Reflector::new(), reflector_: Reflector::new(),
characteristic: JS::from_ref(characteristic), characteristic: Dom::from_ref(characteristic),
uuid: uuid, uuid: uuid,
value: DOMRefCell::new(None), value: DomRefCell::new(None),
instance_id: instance_id, instance_id: instance_id,
} }
} }
@ -51,7 +51,7 @@ impl BluetoothRemoteGATTDescriptor {
characteristic: &BluetoothRemoteGATTCharacteristic, characteristic: &BluetoothRemoteGATTCharacteristic,
uuid: DOMString, uuid: DOMString,
instanceID: String) instanceID: String)
-> Root<BluetoothRemoteGATTDescriptor>{ -> DomRoot<BluetoothRemoteGATTDescriptor>{
reflect_dom_object(box BluetoothRemoteGATTDescriptor::new_inherited(characteristic, reflect_dom_object(box BluetoothRemoteGATTDescriptor::new_inherited(characteristic,
uuid, uuid,
instanceID), instanceID),
@ -70,8 +70,8 @@ impl BluetoothRemoteGATTDescriptor {
impl BluetoothRemoteGATTDescriptorMethods for BluetoothRemoteGATTDescriptor { impl BluetoothRemoteGATTDescriptorMethods for BluetoothRemoteGATTDescriptor {
// https://webbluetoothcg.github.io/web-bluetooth/#dom-bluetoothremotegattdescriptor-characteristic // https://webbluetoothcg.github.io/web-bluetooth/#dom-bluetoothremotegattdescriptor-characteristic
fn Characteristic(&self) -> Root<BluetoothRemoteGATTCharacteristic> { fn Characteristic(&self) -> DomRoot<BluetoothRemoteGATTCharacteristic> {
Root::from_ref(&self.characteristic) DomRoot::from_ref(&self.characteristic)
} }
// https://webbluetoothcg.github.io/web-bluetooth/#dom-bluetoothremotegattdescriptor-uuid // https://webbluetoothcg.github.io/web-bluetooth/#dom-bluetoothremotegattdescriptor-uuid

View file

@ -8,8 +8,8 @@ use dom::bindings::codegen::Bindings::BluetoothRemoteGATTServerBinding;
use dom::bindings::codegen::Bindings::BluetoothRemoteGATTServerBinding::BluetoothRemoteGATTServerMethods; use dom::bindings::codegen::Bindings::BluetoothRemoteGATTServerBinding::BluetoothRemoteGATTServerMethods;
use dom::bindings::error::Error; use dom::bindings::error::Error;
use dom::bindings::error::ErrorResult; use dom::bindings::error::ErrorResult;
use dom::bindings::js::{JS, Root};
use dom::bindings::reflector::{DomObject, Reflector, reflect_dom_object}; use dom::bindings::reflector::{DomObject, Reflector, reflect_dom_object};
use dom::bindings::root::{Dom, DomRoot};
use dom::bluetooth::{AsyncBluetoothListener, get_gatt_children, response_async}; use dom::bluetooth::{AsyncBluetoothListener, get_gatt_children, response_async};
use dom::bluetoothdevice::BluetoothDevice; use dom::bluetoothdevice::BluetoothDevice;
use dom::bluetoothuuid::{BluetoothServiceUUID, BluetoothUUID}; use dom::bluetoothuuid::{BluetoothServiceUUID, BluetoothUUID};
@ -24,7 +24,7 @@ use std::rc::Rc;
#[dom_struct] #[dom_struct]
pub struct BluetoothRemoteGATTServer { pub struct BluetoothRemoteGATTServer {
reflector_: Reflector, reflector_: Reflector,
device: JS<BluetoothDevice>, device: Dom<BluetoothDevice>,
connected: Cell<bool>, connected: Cell<bool>,
} }
@ -32,12 +32,12 @@ impl BluetoothRemoteGATTServer {
pub fn new_inherited(device: &BluetoothDevice) -> BluetoothRemoteGATTServer { pub fn new_inherited(device: &BluetoothDevice) -> BluetoothRemoteGATTServer {
BluetoothRemoteGATTServer { BluetoothRemoteGATTServer {
reflector_: Reflector::new(), reflector_: Reflector::new(),
device: JS::from_ref(device), device: Dom::from_ref(device),
connected: Cell::new(false), connected: Cell::new(false),
} }
} }
pub fn new(global: &GlobalScope, device: &BluetoothDevice) -> Root<BluetoothRemoteGATTServer> { pub fn new(global: &GlobalScope, device: &BluetoothDevice) -> DomRoot<BluetoothRemoteGATTServer> {
reflect_dom_object(box BluetoothRemoteGATTServer::new_inherited(device), reflect_dom_object(box BluetoothRemoteGATTServer::new_inherited(device),
global, global,
BluetoothRemoteGATTServerBinding::Wrap) BluetoothRemoteGATTServerBinding::Wrap)
@ -54,8 +54,8 @@ impl BluetoothRemoteGATTServer {
impl BluetoothRemoteGATTServerMethods for BluetoothRemoteGATTServer { impl BluetoothRemoteGATTServerMethods for BluetoothRemoteGATTServer {
// https://webbluetoothcg.github.io/web-bluetooth/#dom-bluetoothremotegattserver-device // https://webbluetoothcg.github.io/web-bluetooth/#dom-bluetoothremotegattserver-device
fn Device(&self) -> Root<BluetoothDevice> { fn Device(&self) -> DomRoot<BluetoothDevice> {
Root::from_ref(&self.device) DomRoot::from_ref(&self.device)
} }
// https://webbluetoothcg.github.io/web-bluetooth/#dom-bluetoothremotegattserver-connected // https://webbluetoothcg.github.io/web-bluetooth/#dom-bluetoothremotegattserver-connected

View file

@ -7,8 +7,8 @@ use dom::bindings::codegen::Bindings::BluetoothRemoteGATTServerBinding::Bluetoot
use dom::bindings::codegen::Bindings::BluetoothRemoteGATTServiceBinding; use dom::bindings::codegen::Bindings::BluetoothRemoteGATTServiceBinding;
use dom::bindings::codegen::Bindings::BluetoothRemoteGATTServiceBinding::BluetoothRemoteGATTServiceMethods; use dom::bindings::codegen::Bindings::BluetoothRemoteGATTServiceBinding::BluetoothRemoteGATTServiceMethods;
use dom::bindings::error::Error; use dom::bindings::error::Error;
use dom::bindings::js::{JS, Root};
use dom::bindings::reflector::reflect_dom_object; use dom::bindings::reflector::reflect_dom_object;
use dom::bindings::root::{Dom, DomRoot};
use dom::bindings::str::DOMString; use dom::bindings::str::DOMString;
use dom::bluetooth::{AsyncBluetoothListener, get_gatt_children}; use dom::bluetooth::{AsyncBluetoothListener, get_gatt_children};
use dom::bluetoothdevice::BluetoothDevice; use dom::bluetoothdevice::BluetoothDevice;
@ -23,7 +23,7 @@ use std::rc::Rc;
#[dom_struct] #[dom_struct]
pub struct BluetoothRemoteGATTService { pub struct BluetoothRemoteGATTService {
eventtarget: EventTarget, eventtarget: EventTarget,
device: JS<BluetoothDevice>, device: Dom<BluetoothDevice>,
uuid: DOMString, uuid: DOMString,
is_primary: bool, is_primary: bool,
instance_id: String, instance_id: String,
@ -37,7 +37,7 @@ impl BluetoothRemoteGATTService {
-> BluetoothRemoteGATTService { -> BluetoothRemoteGATTService {
BluetoothRemoteGATTService { BluetoothRemoteGATTService {
eventtarget: EventTarget::new_inherited(), eventtarget: EventTarget::new_inherited(),
device: JS::from_ref(device), device: Dom::from_ref(device),
uuid: uuid, uuid: uuid,
is_primary: is_primary, is_primary: is_primary,
instance_id: instance_id, instance_id: instance_id,
@ -49,7 +49,7 @@ impl BluetoothRemoteGATTService {
uuid: DOMString, uuid: DOMString,
isPrimary: bool, isPrimary: bool,
instanceID: String) instanceID: String)
-> Root<BluetoothRemoteGATTService> { -> DomRoot<BluetoothRemoteGATTService> {
reflect_dom_object(box BluetoothRemoteGATTService::new_inherited(device, reflect_dom_object(box BluetoothRemoteGATTService::new_inherited(device,
uuid, uuid,
isPrimary, isPrimary,
@ -65,8 +65,8 @@ impl BluetoothRemoteGATTService {
impl BluetoothRemoteGATTServiceMethods for BluetoothRemoteGATTService { impl BluetoothRemoteGATTServiceMethods for BluetoothRemoteGATTService {
// https://webbluetoothcg.github.io/web-bluetooth/#dom-bluetoothremotegattservice-device // https://webbluetoothcg.github.io/web-bluetooth/#dom-bluetoothremotegattservice-device
fn Device(&self) -> Root<BluetoothDevice> { fn Device(&self) -> DomRoot<BluetoothDevice> {
Root::from_ref(&self.device) DomRoot::from_ref(&self.device)
} }
// https://webbluetoothcg.github.io/web-bluetooth/#dom-bluetoothremotegattservice-isprimary // https://webbluetoothcg.github.io/web-bluetooth/#dom-bluetoothremotegattservice-isprimary

View file

@ -5,13 +5,13 @@
use canvas_traits::canvas::{CanvasGradientStop, FillOrStrokeStyle, LinearGradientStyle, RadialGradientStyle}; use canvas_traits::canvas::{CanvasGradientStop, FillOrStrokeStyle, LinearGradientStyle, RadialGradientStyle};
use cssparser::{Parser, ParserInput, RGBA}; use cssparser::{Parser, ParserInput, RGBA};
use cssparser::Color as CSSColor; use cssparser::Color as CSSColor;
use dom::bindings::cell::DOMRefCell; use dom::bindings::cell::DomRefCell;
use dom::bindings::codegen::Bindings::CanvasGradientBinding; use dom::bindings::codegen::Bindings::CanvasGradientBinding;
use dom::bindings::codegen::Bindings::CanvasGradientBinding::CanvasGradientMethods; use dom::bindings::codegen::Bindings::CanvasGradientBinding::CanvasGradientMethods;
use dom::bindings::error::{Error, ErrorResult}; use dom::bindings::error::{Error, ErrorResult};
use dom::bindings::js::Root;
use dom::bindings::num::Finite; use dom::bindings::num::Finite;
use dom::bindings::reflector::{Reflector, reflect_dom_object}; use dom::bindings::reflector::{Reflector, reflect_dom_object};
use dom::bindings::root::DomRoot;
use dom::bindings::str::DOMString; use dom::bindings::str::DOMString;
use dom::globalscope::GlobalScope; use dom::globalscope::GlobalScope;
use dom_struct::dom_struct; use dom_struct::dom_struct;
@ -21,7 +21,7 @@ use dom_struct::dom_struct;
pub struct CanvasGradient { pub struct CanvasGradient {
reflector_: Reflector, reflector_: Reflector,
style: CanvasGradientStyle, style: CanvasGradientStyle,
stops: DOMRefCell<Vec<CanvasGradientStop>>, stops: DomRefCell<Vec<CanvasGradientStop>>,
} }
#[derive(Clone, HeapSizeOf, JSTraceable)] #[derive(Clone, HeapSizeOf, JSTraceable)]
@ -35,11 +35,11 @@ impl CanvasGradient {
CanvasGradient { CanvasGradient {
reflector_: Reflector::new(), reflector_: Reflector::new(),
style: style, style: style,
stops: DOMRefCell::new(Vec::new()), stops: DomRefCell::new(Vec::new()),
} }
} }
pub fn new(global: &GlobalScope, style: CanvasGradientStyle) -> Root<CanvasGradient> { pub fn new(global: &GlobalScope, style: CanvasGradientStyle) -> DomRoot<CanvasGradient> {
reflect_dom_object(box CanvasGradient::new_inherited(style), reflect_dom_object(box CanvasGradient::new_inherited(style),
global, global,
CanvasGradientBinding::Wrap) CanvasGradientBinding::Wrap)

View file

@ -4,8 +4,8 @@
use canvas_traits::canvas::{FillOrStrokeStyle, RepetitionStyle, SurfaceStyle}; use canvas_traits::canvas::{FillOrStrokeStyle, RepetitionStyle, SurfaceStyle};
use dom::bindings::codegen::Bindings::CanvasPatternBinding; use dom::bindings::codegen::Bindings::CanvasPatternBinding;
use dom::bindings::js::Root;
use dom::bindings::reflector::{Reflector, reflect_dom_object}; use dom::bindings::reflector::{Reflector, reflect_dom_object};
use dom::bindings::root::DomRoot;
use dom::canvasgradient::ToFillOrStrokeStyle; use dom::canvasgradient::ToFillOrStrokeStyle;
use dom::globalscope::GlobalScope; use dom::globalscope::GlobalScope;
use dom_struct::dom_struct; use dom_struct::dom_struct;
@ -49,7 +49,7 @@ impl CanvasPattern {
surface_size: Size2D<i32>, surface_size: Size2D<i32>,
repeat: RepetitionStyle, repeat: RepetitionStyle,
origin_clean: bool) origin_clean: bool)
-> Root<CanvasPattern> { -> DomRoot<CanvasPattern> {
reflect_dom_object(box CanvasPattern::new_inherited(surface_data, surface_size, reflect_dom_object(box CanvasPattern::new_inherited(surface_data, surface_size,
repeat, origin_clean), repeat, origin_clean),
global, global,

View file

@ -8,7 +8,7 @@ use canvas_traits::canvas::{LineCapStyle, LineJoinStyle, LinearGradientStyle};
use canvas_traits::canvas::{RadialGradientStyle, RepetitionStyle, byte_swap_and_premultiply}; use canvas_traits::canvas::{RadialGradientStyle, RepetitionStyle, byte_swap_and_premultiply};
use cssparser::{Parser, ParserInput, RGBA}; use cssparser::{Parser, ParserInput, RGBA};
use cssparser::Color as CSSColor; use cssparser::Color as CSSColor;
use dom::bindings::cell::DOMRefCell; use dom::bindings::cell::DomRefCell;
use dom::bindings::codegen::Bindings::CSSStyleDeclarationBinding::CSSStyleDeclarationMethods; use dom::bindings::codegen::Bindings::CSSStyleDeclarationBinding::CSSStyleDeclarationMethods;
use dom::bindings::codegen::Bindings::CanvasRenderingContext2DBinding; use dom::bindings::codegen::Bindings::CanvasRenderingContext2DBinding;
use dom::bindings::codegen::Bindings::CanvasRenderingContext2DBinding::CanvasFillRule; use dom::bindings::codegen::Bindings::CanvasRenderingContext2DBinding::CanvasFillRule;
@ -21,9 +21,9 @@ use dom::bindings::codegen::Bindings::WindowBinding::WindowMethods;
use dom::bindings::codegen::UnionTypes::StringOrCanvasGradientOrCanvasPattern; use dom::bindings::codegen::UnionTypes::StringOrCanvasGradientOrCanvasPattern;
use dom::bindings::error::{Error, ErrorResult, Fallible}; use dom::bindings::error::{Error, ErrorResult, Fallible};
use dom::bindings::inheritance::Castable; use dom::bindings::inheritance::Castable;
use dom::bindings::js::{JS, LayoutJS, Root};
use dom::bindings::num::Finite; use dom::bindings::num::Finite;
use dom::bindings::reflector::{DomObject, Reflector, reflect_dom_object}; use dom::bindings::reflector::{DomObject, Reflector, reflect_dom_object};
use dom::bindings::root::{Dom, DomRoot, LayoutDom};
use dom::bindings::str::DOMString; use dom::bindings::str::DOMString;
use dom::canvasgradient::{CanvasGradient, CanvasGradientStyle, ToFillOrStrokeStyle}; use dom::canvasgradient::{CanvasGradient, CanvasGradientStyle, ToFillOrStrokeStyle};
use dom::canvaspattern::CanvasPattern; use dom::canvaspattern::CanvasPattern;
@ -55,8 +55,8 @@ use unpremultiplytable::UNPREMULTIPLY_TABLE;
#[allow(dead_code)] #[allow(dead_code)]
enum CanvasFillOrStrokeStyle { enum CanvasFillOrStrokeStyle {
Color(RGBA), Color(RGBA),
Gradient(JS<CanvasGradient>), Gradient(Dom<CanvasGradient>),
Pattern(JS<CanvasPattern>), Pattern(Dom<CanvasPattern>),
} }
// https://html.spec.whatwg.org/multipage/#canvasrenderingcontext2d // https://html.spec.whatwg.org/multipage/#canvasrenderingcontext2d
@ -67,16 +67,16 @@ pub struct CanvasRenderingContext2D {
ipc_renderer: IpcSender<CanvasMsg>, ipc_renderer: IpcSender<CanvasMsg>,
/// For rendering contexts created by an HTML canvas element, this is Some, /// For rendering contexts created by an HTML canvas element, this is Some,
/// for ones created by a paint worklet, this is None. /// for ones created by a paint worklet, this is None.
canvas: Option<JS<HTMLCanvasElement>>, canvas: Option<Dom<HTMLCanvasElement>>,
#[ignore_heap_size_of = "Arc"] #[ignore_heap_size_of = "Arc"]
image_cache: Arc<ImageCache>, image_cache: Arc<ImageCache>,
/// Any missing image URLs. /// Any missing image URLs.
missing_image_urls: DOMRefCell<Vec<ServoUrl>>, missing_image_urls: DomRefCell<Vec<ServoUrl>>,
/// The base URL for resolving CSS image URL values. /// The base URL for resolving CSS image URL values.
/// Needed because of https://github.com/servo/servo/issues/17625 /// Needed because of https://github.com/servo/servo/issues/17625
base_url: ServoUrl, base_url: ServoUrl,
state: DOMRefCell<CanvasContextState>, state: DomRefCell<CanvasContextState>,
saved_states: DOMRefCell<Vec<CanvasContextState>>, saved_states: DomRefCell<Vec<CanvasContextState>>,
origin_clean: Cell<bool>, origin_clean: Cell<bool>,
} }
@ -138,12 +138,12 @@ impl CanvasRenderingContext2D {
CanvasRenderingContext2D { CanvasRenderingContext2D {
reflector_: Reflector::new(), reflector_: Reflector::new(),
ipc_renderer: ipc_renderer, ipc_renderer: ipc_renderer,
canvas: canvas.map(JS::from_ref), canvas: canvas.map(Dom::from_ref),
image_cache: image_cache, image_cache: image_cache,
missing_image_urls: DOMRefCell::new(Vec::new()), missing_image_urls: DomRefCell::new(Vec::new()),
base_url: base_url, base_url: base_url,
state: DOMRefCell::new(CanvasContextState::new()), state: DomRefCell::new(CanvasContextState::new()),
saved_states: DOMRefCell::new(Vec::new()), saved_states: DomRefCell::new(Vec::new()),
origin_clean: Cell::new(true), origin_clean: Cell::new(true),
} }
} }
@ -151,7 +151,7 @@ impl CanvasRenderingContext2D {
pub fn new(global: &GlobalScope, pub fn new(global: &GlobalScope,
canvas: &HTMLCanvasElement, canvas: &HTMLCanvasElement,
size: Size2D<i32>) size: Size2D<i32>)
-> Root<CanvasRenderingContext2D> { -> DomRoot<CanvasRenderingContext2D> {
let window = window_from_node(canvas); let window = window_from_node(canvas);
let image_cache = window.image_cache(); let image_cache = window.image_cache();
let base_url = window.get_url(); let base_url = window.get_url();
@ -585,7 +585,7 @@ pub trait LayoutCanvasRenderingContext2DHelpers {
unsafe fn get_ipc_renderer(&self) -> IpcSender<CanvasMsg>; unsafe fn get_ipc_renderer(&self) -> IpcSender<CanvasMsg>;
} }
impl LayoutCanvasRenderingContext2DHelpers for LayoutJS<CanvasRenderingContext2D> { impl LayoutCanvasRenderingContext2DHelpers for LayoutDom<CanvasRenderingContext2D> {
#[allow(unsafe_code)] #[allow(unsafe_code)]
unsafe fn get_ipc_renderer(&self) -> IpcSender<CanvasMsg> { unsafe fn get_ipc_renderer(&self) -> IpcSender<CanvasMsg> {
(*self.unsafe_get()).ipc_renderer.clone() (*self.unsafe_get()).ipc_renderer.clone()
@ -603,10 +603,10 @@ impl LayoutCanvasRenderingContext2DHelpers for LayoutJS<CanvasRenderingContext2D
// FIXME: this behavior should might be generated by some annotattions to idl. // FIXME: this behavior should might be generated by some annotattions to idl.
impl CanvasRenderingContext2DMethods for CanvasRenderingContext2D { impl CanvasRenderingContext2DMethods for CanvasRenderingContext2D {
// https://html.spec.whatwg.org/multipage/#dom-context-2d-canvas // https://html.spec.whatwg.org/multipage/#dom-context-2d-canvas
fn Canvas(&self) -> Root<HTMLCanvasElement> { fn Canvas(&self) -> DomRoot<HTMLCanvasElement> {
// This method is not called from a paint worklet rendering context, // This method is not called from a paint worklet rendering context,
// so it's OK to panic if self.canvas is None. // so it's OK to panic if self.canvas is None.
Root::from_ref(self.canvas.as_ref().expect("No canvas.")) DomRoot::from_ref(self.canvas.as_ref().expect("No canvas."))
} }
// https://html.spec.whatwg.org/multipage/#dom-context-2d-save // https://html.spec.whatwg.org/multipage/#dom-context-2d-save
@ -997,10 +997,10 @@ impl CanvasRenderingContext2DMethods for CanvasRenderingContext2D {
StringOrCanvasGradientOrCanvasPattern::String(DOMString::from(result)) StringOrCanvasGradientOrCanvasPattern::String(DOMString::from(result))
}, },
CanvasFillOrStrokeStyle::Gradient(ref gradient) => { CanvasFillOrStrokeStyle::Gradient(ref gradient) => {
StringOrCanvasGradientOrCanvasPattern::CanvasGradient(Root::from_ref(&*gradient)) StringOrCanvasGradientOrCanvasPattern::CanvasGradient(DomRoot::from_ref(&*gradient))
}, },
CanvasFillOrStrokeStyle::Pattern(ref pattern) => { CanvasFillOrStrokeStyle::Pattern(ref pattern) => {
StringOrCanvasGradientOrCanvasPattern::CanvasPattern(Root::from_ref(&*pattern)) StringOrCanvasGradientOrCanvasPattern::CanvasPattern(DomRoot::from_ref(&*pattern))
} }
} }
} }
@ -1019,14 +1019,14 @@ impl CanvasRenderingContext2DMethods for CanvasRenderingContext2D {
}, },
StringOrCanvasGradientOrCanvasPattern::CanvasGradient(gradient) => { StringOrCanvasGradientOrCanvasPattern::CanvasGradient(gradient) => {
self.state.borrow_mut().stroke_style = self.state.borrow_mut().stroke_style =
CanvasFillOrStrokeStyle::Gradient(JS::from_ref(&*gradient)); CanvasFillOrStrokeStyle::Gradient(Dom::from_ref(&*gradient));
let msg = CanvasMsg::Canvas2d( let msg = CanvasMsg::Canvas2d(
Canvas2dMsg::SetStrokeStyle(gradient.to_fill_or_stroke_style())); Canvas2dMsg::SetStrokeStyle(gradient.to_fill_or_stroke_style()));
self.ipc_renderer.send(msg).unwrap(); self.ipc_renderer.send(msg).unwrap();
}, },
StringOrCanvasGradientOrCanvasPattern::CanvasPattern(pattern) => { StringOrCanvasGradientOrCanvasPattern::CanvasPattern(pattern) => {
self.state.borrow_mut().stroke_style = self.state.borrow_mut().stroke_style =
CanvasFillOrStrokeStyle::Pattern(JS::from_ref(&*pattern)); CanvasFillOrStrokeStyle::Pattern(Dom::from_ref(&*pattern));
let msg = CanvasMsg::Canvas2d( let msg = CanvasMsg::Canvas2d(
Canvas2dMsg::SetStrokeStyle(pattern.to_fill_or_stroke_style())); Canvas2dMsg::SetStrokeStyle(pattern.to_fill_or_stroke_style()));
self.ipc_renderer.send(msg).unwrap(); self.ipc_renderer.send(msg).unwrap();
@ -1046,10 +1046,10 @@ impl CanvasRenderingContext2DMethods for CanvasRenderingContext2D {
StringOrCanvasGradientOrCanvasPattern::String(DOMString::from(result)) StringOrCanvasGradientOrCanvasPattern::String(DOMString::from(result))
}, },
CanvasFillOrStrokeStyle::Gradient(ref gradient) => { CanvasFillOrStrokeStyle::Gradient(ref gradient) => {
StringOrCanvasGradientOrCanvasPattern::CanvasGradient(Root::from_ref(&*gradient)) StringOrCanvasGradientOrCanvasPattern::CanvasGradient(DomRoot::from_ref(&*gradient))
}, },
CanvasFillOrStrokeStyle::Pattern(ref pattern) => { CanvasFillOrStrokeStyle::Pattern(ref pattern) => {
StringOrCanvasGradientOrCanvasPattern::CanvasPattern(Root::from_ref(&*pattern)) StringOrCanvasGradientOrCanvasPattern::CanvasPattern(DomRoot::from_ref(&*pattern))
} }
} }
} }
@ -1068,14 +1068,14 @@ impl CanvasRenderingContext2DMethods for CanvasRenderingContext2D {
} }
StringOrCanvasGradientOrCanvasPattern::CanvasGradient(gradient) => { StringOrCanvasGradientOrCanvasPattern::CanvasGradient(gradient) => {
self.state.borrow_mut().fill_style = self.state.borrow_mut().fill_style =
CanvasFillOrStrokeStyle::Gradient(JS::from_ref(&*gradient)); CanvasFillOrStrokeStyle::Gradient(Dom::from_ref(&*gradient));
let msg = CanvasMsg::Canvas2d( let msg = CanvasMsg::Canvas2d(
Canvas2dMsg::SetFillStyle(gradient.to_fill_or_stroke_style())); Canvas2dMsg::SetFillStyle(gradient.to_fill_or_stroke_style()));
self.ipc_renderer.send(msg).unwrap(); self.ipc_renderer.send(msg).unwrap();
} }
StringOrCanvasGradientOrCanvasPattern::CanvasPattern(pattern) => { StringOrCanvasGradientOrCanvasPattern::CanvasPattern(pattern) => {
self.state.borrow_mut().fill_style = self.state.borrow_mut().fill_style =
CanvasFillOrStrokeStyle::Pattern(JS::from_ref(&*pattern)); CanvasFillOrStrokeStyle::Pattern(Dom::from_ref(&*pattern));
let msg = CanvasMsg::Canvas2d( let msg = CanvasMsg::Canvas2d(
Canvas2dMsg::SetFillStyle(pattern.to_fill_or_stroke_style())); Canvas2dMsg::SetFillStyle(pattern.to_fill_or_stroke_style()));
self.ipc_renderer.send(msg).unwrap(); self.ipc_renderer.send(msg).unwrap();
@ -1087,7 +1087,7 @@ impl CanvasRenderingContext2DMethods for CanvasRenderingContext2D {
} }
// https://html.spec.whatwg.org/multipage/#dom-context-2d-createimagedata // https://html.spec.whatwg.org/multipage/#dom-context-2d-createimagedata
fn CreateImageData(&self, sw: Finite<f64>, sh: Finite<f64>) -> Fallible<Root<ImageData>> { fn CreateImageData(&self, sw: Finite<f64>, sh: Finite<f64>) -> Fallible<DomRoot<ImageData>> {
if *sw == 0.0 || *sh == 0.0 { if *sw == 0.0 || *sh == 0.0 {
return Err(Error::IndexSize); return Err(Error::IndexSize);
} }
@ -1098,7 +1098,7 @@ impl CanvasRenderingContext2DMethods for CanvasRenderingContext2D {
} }
// https://html.spec.whatwg.org/multipage/#dom-context-2d-createimagedata // https://html.spec.whatwg.org/multipage/#dom-context-2d-createimagedata
fn CreateImageData_(&self, imagedata: &ImageData) -> Fallible<Root<ImageData>> { fn CreateImageData_(&self, imagedata: &ImageData) -> Fallible<DomRoot<ImageData>> {
ImageData::new(&self.global(), ImageData::new(&self.global(),
imagedata.Width(), imagedata.Width(),
imagedata.Height(), imagedata.Height(),
@ -1111,7 +1111,7 @@ impl CanvasRenderingContext2DMethods for CanvasRenderingContext2D {
sy: Finite<f64>, sy: Finite<f64>,
sw: Finite<f64>, sw: Finite<f64>,
sh: Finite<f64>) sh: Finite<f64>)
-> Fallible<Root<ImageData>> { -> Fallible<DomRoot<ImageData>> {
if !self.origin_is_clean() { if !self.origin_is_clean() {
return Err(Error::Security) return Err(Error::Security)
} }
@ -1198,7 +1198,7 @@ impl CanvasRenderingContext2DMethods for CanvasRenderingContext2D {
y0: Finite<f64>, y0: Finite<f64>,
x1: Finite<f64>, x1: Finite<f64>,
y1: Finite<f64>) y1: Finite<f64>)
-> Root<CanvasGradient> { -> DomRoot<CanvasGradient> {
CanvasGradient::new(&self.global(), CanvasGradient::new(&self.global(),
CanvasGradientStyle::Linear(LinearGradientStyle::new(*x0, CanvasGradientStyle::Linear(LinearGradientStyle::new(*x0,
*y0, *y0,
@ -1215,7 +1215,7 @@ impl CanvasRenderingContext2DMethods for CanvasRenderingContext2D {
x1: Finite<f64>, x1: Finite<f64>,
y1: Finite<f64>, y1: Finite<f64>,
r1: Finite<f64>) r1: Finite<f64>)
-> Fallible<Root<CanvasGradient>> { -> Fallible<DomRoot<CanvasGradient>> {
if *r0 < 0. || *r1 < 0. { if *r0 < 0. || *r1 < 0. {
return Err(Error::IndexSize); return Err(Error::IndexSize);
} }
@ -1234,7 +1234,7 @@ impl CanvasRenderingContext2DMethods for CanvasRenderingContext2D {
fn CreatePattern(&self, fn CreatePattern(&self,
image: CanvasImageSource, image: CanvasImageSource,
mut repetition: DOMString) mut repetition: DOMString)
-> Fallible<Root<CanvasPattern>> { -> Fallible<DomRoot<CanvasPattern>> {
let (image_data, image_size) = match image { let (image_data, image_size) = match image {
CanvasImageSource::HTMLImageElement(ref image) => { CanvasImageSource::HTMLImageElement(ref image) => {
// https://html.spec.whatwg.org/multipage/#img-error // https://html.spec.whatwg.org/multipage/#img-error

View file

@ -4,7 +4,7 @@
//! DOM bindings for `CharacterData`. //! DOM bindings for `CharacterData`.
use dom::bindings::cell::DOMRefCell; use dom::bindings::cell::DomRefCell;
use dom::bindings::codegen::Bindings::CharacterDataBinding::CharacterDataMethods; use dom::bindings::codegen::Bindings::CharacterDataBinding::CharacterDataMethods;
use dom::bindings::codegen::Bindings::NodeBinding::NodeBinding::NodeMethods; use dom::bindings::codegen::Bindings::NodeBinding::NodeBinding::NodeMethods;
use dom::bindings::codegen::Bindings::ProcessingInstructionBinding::ProcessingInstructionMethods; use dom::bindings::codegen::Bindings::ProcessingInstructionBinding::ProcessingInstructionMethods;
@ -12,7 +12,7 @@ use dom::bindings::codegen::InheritTypes::{CharacterDataTypeId, NodeTypeId};
use dom::bindings::codegen::UnionTypes::NodeOrString; use dom::bindings::codegen::UnionTypes::NodeOrString;
use dom::bindings::error::{Error, ErrorResult, Fallible}; use dom::bindings::error::{Error, ErrorResult, Fallible};
use dom::bindings::inheritance::Castable; use dom::bindings::inheritance::Castable;
use dom::bindings::js::{LayoutJS, Root}; use dom::bindings::root::{DomRoot, LayoutDom};
use dom::bindings::str::DOMString; use dom::bindings::str::DOMString;
use dom::comment::Comment; use dom::comment::Comment;
use dom::document::Document; use dom::document::Document;
@ -29,28 +29,28 @@ use std::cell::Ref;
#[dom_struct] #[dom_struct]
pub struct CharacterData { pub struct CharacterData {
node: Node, node: Node,
data: DOMRefCell<DOMString>, data: DomRefCell<DOMString>,
} }
impl CharacterData { impl CharacterData {
pub fn new_inherited(data: DOMString, document: &Document) -> CharacterData { pub fn new_inherited(data: DOMString, document: &Document) -> CharacterData {
CharacterData { CharacterData {
node: Node::new_inherited(document), node: Node::new_inherited(document),
data: DOMRefCell::new(data), data: DomRefCell::new(data),
} }
} }
pub fn clone_with_data(&self, data: DOMString, document: &Document) -> Root<Node> { pub fn clone_with_data(&self, data: DOMString, document: &Document) -> DomRoot<Node> {
match self.upcast::<Node>().type_id() { match self.upcast::<Node>().type_id() {
NodeTypeId::CharacterData(CharacterDataTypeId::Comment) => { NodeTypeId::CharacterData(CharacterDataTypeId::Comment) => {
Root::upcast(Comment::new(data, &document)) DomRoot::upcast(Comment::new(data, &document))
} }
NodeTypeId::CharacterData(CharacterDataTypeId::ProcessingInstruction) => { NodeTypeId::CharacterData(CharacterDataTypeId::ProcessingInstruction) => {
let pi = self.downcast::<ProcessingInstruction>().unwrap(); let pi = self.downcast::<ProcessingInstruction>().unwrap();
Root::upcast(ProcessingInstruction::new(pi.Target(), data, &document)) DomRoot::upcast(ProcessingInstruction::new(pi.Target(), data, &document))
}, },
NodeTypeId::CharacterData(CharacterDataTypeId::Text) => { NodeTypeId::CharacterData(CharacterDataTypeId::Text) => {
Root::upcast(Text::new(data, &document)) DomRoot::upcast(Text::new(data, &document))
}, },
_ => unreachable!(), _ => unreachable!(),
} }
@ -237,13 +237,13 @@ impl CharacterDataMethods for CharacterData {
} }
// https://dom.spec.whatwg.org/#dom-nondocumenttypechildnode-previouselementsibling // https://dom.spec.whatwg.org/#dom-nondocumenttypechildnode-previouselementsibling
fn GetPreviousElementSibling(&self) -> Option<Root<Element>> { fn GetPreviousElementSibling(&self) -> Option<DomRoot<Element>> {
self.upcast::<Node>().preceding_siblings().filter_map(Root::downcast).next() self.upcast::<Node>().preceding_siblings().filter_map(DomRoot::downcast).next()
} }
// https://dom.spec.whatwg.org/#dom-nondocumenttypechildnode-nextelementsibling // https://dom.spec.whatwg.org/#dom-nondocumenttypechildnode-nextelementsibling
fn GetNextElementSibling(&self) -> Option<Root<Element>> { fn GetNextElementSibling(&self) -> Option<DomRoot<Element>> {
self.upcast::<Node>().following_siblings().filter_map(Root::downcast).next() self.upcast::<Node>().following_siblings().filter_map(DomRoot::downcast).next()
} }
} }
@ -253,7 +253,7 @@ pub trait LayoutCharacterDataHelpers {
} }
#[allow(unsafe_code)] #[allow(unsafe_code)]
impl LayoutCharacterDataHelpers for LayoutJS<CharacterData> { impl LayoutCharacterDataHelpers for LayoutDom<CharacterData> {
#[inline] #[inline]
unsafe fn data_for_layout(&self) -> &str { unsafe fn data_for_layout(&self) -> &str {
&(*self.unsafe_get()).data.borrow_for_layout() &(*self.unsafe_get()).data.borrow_for_layout()

View file

@ -4,8 +4,8 @@
use dom::bindings::codegen::Bindings::ClientBinding::{ClientMethods, Wrap}; use dom::bindings::codegen::Bindings::ClientBinding::{ClientMethods, Wrap};
use dom::bindings::codegen::Bindings::ClientBinding::FrameType; use dom::bindings::codegen::Bindings::ClientBinding::FrameType;
use dom::bindings::js::{Root, MutNullableJS};
use dom::bindings::reflector::{Reflector, reflect_dom_object}; use dom::bindings::reflector::{Reflector, reflect_dom_object};
use dom::bindings::root::{DomRoot, MutNullableDom};
use dom::bindings::str::{DOMString, USVString}; use dom::bindings::str::{DOMString, USVString};
use dom::serviceworker::ServiceWorker; use dom::serviceworker::ServiceWorker;
use dom::window::Window; use dom::window::Window;
@ -17,7 +17,7 @@ use uuid::Uuid;
#[dom_struct] #[dom_struct]
pub struct Client { pub struct Client {
reflector_: Reflector, reflector_: Reflector,
active_worker: MutNullableJS<ServiceWorker>, active_worker: MutNullableDom<ServiceWorker>,
url: ServoUrl, url: ServoUrl,
frame_type: FrameType, frame_type: FrameType,
#[ignore_heap_size_of = "Defined in uuid"] #[ignore_heap_size_of = "Defined in uuid"]
@ -35,7 +35,7 @@ impl Client {
} }
} }
pub fn new(window: &Window) -> Root<Client> { pub fn new(window: &Window) -> DomRoot<Client> {
reflect_dom_object(box Client::new_inherited(window.get_url()), reflect_dom_object(box Client::new_inherited(window.get_url()),
window, window,
Wrap) Wrap)
@ -45,7 +45,7 @@ impl Client {
self.url.clone() self.url.clone()
} }
pub fn get_controller(&self) -> Option<Root<ServiceWorker>> { pub fn get_controller(&self) -> Option<DomRoot<ServiceWorker>> {
self.active_worker.get() self.active_worker.get()
} }

View file

@ -7,8 +7,8 @@ use dom::bindings::codegen::Bindings::CloseEventBinding::CloseEventMethods;
use dom::bindings::codegen::Bindings::EventBinding::EventMethods; use dom::bindings::codegen::Bindings::EventBinding::EventMethods;
use dom::bindings::error::Fallible; use dom::bindings::error::Fallible;
use dom::bindings::inheritance::Castable; use dom::bindings::inheritance::Castable;
use dom::bindings::js::Root;
use dom::bindings::reflector::reflect_dom_object; use dom::bindings::reflector::reflect_dom_object;
use dom::bindings::root::DomRoot;
use dom::bindings::str::DOMString; use dom::bindings::str::DOMString;
use dom::event::{Event, EventBubbles, EventCancelable}; use dom::event::{Event, EventBubbles, EventCancelable};
use dom::globalscope::GlobalScope; use dom::globalscope::GlobalScope;
@ -33,7 +33,7 @@ impl CloseEvent {
} }
} }
pub fn new_uninitialized(global: &GlobalScope) -> Root<CloseEvent> { pub fn new_uninitialized(global: &GlobalScope) -> DomRoot<CloseEvent> {
reflect_dom_object(box CloseEvent::new_inherited(false, 0, DOMString::new()), reflect_dom_object(box CloseEvent::new_inherited(false, 0, DOMString::new()),
global, global,
CloseEventBinding::Wrap) CloseEventBinding::Wrap)
@ -46,7 +46,7 @@ impl CloseEvent {
wasClean: bool, wasClean: bool,
code: u16, code: u16,
reason: DOMString) reason: DOMString)
-> Root<CloseEvent> { -> DomRoot<CloseEvent> {
let event = box CloseEvent::new_inherited(wasClean, code, reason); let event = box CloseEvent::new_inherited(wasClean, code, reason);
let ev = reflect_dom_object(event, global, CloseEventBinding::Wrap); let ev = reflect_dom_object(event, global, CloseEventBinding::Wrap);
{ {
@ -61,7 +61,7 @@ impl CloseEvent {
pub fn Constructor(global: &GlobalScope, pub fn Constructor(global: &GlobalScope,
type_: DOMString, type_: DOMString,
init: &CloseEventBinding::CloseEventInit) init: &CloseEventBinding::CloseEventInit)
-> Fallible<Root<CloseEvent>> { -> Fallible<DomRoot<CloseEvent>> {
let bubbles = EventBubbles::from(init.parent.bubbles); let bubbles = EventBubbles::from(init.parent.bubbles);
let cancelable = EventCancelable::from(init.parent.cancelable); let cancelable = EventCancelable::from(init.parent.cancelable);
Ok(CloseEvent::new(global, Ok(CloseEvent::new(global,

View file

@ -5,7 +5,7 @@
use dom::bindings::codegen::Bindings::CommentBinding; use dom::bindings::codegen::Bindings::CommentBinding;
use dom::bindings::codegen::Bindings::WindowBinding::WindowMethods; use dom::bindings::codegen::Bindings::WindowBinding::WindowMethods;
use dom::bindings::error::Fallible; use dom::bindings::error::Fallible;
use dom::bindings::js::Root; use dom::bindings::root::DomRoot;
use dom::bindings::str::DOMString; use dom::bindings::str::DOMString;
use dom::characterdata::CharacterData; use dom::characterdata::CharacterData;
use dom::document::Document; use dom::document::Document;
@ -26,13 +26,13 @@ impl Comment {
} }
} }
pub fn new(text: DOMString, document: &Document) -> Root<Comment> { pub fn new(text: DOMString, document: &Document) -> DomRoot<Comment> {
Node::reflect_node(box Comment::new_inherited(text, document), Node::reflect_node(box Comment::new_inherited(text, document),
document, document,
CommentBinding::Wrap) CommentBinding::Wrap)
} }
pub fn Constructor(window: &Window, data: DOMString) -> Fallible<Root<Comment>> { pub fn Constructor(window: &Window, data: DOMString) -> Fallible<DomRoot<Comment>> {
let document = window.Document(); let document = window.Document();
Ok(Comment::new(data, &document)) Ok(Comment::new(data, &document))
} }

View file

@ -5,8 +5,8 @@
use dom::bindings::codegen::Bindings::CompositionEventBinding::{self, CompositionEventMethods}; use dom::bindings::codegen::Bindings::CompositionEventBinding::{self, CompositionEventMethods};
use dom::bindings::codegen::Bindings::UIEventBinding::UIEventBinding::UIEventMethods; use dom::bindings::codegen::Bindings::UIEventBinding::UIEventBinding::UIEventMethods;
use dom::bindings::error::Fallible; use dom::bindings::error::Fallible;
use dom::bindings::js::{Root, RootedReference};
use dom::bindings::reflector::reflect_dom_object; use dom::bindings::reflector::reflect_dom_object;
use dom::bindings::root::{DomRoot, RootedReference};
use dom::bindings::str::DOMString; use dom::bindings::str::DOMString;
use dom::uievent::UIEvent; use dom::uievent::UIEvent;
use dom::window::Window; use dom::window::Window;
@ -25,7 +25,7 @@ impl CompositionEvent {
cancelable: bool, cancelable: bool,
view: Option<&Window>, view: Option<&Window>,
detail: i32, detail: i32,
data: DOMString) -> Root<CompositionEvent> { data: DOMString) -> DomRoot<CompositionEvent> {
let ev = reflect_dom_object(box CompositionEvent { let ev = reflect_dom_object(box CompositionEvent {
uievent: UIEvent::new_inherited(), uievent: UIEvent::new_inherited(),
data: data, data: data,
@ -39,7 +39,7 @@ impl CompositionEvent {
pub fn Constructor(window: &Window, pub fn Constructor(window: &Window,
type_: DOMString, type_: DOMString,
init: &CompositionEventBinding::CompositionEventInit) init: &CompositionEventBinding::CompositionEventInit)
-> Fallible<Root<CompositionEvent>> { -> Fallible<DomRoot<CompositionEvent>> {
let event = CompositionEvent::new(window, let event = CompositionEvent::new(window,
type_, type_,
init.parent.parent.bubbles, init.parent.parent.bubbles,

View file

@ -3,8 +3,8 @@
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use dom::bindings::error::{report_pending_exception, throw_dom_exception}; use dom::bindings::error::{report_pending_exception, throw_dom_exception};
use dom::bindings::js::Root;
use dom::bindings::reflector::DomObject; use dom::bindings::reflector::DomObject;
use dom::bindings::root::DomRoot;
use dom::customelementregistry::{is_valid_custom_element_name, upgrade_element}; use dom::customelementregistry::{is_valid_custom_element_name, upgrade_element};
use dom::document::Document; use dom::document::Document;
use dom::element::{CustomElementCreationMode, CustomElementState, Element, ElementCreator}; use dom::element::{CustomElementCreationMode, CustomElementState, Element, ElementCreator};
@ -87,17 +87,17 @@ use servo_config::prefs::PREFS;
fn create_svg_element(name: QualName, fn create_svg_element(name: QualName,
prefix: Option<Prefix>, prefix: Option<Prefix>,
document: &Document) document: &Document)
-> Root<Element> { -> DomRoot<Element> {
assert!(name.ns == ns!(svg)); assert!(name.ns == ns!(svg));
macro_rules! make( macro_rules! make(
($ctor:ident) => ({ ($ctor:ident) => ({
let obj = $ctor::new(name.local, prefix, document); let obj = $ctor::new(name.local, prefix, document);
Root::upcast(obj) DomRoot::upcast(obj)
}); });
($ctor:ident, $($arg:expr),+) => ({ ($ctor:ident, $($arg:expr),+) => ({
let obj = $ctor::new(name.local, prefix, document, $($arg),+); let obj = $ctor::new(name.local, prefix, document, $($arg),+);
Root::upcast(obj) DomRoot::upcast(obj)
}) })
); );
@ -119,7 +119,7 @@ fn create_html_element(name: QualName,
document: &Document, document: &Document,
creator: ElementCreator, creator: ElementCreator,
mode: CustomElementCreationMode) mode: CustomElementCreationMode)
-> Root<Element> { -> DomRoot<Element> {
assert!(name.ns == ns!(html)); assert!(name.ns == ns!(html));
// Step 4 // Step 4
@ -129,7 +129,7 @@ fn create_html_element(name: QualName,
if definition.is_autonomous() { if definition.is_autonomous() {
match mode { match mode {
CustomElementCreationMode::Asynchronous => { CustomElementCreationMode::Asynchronous => {
let result = Root::upcast::<Element>( let result = DomRoot::upcast::<Element>(
HTMLElement::new(name.local.clone(), prefix.clone(), document)); HTMLElement::new(name.local.clone(), prefix.clone(), document));
result.set_custom_element_state(CustomElementState::Undefined); result.set_custom_element_state(CustomElementState::Undefined);
ScriptThread::enqueue_upgrade_reaction(&*result, definition); ScriptThread::enqueue_upgrade_reaction(&*result, definition);
@ -155,7 +155,7 @@ fn create_html_element(name: QualName,
} }
// Step 6.1.2 // Step 6.1.2
let element = Root::upcast::<Element>( let element = DomRoot::upcast::<Element>(
HTMLUnknownElement::new(local_name, prefix, document)); HTMLUnknownElement::new(local_name, prefix, document));
element.set_custom_element_state(CustomElementState::Failed); element.set_custom_element_state(CustomElementState::Failed);
element element
@ -195,17 +195,17 @@ pub fn create_native_html_element(name: QualName,
prefix: Option<Prefix>, prefix: Option<Prefix>,
document: &Document, document: &Document,
creator: ElementCreator) creator: ElementCreator)
-> Root<Element> { -> DomRoot<Element> {
assert!(name.ns == ns!(html)); assert!(name.ns == ns!(html));
macro_rules! make( macro_rules! make(
($ctor:ident) => ({ ($ctor:ident) => ({
let obj = $ctor::new(name.local, prefix, document); let obj = $ctor::new(name.local, prefix, document);
Root::upcast(obj) DomRoot::upcast(obj)
}); });
($ctor:ident, $($arg:expr),+) => ({ ($ctor:ident, $($arg:expr),+) => ({
let obj = $ctor::new(name.local, prefix, document, $($arg),+); let obj = $ctor::new(name.local, prefix, document, $($arg),+);
Root::upcast(obj) DomRoot::upcast(obj)
}) })
); );
@ -364,7 +364,7 @@ pub fn create_element(name: QualName,
document: &Document, document: &Document,
creator: ElementCreator, creator: ElementCreator,
mode: CustomElementCreationMode) mode: CustomElementCreationMode)
-> Root<Element> { -> DomRoot<Element> {
let prefix = name.prefix.clone(); let prefix = name.prefix.clone();
match name.ns { match name.ns {
ns!(html) => create_html_element(name, prefix, is, document, creator, mode), ns!(html) => create_html_element(name, prefix, is, document, creator, mode),

View file

@ -3,12 +3,12 @@
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use core::nonzero::NonZero; use core::nonzero::NonZero;
use dom::bindings::cell::DOMRefCell; use dom::bindings::cell::DomRefCell;
use dom::bindings::codegen::Bindings::CryptoBinding; use dom::bindings::codegen::Bindings::CryptoBinding;
use dom::bindings::codegen::Bindings::CryptoBinding::CryptoMethods; use dom::bindings::codegen::Bindings::CryptoBinding::CryptoMethods;
use dom::bindings::error::{Error, Fallible}; use dom::bindings::error::{Error, Fallible};
use dom::bindings::js::Root;
use dom::bindings::reflector::{Reflector, reflect_dom_object}; use dom::bindings::reflector::{Reflector, reflect_dom_object};
use dom::bindings::root::DomRoot;
use dom::globalscope::GlobalScope; use dom::globalscope::GlobalScope;
use dom_struct::dom_struct; use dom_struct::dom_struct;
use js::jsapi::{JSContext, JSObject}; use js::jsapi::{JSContext, JSObject};
@ -22,18 +22,18 @@ unsafe_no_jsmanaged_fields!(ServoRng);
pub struct Crypto { pub struct Crypto {
reflector_: Reflector, reflector_: Reflector,
#[ignore_heap_size_of = "Defined in rand"] #[ignore_heap_size_of = "Defined in rand"]
rng: DOMRefCell<ServoRng>, rng: DomRefCell<ServoRng>,
} }
impl Crypto { impl Crypto {
fn new_inherited() -> Crypto { fn new_inherited() -> Crypto {
Crypto { Crypto {
reflector_: Reflector::new(), reflector_: Reflector::new(),
rng: DOMRefCell::new(ServoRng::new()), rng: DomRefCell::new(ServoRng::new()),
} }
} }
pub fn new(global: &GlobalScope) -> Root<Crypto> { pub fn new(global: &GlobalScope) -> DomRoot<Crypto> {
reflect_dom_object(box Crypto::new_inherited(), global, CryptoBinding::Wrap) reflect_dom_object(box Crypto::new_inherited(), global, CryptoBinding::Wrap)
} }
} }

View file

@ -3,8 +3,8 @@
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use dom::bindings::codegen::Bindings::CSSFontFaceRuleBinding; use dom::bindings::codegen::Bindings::CSSFontFaceRuleBinding;
use dom::bindings::js::Root;
use dom::bindings::reflector::reflect_dom_object; use dom::bindings::reflector::reflect_dom_object;
use dom::bindings::root::DomRoot;
use dom::bindings::str::DOMString; use dom::bindings::str::DOMString;
use dom::cssrule::{CSSRule, SpecificCSSRule}; use dom::cssrule::{CSSRule, SpecificCSSRule};
use dom::cssstylesheet::CSSStyleSheet; use dom::cssstylesheet::CSSStyleSheet;
@ -32,7 +32,7 @@ impl CSSFontFaceRule {
#[allow(unrooted_must_root)] #[allow(unrooted_must_root)]
pub fn new(window: &Window, parent_stylesheet: &CSSStyleSheet, pub fn new(window: &Window, parent_stylesheet: &CSSStyleSheet,
fontfacerule: Arc<Locked<FontFaceRule>>) -> Root<CSSFontFaceRule> { fontfacerule: Arc<Locked<FontFaceRule>>) -> DomRoot<CSSFontFaceRule> {
reflect_dom_object(box CSSFontFaceRule::new_inherited(parent_stylesheet, fontfacerule), reflect_dom_object(box CSSFontFaceRule::new_inherited(parent_stylesheet, fontfacerule),
window, window,
CSSFontFaceRuleBinding::Wrap) CSSFontFaceRuleBinding::Wrap)

View file

@ -5,8 +5,8 @@
use dom::bindings::codegen::Bindings::CSSGroupingRuleBinding::CSSGroupingRuleMethods; use dom::bindings::codegen::Bindings::CSSGroupingRuleBinding::CSSGroupingRuleMethods;
use dom::bindings::error::{ErrorResult, Fallible}; use dom::bindings::error::{ErrorResult, Fallible};
use dom::bindings::inheritance::Castable; use dom::bindings::inheritance::Castable;
use dom::bindings::js::{MutNullableJS, Root};
use dom::bindings::reflector::DomObject; use dom::bindings::reflector::DomObject;
use dom::bindings::root::{DomRoot, MutNullableDom};
use dom::bindings::str::DOMString; use dom::bindings::str::DOMString;
use dom::cssrule::CSSRule; use dom::cssrule::CSSRule;
use dom::cssrulelist::{CSSRuleList, RulesSource}; use dom::cssrulelist::{CSSRuleList, RulesSource};
@ -21,7 +21,7 @@ pub struct CSSGroupingRule {
cssrule: CSSRule, cssrule: CSSRule,
#[ignore_heap_size_of = "Arc"] #[ignore_heap_size_of = "Arc"]
rules: Arc<Locked<StyleCssRules>>, rules: Arc<Locked<StyleCssRules>>,
rulelist: MutNullableJS<CSSRuleList>, rulelist: MutNullableDom<CSSRuleList>,
} }
impl CSSGroupingRule { impl CSSGroupingRule {
@ -30,11 +30,11 @@ impl CSSGroupingRule {
CSSGroupingRule { CSSGroupingRule {
cssrule: CSSRule::new_inherited(parent_stylesheet), cssrule: CSSRule::new_inherited(parent_stylesheet),
rules: rules, rules: rules,
rulelist: MutNullableJS::new(None), rulelist: MutNullableDom::new(None),
} }
} }
fn rulelist(&self) -> Root<CSSRuleList> { fn rulelist(&self) -> DomRoot<CSSRuleList> {
let parent_stylesheet = self.upcast::<CSSRule>().parent_stylesheet(); let parent_stylesheet = self.upcast::<CSSRule>().parent_stylesheet();
self.rulelist.or_init(|| CSSRuleList::new(self.global().as_window(), self.rulelist.or_init(|| CSSRuleList::new(self.global().as_window(),
parent_stylesheet, parent_stylesheet,
@ -52,7 +52,7 @@ impl CSSGroupingRule {
impl CSSGroupingRuleMethods for CSSGroupingRule { impl CSSGroupingRuleMethods for CSSGroupingRule {
// https://drafts.csswg.org/cssom/#dom-cssgroupingrule-cssrules // https://drafts.csswg.org/cssom/#dom-cssgroupingrule-cssrules
fn CssRules(&self) -> Root<CSSRuleList> { fn CssRules(&self) -> DomRoot<CSSRuleList> {
// XXXManishearth check origin clean flag // XXXManishearth check origin clean flag
self.rulelist() self.rulelist()
} }

View file

@ -3,8 +3,8 @@
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use dom::bindings::codegen::Bindings::CSSImportRuleBinding; use dom::bindings::codegen::Bindings::CSSImportRuleBinding;
use dom::bindings::js::Root;
use dom::bindings::reflector::reflect_dom_object; use dom::bindings::reflector::reflect_dom_object;
use dom::bindings::root::DomRoot;
use dom::bindings::str::DOMString; use dom::bindings::str::DOMString;
use dom::cssrule::{CSSRule, SpecificCSSRule}; use dom::cssrule::{CSSRule, SpecificCSSRule};
use dom::cssstylesheet::CSSStyleSheet; use dom::cssstylesheet::CSSStyleSheet;
@ -34,7 +34,7 @@ impl CSSImportRule {
#[allow(unrooted_must_root)] #[allow(unrooted_must_root)]
pub fn new(window: &Window, pub fn new(window: &Window,
parent_stylesheet: &CSSStyleSheet, parent_stylesheet: &CSSStyleSheet,
import_rule: Arc<Locked<ImportRule>>) -> Root<Self> { import_rule: Arc<Locked<ImportRule>>) -> DomRoot<Self> {
reflect_dom_object(box Self::new_inherited(parent_stylesheet, import_rule), reflect_dom_object(box Self::new_inherited(parent_stylesheet, import_rule),
window, window,
CSSImportRuleBinding::Wrap) CSSImportRuleBinding::Wrap)

View file

@ -4,8 +4,8 @@
use dom::bindings::codegen::Bindings::CSSKeyframeRuleBinding::{self, CSSKeyframeRuleMethods}; use dom::bindings::codegen::Bindings::CSSKeyframeRuleBinding::{self, CSSKeyframeRuleMethods};
use dom::bindings::inheritance::Castable; use dom::bindings::inheritance::Castable;
use dom::bindings::js::{JS, MutNullableJS, Root};
use dom::bindings::reflector::{DomObject, reflect_dom_object}; use dom::bindings::reflector::{DomObject, reflect_dom_object};
use dom::bindings::root::{Dom, DomRoot, MutNullableDom};
use dom::bindings::str::DOMString; use dom::bindings::str::DOMString;
use dom::cssrule::{CSSRule, SpecificCSSRule}; use dom::cssrule::{CSSRule, SpecificCSSRule};
use dom::cssstyledeclaration::{CSSModificationAccess, CSSStyleDeclaration, CSSStyleOwner}; use dom::cssstyledeclaration::{CSSModificationAccess, CSSStyleDeclaration, CSSStyleOwner};
@ -21,7 +21,7 @@ pub struct CSSKeyframeRule {
cssrule: CSSRule, cssrule: CSSRule,
#[ignore_heap_size_of = "Arc"] #[ignore_heap_size_of = "Arc"]
keyframerule: Arc<Locked<Keyframe>>, keyframerule: Arc<Locked<Keyframe>>,
style_decl: MutNullableJS<CSSStyleDeclaration>, style_decl: MutNullableDom<CSSStyleDeclaration>,
} }
impl CSSKeyframeRule { impl CSSKeyframeRule {
@ -36,7 +36,7 @@ impl CSSKeyframeRule {
#[allow(unrooted_must_root)] #[allow(unrooted_must_root)]
pub fn new(window: &Window, parent_stylesheet: &CSSStyleSheet, pub fn new(window: &Window, parent_stylesheet: &CSSStyleSheet,
keyframerule: Arc<Locked<Keyframe>>) -> Root<CSSKeyframeRule> { keyframerule: Arc<Locked<Keyframe>>) -> DomRoot<CSSKeyframeRule> {
reflect_dom_object(box CSSKeyframeRule::new_inherited(parent_stylesheet, keyframerule), reflect_dom_object(box CSSKeyframeRule::new_inherited(parent_stylesheet, keyframerule),
window, window,
CSSKeyframeRuleBinding::Wrap) CSSKeyframeRuleBinding::Wrap)
@ -45,13 +45,13 @@ impl CSSKeyframeRule {
impl CSSKeyframeRuleMethods for CSSKeyframeRule { impl CSSKeyframeRuleMethods for CSSKeyframeRule {
// https://drafts.csswg.org/css-animations/#dom-csskeyframerule-style // https://drafts.csswg.org/css-animations/#dom-csskeyframerule-style
fn Style(&self) -> Root<CSSStyleDeclaration> { fn Style(&self) -> DomRoot<CSSStyleDeclaration> {
self.style_decl.or_init(|| { self.style_decl.or_init(|| {
let guard = self.cssrule.shared_lock().read(); let guard = self.cssrule.shared_lock().read();
CSSStyleDeclaration::new( CSSStyleDeclaration::new(
self.global().as_window(), self.global().as_window(),
CSSStyleOwner::CSSRule( CSSStyleOwner::CSSRule(
JS::from_ref(self.upcast()), Dom::from_ref(self.upcast()),
self.keyframerule.read_with(&guard).block.clone(), self.keyframerule.read_with(&guard).block.clone(),
), ),
None, None,

View file

@ -7,8 +7,8 @@ use dom::bindings::codegen::Bindings::CSSKeyframesRuleBinding;
use dom::bindings::codegen::Bindings::CSSKeyframesRuleBinding::CSSKeyframesRuleMethods; use dom::bindings::codegen::Bindings::CSSKeyframesRuleBinding::CSSKeyframesRuleMethods;
use dom::bindings::error::ErrorResult; use dom::bindings::error::ErrorResult;
use dom::bindings::inheritance::Castable; use dom::bindings::inheritance::Castable;
use dom::bindings::js::{MutNullableJS, Root};
use dom::bindings::reflector::{DomObject, reflect_dom_object}; use dom::bindings::reflector::{DomObject, reflect_dom_object};
use dom::bindings::root::{DomRoot, MutNullableDom};
use dom::bindings::str::DOMString; use dom::bindings::str::DOMString;
use dom::csskeyframerule::CSSKeyframeRule; use dom::csskeyframerule::CSSKeyframeRule;
use dom::cssrule::{CSSRule, SpecificCSSRule}; use dom::cssrule::{CSSRule, SpecificCSSRule};
@ -26,7 +26,7 @@ pub struct CSSKeyframesRule {
cssrule: CSSRule, cssrule: CSSRule,
#[ignore_heap_size_of = "Arc"] #[ignore_heap_size_of = "Arc"]
keyframesrule: Arc<Locked<KeyframesRule>>, keyframesrule: Arc<Locked<KeyframesRule>>,
rulelist: MutNullableJS<CSSRuleList>, rulelist: MutNullableDom<CSSRuleList>,
} }
impl CSSKeyframesRule { impl CSSKeyframesRule {
@ -35,19 +35,19 @@ impl CSSKeyframesRule {
CSSKeyframesRule { CSSKeyframesRule {
cssrule: CSSRule::new_inherited(parent_stylesheet), cssrule: CSSRule::new_inherited(parent_stylesheet),
keyframesrule: keyframesrule, keyframesrule: keyframesrule,
rulelist: MutNullableJS::new(None), rulelist: MutNullableDom::new(None),
} }
} }
#[allow(unrooted_must_root)] #[allow(unrooted_must_root)]
pub fn new(window: &Window, parent_stylesheet: &CSSStyleSheet, pub fn new(window: &Window, parent_stylesheet: &CSSStyleSheet,
keyframesrule: Arc<Locked<KeyframesRule>>) -> Root<CSSKeyframesRule> { keyframesrule: Arc<Locked<KeyframesRule>>) -> DomRoot<CSSKeyframesRule> {
reflect_dom_object(box CSSKeyframesRule::new_inherited(parent_stylesheet, keyframesrule), reflect_dom_object(box CSSKeyframesRule::new_inherited(parent_stylesheet, keyframesrule),
window, window,
CSSKeyframesRuleBinding::Wrap) CSSKeyframesRuleBinding::Wrap)
} }
fn rulelist(&self) -> Root<CSSRuleList> { fn rulelist(&self) -> DomRoot<CSSRuleList> {
self.rulelist.or_init(|| { self.rulelist.or_init(|| {
let parent_stylesheet = &self.upcast::<CSSRule>().parent_stylesheet(); let parent_stylesheet = &self.upcast::<CSSRule>().parent_stylesheet();
CSSRuleList::new(self.global().as_window(), CSSRuleList::new(self.global().as_window(),
@ -76,7 +76,7 @@ impl CSSKeyframesRule {
impl CSSKeyframesRuleMethods for CSSKeyframesRule { impl CSSKeyframesRuleMethods for CSSKeyframesRule {
// https://drafts.csswg.org/css-animations/#dom-csskeyframesrule-cssrules // https://drafts.csswg.org/css-animations/#dom-csskeyframesrule-cssrules
fn CssRules(&self) -> Root<CSSRuleList> { fn CssRules(&self) -> DomRoot<CSSRuleList> {
self.rulelist() self.rulelist()
} }
@ -104,10 +104,10 @@ impl CSSKeyframesRuleMethods for CSSKeyframesRule {
} }
// https://drafts.csswg.org/css-animations/#dom-csskeyframesrule-findrule // https://drafts.csswg.org/css-animations/#dom-csskeyframesrule-findrule
fn FindRule(&self, selector: DOMString) -> Option<Root<CSSKeyframeRule>> { fn FindRule(&self, selector: DOMString) -> Option<DomRoot<CSSKeyframeRule>> {
self.find_rule(&selector).and_then(|idx| { self.find_rule(&selector).and_then(|idx| {
self.rulelist().item(idx as u32) self.rulelist().item(idx as u32)
}).and_then(Root::downcast) }).and_then(DomRoot::downcast)
} }
// https://drafts.csswg.org/css-animations/#dom-csskeyframesrule-name // https://drafts.csswg.org/css-animations/#dom-csskeyframesrule-name

View file

@ -6,8 +6,8 @@ use cssparser::{Parser, ParserInput};
use dom::bindings::codegen::Bindings::CSSMediaRuleBinding; use dom::bindings::codegen::Bindings::CSSMediaRuleBinding;
use dom::bindings::codegen::Bindings::CSSMediaRuleBinding::CSSMediaRuleMethods; use dom::bindings::codegen::Bindings::CSSMediaRuleBinding::CSSMediaRuleMethods;
use dom::bindings::codegen::Bindings::WindowBinding::WindowBinding::WindowMethods; use dom::bindings::codegen::Bindings::WindowBinding::WindowBinding::WindowMethods;
use dom::bindings::js::{MutNullableJS, Root};
use dom::bindings::reflector::{DomObject, reflect_dom_object}; use dom::bindings::reflector::{DomObject, reflect_dom_object};
use dom::bindings::root::{DomRoot, MutNullableDom};
use dom::bindings::str::DOMString; use dom::bindings::str::DOMString;
use dom::cssconditionrule::CSSConditionRule; use dom::cssconditionrule::CSSConditionRule;
use dom::cssrule::SpecificCSSRule; use dom::cssrule::SpecificCSSRule;
@ -27,7 +27,7 @@ pub struct CSSMediaRule {
cssconditionrule: CSSConditionRule, cssconditionrule: CSSConditionRule,
#[ignore_heap_size_of = "Arc"] #[ignore_heap_size_of = "Arc"]
mediarule: Arc<Locked<MediaRule>>, mediarule: Arc<Locked<MediaRule>>,
medialist: MutNullableJS<MediaList>, medialist: MutNullableDom<MediaList>,
} }
impl CSSMediaRule { impl CSSMediaRule {
@ -38,19 +38,19 @@ impl CSSMediaRule {
CSSMediaRule { CSSMediaRule {
cssconditionrule: CSSConditionRule::new_inherited(parent_stylesheet, list), cssconditionrule: CSSConditionRule::new_inherited(parent_stylesheet, list),
mediarule: mediarule, mediarule: mediarule,
medialist: MutNullableJS::new(None), medialist: MutNullableDom::new(None),
} }
} }
#[allow(unrooted_must_root)] #[allow(unrooted_must_root)]
pub fn new(window: &Window, parent_stylesheet: &CSSStyleSheet, pub fn new(window: &Window, parent_stylesheet: &CSSStyleSheet,
mediarule: Arc<Locked<MediaRule>>) -> Root<CSSMediaRule> { mediarule: Arc<Locked<MediaRule>>) -> DomRoot<CSSMediaRule> {
reflect_dom_object(box CSSMediaRule::new_inherited(parent_stylesheet, mediarule), reflect_dom_object(box CSSMediaRule::new_inherited(parent_stylesheet, mediarule),
window, window,
CSSMediaRuleBinding::Wrap) CSSMediaRuleBinding::Wrap)
} }
fn medialist(&self) -> Root<MediaList> { fn medialist(&self) -> DomRoot<MediaList> {
self.medialist.or_init(|| { self.medialist.or_init(|| {
let guard = self.cssconditionrule.shared_lock().read(); let guard = self.cssconditionrule.shared_lock().read();
MediaList::new(self.global().as_window(), MediaList::new(self.global().as_window(),
@ -108,7 +108,7 @@ impl SpecificCSSRule for CSSMediaRule {
impl CSSMediaRuleMethods for CSSMediaRule { impl CSSMediaRuleMethods for CSSMediaRule {
// https://drafts.csswg.org/cssom/#dom-cssgroupingrule-media // https://drafts.csswg.org/cssom/#dom-cssgroupingrule-media
fn Media(&self) -> Root<MediaList> { fn Media(&self) -> DomRoot<MediaList> {
self.medialist() self.medialist()
} }
} }

View file

@ -4,8 +4,8 @@
use dom::bindings::codegen::Bindings::CSSNamespaceRuleBinding; use dom::bindings::codegen::Bindings::CSSNamespaceRuleBinding;
use dom::bindings::codegen::Bindings::CSSNamespaceRuleBinding::CSSNamespaceRuleMethods; use dom::bindings::codegen::Bindings::CSSNamespaceRuleBinding::CSSNamespaceRuleMethods;
use dom::bindings::js::Root;
use dom::bindings::reflector::reflect_dom_object; use dom::bindings::reflector::reflect_dom_object;
use dom::bindings::root::DomRoot;
use dom::bindings::str::DOMString; use dom::bindings::str::DOMString;
use dom::cssrule::{CSSRule, SpecificCSSRule}; use dom::cssrule::{CSSRule, SpecificCSSRule};
use dom::cssstylesheet::CSSStyleSheet; use dom::cssstylesheet::CSSStyleSheet;
@ -33,7 +33,7 @@ impl CSSNamespaceRule {
#[allow(unrooted_must_root)] #[allow(unrooted_must_root)]
pub fn new(window: &Window, parent_stylesheet: &CSSStyleSheet, pub fn new(window: &Window, parent_stylesheet: &CSSStyleSheet,
namespacerule: Arc<Locked<NamespaceRule>>) -> Root<CSSNamespaceRule> { namespacerule: Arc<Locked<NamespaceRule>>) -> DomRoot<CSSNamespaceRule> {
reflect_dom_object(box CSSNamespaceRule::new_inherited(parent_stylesheet, namespacerule), reflect_dom_object(box CSSNamespaceRule::new_inherited(parent_stylesheet, namespacerule),
window, window,
CSSNamespaceRuleBinding::Wrap) CSSNamespaceRuleBinding::Wrap)

View file

@ -4,8 +4,8 @@
use dom::bindings::codegen::Bindings::CSSRuleBinding::CSSRuleMethods; use dom::bindings::codegen::Bindings::CSSRuleBinding::CSSRuleMethods;
use dom::bindings::inheritance::Castable; use dom::bindings::inheritance::Castable;
use dom::bindings::js::{JS, Root};
use dom::bindings::reflector::Reflector; use dom::bindings::reflector::Reflector;
use dom::bindings::root::{Dom, DomRoot};
use dom::bindings::str::DOMString; use dom::bindings::str::DOMString;
use dom::cssfontfacerule::CSSFontFaceRule; use dom::cssfontfacerule::CSSFontFaceRule;
use dom::cssimportrule::CSSImportRule; use dom::cssimportrule::CSSImportRule;
@ -27,7 +27,7 @@ use style::stylesheets::CssRule as StyleCssRule;
#[dom_struct] #[dom_struct]
pub struct CSSRule { pub struct CSSRule {
reflector_: Reflector, reflector_: Reflector,
parent_stylesheet: JS<CSSStyleSheet>, parent_stylesheet: Dom<CSSStyleSheet>,
/// Whether the parentStyleSheet attribute should return null. /// Whether the parentStyleSheet attribute should return null.
/// We keep parent_stylesheet in that case because insertRule needs it /// We keep parent_stylesheet in that case because insertRule needs it
@ -40,7 +40,7 @@ impl CSSRule {
pub fn new_inherited(parent_stylesheet: &CSSStyleSheet) -> CSSRule { pub fn new_inherited(parent_stylesheet: &CSSStyleSheet) -> CSSRule {
CSSRule { CSSRule {
reflector_: Reflector::new(), reflector_: Reflector::new(),
parent_stylesheet: JS::from_ref(parent_stylesheet), parent_stylesheet: Dom::from_ref(parent_stylesheet),
parent_stylesheet_removed: Cell::new(false), parent_stylesheet_removed: Cell::new(false),
} }
} }
@ -72,19 +72,19 @@ impl CSSRule {
// Given a StyleCssRule, create a new instance of a derived class of // Given a StyleCssRule, create a new instance of a derived class of
// CSSRule based on which rule it is // CSSRule based on which rule it is
pub fn new_specific(window: &Window, parent_stylesheet: &CSSStyleSheet, pub fn new_specific(window: &Window, parent_stylesheet: &CSSStyleSheet,
rule: StyleCssRule) -> Root<CSSRule> { rule: StyleCssRule) -> DomRoot<CSSRule> {
// be sure to update the match in as_specific when this is updated // be sure to update the match in as_specific when this is updated
match rule { match rule {
StyleCssRule::Import(s) => Root::upcast(CSSImportRule::new(window, parent_stylesheet, s)), StyleCssRule::Import(s) => DomRoot::upcast(CSSImportRule::new(window, parent_stylesheet, s)),
StyleCssRule::Style(s) => Root::upcast(CSSStyleRule::new(window, parent_stylesheet, s)), StyleCssRule::Style(s) => DomRoot::upcast(CSSStyleRule::new(window, parent_stylesheet, s)),
StyleCssRule::FontFace(s) => Root::upcast(CSSFontFaceRule::new(window, parent_stylesheet, s)), StyleCssRule::FontFace(s) => DomRoot::upcast(CSSFontFaceRule::new(window, parent_stylesheet, s)),
StyleCssRule::FontFeatureValues(_) => unimplemented!(), StyleCssRule::FontFeatureValues(_) => unimplemented!(),
StyleCssRule::CounterStyle(_) => unimplemented!(), StyleCssRule::CounterStyle(_) => unimplemented!(),
StyleCssRule::Keyframes(s) => Root::upcast(CSSKeyframesRule::new(window, parent_stylesheet, s)), StyleCssRule::Keyframes(s) => DomRoot::upcast(CSSKeyframesRule::new(window, parent_stylesheet, s)),
StyleCssRule::Media(s) => Root::upcast(CSSMediaRule::new(window, parent_stylesheet, s)), StyleCssRule::Media(s) => DomRoot::upcast(CSSMediaRule::new(window, parent_stylesheet, s)),
StyleCssRule::Namespace(s) => Root::upcast(CSSNamespaceRule::new(window, parent_stylesheet, s)), StyleCssRule::Namespace(s) => DomRoot::upcast(CSSNamespaceRule::new(window, parent_stylesheet, s)),
StyleCssRule::Viewport(s) => Root::upcast(CSSViewportRule::new(window, parent_stylesheet, s)), StyleCssRule::Viewport(s) => DomRoot::upcast(CSSViewportRule::new(window, parent_stylesheet, s)),
StyleCssRule::Supports(s) => Root::upcast(CSSSupportsRule::new(window, parent_stylesheet, s)), StyleCssRule::Supports(s) => DomRoot::upcast(CSSSupportsRule::new(window, parent_stylesheet, s)),
StyleCssRule::Page(_) => unreachable!(), StyleCssRule::Page(_) => unreachable!(),
StyleCssRule::Document(_) => unimplemented!(), // TODO StyleCssRule::Document(_) => unimplemented!(), // TODO
} }
@ -121,11 +121,11 @@ impl CSSRuleMethods for CSSRule {
} }
// https://drafts.csswg.org/cssom/#dom-cssrule-parentstylesheet // https://drafts.csswg.org/cssom/#dom-cssrule-parentstylesheet
fn GetParentStyleSheet(&self) -> Option<Root<CSSStyleSheet>> { fn GetParentStyleSheet(&self) -> Option<DomRoot<CSSStyleSheet>> {
if self.parent_stylesheet_removed.get() { if self.parent_stylesheet_removed.get() {
None None
} else { } else {
Some(Root::from_ref(&*self.parent_stylesheet)) Some(DomRoot::from_ref(&*self.parent_stylesheet))
} }
} }

View file

@ -2,12 +2,12 @@
* License, v. 2.0. If a copy of the MPL was not distributed with this * 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/. */ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use dom::bindings::cell::DOMRefCell; use dom::bindings::cell::DomRefCell;
use dom::bindings::codegen::Bindings::CSSRuleListBinding; use dom::bindings::codegen::Bindings::CSSRuleListBinding;
use dom::bindings::codegen::Bindings::CSSRuleListBinding::CSSRuleListMethods; use dom::bindings::codegen::Bindings::CSSRuleListBinding::CSSRuleListMethods;
use dom::bindings::error::{Error, ErrorResult, Fallible}; use dom::bindings::error::{Error, ErrorResult, Fallible};
use dom::bindings::js::{JS, MutNullableJS, Root};
use dom::bindings::reflector::{DomObject, Reflector, reflect_dom_object}; use dom::bindings::reflector::{DomObject, Reflector, reflect_dom_object};
use dom::bindings::root::{Dom, DomRoot, MutNullableDom};
use dom::csskeyframerule::CSSKeyframeRule; use dom::csskeyframerule::CSSKeyframeRule;
use dom::cssrule::CSSRule; use dom::cssrule::CSSRule;
use dom::cssstylesheet::CSSStyleSheet; use dom::cssstylesheet::CSSStyleSheet;
@ -36,10 +36,10 @@ impl From<RulesMutateError> for Error {
#[dom_struct] #[dom_struct]
pub struct CSSRuleList { pub struct CSSRuleList {
reflector_: Reflector, reflector_: Reflector,
parent_stylesheet: JS<CSSStyleSheet>, parent_stylesheet: Dom<CSSStyleSheet>,
#[ignore_heap_size_of = "Arc"] #[ignore_heap_size_of = "Arc"]
rules: RulesSource, rules: RulesSource,
dom_rules: DOMRefCell<Vec<MutNullableJS<CSSRule>>> dom_rules: DomRefCell<Vec<MutNullableDom<CSSRule>>>
} }
pub enum RulesSource { pub enum RulesSource {
@ -53,24 +53,24 @@ impl CSSRuleList {
let guard = parent_stylesheet.shared_lock().read(); let guard = parent_stylesheet.shared_lock().read();
let dom_rules = match rules { let dom_rules = match rules {
RulesSource::Rules(ref rules) => { RulesSource::Rules(ref rules) => {
rules.read_with(&guard).0.iter().map(|_| MutNullableJS::new(None)).collect() rules.read_with(&guard).0.iter().map(|_| MutNullableDom::new(None)).collect()
} }
RulesSource::Keyframes(ref rules) => { RulesSource::Keyframes(ref rules) => {
rules.read_with(&guard).keyframes.iter().map(|_| MutNullableJS::new(None)).collect() rules.read_with(&guard).keyframes.iter().map(|_| MutNullableDom::new(None)).collect()
} }
}; };
CSSRuleList { CSSRuleList {
reflector_: Reflector::new(), reflector_: Reflector::new(),
parent_stylesheet: JS::from_ref(parent_stylesheet), parent_stylesheet: Dom::from_ref(parent_stylesheet),
rules: rules, rules: rules,
dom_rules: DOMRefCell::new(dom_rules), dom_rules: DomRefCell::new(dom_rules),
} }
} }
#[allow(unrooted_must_root)] #[allow(unrooted_must_root)]
pub fn new(window: &Window, parent_stylesheet: &CSSStyleSheet, pub fn new(window: &Window, parent_stylesheet: &CSSStyleSheet,
rules: RulesSource) -> Root<CSSRuleList> { rules: RulesSource) -> DomRoot<CSSRuleList> {
reflect_dom_object(box CSSRuleList::new_inherited(parent_stylesheet, rules), reflect_dom_object(box CSSRuleList::new_inherited(parent_stylesheet, rules),
window, window,
CSSRuleListBinding::Wrap) CSSRuleListBinding::Wrap)
@ -102,7 +102,7 @@ impl CSSRuleList {
let parent_stylesheet = &*self.parent_stylesheet; let parent_stylesheet = &*self.parent_stylesheet;
let dom_rule = CSSRule::new_specific(&window, parent_stylesheet, new_rule); let dom_rule = CSSRule::new_specific(&window, parent_stylesheet, new_rule);
self.dom_rules.borrow_mut().insert(index, MutNullableJS::new(Some(&*dom_rule))); self.dom_rules.borrow_mut().insert(index, MutNullableDom::new(Some(&*dom_rule)));
Ok((idx)) Ok((idx))
} }
@ -133,11 +133,11 @@ impl CSSRuleList {
// Remove parent stylesheets from all children // Remove parent stylesheets from all children
pub fn deparent_all(&self) { pub fn deparent_all(&self) {
for rule in self.dom_rules.borrow().iter() { for rule in self.dom_rules.borrow().iter() {
rule.get().map(|r| Root::upcast(r).deparent()); rule.get().map(|r| DomRoot::upcast(r).deparent());
} }
} }
pub fn item(&self, idx: u32) -> Option<Root<CSSRule>> { pub fn item(&self, idx: u32) -> Option<DomRoot<CSSRule>> {
self.dom_rules.borrow().get(idx as usize).map(|rule| { self.dom_rules.borrow().get(idx as usize).map(|rule| {
rule.or_init(|| { rule.or_init(|| {
let parent_stylesheet = &self.parent_stylesheet; let parent_stylesheet = &self.parent_stylesheet;
@ -149,7 +149,7 @@ impl CSSRuleList {
rules.read_with(&guard).0[idx as usize].clone()) rules.read_with(&guard).0[idx as usize].clone())
} }
RulesSource::Keyframes(ref rules) => { RulesSource::Keyframes(ref rules) => {
Root::upcast(CSSKeyframeRule::new(self.global().as_window(), DomRoot::upcast(CSSKeyframeRule::new(self.global().as_window(),
parent_stylesheet, parent_stylesheet,
rules.read_with(&guard) rules.read_with(&guard)
.keyframes[idx as usize] .keyframes[idx as usize]
@ -170,13 +170,13 @@ impl CSSRuleList {
if let RulesSource::Rules(..) = self.rules { if let RulesSource::Rules(..) = self.rules {
panic!("Can only call append_lazy_rule with keyframes-backed CSSRules"); panic!("Can only call append_lazy_rule with keyframes-backed CSSRules");
} }
self.dom_rules.borrow_mut().push(MutNullableJS::new(None)); self.dom_rules.borrow_mut().push(MutNullableDom::new(None));
} }
} }
impl CSSRuleListMethods for CSSRuleList { impl CSSRuleListMethods for CSSRuleList {
// https://drafts.csswg.org/cssom/#ref-for-dom-cssrulelist-item-1 // https://drafts.csswg.org/cssom/#ref-for-dom-cssrulelist-item-1
fn Item(&self, idx: u32) -> Option<Root<CSSRule>> { fn Item(&self, idx: u32) -> Option<DomRoot<CSSRule>> {
self.item(idx) self.item(idx)
} }
@ -186,7 +186,7 @@ impl CSSRuleListMethods for CSSRuleList {
} }
// check-tidy: no specs after this line // check-tidy: no specs after this line
fn IndexedGetter(&self, index: u32) -> Option<Root<CSSRule>> { fn IndexedGetter(&self, index: u32) -> Option<DomRoot<CSSRule>> {
self.Item(index) self.Item(index)
} }
} }

View file

@ -6,8 +6,8 @@ use dom::bindings::codegen::Bindings::CSSStyleDeclarationBinding::{self, CSSStyl
use dom::bindings::codegen::Bindings::WindowBinding::WindowMethods; use dom::bindings::codegen::Bindings::WindowBinding::WindowMethods;
use dom::bindings::error::{Error, ErrorResult, Fallible}; use dom::bindings::error::{Error, ErrorResult, Fallible};
use dom::bindings::inheritance::Castable; use dom::bindings::inheritance::Castable;
use dom::bindings::js::{JS, Root};
use dom::bindings::reflector::{DomObject, Reflector, reflect_dom_object}; use dom::bindings::reflector::{DomObject, Reflector, reflect_dom_object};
use dom::bindings::root::{Dom, DomRoot};
use dom::bindings::str::DOMString; use dom::bindings::str::DOMString;
use dom::cssrule::CSSRule; use dom::cssrule::CSSRule;
use dom::element::Element; use dom::element::Element;
@ -36,8 +36,8 @@ pub struct CSSStyleDeclaration {
#[derive(HeapSizeOf, JSTraceable)] #[derive(HeapSizeOf, JSTraceable)]
#[must_root] #[must_root]
pub enum CSSStyleOwner { pub enum CSSStyleOwner {
Element(JS<Element>), Element(Dom<Element>),
CSSRule(JS<CSSRule>, CSSRule(Dom<CSSRule>,
#[ignore_heap_size_of = "Arc"] #[ignore_heap_size_of = "Arc"]
Arc<Locked<PropertyDeclarationBlock>>), Arc<Locked<PropertyDeclarationBlock>>),
} }
@ -137,10 +137,10 @@ impl CSSStyleOwner {
} }
} }
fn window(&self) -> Root<Window> { fn window(&self) -> DomRoot<Window> {
match *self { match *self {
CSSStyleOwner::Element(ref el) => window_from_node(&**el), CSSStyleOwner::Element(ref el) => window_from_node(&**el),
CSSStyleOwner::CSSRule(ref rule, _) => Root::from_ref(rule.global().as_window()), CSSStyleOwner::CSSRule(ref rule, _) => DomRoot::from_ref(rule.global().as_window()),
} }
} }
@ -192,7 +192,7 @@ impl CSSStyleDeclaration {
owner: CSSStyleOwner, owner: CSSStyleOwner,
pseudo: Option<PseudoElement>, pseudo: Option<PseudoElement>,
modification_access: CSSModificationAccess) modification_access: CSSModificationAccess)
-> Root<CSSStyleDeclaration> { -> DomRoot<CSSStyleDeclaration> {
reflect_dom_object(box CSSStyleDeclaration::new_inherited(owner, reflect_dom_object(box CSSStyleDeclaration::new_inherited(owner,
pseudo, pseudo,
modification_access), modification_access),

View file

@ -7,8 +7,8 @@ use cssparser::ToCss;
use dom::bindings::codegen::Bindings::CSSStyleRuleBinding::{self, CSSStyleRuleMethods}; use dom::bindings::codegen::Bindings::CSSStyleRuleBinding::{self, CSSStyleRuleMethods};
use dom::bindings::codegen::Bindings::WindowBinding::WindowBinding::WindowMethods; use dom::bindings::codegen::Bindings::WindowBinding::WindowBinding::WindowMethods;
use dom::bindings::inheritance::Castable; use dom::bindings::inheritance::Castable;
use dom::bindings::js::{JS, MutNullableJS, Root};
use dom::bindings::reflector::{DomObject, reflect_dom_object}; use dom::bindings::reflector::{DomObject, reflect_dom_object};
use dom::bindings::root::{Dom, DomRoot, MutNullableDom};
use dom::bindings::str::DOMString; use dom::bindings::str::DOMString;
use dom::cssrule::{CSSRule, SpecificCSSRule}; use dom::cssrule::{CSSRule, SpecificCSSRule};
use dom::cssstyledeclaration::{CSSModificationAccess, CSSStyleDeclaration, CSSStyleOwner}; use dom::cssstyledeclaration::{CSSModificationAccess, CSSStyleDeclaration, CSSStyleOwner};
@ -27,7 +27,7 @@ pub struct CSSStyleRule {
cssrule: CSSRule, cssrule: CSSRule,
#[ignore_heap_size_of = "Arc"] #[ignore_heap_size_of = "Arc"]
stylerule: Arc<Locked<StyleRule>>, stylerule: Arc<Locked<StyleRule>>,
style_decl: MutNullableJS<CSSStyleDeclaration>, style_decl: MutNullableDom<CSSStyleDeclaration>,
} }
impl CSSStyleRule { impl CSSStyleRule {
@ -42,7 +42,7 @@ impl CSSStyleRule {
#[allow(unrooted_must_root)] #[allow(unrooted_must_root)]
pub fn new(window: &Window, parent_stylesheet: &CSSStyleSheet, pub fn new(window: &Window, parent_stylesheet: &CSSStyleSheet,
stylerule: Arc<Locked<StyleRule>>) -> Root<CSSStyleRule> { stylerule: Arc<Locked<StyleRule>>) -> DomRoot<CSSStyleRule> {
reflect_dom_object(box CSSStyleRule::new_inherited(parent_stylesheet, stylerule), reflect_dom_object(box CSSStyleRule::new_inherited(parent_stylesheet, stylerule),
window, window,
CSSStyleRuleBinding::Wrap) CSSStyleRuleBinding::Wrap)
@ -63,13 +63,13 @@ impl SpecificCSSRule for CSSStyleRule {
impl CSSStyleRuleMethods for CSSStyleRule { impl CSSStyleRuleMethods for CSSStyleRule {
// https://drafts.csswg.org/cssom/#dom-cssstylerule-style // https://drafts.csswg.org/cssom/#dom-cssstylerule-style
fn Style(&self) -> Root<CSSStyleDeclaration> { fn Style(&self) -> DomRoot<CSSStyleDeclaration> {
self.style_decl.or_init(|| { self.style_decl.or_init(|| {
let guard = self.cssrule.shared_lock().read(); let guard = self.cssrule.shared_lock().read();
CSSStyleDeclaration::new( CSSStyleDeclaration::new(
self.global().as_window(), self.global().as_window(),
CSSStyleOwner::CSSRule( CSSStyleOwner::CSSRule(
JS::from_ref(self.upcast()), Dom::from_ref(self.upcast()),
self.stylerule.read_with(&guard).block.clone() self.stylerule.read_with(&guard).block.clone()
), ),
None, None,

View file

@ -6,8 +6,8 @@ use dom::bindings::codegen::Bindings::CSSStyleSheetBinding;
use dom::bindings::codegen::Bindings::CSSStyleSheetBinding::CSSStyleSheetMethods; use dom::bindings::codegen::Bindings::CSSStyleSheetBinding::CSSStyleSheetMethods;
use dom::bindings::codegen::Bindings::WindowBinding::WindowBinding::WindowMethods; use dom::bindings::codegen::Bindings::WindowBinding::WindowBinding::WindowMethods;
use dom::bindings::error::{Error, ErrorResult, Fallible}; use dom::bindings::error::{Error, ErrorResult, Fallible};
use dom::bindings::js::{JS, MutNullableJS, Root};
use dom::bindings::reflector::{reflect_dom_object, DomObject}; use dom::bindings::reflector::{reflect_dom_object, DomObject};
use dom::bindings::root::{Dom, DomRoot, MutNullableDom};
use dom::bindings::str::DOMString; use dom::bindings::str::DOMString;
use dom::cssrulelist::{CSSRuleList, RulesSource}; use dom::cssrulelist::{CSSRuleList, RulesSource};
use dom::element::Element; use dom::element::Element;
@ -22,8 +22,8 @@ use style::stylesheets::Stylesheet as StyleStyleSheet;
#[dom_struct] #[dom_struct]
pub struct CSSStyleSheet { pub struct CSSStyleSheet {
stylesheet: StyleSheet, stylesheet: StyleSheet,
owner: JS<Element>, owner: Dom<Element>,
rulelist: MutNullableJS<CSSRuleList>, rulelist: MutNullableDom<CSSRuleList>,
#[ignore_heap_size_of = "Arc"] #[ignore_heap_size_of = "Arc"]
style_stylesheet: Arc<StyleStyleSheet>, style_stylesheet: Arc<StyleStyleSheet>,
origin_clean: Cell<bool>, origin_clean: Cell<bool>,
@ -37,8 +37,8 @@ impl CSSStyleSheet {
stylesheet: Arc<StyleStyleSheet>) -> CSSStyleSheet { stylesheet: Arc<StyleStyleSheet>) -> CSSStyleSheet {
CSSStyleSheet { CSSStyleSheet {
stylesheet: StyleSheet::new_inherited(type_, href, title), stylesheet: StyleSheet::new_inherited(type_, href, title),
owner: JS::from_ref(owner), owner: Dom::from_ref(owner),
rulelist: MutNullableJS::new(None), rulelist: MutNullableDom::new(None),
style_stylesheet: stylesheet, style_stylesheet: stylesheet,
origin_clean: Cell::new(true), origin_clean: Cell::new(true),
} }
@ -50,13 +50,13 @@ impl CSSStyleSheet {
type_: DOMString, type_: DOMString,
href: Option<DOMString>, href: Option<DOMString>,
title: Option<DOMString>, title: Option<DOMString>,
stylesheet: Arc<StyleStyleSheet>) -> Root<CSSStyleSheet> { stylesheet: Arc<StyleStyleSheet>) -> DomRoot<CSSStyleSheet> {
reflect_dom_object(box CSSStyleSheet::new_inherited(owner, type_, href, title, stylesheet), reflect_dom_object(box CSSStyleSheet::new_inherited(owner, type_, href, title, stylesheet),
window, window,
CSSStyleSheetBinding::Wrap) CSSStyleSheetBinding::Wrap)
} }
fn rulelist(&self) -> Root<CSSRuleList> { fn rulelist(&self) -> DomRoot<CSSRuleList> {
self.rulelist.or_init(|| { self.rulelist.or_init(|| {
let rules = self.style_stylesheet.contents.rules.clone(); let rules = self.style_stylesheet.contents.rules.clone();
CSSRuleList::new( CSSRuleList::new(
@ -92,7 +92,7 @@ impl CSSStyleSheet {
impl CSSStyleSheetMethods for CSSStyleSheet { impl CSSStyleSheetMethods for CSSStyleSheet {
// https://drafts.csswg.org/cssom/#dom-cssstylesheet-cssrules // https://drafts.csswg.org/cssom/#dom-cssstylesheet-cssrules
fn GetCssRules(&self) -> Fallible<Root<CSSRuleList>> { fn GetCssRules(&self) -> Fallible<DomRoot<CSSRuleList>> {
if !self.origin_clean.get() { if !self.origin_clean.get() {
return Err(Error::Security); return Err(Error::Security);
} }

View file

@ -6,9 +6,9 @@ use cssparser::Parser;
use cssparser::ParserInput; use cssparser::ParserInput;
use dom::bindings::codegen::Bindings::CSSStyleValueBinding::CSSStyleValueMethods; use dom::bindings::codegen::Bindings::CSSStyleValueBinding::CSSStyleValueMethods;
use dom::bindings::codegen::Bindings::CSSStyleValueBinding::Wrap; use dom::bindings::codegen::Bindings::CSSStyleValueBinding::Wrap;
use dom::bindings::js::Root;
use dom::bindings::reflector::Reflector; use dom::bindings::reflector::Reflector;
use dom::bindings::reflector::reflect_dom_object; use dom::bindings::reflector::reflect_dom_object;
use dom::bindings::root::DomRoot;
use dom::bindings::str::DOMString; use dom::bindings::str::DOMString;
use dom::globalscope::GlobalScope; use dom::globalscope::GlobalScope;
use dom_struct::dom_struct; use dom_struct::dom_struct;
@ -28,7 +28,7 @@ impl CSSStyleValue {
} }
} }
pub fn new(global: &GlobalScope, value: String) -> Root<CSSStyleValue> { pub fn new(global: &GlobalScope, value: String) -> DomRoot<CSSStyleValue> {
reflect_dom_object(box CSSStyleValue::new_inherited(value), global, Wrap) reflect_dom_object(box CSSStyleValue::new_inherited(value), global, Wrap)
} }
} }

View file

@ -5,8 +5,8 @@
use cssparser::{Parser, ParserInput}; use cssparser::{Parser, ParserInput};
use dom::bindings::codegen::Bindings::CSSSupportsRuleBinding; use dom::bindings::codegen::Bindings::CSSSupportsRuleBinding;
use dom::bindings::codegen::Bindings::WindowBinding::WindowBinding::WindowMethods; use dom::bindings::codegen::Bindings::WindowBinding::WindowBinding::WindowMethods;
use dom::bindings::js::Root;
use dom::bindings::reflector::{DomObject, reflect_dom_object}; use dom::bindings::reflector::{DomObject, reflect_dom_object};
use dom::bindings::root::DomRoot;
use dom::bindings::str::DOMString; use dom::bindings::str::DOMString;
use dom::cssconditionrule::CSSConditionRule; use dom::cssconditionrule::CSSConditionRule;
use dom::cssrule::SpecificCSSRule; use dom::cssrule::SpecificCSSRule;
@ -40,7 +40,7 @@ impl CSSSupportsRule {
#[allow(unrooted_must_root)] #[allow(unrooted_must_root)]
pub fn new(window: &Window, parent_stylesheet: &CSSStyleSheet, pub fn new(window: &Window, parent_stylesheet: &CSSStyleSheet,
supportsrule: Arc<Locked<SupportsRule>>) -> Root<CSSSupportsRule> { supportsrule: Arc<Locked<SupportsRule>>) -> DomRoot<CSSSupportsRule> {
reflect_dom_object(box CSSSupportsRule::new_inherited(parent_stylesheet, supportsrule), reflect_dom_object(box CSSSupportsRule::new_inherited(parent_stylesheet, supportsrule),
window, window,
CSSSupportsRuleBinding::Wrap) CSSSupportsRuleBinding::Wrap)

View file

@ -3,8 +3,8 @@
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use dom::bindings::codegen::Bindings::CSSViewportRuleBinding; use dom::bindings::codegen::Bindings::CSSViewportRuleBinding;
use dom::bindings::js::Root;
use dom::bindings::reflector::reflect_dom_object; use dom::bindings::reflector::reflect_dom_object;
use dom::bindings::root::DomRoot;
use dom::bindings::str::DOMString; use dom::bindings::str::DOMString;
use dom::cssrule::{CSSRule, SpecificCSSRule}; use dom::cssrule::{CSSRule, SpecificCSSRule};
use dom::cssstylesheet::CSSStyleSheet; use dom::cssstylesheet::CSSStyleSheet;
@ -31,7 +31,7 @@ impl CSSViewportRule {
#[allow(unrooted_must_root)] #[allow(unrooted_must_root)]
pub fn new(window: &Window, parent_stylesheet: &CSSStyleSheet, pub fn new(window: &Window, parent_stylesheet: &CSSStyleSheet,
viewportrule: Arc<Locked<ViewportRule>>) -> Root<CSSViewportRule> { viewportrule: Arc<Locked<ViewportRule>>) -> DomRoot<CSSViewportRule> {
reflect_dom_object(box CSSViewportRule::new_inherited(parent_stylesheet, viewportrule), reflect_dom_object(box CSSViewportRule::new_inherited(parent_stylesheet, viewportrule),
window, window,
CSSViewportRuleBinding::Wrap) CSSViewportRuleBinding::Wrap)

View file

@ -3,7 +3,7 @@
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use dom::bindings::callback::{CallbackContainer, ExceptionHandling}; use dom::bindings::callback::{CallbackContainer, ExceptionHandling};
use dom::bindings::cell::DOMRefCell; use dom::bindings::cell::DomRefCell;
use dom::bindings::codegen::Bindings::CustomElementRegistryBinding; use dom::bindings::codegen::Bindings::CustomElementRegistryBinding;
use dom::bindings::codegen::Bindings::CustomElementRegistryBinding::CustomElementRegistryMethods; use dom::bindings::codegen::Bindings::CustomElementRegistryBinding::CustomElementRegistryMethods;
use dom::bindings::codegen::Bindings::CustomElementRegistryBinding::ElementDefinitionOptions; use dom::bindings::codegen::Bindings::CustomElementRegistryBinding::ElementDefinitionOptions;
@ -13,8 +13,8 @@ use dom::bindings::codegen::Bindings::WindowBinding::WindowBinding::WindowMethod
use dom::bindings::conversions::{ConversionResult, FromJSValConvertible, StringificationBehavior}; use dom::bindings::conversions::{ConversionResult, FromJSValConvertible, StringificationBehavior};
use dom::bindings::error::{Error, ErrorResult, Fallible, report_pending_exception, throw_dom_exception}; use dom::bindings::error::{Error, ErrorResult, Fallible, report_pending_exception, throw_dom_exception};
use dom::bindings::inheritance::Castable; use dom::bindings::inheritance::Castable;
use dom::bindings::js::{JS, Root};
use dom::bindings::reflector::{DomObject, Reflector, reflect_dom_object}; use dom::bindings::reflector::{DomObject, Reflector, reflect_dom_object};
use dom::bindings::root::{Dom, DomRoot};
use dom::bindings::str::DOMString; use dom::bindings::str::DOMString;
use dom::document::Document; use dom::document::Document;
use dom::domexception::{DOMErrorName, DOMException}; use dom::domexception::{DOMErrorName, DOMException};
@ -45,29 +45,29 @@ use std::rc::Rc;
pub struct CustomElementRegistry { pub struct CustomElementRegistry {
reflector_: Reflector, reflector_: Reflector,
window: JS<Window>, window: Dom<Window>,
#[ignore_heap_size_of = "Rc"] #[ignore_heap_size_of = "Rc"]
when_defined: DOMRefCell<HashMap<LocalName, Rc<Promise>>>, when_defined: DomRefCell<HashMap<LocalName, Rc<Promise>>>,
element_definition_is_running: Cell<bool>, element_definition_is_running: Cell<bool>,
#[ignore_heap_size_of = "Rc"] #[ignore_heap_size_of = "Rc"]
definitions: DOMRefCell<HashMap<LocalName, Rc<CustomElementDefinition>>>, definitions: DomRefCell<HashMap<LocalName, Rc<CustomElementDefinition>>>,
} }
impl CustomElementRegistry { impl CustomElementRegistry {
fn new_inherited(window: &Window) -> CustomElementRegistry { fn new_inherited(window: &Window) -> CustomElementRegistry {
CustomElementRegistry { CustomElementRegistry {
reflector_: Reflector::new(), reflector_: Reflector::new(),
window: JS::from_ref(window), window: Dom::from_ref(window),
when_defined: DOMRefCell::new(HashMap::new()), when_defined: DomRefCell::new(HashMap::new()),
element_definition_is_running: Cell::new(false), element_definition_is_running: Cell::new(false),
definitions: DOMRefCell::new(HashMap::new()), definitions: DomRefCell::new(HashMap::new()),
} }
} }
pub fn new(window: &Window) -> Root<CustomElementRegistry> { pub fn new(window: &Window) -> DomRoot<CustomElementRegistry> {
reflect_dom_object(box CustomElementRegistry::new_inherited(window), reflect_dom_object(box CustomElementRegistry::new_inherited(window),
window, window,
CustomElementRegistryBinding::Wrap) CustomElementRegistryBinding::Wrap)
@ -304,7 +304,7 @@ impl CustomElementRegistryMethods for CustomElementRegistry {
let document = self.window.Document(); let document = self.window.Document();
// Steps 14-15 // Steps 14-15
for candidate in document.upcast::<Node>().traverse_preorder().filter_map(Root::downcast::<Element>) { for candidate in document.upcast::<Node>().traverse_preorder().filter_map(DomRoot::downcast::<Element>) {
let is = candidate.get_is(); let is = candidate.get_is();
if *candidate.local_name() == local_name && if *candidate.local_name() == local_name &&
*candidate.namespace() == ns!(html) && *candidate.namespace() == ns!(html) &&
@ -386,7 +386,7 @@ pub struct LifecycleCallbacks {
#[derive(Clone, HeapSizeOf, JSTraceable)] #[derive(Clone, HeapSizeOf, JSTraceable)]
pub enum ConstructionStackEntry { pub enum ConstructionStackEntry {
Element(Root<Element>), Element(DomRoot<Element>),
AlreadyConstructedMarker, AlreadyConstructedMarker,
} }
@ -404,7 +404,7 @@ pub struct CustomElementDefinition {
pub callbacks: LifecycleCallbacks, pub callbacks: LifecycleCallbacks,
pub construction_stack: DOMRefCell<Vec<ConstructionStackEntry>>, pub construction_stack: DomRefCell<Vec<ConstructionStackEntry>>,
} }
impl CustomElementDefinition { impl CustomElementDefinition {
@ -431,7 +431,7 @@ impl CustomElementDefinition {
/// https://dom.spec.whatwg.org/#concept-create-element Step 6.1 /// https://dom.spec.whatwg.org/#concept-create-element Step 6.1
#[allow(unsafe_code)] #[allow(unsafe_code)]
pub fn create_element(&self, document: &Document, prefix: Option<Prefix>) -> Fallible<Root<Element>> { pub fn create_element(&self, document: &Document, prefix: Option<Prefix>) -> Fallible<DomRoot<Element>> {
let window = document.window(); let window = document.window();
let cx = window.get_cx(); let cx = window.get_cx();
// Step 2 // Step 2
@ -447,7 +447,7 @@ impl CustomElementDefinition {
} }
rooted!(in(cx) let element_val = ObjectValue(element.get())); rooted!(in(cx) let element_val = ObjectValue(element.get()));
let element: Root<Element> = match unsafe { Root::from_jsval(cx, element_val.handle(), ()) } { let element: DomRoot<Element> = match unsafe { DomRoot::from_jsval(cx, element_val.handle(), ()) } {
Ok(ConversionResult::Success(element)) => element, Ok(ConversionResult::Success(element)) => element,
Ok(ConversionResult::Failure(..)) => Ok(ConversionResult::Failure(..)) =>
return Err(Error::Type("Constructor did not return a DOM node".to_owned())), return Err(Error::Type("Constructor did not return a DOM node".to_owned())),
@ -504,7 +504,7 @@ pub fn upgrade_element(definition: Rc<CustomElementDefinition>, element: &Elemen
} }
// Step 5 // Step 5
definition.construction_stack.borrow_mut().push(ConstructionStackEntry::Element(Root::from_ref(element))); definition.construction_stack.borrow_mut().push(ConstructionStackEntry::Element(DomRoot::from_ref(element)));
// Step 7 // Step 7
let result = run_upgrade_constructor(&definition.constructor, element); let result = run_upgrade_constructor(&definition.constructor, element);
@ -612,7 +612,7 @@ impl CustomElementReaction {
pub enum CallbackReaction { pub enum CallbackReaction {
Connected, Connected,
Disconnected, Disconnected,
Adopted(Root<Document>, Root<Document>), Adopted(DomRoot<Document>, DomRoot<Document>),
AttributeChanged(LocalName, Option<DOMString>, Option<DOMString>, Namespace), AttributeChanged(LocalName, Option<DOMString>, Option<DOMString>, Namespace),
} }
@ -627,7 +627,7 @@ enum BackupElementQueueFlag {
#[derive(HeapSizeOf, JSTraceable)] #[derive(HeapSizeOf, JSTraceable)]
#[must_root] #[must_root]
pub struct CustomElementReactionStack { pub struct CustomElementReactionStack {
stack: DOMRefCell<Vec<ElementQueue>>, stack: DomRefCell<Vec<ElementQueue>>,
backup_queue: ElementQueue, backup_queue: ElementQueue,
processing_backup_element_queue: Cell<BackupElementQueueFlag>, processing_backup_element_queue: Cell<BackupElementQueueFlag>,
} }
@ -635,7 +635,7 @@ pub struct CustomElementReactionStack {
impl CustomElementReactionStack { impl CustomElementReactionStack {
pub fn new() -> CustomElementReactionStack { pub fn new() -> CustomElementReactionStack {
CustomElementReactionStack { CustomElementReactionStack {
stack: DOMRefCell::new(Vec::new()), stack: DomRefCell::new(Vec::new()),
backup_queue: ElementQueue::new(), backup_queue: ElementQueue::new(),
processing_backup_element_queue: Cell::new(BackupElementQueueFlag::NotProcessing), processing_backup_element_queue: Cell::new(BackupElementQueueFlag::NotProcessing),
} }
@ -776,7 +776,7 @@ impl CustomElementReactionStack {
#[derive(HeapSizeOf, JSTraceable)] #[derive(HeapSizeOf, JSTraceable)]
#[must_root] #[must_root]
struct ElementQueue { struct ElementQueue {
queue: DOMRefCell<VecDeque<JS<Element>>>, queue: DomRefCell<VecDeque<Dom<Element>>>,
} }
impl ElementQueue { impl ElementQueue {
@ -795,12 +795,12 @@ impl ElementQueue {
self.queue.borrow_mut().clear(); self.queue.borrow_mut().clear();
} }
fn next_element(&self) -> Option<Root<Element>> { fn next_element(&self) -> Option<DomRoot<Element>> {
self.queue.borrow_mut().pop_front().as_ref().map(JS::deref).map(Root::from_ref) self.queue.borrow_mut().pop_front().as_ref().map(Dom::deref).map(DomRoot::from_ref)
} }
fn append_element(&self, element: &Element) { fn append_element(&self, element: &Element) {
self.queue.borrow_mut().push_back(JS::from_ref(element)); self.queue.borrow_mut().push_back(Dom::from_ref(element));
} }
} }

View file

@ -7,8 +7,8 @@ use dom::bindings::codegen::Bindings::CustomEventBinding::CustomEventMethods;
use dom::bindings::codegen::Bindings::EventBinding::EventMethods; use dom::bindings::codegen::Bindings::EventBinding::EventMethods;
use dom::bindings::error::Fallible; use dom::bindings::error::Fallible;
use dom::bindings::inheritance::Castable; use dom::bindings::inheritance::Castable;
use dom::bindings::js::Root;
use dom::bindings::reflector::reflect_dom_object; use dom::bindings::reflector::reflect_dom_object;
use dom::bindings::root::DomRoot;
use dom::bindings::str::DOMString; use dom::bindings::str::DOMString;
use dom::bindings::trace::RootedTraceableBox; use dom::bindings::trace::RootedTraceableBox;
use dom::event::Event; use dom::event::Event;
@ -34,7 +34,7 @@ impl CustomEvent {
} }
} }
pub fn new_uninitialized(global: &GlobalScope) -> Root<CustomEvent> { pub fn new_uninitialized(global: &GlobalScope) -> DomRoot<CustomEvent> {
reflect_dom_object(box CustomEvent::new_inherited(), reflect_dom_object(box CustomEvent::new_inherited(),
global, global,
CustomEventBinding::Wrap) CustomEventBinding::Wrap)
@ -44,7 +44,7 @@ impl CustomEvent {
bubbles: bool, bubbles: bool,
cancelable: bool, cancelable: bool,
detail: HandleValue) detail: HandleValue)
-> Root<CustomEvent> { -> DomRoot<CustomEvent> {
let ev = CustomEvent::new_uninitialized(global); let ev = CustomEvent::new_uninitialized(global);
ev.init_custom_event(type_, bubbles, cancelable, detail); ev.init_custom_event(type_, bubbles, cancelable, detail);
ev ev
@ -54,7 +54,7 @@ impl CustomEvent {
pub fn Constructor(global: &GlobalScope, pub fn Constructor(global: &GlobalScope,
type_: DOMString, type_: DOMString,
init: RootedTraceableBox<CustomEventBinding::CustomEventInit>) init: RootedTraceableBox<CustomEventBinding::CustomEventInit>)
-> Fallible<Root<CustomEvent>> { -> Fallible<DomRoot<CustomEvent>> {
Ok(CustomEvent::new(global, Ok(CustomEvent::new(global,
Atom::from(type_), Atom::from(type_),
init.parent.bubbles, init.parent.bubbles,

View file

@ -6,13 +6,13 @@ use devtools;
use devtools_traits::DevtoolScriptControlMsg; use devtools_traits::DevtoolScriptControlMsg;
use dom::abstractworker::{SharedRt, SimpleWorkerErrorHandler, WorkerScriptMsg}; use dom::abstractworker::{SharedRt, SimpleWorkerErrorHandler, WorkerScriptMsg};
use dom::abstractworkerglobalscope::{SendableWorkerScriptChan, WorkerThreadWorkerChan}; use dom::abstractworkerglobalscope::{SendableWorkerScriptChan, WorkerThreadWorkerChan};
use dom::bindings::cell::DOMRefCell; use dom::bindings::cell::DomRefCell;
use dom::bindings::codegen::Bindings::DedicatedWorkerGlobalScopeBinding; use dom::bindings::codegen::Bindings::DedicatedWorkerGlobalScopeBinding;
use dom::bindings::codegen::Bindings::DedicatedWorkerGlobalScopeBinding::DedicatedWorkerGlobalScopeMethods; use dom::bindings::codegen::Bindings::DedicatedWorkerGlobalScopeBinding::DedicatedWorkerGlobalScopeMethods;
use dom::bindings::error::{ErrorInfo, ErrorResult}; use dom::bindings::error::{ErrorInfo, ErrorResult};
use dom::bindings::inheritance::Castable; use dom::bindings::inheritance::Castable;
use dom::bindings::js::{Root, RootCollection};
use dom::bindings::reflector::DomObject; use dom::bindings::reflector::DomObject;
use dom::bindings::root::{DomRoot, RootCollection};
use dom::bindings::str::DOMString; use dom::bindings::str::DOMString;
use dom::bindings::structuredclone::StructuredCloneData; use dom::bindings::structuredclone::StructuredCloneData;
use dom::errorevent::ErrorEvent; use dom::errorevent::ErrorEvent;
@ -86,8 +86,8 @@ pub struct DedicatedWorkerGlobalScope {
own_sender: Sender<(TrustedWorkerAddress, WorkerScriptMsg)>, own_sender: Sender<(TrustedWorkerAddress, WorkerScriptMsg)>,
#[ignore_heap_size_of = "Defined in std"] #[ignore_heap_size_of = "Defined in std"]
timer_event_port: Receiver<(TrustedWorkerAddress, TimerEvent)>, timer_event_port: Receiver<(TrustedWorkerAddress, TimerEvent)>,
#[ignore_heap_size_of = "Trusted<T> has unclear ownership like JS<T>"] #[ignore_heap_size_of = "Trusted<T> has unclear ownership like Dom<T>"]
worker: DOMRefCell<Option<TrustedWorkerAddress>>, worker: DomRefCell<Option<TrustedWorkerAddress>>,
#[ignore_heap_size_of = "Can't measure trait objects"] #[ignore_heap_size_of = "Can't measure trait objects"]
/// Sender to the parent thread. /// Sender to the parent thread.
parent_sender: Box<ScriptChan + Send>, parent_sender: Box<ScriptChan + Send>,
@ -116,7 +116,7 @@ impl DedicatedWorkerGlobalScope {
own_sender: own_sender, own_sender: own_sender,
timer_event_port: timer_event_port, timer_event_port: timer_event_port,
parent_sender: parent_sender, parent_sender: parent_sender,
worker: DOMRefCell::new(None), worker: DomRefCell::new(None),
} }
} }
@ -131,7 +131,7 @@ impl DedicatedWorkerGlobalScope {
timer_event_chan: IpcSender<TimerEvent>, timer_event_chan: IpcSender<TimerEvent>,
timer_event_port: Receiver<(TrustedWorkerAddress, TimerEvent)>, timer_event_port: Receiver<(TrustedWorkerAddress, TimerEvent)>,
closing: Arc<AtomicBool>) closing: Arc<AtomicBool>)
-> Root<DedicatedWorkerGlobalScope> { -> DomRoot<DedicatedWorkerGlobalScope> {
let cx = runtime.cx(); let cx = runtime.cx();
let scope = box DedicatedWorkerGlobalScope::new_inherited(init, let scope = box DedicatedWorkerGlobalScope::new_inherited(init,
worker_url, worker_url,
@ -387,7 +387,7 @@ impl DedicatedWorkerGlobalScope {
#[allow(unsafe_code)] #[allow(unsafe_code)]
unsafe extern "C" fn interrupt_callback(cx: *mut JSContext) -> bool { unsafe extern "C" fn interrupt_callback(cx: *mut JSContext) -> bool {
let worker = let worker =
Root::downcast::<WorkerGlobalScope>(GlobalScope::from_context(cx)) DomRoot::downcast::<WorkerGlobalScope>(GlobalScope::from_context(cx))
.expect("global is not a worker scope"); .expect("global is not a worker scope");
assert!(worker.is::<DedicatedWorkerGlobalScope>()); assert!(worker.is::<DedicatedWorkerGlobalScope>());

View file

@ -5,9 +5,9 @@
use dom::bindings::codegen::Bindings::DissimilarOriginLocationBinding; use dom::bindings::codegen::Bindings::DissimilarOriginLocationBinding;
use dom::bindings::codegen::Bindings::DissimilarOriginLocationBinding::DissimilarOriginLocationMethods; use dom::bindings::codegen::Bindings::DissimilarOriginLocationBinding::DissimilarOriginLocationMethods;
use dom::bindings::error::{Error, ErrorResult, Fallible}; use dom::bindings::error::{Error, ErrorResult, Fallible};
use dom::bindings::js::{JS, Root};
use dom::bindings::reflector::Reflector; use dom::bindings::reflector::Reflector;
use dom::bindings::reflector::reflect_dom_object; use dom::bindings::reflector::reflect_dom_object;
use dom::bindings::root::{Dom, DomRoot};
use dom::bindings::str::DOMString; use dom::bindings::str::DOMString;
use dom::bindings::str::USVString; use dom::bindings::str::USVString;
use dom::dissimilaroriginwindow::DissimilarOriginWindow; use dom::dissimilaroriginwindow::DissimilarOriginWindow;
@ -27,7 +27,7 @@ pub struct DissimilarOriginLocation {
reflector: Reflector, reflector: Reflector,
/// The window associated with this location. /// The window associated with this location.
window: JS<DissimilarOriginWindow>, window: Dom<DissimilarOriginWindow>,
} }
impl DissimilarOriginLocation { impl DissimilarOriginLocation {
@ -35,11 +35,11 @@ impl DissimilarOriginLocation {
fn new_inherited(window: &DissimilarOriginWindow) -> DissimilarOriginLocation { fn new_inherited(window: &DissimilarOriginWindow) -> DissimilarOriginLocation {
DissimilarOriginLocation { DissimilarOriginLocation {
reflector: Reflector::new(), reflector: Reflector::new(),
window: JS::from_ref(window), window: Dom::from_ref(window),
} }
} }
pub fn new(window: &DissimilarOriginWindow) -> Root<DissimilarOriginLocation> { pub fn new(window: &DissimilarOriginWindow) -> DomRoot<DissimilarOriginLocation> {
reflect_dom_object(box DissimilarOriginLocation::new_inherited(window), reflect_dom_object(box DissimilarOriginLocation::new_inherited(window),
window, window,
DissimilarOriginLocationBinding::Wrap) DissimilarOriginLocationBinding::Wrap)

View file

@ -6,7 +6,7 @@ use dom::bindings::codegen::Bindings::DissimilarOriginWindowBinding;
use dom::bindings::codegen::Bindings::DissimilarOriginWindowBinding::DissimilarOriginWindowMethods; use dom::bindings::codegen::Bindings::DissimilarOriginWindowBinding::DissimilarOriginWindowMethods;
use dom::bindings::error::{Error, ErrorResult}; use dom::bindings::error::{Error, ErrorResult};
use dom::bindings::inheritance::Castable; use dom::bindings::inheritance::Castable;
use dom::bindings::js::{JS, MutNullableJS, Root}; use dom::bindings::root::{Dom, DomRoot, MutNullableDom};
use dom::bindings::str::DOMString; use dom::bindings::str::DOMString;
use dom::bindings::structuredclone::StructuredCloneData; use dom::bindings::structuredclone::StructuredCloneData;
use dom::dissimilaroriginlocation::DissimilarOriginLocation; use dom::dissimilaroriginlocation::DissimilarOriginLocation;
@ -37,10 +37,10 @@ pub struct DissimilarOriginWindow {
globalscope: GlobalScope, globalscope: GlobalScope,
/// The window proxy for this window. /// The window proxy for this window.
window_proxy: JS<WindowProxy>, window_proxy: Dom<WindowProxy>,
/// The location of this window, initialized lazily. /// The location of this window, initialized lazily.
location: MutNullableJS<DissimilarOriginLocation>, location: MutNullableDom<DissimilarOriginLocation>,
} }
impl DissimilarOriginWindow { impl DissimilarOriginWindow {
@ -48,7 +48,7 @@ impl DissimilarOriginWindow {
pub fn new( pub fn new(
global_to_clone_from: &GlobalScope, global_to_clone_from: &GlobalScope,
window_proxy: &WindowProxy, window_proxy: &WindowProxy,
) -> Root<Self> { ) -> DomRoot<Self> {
let cx = global_to_clone_from.get_cx(); let cx = global_to_clone_from.get_cx();
// Any timer events fired on this window are ignored. // Any timer events fired on this window are ignored.
let (timer_event_chan, _) = ipc::channel().unwrap(); let (timer_event_chan, _) = ipc::channel().unwrap();
@ -67,7 +67,7 @@ impl DissimilarOriginWindow {
// here, but this whole DOM interface is a hack anyway. // here, but this whole DOM interface is a hack anyway.
global_to_clone_from.microtask_queue().clone(), global_to_clone_from.microtask_queue().clone(),
), ),
window_proxy: JS::from_ref(window_proxy), window_proxy: Dom::from_ref(window_proxy),
location: Default::default(), location: Default::default(),
}; };
unsafe { DissimilarOriginWindowBinding::Wrap(cx, win) } unsafe { DissimilarOriginWindowBinding::Wrap(cx, win) }
@ -80,42 +80,42 @@ impl DissimilarOriginWindow {
impl DissimilarOriginWindowMethods for DissimilarOriginWindow { impl DissimilarOriginWindowMethods for DissimilarOriginWindow {
// https://html.spec.whatwg.org/multipage/#dom-window // https://html.spec.whatwg.org/multipage/#dom-window
fn Window(&self) -> Root<WindowProxy> { fn Window(&self) -> DomRoot<WindowProxy> {
Root::from_ref(&*self.window_proxy) DomRoot::from_ref(&*self.window_proxy)
} }
// https://html.spec.whatwg.org/multipage/#dom-self // https://html.spec.whatwg.org/multipage/#dom-self
fn Self_(&self) -> Root<WindowProxy> { fn Self_(&self) -> DomRoot<WindowProxy> {
Root::from_ref(&*self.window_proxy) DomRoot::from_ref(&*self.window_proxy)
} }
// https://html.spec.whatwg.org/multipage/#dom-frames // https://html.spec.whatwg.org/multipage/#dom-frames
fn Frames(&self) -> Root<WindowProxy> { fn Frames(&self) -> DomRoot<WindowProxy> {
Root::from_ref(&*self.window_proxy) DomRoot::from_ref(&*self.window_proxy)
} }
// https://html.spec.whatwg.org/multipage/#dom-parent // https://html.spec.whatwg.org/multipage/#dom-parent
fn GetParent(&self) -> Option<Root<WindowProxy>> { fn GetParent(&self) -> Option<DomRoot<WindowProxy>> {
// Steps 1-3. // Steps 1-3.
if self.window_proxy.is_browsing_context_discarded() { if self.window_proxy.is_browsing_context_discarded() {
return None; return None;
} }
// Step 4. // Step 4.
if let Some(parent) = self.window_proxy.parent() { if let Some(parent) = self.window_proxy.parent() {
return Some(Root::from_ref(parent)); return Some(DomRoot::from_ref(parent));
} }
// Step 5. // Step 5.
Some(Root::from_ref(&*self.window_proxy)) Some(DomRoot::from_ref(&*self.window_proxy))
} }
// https://html.spec.whatwg.org/multipage/#dom-top // https://html.spec.whatwg.org/multipage/#dom-top
fn GetTop(&self) -> Option<Root<WindowProxy>> { fn GetTop(&self) -> Option<DomRoot<WindowProxy>> {
// Steps 1-3. // Steps 1-3.
if self.window_proxy.is_browsing_context_discarded() { if self.window_proxy.is_browsing_context_discarded() {
return None; return None;
} }
// Steps 4-5. // Steps 4-5.
Some(Root::from_ref(self.window_proxy.top())) Some(DomRoot::from_ref(self.window_proxy.top()))
} }
// https://html.spec.whatwg.org/multipage/#dom-length // https://html.spec.whatwg.org/multipage/#dom-length
@ -184,7 +184,7 @@ impl DissimilarOriginWindowMethods for DissimilarOriginWindow {
} }
// https://html.spec.whatwg.org/multipage/#dom-location // https://html.spec.whatwg.org/multipage/#dom-location
fn Location(&self) -> Root<DissimilarOriginLocation> { fn Location(&self) -> DomRoot<DissimilarOriginLocation> {
self.location.or_init(|| DissimilarOriginLocation::new(self)) self.location.or_init(|| DissimilarOriginLocation::new(self))
} }
} }

File diff suppressed because it is too large Load diff

View file

@ -8,7 +8,7 @@ use dom::bindings::codegen::Bindings::WindowBinding::WindowMethods;
use dom::bindings::codegen::UnionTypes::NodeOrString; use dom::bindings::codegen::UnionTypes::NodeOrString;
use dom::bindings::error::{ErrorResult, Fallible}; use dom::bindings::error::{ErrorResult, Fallible};
use dom::bindings::inheritance::Castable; use dom::bindings::inheritance::Castable;
use dom::bindings::js::Root; use dom::bindings::root::DomRoot;
use dom::bindings::str::DOMString; use dom::bindings::str::DOMString;
use dom::document::Document; use dom::document::Document;
use dom::element::Element; use dom::element::Element;
@ -33,13 +33,13 @@ impl DocumentFragment {
} }
} }
pub fn new(document: &Document) -> Root<DocumentFragment> { pub fn new(document: &Document) -> DomRoot<DocumentFragment> {
Node::reflect_node(box DocumentFragment::new_inherited(document), Node::reflect_node(box DocumentFragment::new_inherited(document),
document, document,
DocumentFragmentBinding::Wrap) DocumentFragmentBinding::Wrap)
} }
pub fn Constructor(window: &Window) -> Fallible<Root<DocumentFragment>> { pub fn Constructor(window: &Window) -> Fallible<DomRoot<DocumentFragment>> {
let document = window.Document(); let document = window.Document();
Ok(DocumentFragment::new(&document)) Ok(DocumentFragment::new(&document))
@ -48,16 +48,16 @@ impl DocumentFragment {
impl DocumentFragmentMethods for DocumentFragment { impl DocumentFragmentMethods for DocumentFragment {
// https://dom.spec.whatwg.org/#dom-parentnode-children // https://dom.spec.whatwg.org/#dom-parentnode-children
fn Children(&self) -> Root<HTMLCollection> { fn Children(&self) -> DomRoot<HTMLCollection> {
let window = window_from_node(self); let window = window_from_node(self);
HTMLCollection::children(&window, self.upcast()) HTMLCollection::children(&window, self.upcast())
} }
// https://dom.spec.whatwg.org/#dom-nonelementparentnode-getelementbyid // https://dom.spec.whatwg.org/#dom-nonelementparentnode-getelementbyid
fn GetElementById(&self, id: DOMString) -> Option<Root<Element>> { fn GetElementById(&self, id: DOMString) -> Option<DomRoot<Element>> {
let node = self.upcast::<Node>(); let node = self.upcast::<Node>();
let id = Atom::from(id); let id = Atom::from(id);
node.traverse_preorder().filter_map(Root::downcast::<Element>).find(|descendant| { node.traverse_preorder().filter_map(DomRoot::downcast::<Element>).find(|descendant| {
match descendant.get_attribute(&ns!(), &local_name!("id")) { match descendant.get_attribute(&ns!(), &local_name!("id")) {
None => false, None => false,
Some(attr) => *attr.value().as_atom() == id, Some(attr) => *attr.value().as_atom() == id,
@ -66,13 +66,13 @@ impl DocumentFragmentMethods for DocumentFragment {
} }
// https://dom.spec.whatwg.org/#dom-parentnode-firstelementchild // https://dom.spec.whatwg.org/#dom-parentnode-firstelementchild
fn GetFirstElementChild(&self) -> Option<Root<Element>> { fn GetFirstElementChild(&self) -> Option<DomRoot<Element>> {
self.upcast::<Node>().child_elements().next() self.upcast::<Node>().child_elements().next()
} }
// https://dom.spec.whatwg.org/#dom-parentnode-lastelementchild // https://dom.spec.whatwg.org/#dom-parentnode-lastelementchild
fn GetLastElementChild(&self) -> Option<Root<Element>> { fn GetLastElementChild(&self) -> Option<DomRoot<Element>> {
self.upcast::<Node>().rev_children().filter_map(Root::downcast::<Element>).next() self.upcast::<Node>().rev_children().filter_map(DomRoot::downcast::<Element>).next()
} }
// https://dom.spec.whatwg.org/#dom-parentnode-childelementcount // https://dom.spec.whatwg.org/#dom-parentnode-childelementcount
@ -91,12 +91,12 @@ impl DocumentFragmentMethods for DocumentFragment {
} }
// https://dom.spec.whatwg.org/#dom-parentnode-queryselector // https://dom.spec.whatwg.org/#dom-parentnode-queryselector
fn QuerySelector(&self, selectors: DOMString) -> Fallible<Option<Root<Element>>> { fn QuerySelector(&self, selectors: DOMString) -> Fallible<Option<DomRoot<Element>>> {
self.upcast::<Node>().query_selector(selectors) self.upcast::<Node>().query_selector(selectors)
} }
// https://dom.spec.whatwg.org/#dom-parentnode-queryselectorall // https://dom.spec.whatwg.org/#dom-parentnode-queryselectorall
fn QuerySelectorAll(&self, selectors: DOMString) -> Fallible<Root<NodeList>> { fn QuerySelectorAll(&self, selectors: DOMString) -> Fallible<DomRoot<NodeList>> {
self.upcast::<Node>().query_selector_all(selectors) self.upcast::<Node>().query_selector_all(selectors)
} }
} }

View file

@ -7,7 +7,7 @@ use dom::bindings::codegen::Bindings::DocumentTypeBinding::DocumentTypeMethods;
use dom::bindings::codegen::UnionTypes::NodeOrString; use dom::bindings::codegen::UnionTypes::NodeOrString;
use dom::bindings::error::ErrorResult; use dom::bindings::error::ErrorResult;
use dom::bindings::inheritance::Castable; use dom::bindings::inheritance::Castable;
use dom::bindings::js::Root; use dom::bindings::root::DomRoot;
use dom::bindings::str::DOMString; use dom::bindings::str::DOMString;
use dom::document::Document; use dom::document::Document;
use dom::node::Node; use dom::node::Node;
@ -41,7 +41,7 @@ impl DocumentType {
public_id: Option<DOMString>, public_id: Option<DOMString>,
system_id: Option<DOMString>, system_id: Option<DOMString>,
document: &Document) document: &Document)
-> Root<DocumentType> { -> DomRoot<DocumentType> {
Node::reflect_node(box DocumentType::new_inherited(name, public_id, system_id, document), Node::reflect_node(box DocumentType::new_inherited(name, public_id, system_id, document),
document, document,
DocumentTypeBinding::Wrap) DocumentTypeBinding::Wrap)

View file

@ -5,8 +5,8 @@
use dom::bindings::codegen::Bindings::DOMExceptionBinding; use dom::bindings::codegen::Bindings::DOMExceptionBinding;
use dom::bindings::codegen::Bindings::DOMExceptionBinding::DOMExceptionConstants; use dom::bindings::codegen::Bindings::DOMExceptionBinding::DOMExceptionConstants;
use dom::bindings::codegen::Bindings::DOMExceptionBinding::DOMExceptionMethods; use dom::bindings::codegen::Bindings::DOMExceptionBinding::DOMExceptionMethods;
use dom::bindings::js::Root;
use dom::bindings::reflector::{Reflector, reflect_dom_object}; use dom::bindings::reflector::{Reflector, reflect_dom_object};
use dom::bindings::root::DomRoot;
use dom::bindings::str::DOMString; use dom::bindings::str::DOMString;
use dom::globalscope::GlobalScope; use dom::globalscope::GlobalScope;
use dom_struct::dom_struct; use dom_struct::dom_struct;
@ -51,7 +51,7 @@ impl DOMException {
} }
} }
pub fn new(global: &GlobalScope, code: DOMErrorName) -> Root<DOMException> { pub fn new(global: &GlobalScope, code: DOMErrorName) -> DomRoot<DOMException> {
reflect_dom_object(box DOMException::new_inherited(code), reflect_dom_object(box DOMException::new_inherited(code),
global, global,
DOMExceptionBinding::Wrap) DOMExceptionBinding::Wrap)

View file

@ -9,8 +9,8 @@ use dom::bindings::codegen::Bindings::DocumentBinding::{DocumentMethods, Element
use dom::bindings::codegen::Bindings::NodeBinding::NodeMethods; use dom::bindings::codegen::Bindings::NodeBinding::NodeMethods;
use dom::bindings::error::Fallible; use dom::bindings::error::Fallible;
use dom::bindings::inheritance::Castable; use dom::bindings::inheritance::Castable;
use dom::bindings::js::{JS, Root};
use dom::bindings::reflector::{Reflector, reflect_dom_object}; use dom::bindings::reflector::{Reflector, reflect_dom_object};
use dom::bindings::root::{Dom, DomRoot};
use dom::bindings::str::DOMString; use dom::bindings::str::DOMString;
use dom::bindings::xmlname::{namespace_from_domstring, validate_qualified_name}; use dom::bindings::xmlname::{namespace_from_domstring, validate_qualified_name};
use dom::document::{Document, HasBrowsingContext, IsHTMLDocument}; use dom::document::{Document, HasBrowsingContext, IsHTMLDocument};
@ -30,18 +30,18 @@ use script_traits::DocumentActivity;
#[dom_struct] #[dom_struct]
pub struct DOMImplementation { pub struct DOMImplementation {
reflector_: Reflector, reflector_: Reflector,
document: JS<Document>, document: Dom<Document>,
} }
impl DOMImplementation { impl DOMImplementation {
fn new_inherited(document: &Document) -> DOMImplementation { fn new_inherited(document: &Document) -> DOMImplementation {
DOMImplementation { DOMImplementation {
reflector_: Reflector::new(), reflector_: Reflector::new(),
document: JS::from_ref(document), document: Dom::from_ref(document),
} }
} }
pub fn new(document: &Document) -> Root<DOMImplementation> { pub fn new(document: &Document) -> DomRoot<DOMImplementation> {
let window = document.window(); let window = document.window();
reflect_dom_object(box DOMImplementation::new_inherited(document), reflect_dom_object(box DOMImplementation::new_inherited(document),
window, window,
@ -56,7 +56,7 @@ impl DOMImplementationMethods for DOMImplementation {
qualified_name: DOMString, qualified_name: DOMString,
pubid: DOMString, pubid: DOMString,
sysid: DOMString) sysid: DOMString)
-> Fallible<Root<DocumentType>> { -> Fallible<DomRoot<DocumentType>> {
validate_qualified_name(&qualified_name)?; validate_qualified_name(&qualified_name)?;
Ok(DocumentType::new(qualified_name, Some(pubid), Some(sysid), &self.document)) Ok(DocumentType::new(qualified_name, Some(pubid), Some(sysid), &self.document))
} }
@ -66,7 +66,7 @@ impl DOMImplementationMethods for DOMImplementation {
maybe_namespace: Option<DOMString>, maybe_namespace: Option<DOMString>,
qname: DOMString, qname: DOMString,
maybe_doctype: Option<&DocumentType>) maybe_doctype: Option<&DocumentType>)
-> Fallible<Root<XMLDocument>> { -> Fallible<DomRoot<XMLDocument>> {
let win = self.document.window(); let win = self.document.window();
let loader = DocumentLoader::new(&self.document.loader()); let loader = DocumentLoader::new(&self.document.loader());
let namespace = namespace_from_domstring(maybe_namespace.to_owned()); let namespace = namespace_from_domstring(maybe_namespace.to_owned());
@ -121,7 +121,7 @@ impl DOMImplementationMethods for DOMImplementation {
} }
// https://dom.spec.whatwg.org/#dom-domimplementation-createhtmldocument // https://dom.spec.whatwg.org/#dom-domimplementation-createhtmldocument
fn CreateHTMLDocument(&self, title: Option<DOMString>) -> Root<Document> { fn CreateHTMLDocument(&self, title: Option<DOMString>) -> DomRoot<Document> {
let win = self.document.window(); let win = self.document.window();
let loader = DocumentLoader::new(&self.document.loader()); let loader = DocumentLoader::new(&self.document.loader());
@ -149,14 +149,14 @@ impl DOMImplementationMethods for DOMImplementation {
{ {
// Step 4. // Step 4.
let doc_node = doc.upcast::<Node>(); let doc_node = doc.upcast::<Node>();
let doc_html = Root::upcast::<Node>(HTMLHtmlElement::new(local_name!("html"), let doc_html = DomRoot::upcast::<Node>(HTMLHtmlElement::new(local_name!("html"),
None, None,
&doc)); &doc));
doc_node.AppendChild(&doc_html).expect("Appending failed"); doc_node.AppendChild(&doc_html).expect("Appending failed");
{ {
// Step 5. // Step 5.
let doc_head = Root::upcast::<Node>(HTMLHeadElement::new(local_name!("head"), let doc_head = DomRoot::upcast::<Node>(HTMLHeadElement::new(local_name!("head"),
None, None,
&doc)); &doc));
doc_html.AppendChild(&doc_head).unwrap(); doc_html.AppendChild(&doc_head).unwrap();
@ -165,7 +165,7 @@ impl DOMImplementationMethods for DOMImplementation {
if let Some(title_str) = title { if let Some(title_str) = title {
// Step 6.1. // Step 6.1.
let doc_title = let doc_title =
Root::upcast::<Node>(HTMLTitleElement::new(local_name!("title"), DomRoot::upcast::<Node>(HTMLTitleElement::new(local_name!("title"),
None, None,
&doc)); &doc));
doc_head.AppendChild(&doc_title).unwrap(); doc_head.AppendChild(&doc_title).unwrap();

View file

@ -6,8 +6,8 @@ use dom::bindings::codegen::Bindings::DOMMatrixBinding::{Wrap, DOMMatrixMethods,
use dom::bindings::codegen::Bindings::DOMMatrixReadOnlyBinding::DOMMatrixReadOnlyMethods; use dom::bindings::codegen::Bindings::DOMMatrixReadOnlyBinding::DOMMatrixReadOnlyMethods;
use dom::bindings::error::Fallible; use dom::bindings::error::Fallible;
use dom::bindings::inheritance::Castable; use dom::bindings::inheritance::Castable;
use dom::bindings::js::Root;
use dom::bindings::reflector::reflect_dom_object; use dom::bindings::reflector::reflect_dom_object;
use dom::bindings::root::DomRoot;
use dom::dommatrixreadonly::{dommatrixinit_to_matrix, DOMMatrixReadOnly, entries_to_matrix}; use dom::dommatrixreadonly::{dommatrixinit_to_matrix, DOMMatrixReadOnly, entries_to_matrix};
use dom::globalscope::GlobalScope; use dom::globalscope::GlobalScope;
use dom_struct::dom_struct; use dom_struct::dom_struct;
@ -21,7 +21,7 @@ pub struct DOMMatrix {
impl DOMMatrix { impl DOMMatrix {
#[allow(unrooted_must_root)] #[allow(unrooted_must_root)]
pub fn new(global: &GlobalScope, is2D: bool, matrix: Transform3D<f64>) -> Root<Self> { pub fn new(global: &GlobalScope, is2D: bool, matrix: Transform3D<f64>) -> DomRoot<Self> {
let dommatrix = Self::new_inherited(is2D, matrix); let dommatrix = Self::new_inherited(is2D, matrix);
reflect_dom_object(box dommatrix, global, Wrap) reflect_dom_object(box dommatrix, global, Wrap)
} }
@ -33,12 +33,12 @@ impl DOMMatrix {
} }
// https://drafts.fxtf.org/geometry-1/#dom-dommatrix-dommatrix // https://drafts.fxtf.org/geometry-1/#dom-dommatrix-dommatrix
pub fn Constructor(global: &GlobalScope) -> Fallible<Root<Self>> { pub fn Constructor(global: &GlobalScope) -> Fallible<DomRoot<Self>> {
Self::Constructor_(global, vec![1.0, 0.0, 0.0, 1.0, 0.0, 0.0]) 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 // https://drafts.fxtf.org/geometry-1/#dom-dommatrix-dommatrix-numbersequence
pub fn Constructor_(global: &GlobalScope, entries: Vec<f64>) -> Fallible<Root<Self>> { pub fn Constructor_(global: &GlobalScope, entries: Vec<f64>) -> Fallible<DomRoot<Self>> {
entries_to_matrix(&entries[..]) entries_to_matrix(&entries[..])
.map(|(is2D, matrix)| { .map(|(is2D, matrix)| {
Self::new(global, is2D, matrix) Self::new(global, is2D, matrix)
@ -46,14 +46,14 @@ impl DOMMatrix {
} }
// https://drafts.fxtf.org/geometry-1/#dom-dommatrix-frommatrix // https://drafts.fxtf.org/geometry-1/#dom-dommatrix-frommatrix
pub fn FromMatrix(global: &GlobalScope, other: &DOMMatrixInit) -> Fallible<Root<Self>> { pub fn FromMatrix(global: &GlobalScope, other: &DOMMatrixInit) -> Fallible<DomRoot<Self>> {
dommatrixinit_to_matrix(&other) dommatrixinit_to_matrix(&other)
.map(|(is2D, matrix)| { .map(|(is2D, matrix)| {
Self::new(global, is2D, matrix) Self::new(global, is2D, matrix)
}) })
} }
pub fn from_readonly(global: &GlobalScope, ro: &DOMMatrixReadOnly) -> Root<Self> { pub fn from_readonly(global: &GlobalScope, ro: &DOMMatrixReadOnly) -> DomRoot<Self> {
Self::new(global, ro.is_2d(), ro.matrix().clone()) Self::new(global, ro.is_2d(), ro.matrix().clone())
} }
} }
@ -280,91 +280,91 @@ impl DOMMatrixMethods for DOMMatrix {
} }
// https://drafts.fxtf.org/geometry-1/#dom-dommatrix-multiplyself // https://drafts.fxtf.org/geometry-1/#dom-dommatrix-multiplyself
fn MultiplySelf(&self, other:&DOMMatrixInit) -> Fallible<Root<DOMMatrix>> { fn MultiplySelf(&self, other:&DOMMatrixInit) -> Fallible<DomRoot<DOMMatrix>> {
// Steps 1-3. // Steps 1-3.
self.upcast::<DOMMatrixReadOnly>().multiply_self(other) self.upcast::<DOMMatrixReadOnly>().multiply_self(other)
// Step 4. // Step 4.
.and(Ok(Root::from_ref(&self))) .and(Ok(DomRoot::from_ref(&self)))
} }
// https://drafts.fxtf.org/geometry-1/#dom-dommatrix-premultiplyself // https://drafts.fxtf.org/geometry-1/#dom-dommatrix-premultiplyself
fn PreMultiplySelf(&self, other:&DOMMatrixInit) -> Fallible<Root<DOMMatrix>> { fn PreMultiplySelf(&self, other:&DOMMatrixInit) -> Fallible<DomRoot<DOMMatrix>> {
// Steps 1-3. // Steps 1-3.
self.upcast::<DOMMatrixReadOnly>().pre_multiply_self(other) self.upcast::<DOMMatrixReadOnly>().pre_multiply_self(other)
// Step 4. // Step 4.
.and(Ok(Root::from_ref(&self))) .and(Ok(DomRoot::from_ref(&self)))
} }
// https://drafts.fxtf.org/geometry-1/#dom-dommatrix-translateself // https://drafts.fxtf.org/geometry-1/#dom-dommatrix-translateself
fn TranslateSelf(&self, tx: f64, ty: f64, tz: f64) -> Root<DOMMatrix> { fn TranslateSelf(&self, tx: f64, ty: f64, tz: f64) -> DomRoot<DOMMatrix> {
// Steps 1-2. // Steps 1-2.
self.upcast::<DOMMatrixReadOnly>().translate_self(tx, ty, tz); self.upcast::<DOMMatrixReadOnly>().translate_self(tx, ty, tz);
// Step 3. // Step 3.
Root::from_ref(&self) DomRoot::from_ref(&self)
} }
// https://drafts.fxtf.org/geometry-1/#dom-dommatrix-scaleself // https://drafts.fxtf.org/geometry-1/#dom-dommatrix-scaleself
fn ScaleSelf(&self, scaleX: f64, scaleY: Option<f64>, scaleZ: f64, fn ScaleSelf(&self, scaleX: f64, scaleY: Option<f64>, scaleZ: f64,
originX: f64, originY: f64, originZ: f64) -> Root<DOMMatrix> { originX: f64, originY: f64, originZ: f64) -> DomRoot<DOMMatrix> {
// Steps 1-6. // Steps 1-6.
self.upcast::<DOMMatrixReadOnly>().scale_self(scaleX, scaleY, scaleZ, originX, originY, originZ); self.upcast::<DOMMatrixReadOnly>().scale_self(scaleX, scaleY, scaleZ, originX, originY, originZ);
// Step 7. // Step 7.
Root::from_ref(&self) DomRoot::from_ref(&self)
} }
// https://drafts.fxtf.org/geometry-1/#dom-dommatrix-scale3dself // https://drafts.fxtf.org/geometry-1/#dom-dommatrix-scale3dself
fn Scale3dSelf(&self, scale: f64, originX: f64, originY: f64, originZ: f64) -> Root<DOMMatrix> { fn Scale3dSelf(&self, scale: f64, originX: f64, originY: f64, originZ: f64) -> DomRoot<DOMMatrix> {
// Steps 1-4. // Steps 1-4.
self.upcast::<DOMMatrixReadOnly>().scale_3d_self(scale, originX, originY, originZ); self.upcast::<DOMMatrixReadOnly>().scale_3d_self(scale, originX, originY, originZ);
// Step 5. // Step 5.
Root::from_ref(&self) DomRoot::from_ref(&self)
} }
// https://drafts.fxtf.org/geometry-1/#dom-dommatrix-rotateself // https://drafts.fxtf.org/geometry-1/#dom-dommatrix-rotateself
fn RotateSelf(&self, rotX: f64, rotY: Option<f64>, rotZ: Option<f64>) -> Root<DOMMatrix> { fn RotateSelf(&self, rotX: f64, rotY: Option<f64>, rotZ: Option<f64>) -> DomRoot<DOMMatrix> {
// Steps 1-7. // Steps 1-7.
self.upcast::<DOMMatrixReadOnly>().rotate_self(rotX, rotY, rotZ); self.upcast::<DOMMatrixReadOnly>().rotate_self(rotX, rotY, rotZ);
// Step 8. // Step 8.
Root::from_ref(&self) DomRoot::from_ref(&self)
} }
// https://drafts.fxtf.org/geometry-1/#dom-dommatrix-rotatefromvectorself // https://drafts.fxtf.org/geometry-1/#dom-dommatrix-rotatefromvectorself
fn RotateFromVectorSelf(&self, x: f64, y: f64) -> Root<DOMMatrix> { fn RotateFromVectorSelf(&self, x: f64, y: f64) -> DomRoot<DOMMatrix> {
// Step 1. // Step 1.
self.upcast::<DOMMatrixReadOnly>().rotate_from_vector_self(x, y); self.upcast::<DOMMatrixReadOnly>().rotate_from_vector_self(x, y);
// Step 2. // Step 2.
Root::from_ref(&self) DomRoot::from_ref(&self)
} }
// https://drafts.fxtf.org/geometry-1/#dom-dommatrix-rotateaxisangleself // https://drafts.fxtf.org/geometry-1/#dom-dommatrix-rotateaxisangleself
fn RotateAxisAngleSelf(&self, x: f64, y: f64, z: f64, angle: f64) -> Root<DOMMatrix> { fn RotateAxisAngleSelf(&self, x: f64, y: f64, z: f64, angle: f64) -> DomRoot<DOMMatrix> {
// Steps 1-2. // Steps 1-2.
self.upcast::<DOMMatrixReadOnly>().rotate_axis_angle_self(x, y, z, angle); self.upcast::<DOMMatrixReadOnly>().rotate_axis_angle_self(x, y, z, angle);
// Step 3. // Step 3.
Root::from_ref(&self) DomRoot::from_ref(&self)
} }
// https://drafts.fxtf.org/geometry-1/#dom-dommatrix-skewxself // https://drafts.fxtf.org/geometry-1/#dom-dommatrix-skewxself
fn SkewXSelf(&self, sx: f64) -> Root<DOMMatrix> { fn SkewXSelf(&self, sx: f64) -> DomRoot<DOMMatrix> {
// Step 1. // Step 1.
self.upcast::<DOMMatrixReadOnly>().skew_x_self(sx); self.upcast::<DOMMatrixReadOnly>().skew_x_self(sx);
// Step 2. // Step 2.
Root::from_ref(&self) DomRoot::from_ref(&self)
} }
// https://drafts.fxtf.org/geometry-1/#dom-dommatrix-skewyself // https://drafts.fxtf.org/geometry-1/#dom-dommatrix-skewyself
fn SkewYSelf(&self, sy: f64) -> Root<DOMMatrix> { fn SkewYSelf(&self, sy: f64) -> DomRoot<DOMMatrix> {
// Step 1. // Step 1.
self.upcast::<DOMMatrixReadOnly>().skew_y_self(sy); self.upcast::<DOMMatrixReadOnly>().skew_y_self(sy);
// Step 2. // Step 2.
Root::from_ref(&self) DomRoot::from_ref(&self)
} }
// https://drafts.fxtf.org/geometry-1/#dom-dommatrix-invertself // https://drafts.fxtf.org/geometry-1/#dom-dommatrix-invertself
fn InvertSelf(&self) -> Root<DOMMatrix> { fn InvertSelf(&self) -> DomRoot<DOMMatrix> {
// Steps 1-2. // Steps 1-2.
self.upcast::<DOMMatrixReadOnly>().invert_self(); self.upcast::<DOMMatrixReadOnly>().invert_self();
// Step 3. // Step 3.
Root::from_ref(&self) DomRoot::from_ref(&self)
} }
} }

View file

@ -2,14 +2,14 @@
* License, v. 2.0. If a copy of the MPL was not distributed with this * 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/. */ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use dom::bindings::cell::DOMRefCell; use dom::bindings::cell::DomRefCell;
use dom::bindings::codegen::Bindings::DOMMatrixBinding::{DOMMatrixInit, DOMMatrixMethods}; use dom::bindings::codegen::Bindings::DOMMatrixBinding::{DOMMatrixInit, DOMMatrixMethods};
use dom::bindings::codegen::Bindings::DOMMatrixReadOnlyBinding::{DOMMatrixReadOnlyMethods, Wrap}; use dom::bindings::codegen::Bindings::DOMMatrixReadOnlyBinding::{DOMMatrixReadOnlyMethods, Wrap};
use dom::bindings::codegen::Bindings::DOMPointBinding::DOMPointInit; use dom::bindings::codegen::Bindings::DOMPointBinding::DOMPointInit;
use dom::bindings::error; use dom::bindings::error;
use dom::bindings::error::Fallible; use dom::bindings::error::Fallible;
use dom::bindings::js::Root;
use dom::bindings::reflector::{reflect_dom_object, DomObject, Reflector}; use dom::bindings::reflector::{reflect_dom_object, DomObject, Reflector};
use dom::bindings::root::DomRoot;
use dom::dommatrix::DOMMatrix; use dom::dommatrix::DOMMatrix;
use dom::dompoint::DOMPoint; use dom::dompoint::DOMPoint;
use dom::globalscope::GlobalScope; use dom::globalscope::GlobalScope;
@ -21,13 +21,13 @@ use std::f64;
#[dom_struct] #[dom_struct]
pub struct DOMMatrixReadOnly { pub struct DOMMatrixReadOnly {
reflector_: Reflector, reflector_: Reflector,
matrix: DOMRefCell<Transform3D<f64>>, matrix: DomRefCell<Transform3D<f64>>,
is2D: Cell<bool>, is2D: Cell<bool>,
} }
impl DOMMatrixReadOnly { impl DOMMatrixReadOnly {
#[allow(unrooted_must_root)] #[allow(unrooted_must_root)]
pub fn new(global: &GlobalScope, is2D: bool, matrix: Transform3D<f64>) -> Root<Self> { pub fn new(global: &GlobalScope, is2D: bool, matrix: Transform3D<f64>) -> DomRoot<Self> {
let dommatrix = Self::new_inherited(is2D, matrix); let dommatrix = Self::new_inherited(is2D, matrix);
reflect_dom_object(box dommatrix, global, Wrap) reflect_dom_object(box dommatrix, global, Wrap)
} }
@ -35,18 +35,18 @@ impl DOMMatrixReadOnly {
pub fn new_inherited(is2D: bool, matrix: Transform3D<f64>) -> Self { pub fn new_inherited(is2D: bool, matrix: Transform3D<f64>) -> Self {
DOMMatrixReadOnly { DOMMatrixReadOnly {
reflector_: Reflector::new(), reflector_: Reflector::new(),
matrix: DOMRefCell::new(matrix), matrix: DomRefCell::new(matrix),
is2D: Cell::new(is2D), is2D: Cell::new(is2D),
} }
} }
// https://drafts.fxtf.org/geometry-1/#dom-dommatrixreadonly-dommatrixreadonly // https://drafts.fxtf.org/geometry-1/#dom-dommatrixreadonly-dommatrixreadonly
pub fn Constructor(global: &GlobalScope) -> Fallible<Root<Self>> { pub fn Constructor(global: &GlobalScope) -> Fallible<DomRoot<Self>> {
Ok(Self::new(global, true, Transform3D::identity())) Ok(Self::new(global, true, Transform3D::identity()))
} }
// https://drafts.fxtf.org/geometry-1/#dom-dommatrixreadonly-dommatrixreadonly-numbersequence // https://drafts.fxtf.org/geometry-1/#dom-dommatrixreadonly-dommatrixreadonly-numbersequence
pub fn Constructor_(global: &GlobalScope, entries: Vec<f64>) -> Fallible<Root<Self>> { pub fn Constructor_(global: &GlobalScope, entries: Vec<f64>) -> Fallible<DomRoot<Self>> {
entries_to_matrix(&entries[..]) entries_to_matrix(&entries[..])
.map(|(is2D, matrix)| { .map(|(is2D, matrix)| {
Self::new(global, is2D, matrix) Self::new(global, is2D, matrix)
@ -54,7 +54,7 @@ impl DOMMatrixReadOnly {
} }
// https://drafts.fxtf.org/geometry-1/#dom-dommatrixreadonly-frommatrix // https://drafts.fxtf.org/geometry-1/#dom-dommatrixreadonly-frommatrix
pub fn FromMatrix(global: &GlobalScope, other: &DOMMatrixInit) -> Fallible<Root<Self>> { pub fn FromMatrix(global: &GlobalScope, other: &DOMMatrixInit) -> Fallible<DomRoot<Self>> {
dommatrixinit_to_matrix(&other) dommatrixinit_to_matrix(&other)
.map(|(is2D, matrix)| { .map(|(is2D, matrix)| {
Self::new(global, is2D, matrix) Self::new(global, is2D, matrix)
@ -463,55 +463,55 @@ impl DOMMatrixReadOnlyMethods for DOMMatrixReadOnly {
} }
// https://drafts.fxtf.org/geometry-1/#dom-dommatrixreadonly-translate // https://drafts.fxtf.org/geometry-1/#dom-dommatrixreadonly-translate
fn Translate(&self, tx: f64, ty: f64, tz: f64) -> Root<DOMMatrix> { fn Translate(&self, tx: f64, ty: f64, tz: f64) -> DomRoot<DOMMatrix> {
DOMMatrix::from_readonly(&self.global(), self).TranslateSelf(tx, ty, tz) DOMMatrix::from_readonly(&self.global(), self).TranslateSelf(tx, ty, tz)
} }
// https://drafts.fxtf.org/geometry-1/#dom-dommatrixreadonly-scale // https://drafts.fxtf.org/geometry-1/#dom-dommatrixreadonly-scale
fn Scale(&self, scaleX: f64, scaleY: Option<f64>, scaleZ: f64, fn Scale(&self, scaleX: f64, scaleY: Option<f64>, scaleZ: f64,
originX: f64, originY: f64, originZ: f64) -> Root<DOMMatrix> { originX: f64, originY: f64, originZ: f64) -> DomRoot<DOMMatrix> {
DOMMatrix::from_readonly(&self.global(), self) DOMMatrix::from_readonly(&self.global(), self)
.ScaleSelf(scaleX, scaleY, scaleZ, originX, originY, originZ) .ScaleSelf(scaleX, scaleY, scaleZ, originX, originY, originZ)
} }
// https://drafts.fxtf.org/geometry-1/#dom-dommatrixreadonly-scale3d // https://drafts.fxtf.org/geometry-1/#dom-dommatrixreadonly-scale3d
fn Scale3d(&self, scale: f64, originX: f64, originY: f64, originZ: f64) -> Root<DOMMatrix> { fn Scale3d(&self, scale: f64, originX: f64, originY: f64, originZ: f64) -> DomRoot<DOMMatrix> {
DOMMatrix::from_readonly(&self.global(), self) DOMMatrix::from_readonly(&self.global(), self)
.Scale3dSelf(scale, originX, originY, originZ) .Scale3dSelf(scale, originX, originY, originZ)
} }
// https://drafts.fxtf.org/geometry-1/#dom-dommatrixreadonly-rotate // https://drafts.fxtf.org/geometry-1/#dom-dommatrixreadonly-rotate
fn Rotate(&self, rotX: f64, rotY: Option<f64>, rotZ: Option<f64>) -> Root<DOMMatrix> { fn Rotate(&self, rotX: f64, rotY: Option<f64>, rotZ: Option<f64>) -> DomRoot<DOMMatrix> {
DOMMatrix::from_readonly(&self.global(), self).RotateSelf(rotX, rotY, rotZ) DOMMatrix::from_readonly(&self.global(), self).RotateSelf(rotX, rotY, rotZ)
} }
// https://drafts.fxtf.org/geometry-1/#dom-dommatrixreadonly-rotatefromvector // https://drafts.fxtf.org/geometry-1/#dom-dommatrixreadonly-rotatefromvector
fn RotateFromVector(&self, x: f64, y: f64) -> Root<DOMMatrix> { fn RotateFromVector(&self, x: f64, y: f64) -> DomRoot<DOMMatrix> {
DOMMatrix::from_readonly(&self.global(), self).RotateFromVectorSelf(x, y) DOMMatrix::from_readonly(&self.global(), self).RotateFromVectorSelf(x, y)
} }
// https://drafts.fxtf.org/geometry-1/#dom-dommatrixreadonly-rotateaxisangle // https://drafts.fxtf.org/geometry-1/#dom-dommatrixreadonly-rotateaxisangle
fn RotateAxisAngle(&self, x: f64, y: f64, z: f64, angle: f64) -> Root<DOMMatrix> { fn RotateAxisAngle(&self, x: f64, y: f64, z: f64, angle: f64) -> DomRoot<DOMMatrix> {
DOMMatrix::from_readonly(&self.global(), 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 // https://drafts.fxtf.org/geometry-1/#dom-dommatrixreadonly-skewx
fn SkewX(&self, sx: f64) -> Root<DOMMatrix> { fn SkewX(&self, sx: f64) -> DomRoot<DOMMatrix> {
DOMMatrix::from_readonly(&self.global(), self).SkewXSelf(sx) DOMMatrix::from_readonly(&self.global(), self).SkewXSelf(sx)
} }
// https://drafts.fxtf.org/geometry-1/#dom-dommatrixreadonly-skewy // https://drafts.fxtf.org/geometry-1/#dom-dommatrixreadonly-skewy
fn SkewY(&self, sy: f64) -> Root<DOMMatrix> { fn SkewY(&self, sy: f64) -> DomRoot<DOMMatrix> {
DOMMatrix::from_readonly(&self.global(), self).SkewYSelf(sy) DOMMatrix::from_readonly(&self.global(), self).SkewYSelf(sy)
} }
// https://drafts.fxtf.org/geometry-1/#dom-dommatrixreadonly-multiply // https://drafts.fxtf.org/geometry-1/#dom-dommatrixreadonly-multiply
fn Multiply(&self, other: &DOMMatrixInit) -> Fallible<Root<DOMMatrix>> { fn Multiply(&self, other: &DOMMatrixInit) -> Fallible<DomRoot<DOMMatrix>> {
DOMMatrix::from_readonly(&self.global(), self).MultiplySelf(&other) DOMMatrix::from_readonly(&self.global(), self).MultiplySelf(&other)
} }
// https://drafts.fxtf.org/geometry-1/#dom-dommatrixreadonly-flipx // https://drafts.fxtf.org/geometry-1/#dom-dommatrixreadonly-flipx
fn FlipX(&self) -> Root<DOMMatrix> { fn FlipX(&self) -> DomRoot<DOMMatrix> {
let is2D = self.is2D.get(); let is2D = self.is2D.get();
let flip = Transform3D::row_major(-1.0, 0.0, 0.0, 0.0, let flip = Transform3D::row_major(-1.0, 0.0, 0.0, 0.0,
0.0, 1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0,
@ -522,7 +522,7 @@ impl DOMMatrixReadOnlyMethods for DOMMatrixReadOnly {
} }
// https://drafts.fxtf.org/geometry-1/#dom-dommatrixreadonly-flipy // https://drafts.fxtf.org/geometry-1/#dom-dommatrixreadonly-flipy
fn FlipY(&self) -> Root<DOMMatrix> { fn FlipY(&self) -> DomRoot<DOMMatrix> {
let is2D = self.is2D.get(); let is2D = self.is2D.get();
let flip = Transform3D::row_major(1.0, 0.0, 0.0, 0.0, let flip = Transform3D::row_major(1.0, 0.0, 0.0, 0.0,
0.0, -1.0, 0.0, 0.0, 0.0, -1.0, 0.0, 0.0,
@ -533,12 +533,12 @@ impl DOMMatrixReadOnlyMethods for DOMMatrixReadOnly {
} }
// https://drafts.fxtf.org/geometry-1/#dom-dommatrixreadonly-inverse // https://drafts.fxtf.org/geometry-1/#dom-dommatrixreadonly-inverse
fn Inverse(&self) -> Root<DOMMatrix> { fn Inverse(&self) -> DomRoot<DOMMatrix> {
DOMMatrix::from_readonly(&self.global(), self).InvertSelf() DOMMatrix::from_readonly(&self.global(), self).InvertSelf()
} }
// https://drafts.fxtf.org/geometry-1/#dom-dommatrixreadonly-transformpoint // https://drafts.fxtf.org/geometry-1/#dom-dommatrixreadonly-transformpoint
fn TransformPoint(&self, point: &DOMPointInit) -> Root<DOMPoint> { fn TransformPoint(&self, point: &DOMPointInit) -> DomRoot<DOMPoint> {
// Euclid always normalizes the homogeneous coordinate which is usually the right // Euclid always normalizes the homogeneous coordinate which is usually the right
// thing but may (?) not be compliant with the CSS matrix spec (or at least is // thing but may (?) not be compliant with the CSS matrix spec (or at least is
// probably not the behavior web authors will expect even if it is mathematically // probably not the behavior web authors will expect even if it is mathematically

View file

@ -12,8 +12,8 @@ use dom::bindings::codegen::Bindings::DOMParserBinding::SupportedType::Text_xml;
use dom::bindings::codegen::Bindings::DocumentBinding::DocumentReadyState; use dom::bindings::codegen::Bindings::DocumentBinding::DocumentReadyState;
use dom::bindings::codegen::Bindings::WindowBinding::WindowMethods; use dom::bindings::codegen::Bindings::WindowBinding::WindowMethods;
use dom::bindings::error::Fallible; use dom::bindings::error::Fallible;
use dom::bindings::js::{JS, Root};
use dom::bindings::reflector::{Reflector, reflect_dom_object}; use dom::bindings::reflector::{Reflector, reflect_dom_object};
use dom::bindings::root::{Dom, DomRoot};
use dom::bindings::str::DOMString; use dom::bindings::str::DOMString;
use dom::document::{Document, HasBrowsingContext, IsHTMLDocument}; use dom::document::{Document, HasBrowsingContext, IsHTMLDocument};
use dom::document::DocumentSource; use dom::document::DocumentSource;
@ -25,24 +25,24 @@ use script_traits::DocumentActivity;
#[dom_struct] #[dom_struct]
pub struct DOMParser { pub struct DOMParser {
reflector_: Reflector, reflector_: Reflector,
window: JS<Window>, // XXXjdm Document instead? window: Dom<Window>, // XXXjdm Document instead?
} }
impl DOMParser { impl DOMParser {
fn new_inherited(window: &Window) -> DOMParser { fn new_inherited(window: &Window) -> DOMParser {
DOMParser { DOMParser {
reflector_: Reflector::new(), reflector_: Reflector::new(),
window: JS::from_ref(window), window: Dom::from_ref(window),
} }
} }
pub fn new(window: &Window) -> Root<DOMParser> { pub fn new(window: &Window) -> DomRoot<DOMParser> {
reflect_dom_object(box DOMParser::new_inherited(window), reflect_dom_object(box DOMParser::new_inherited(window),
window, window,
DOMParserBinding::Wrap) DOMParserBinding::Wrap)
} }
pub fn Constructor(window: &Window) -> Fallible<Root<DOMParser>> { pub fn Constructor(window: &Window) -> Fallible<DomRoot<DOMParser>> {
Ok(DOMParser::new(window)) Ok(DOMParser::new(window))
} }
} }
@ -52,7 +52,7 @@ impl DOMParserMethods for DOMParser {
fn ParseFromString(&self, fn ParseFromString(&self,
s: DOMString, s: DOMString,
ty: DOMParserBinding::SupportedType) ty: DOMParserBinding::SupportedType)
-> Fallible<Root<Document>> { -> Fallible<DomRoot<Document>> {
let url = self.window.get_url(); let url = self.window.get_url();
let content_type = DOMString::from(ty.as_str()); let content_type = DOMString::from(ty.as_str());
let doc = self.window.Document(); let doc = self.window.Document();

View file

@ -5,8 +5,8 @@
use dom::bindings::codegen::Bindings::DOMPointBinding::{DOMPointInit, DOMPointMethods, Wrap}; use dom::bindings::codegen::Bindings::DOMPointBinding::{DOMPointInit, DOMPointMethods, Wrap};
use dom::bindings::codegen::Bindings::DOMPointReadOnlyBinding::DOMPointReadOnlyMethods; use dom::bindings::codegen::Bindings::DOMPointReadOnlyBinding::DOMPointReadOnlyMethods;
use dom::bindings::error::Fallible; use dom::bindings::error::Fallible;
use dom::bindings::js::Root;
use dom::bindings::reflector::reflect_dom_object; use dom::bindings::reflector::reflect_dom_object;
use dom::bindings::root::DomRoot;
use dom::dompointreadonly::{DOMPointReadOnly, DOMPointWriteMethods}; use dom::dompointreadonly::{DOMPointReadOnly, DOMPointWriteMethods};
use dom::globalscope::GlobalScope; use dom::globalscope::GlobalScope;
use dom_struct::dom_struct; use dom_struct::dom_struct;
@ -24,7 +24,7 @@ impl DOMPoint {
} }
} }
pub fn new(global: &GlobalScope, x: f64, y: f64, z: f64, w: f64) -> Root<DOMPoint> { pub fn new(global: &GlobalScope, x: f64, y: f64, z: f64, w: f64) -> DomRoot<DOMPoint> {
reflect_dom_object(box DOMPoint::new_inherited(x, y, z, w), global, Wrap) reflect_dom_object(box DOMPoint::new_inherited(x, y, z, w), global, Wrap)
} }
@ -33,11 +33,11 @@ impl DOMPoint {
y: f64, y: f64,
z: f64, z: f64,
w: f64) w: f64)
-> Fallible<Root<DOMPoint>> { -> Fallible<DomRoot<DOMPoint>> {
Ok(DOMPoint::new(global, x, y, z, w)) Ok(DOMPoint::new(global, x, y, z, w))
} }
pub fn new_from_init(global: &GlobalScope, p: &DOMPointInit) -> Root<DOMPoint> { pub fn new_from_init(global: &GlobalScope, p: &DOMPointInit) -> DomRoot<DOMPoint> {
DOMPoint::new(global, p.x, p.y, p.z, p.w) DOMPoint::new(global, p.x, p.y, p.z, p.w)
} }
} }

View file

@ -4,8 +4,8 @@
use dom::bindings::codegen::Bindings::DOMPointReadOnlyBinding::{DOMPointReadOnlyMethods, Wrap}; use dom::bindings::codegen::Bindings::DOMPointReadOnlyBinding::{DOMPointReadOnlyMethods, Wrap};
use dom::bindings::error::Fallible; use dom::bindings::error::Fallible;
use dom::bindings::js::Root;
use dom::bindings::reflector::{Reflector, reflect_dom_object}; use dom::bindings::reflector::{Reflector, reflect_dom_object};
use dom::bindings::root::DomRoot;
use dom::globalscope::GlobalScope; use dom::globalscope::GlobalScope;
use dom_struct::dom_struct; use dom_struct::dom_struct;
use std::cell::Cell; use std::cell::Cell;
@ -31,7 +31,7 @@ impl DOMPointReadOnly {
} }
} }
pub fn new(global: &GlobalScope, x: f64, y: f64, z: f64, w: f64) -> Root<DOMPointReadOnly> { pub fn new(global: &GlobalScope, x: f64, y: f64, z: f64, w: f64) -> DomRoot<DOMPointReadOnly> {
reflect_dom_object(box DOMPointReadOnly::new_inherited(x, y, z, w), reflect_dom_object(box DOMPointReadOnly::new_inherited(x, y, z, w),
global, global,
Wrap) Wrap)
@ -42,7 +42,7 @@ impl DOMPointReadOnly {
y: f64, y: f64,
z: f64, z: f64,
w: f64) w: f64)
-> Fallible<Root<DOMPointReadOnly>> { -> Fallible<DomRoot<DOMPointReadOnly>> {
Ok(DOMPointReadOnly::new(global, x, y, z, w)) Ok(DOMPointReadOnly::new(global, x, y, z, w))
} }
} }

View file

@ -6,8 +6,8 @@ use dom::bindings::codegen::Bindings::DOMPointBinding::{DOMPointInit, DOMPointMe
use dom::bindings::codegen::Bindings::DOMQuadBinding::{DOMQuadInit, DOMQuadMethods, Wrap}; use dom::bindings::codegen::Bindings::DOMQuadBinding::{DOMQuadInit, DOMQuadMethods, Wrap};
use dom::bindings::codegen::Bindings::DOMRectReadOnlyBinding::DOMRectInit; use dom::bindings::codegen::Bindings::DOMRectReadOnlyBinding::DOMRectInit;
use dom::bindings::error::Fallible; use dom::bindings::error::Fallible;
use dom::bindings::js::{Root, JS};
use dom::bindings::reflector::{DomObject, Reflector, reflect_dom_object}; use dom::bindings::reflector::{DomObject, Reflector, reflect_dom_object};
use dom::bindings::root::{Dom, DomRoot};
use dom::dompoint::DOMPoint; use dom::dompoint::DOMPoint;
use dom::domrect::DOMRect; use dom::domrect::DOMRect;
use dom::globalscope::GlobalScope; use dom::globalscope::GlobalScope;
@ -17,10 +17,10 @@ use dom_struct::dom_struct;
#[dom_struct] #[dom_struct]
pub struct DOMQuad { pub struct DOMQuad {
reflector_: Reflector, reflector_: Reflector,
p1: JS<DOMPoint>, p1: Dom<DOMPoint>,
p2: JS<DOMPoint>, p2: Dom<DOMPoint>,
p3: JS<DOMPoint>, p3: Dom<DOMPoint>,
p4: JS<DOMPoint>, p4: Dom<DOMPoint>,
} }
impl DOMQuad { impl DOMQuad {
@ -31,10 +31,10 @@ impl DOMQuad {
-> DOMQuad { -> DOMQuad {
DOMQuad { DOMQuad {
reflector_: Reflector::new(), reflector_: Reflector::new(),
p1: JS::from_ref(p1), p1: Dom::from_ref(p1),
p2: JS::from_ref(p2), p2: Dom::from_ref(p2),
p3: JS::from_ref(p3), p3: Dom::from_ref(p3),
p4: JS::from_ref(p4), p4: Dom::from_ref(p4),
} }
} }
@ -42,7 +42,7 @@ impl DOMQuad {
p1: &DOMPoint, p1: &DOMPoint,
p2: &DOMPoint, p2: &DOMPoint,
p3: &DOMPoint, p3: &DOMPoint,
p4: &DOMPoint) -> Root<DOMQuad> { p4: &DOMPoint) -> DomRoot<DOMQuad> {
reflect_dom_object(box DOMQuad::new_inherited(p1, p2, p3, p4), reflect_dom_object(box DOMQuad::new_inherited(p1, p2, p3, p4),
global, global,
Wrap) Wrap)
@ -53,7 +53,7 @@ impl DOMQuad {
p2: &DOMPointInit, p2: &DOMPointInit,
p3: &DOMPointInit, p3: &DOMPointInit,
p4: &DOMPointInit) p4: &DOMPointInit)
-> Fallible<Root<DOMQuad>> { -> Fallible<DomRoot<DOMQuad>> {
Ok(DOMQuad::new(global, Ok(DOMQuad::new(global,
&*DOMPoint::new_from_init(global, p1), &*DOMPoint::new_from_init(global, p1),
&*DOMPoint::new_from_init(global, p2), &*DOMPoint::new_from_init(global, p2),
@ -62,7 +62,7 @@ impl DOMQuad {
} }
// https://drafts.fxtf.org/geometry/#dom-domquad-fromrect // https://drafts.fxtf.org/geometry/#dom-domquad-fromrect
pub fn FromRect(global: &GlobalScope, other: &DOMRectInit) -> Root<DOMQuad> { pub fn FromRect(global: &GlobalScope, other: &DOMRectInit) -> DomRoot<DOMQuad> {
DOMQuad::new(global, DOMQuad::new(global,
&*DOMPoint::new(global, other.x, other.y, 0f64, 1f64), &*DOMPoint::new(global, other.x, other.y, 0f64, 1f64),
&*DOMPoint::new(global, other.x + other.width, other.y, 0f64, 1f64), &*DOMPoint::new(global, other.x + other.width, other.y, 0f64, 1f64),
@ -71,7 +71,7 @@ impl DOMQuad {
} }
// https://drafts.fxtf.org/geometry/#dom-domquad-fromquad // https://drafts.fxtf.org/geometry/#dom-domquad-fromquad
pub fn FromQuad(global: &GlobalScope, other: &DOMQuadInit) -> Root<DOMQuad> { pub fn FromQuad(global: &GlobalScope, other: &DOMQuadInit) -> DomRoot<DOMQuad> {
DOMQuad::new(global, DOMQuad::new(global,
&DOMPoint::new_from_init(global, &other.p1), &DOMPoint::new_from_init(global, &other.p1),
&DOMPoint::new_from_init(global, &other.p2), &DOMPoint::new_from_init(global, &other.p2),
@ -82,27 +82,27 @@ impl DOMQuad {
impl DOMQuadMethods for DOMQuad { impl DOMQuadMethods for DOMQuad {
// https://drafts.fxtf.org/geometry/#dom-domquad-p1 // https://drafts.fxtf.org/geometry/#dom-domquad-p1
fn P1(&self) -> Root<DOMPoint> { fn P1(&self) -> DomRoot<DOMPoint> {
Root::from_ref(&self.p1) DomRoot::from_ref(&self.p1)
} }
// https://drafts.fxtf.org/geometry/#dom-domquad-p2 // https://drafts.fxtf.org/geometry/#dom-domquad-p2
fn P2(&self) -> Root<DOMPoint> { fn P2(&self) -> DomRoot<DOMPoint> {
Root::from_ref(&self.p2) DomRoot::from_ref(&self.p2)
} }
// https://drafts.fxtf.org/geometry/#dom-domquad-p3 // https://drafts.fxtf.org/geometry/#dom-domquad-p3
fn P3(&self) -> Root<DOMPoint> { fn P3(&self) -> DomRoot<DOMPoint> {
Root::from_ref(&self.p3) DomRoot::from_ref(&self.p3)
} }
// https://drafts.fxtf.org/geometry/#dom-domquad-p4 // https://drafts.fxtf.org/geometry/#dom-domquad-p4
fn P4(&self) -> Root<DOMPoint> { fn P4(&self) -> DomRoot<DOMPoint> {
Root::from_ref(&self.p4) DomRoot::from_ref(&self.p4)
} }
// https://drafts.fxtf.org/geometry/#dom-domquad-getbounds // https://drafts.fxtf.org/geometry/#dom-domquad-getbounds
fn GetBounds(&self) -> Root<DOMRect> { fn GetBounds(&self) -> DomRoot<DOMRect> {
let left = self.p1.X().min(self.p2.X()).min(self.p3.X()).min(self.p4.X()); let left = self.p1.X().min(self.p2.X()).min(self.p3.X()).min(self.p4.X());
let top = self.p1.Y().min(self.p2.Y()).min(self.p3.Y()).min(self.p4.Y()); let top = self.p1.Y().min(self.p2.Y()).min(self.p3.Y()).min(self.p4.Y());
let right = self.p1.X().max(self.p2.X()).max(self.p3.X()).max(self.p4.X()); let right = self.p1.X().max(self.p2.X()).max(self.p3.X()).max(self.p4.X());

View file

@ -6,8 +6,8 @@ use dom::bindings::codegen::Bindings::DOMRectBinding;
use dom::bindings::codegen::Bindings::DOMRectBinding::DOMRectMethods; use dom::bindings::codegen::Bindings::DOMRectBinding::DOMRectMethods;
use dom::bindings::codegen::Bindings::DOMRectReadOnlyBinding::DOMRectReadOnlyMethods; use dom::bindings::codegen::Bindings::DOMRectReadOnlyBinding::DOMRectReadOnlyMethods;
use dom::bindings::error::Fallible; use dom::bindings::error::Fallible;
use dom::bindings::js::Root;
use dom::bindings::reflector::reflect_dom_object; use dom::bindings::reflector::reflect_dom_object;
use dom::bindings::root::DomRoot;
use dom::domrectreadonly::DOMRectReadOnly; use dom::domrectreadonly::DOMRectReadOnly;
use dom::globalscope::GlobalScope; use dom::globalscope::GlobalScope;
use dom_struct::dom_struct; use dom_struct::dom_struct;
@ -24,7 +24,7 @@ impl DOMRect {
} }
} }
pub fn new(global: &GlobalScope, x: f64, y: f64, width: f64, height: f64) -> Root<DOMRect> { pub fn new(global: &GlobalScope, x: f64, y: f64, width: f64, height: f64) -> DomRoot<DOMRect> {
reflect_dom_object(box DOMRect::new_inherited(x, y, width, height), reflect_dom_object(box DOMRect::new_inherited(x, y, width, height),
global, global,
DOMRectBinding::Wrap) DOMRectBinding::Wrap)
@ -35,7 +35,7 @@ impl DOMRect {
y: f64, y: f64,
width: f64, width: f64,
height: f64) height: f64)
-> Fallible<Root<DOMRect>> { -> Fallible<DomRoot<DOMRect>> {
Ok(DOMRect::new(global, x, y, width, height)) Ok(DOMRect::new(global, x, y, width, height))
} }
} }

View file

@ -4,8 +4,8 @@
use dom::bindings::codegen::Bindings::DOMRectReadOnlyBinding::{DOMRectReadOnlyMethods, Wrap}; use dom::bindings::codegen::Bindings::DOMRectReadOnlyBinding::{DOMRectReadOnlyMethods, Wrap};
use dom::bindings::error::Fallible; use dom::bindings::error::Fallible;
use dom::bindings::js::Root;
use dom::bindings::reflector::{Reflector, reflect_dom_object}; use dom::bindings::reflector::{Reflector, reflect_dom_object};
use dom::bindings::root::DomRoot;
use dom::globalscope::GlobalScope; use dom::globalscope::GlobalScope;
use dom_struct::dom_struct; use dom_struct::dom_struct;
use std::cell::Cell; use std::cell::Cell;
@ -35,7 +35,7 @@ impl DOMRectReadOnly {
y: f64, y: f64,
width: f64, width: f64,
height: f64) height: f64)
-> Root<DOMRectReadOnly> { -> DomRoot<DOMRectReadOnly> {
reflect_dom_object(box DOMRectReadOnly::new_inherited(x, y, width, height), reflect_dom_object(box DOMRectReadOnly::new_inherited(x, y, width, height),
global, global,
Wrap) Wrap)
@ -46,7 +46,7 @@ impl DOMRectReadOnly {
y: f64, y: f64,
width: f64, width: f64,
height: f64) height: f64)
-> Fallible<Root<DOMRectReadOnly>> { -> Fallible<DomRoot<DOMRectReadOnly>> {
Ok(DOMRectReadOnly::new(global, x, y, width, height)) Ok(DOMRectReadOnly::new(global, x, y, width, height))
} }

View file

@ -5,8 +5,8 @@
use dom::bindings::codegen::Bindings::DOMStringMapBinding; use dom::bindings::codegen::Bindings::DOMStringMapBinding;
use dom::bindings::codegen::Bindings::DOMStringMapBinding::DOMStringMapMethods; use dom::bindings::codegen::Bindings::DOMStringMapBinding::DOMStringMapMethods;
use dom::bindings::error::ErrorResult; use dom::bindings::error::ErrorResult;
use dom::bindings::js::{JS, Root};
use dom::bindings::reflector::{Reflector, reflect_dom_object}; use dom::bindings::reflector::{Reflector, reflect_dom_object};
use dom::bindings::root::{Dom, DomRoot};
use dom::bindings::str::DOMString; use dom::bindings::str::DOMString;
use dom::htmlelement::HTMLElement; use dom::htmlelement::HTMLElement;
use dom::node::window_from_node; use dom::node::window_from_node;
@ -15,18 +15,18 @@ use dom_struct::dom_struct;
#[dom_struct] #[dom_struct]
pub struct DOMStringMap { pub struct DOMStringMap {
reflector_: Reflector, reflector_: Reflector,
element: JS<HTMLElement>, element: Dom<HTMLElement>,
} }
impl DOMStringMap { impl DOMStringMap {
fn new_inherited(element: &HTMLElement) -> DOMStringMap { fn new_inherited(element: &HTMLElement) -> DOMStringMap {
DOMStringMap { DOMStringMap {
reflector_: Reflector::new(), reflector_: Reflector::new(),
element: JS::from_ref(element), element: Dom::from_ref(element),
} }
} }
pub fn new(element: &HTMLElement) -> Root<DOMStringMap> { pub fn new(element: &HTMLElement) -> DomRoot<DOMStringMap> {
let window = window_from_node(element); let window = window_from_node(element);
reflect_dom_object(box DOMStringMap::new_inherited(element), reflect_dom_object(box DOMStringMap::new_inherited(element),
&*window, &*window,

View file

@ -6,8 +6,8 @@ use dom::attr::Attr;
use dom::bindings::codegen::Bindings::DOMTokenListBinding; use dom::bindings::codegen::Bindings::DOMTokenListBinding;
use dom::bindings::codegen::Bindings::DOMTokenListBinding::DOMTokenListMethods; use dom::bindings::codegen::Bindings::DOMTokenListBinding::DOMTokenListMethods;
use dom::bindings::error::{Error, ErrorResult, Fallible}; use dom::bindings::error::{Error, ErrorResult, Fallible};
use dom::bindings::js::{JS, Root};
use dom::bindings::reflector::{Reflector, reflect_dom_object}; use dom::bindings::reflector::{Reflector, reflect_dom_object};
use dom::bindings::root::{Dom, DomRoot};
use dom::bindings::str::DOMString; use dom::bindings::str::DOMString;
use dom::element::Element; use dom::element::Element;
use dom::node::window_from_node; use dom::node::window_from_node;
@ -19,7 +19,7 @@ use style::str::HTML_SPACE_CHARACTERS;
#[dom_struct] #[dom_struct]
pub struct DOMTokenList { pub struct DOMTokenList {
reflector_: Reflector, reflector_: Reflector,
element: JS<Element>, element: Dom<Element>,
local_name: LocalName, local_name: LocalName,
} }
@ -27,19 +27,19 @@ impl DOMTokenList {
pub fn new_inherited(element: &Element, local_name: LocalName) -> DOMTokenList { pub fn new_inherited(element: &Element, local_name: LocalName) -> DOMTokenList {
DOMTokenList { DOMTokenList {
reflector_: Reflector::new(), reflector_: Reflector::new(),
element: JS::from_ref(element), element: Dom::from_ref(element),
local_name: local_name, local_name: local_name,
} }
} }
pub fn new(element: &Element, local_name: &LocalName) -> Root<DOMTokenList> { pub fn new(element: &Element, local_name: &LocalName) -> DomRoot<DOMTokenList> {
let window = window_from_node(element); let window = window_from_node(element);
reflect_dom_object(box DOMTokenList::new_inherited(element, local_name.clone()), reflect_dom_object(box DOMTokenList::new_inherited(element, local_name.clone()),
&*window, &*window,
DOMTokenListBinding::Wrap) DOMTokenListBinding::Wrap)
} }
fn attribute(&self) -> Option<Root<Attr>> { fn attribute(&self) -> Option<DomRoot<Attr>> {
self.element.get_attribute(&ns!(), &self.local_name) self.element.get_attribute(&ns!(), &self.local_name)
} }

View file

@ -7,7 +7,7 @@
use devtools_traits::AttrInfo; use devtools_traits::AttrInfo;
use dom::activation::Activatable; use dom::activation::Activatable;
use dom::attr::{Attr, AttrHelpersForLayout}; use dom::attr::{Attr, AttrHelpersForLayout};
use dom::bindings::cell::DOMRefCell; use dom::bindings::cell::DomRefCell;
use dom::bindings::codegen::Bindings::AttrBinding::AttrMethods; use dom::bindings::codegen::Bindings::AttrBinding::AttrMethods;
use dom::bindings::codegen::Bindings::DocumentBinding::DocumentMethods; use dom::bindings::codegen::Bindings::DocumentBinding::DocumentMethods;
use dom::bindings::codegen::Bindings::ElementBinding; use dom::bindings::codegen::Bindings::ElementBinding;
@ -22,10 +22,9 @@ use dom::bindings::codegen::UnionTypes::NodeOrString;
use dom::bindings::conversions::DerivedFrom; use dom::bindings::conversions::DerivedFrom;
use dom::bindings::error::{Error, ErrorResult, Fallible}; use dom::bindings::error::{Error, ErrorResult, Fallible};
use dom::bindings::inheritance::{Castable, ElementTypeId, HTMLElementTypeId, NodeTypeId}; use dom::bindings::inheritance::{Castable, ElementTypeId, HTMLElementTypeId, NodeTypeId};
use dom::bindings::js::{JS, LayoutJS, MutNullableJS};
use dom::bindings::js::{Root, RootedReference};
use dom::bindings::refcounted::{Trusted, TrustedPromise}; use dom::bindings::refcounted::{Trusted, TrustedPromise};
use dom::bindings::reflector::DomObject; use dom::bindings::reflector::DomObject;
use dom::bindings::root::{Dom, DomRoot, LayoutDom, MutNullableDom, RootedReference};
use dom::bindings::str::DOMString; use dom::bindings::str::DOMString;
use dom::bindings::xmlname::{namespace_from_domstring, validate_and_extract, xml_name_type}; use dom::bindings::xmlname::{namespace_from_domstring, validate_and_extract, xml_name_type};
use dom::bindings::xmlname::XMLName::InvalidXMLName; use dom::bindings::xmlname::XMLName::InvalidXMLName;
@ -131,14 +130,14 @@ pub struct Element {
local_name: LocalName, local_name: LocalName,
tag_name: TagName, tag_name: TagName,
namespace: Namespace, namespace: Namespace,
prefix: DOMRefCell<Option<Prefix>>, prefix: DomRefCell<Option<Prefix>>,
attrs: DOMRefCell<Vec<JS<Attr>>>, attrs: DomRefCell<Vec<Dom<Attr>>>,
id_attribute: DOMRefCell<Option<Atom>>, id_attribute: DomRefCell<Option<Atom>>,
is: DOMRefCell<Option<LocalName>>, is: DomRefCell<Option<LocalName>>,
#[ignore_heap_size_of = "Arc"] #[ignore_heap_size_of = "Arc"]
style_attribute: DOMRefCell<Option<Arc<Locked<PropertyDeclarationBlock>>>>, style_attribute: DomRefCell<Option<Arc<Locked<PropertyDeclarationBlock>>>>,
attr_list: MutNullableJS<NamedNodeMap>, attr_list: MutNullableDom<NamedNodeMap>,
class_list: MutNullableJS<DOMTokenList>, class_list: MutNullableDom<DOMTokenList>,
state: Cell<ElementState>, state: Cell<ElementState>,
/// These flags are set by the style system to indicate the that certain /// These flags are set by the style system to indicate the that certain
/// operations may require restyling this element or its descendants. The /// operations may require restyling this element or its descendants. The
@ -147,10 +146,10 @@ pub struct Element {
#[ignore_heap_size_of = "bitflags defined in rust-selectors"] #[ignore_heap_size_of = "bitflags defined in rust-selectors"]
selector_flags: Cell<ElementSelectorFlags>, selector_flags: Cell<ElementSelectorFlags>,
/// https://html.spec.whatwg.org/multipage/#custom-element-reaction-queue /// https://html.spec.whatwg.org/multipage/#custom-element-reaction-queue
custom_element_reaction_queue: DOMRefCell<Vec<CustomElementReaction>>, custom_element_reaction_queue: DomRefCell<Vec<CustomElementReaction>>,
/// https://dom.spec.whatwg.org/#concept-element-custom-element-definition /// https://dom.spec.whatwg.org/#concept-element-custom-element-definition
#[ignore_heap_size_of = "Rc"] #[ignore_heap_size_of = "Rc"]
custom_element_definition: DOMRefCell<Option<Rc<CustomElementDefinition>>>, custom_element_definition: DomRefCell<Option<Rc<CustomElementDefinition>>>,
/// https://dom.spec.whatwg.org/#concept-element-custom-element-state /// https://dom.spec.whatwg.org/#concept-element-custom-element-state
custom_element_state: Cell<CustomElementState>, custom_element_state: Cell<CustomElementState>,
} }
@ -165,7 +164,7 @@ impl fmt::Debug for Element {
} }
} }
impl fmt::Debug for Root<Element> { impl fmt::Debug for DomRoot<Element> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
(**self).fmt(f) (**self).fmt(f)
} }
@ -236,7 +235,7 @@ impl Element {
document: &Document, document: &Document,
creator: ElementCreator, creator: ElementCreator,
mode: CustomElementCreationMode) mode: CustomElementCreationMode)
-> Root<Element> { -> DomRoot<Element> {
create_element(name, is, document, creator, mode) create_element(name, is, document, creator, mode)
} }
@ -256,11 +255,11 @@ impl Element {
local_name: local_name, local_name: local_name,
tag_name: TagName::new(), tag_name: TagName::new(),
namespace: namespace, namespace: namespace,
prefix: DOMRefCell::new(prefix), prefix: DomRefCell::new(prefix),
attrs: DOMRefCell::new(vec![]), attrs: DomRefCell::new(vec![]),
id_attribute: DOMRefCell::new(None), id_attribute: DomRefCell::new(None),
is: DOMRefCell::new(None), is: DomRefCell::new(None),
style_attribute: DOMRefCell::new(None), style_attribute: DomRefCell::new(None),
attr_list: Default::default(), attr_list: Default::default(),
class_list: Default::default(), class_list: Default::default(),
state: Cell::new(state), state: Cell::new(state),
@ -274,7 +273,7 @@ impl Element {
pub fn new(local_name: LocalName, pub fn new(local_name: LocalName,
namespace: Namespace, namespace: Namespace,
prefix: Option<Prefix>, prefix: Option<Prefix>,
document: &Document) -> Root<Element> { document: &Document) -> DomRoot<Element> {
Node::reflect_node( Node::reflect_node(
box Element::new_inherited(local_name, namespace, prefix, document), box Element::new_inherited(local_name, namespace, prefix, document),
document, document,
@ -385,7 +384,7 @@ pub trait RawLayoutElementHelpers {
#[inline] #[inline]
#[allow(unsafe_code)] #[allow(unsafe_code)]
pub unsafe fn get_attr_for_layout<'a>(elem: &'a Element, namespace: &Namespace, name: &LocalName) pub unsafe fn get_attr_for_layout<'a>(elem: &'a Element, namespace: &Namespace, name: &LocalName)
-> Option<LayoutJS<Attr>> { -> Option<LayoutDom<Attr>> {
// cast to point to T in RefCell<T> directly // cast to point to T in RefCell<T> directly
let attrs = elem.attrs.borrow_for_layout(); let attrs = elem.attrs.borrow_for_layout();
attrs.iter().find(|attr| { attrs.iter().find(|attr| {
@ -454,7 +453,7 @@ pub trait LayoutElementHelpers {
fn has_selector_flags(&self, flags: ElementSelectorFlags) -> bool; fn has_selector_flags(&self, flags: ElementSelectorFlags) -> bool;
} }
impl LayoutElementHelpers for LayoutJS<Element> { impl LayoutElementHelpers for LayoutDom<Element> {
#[allow(unsafe_code)] #[allow(unsafe_code)]
#[inline] #[inline]
unsafe fn has_class_for_layout(&self, name: &Atom, case_sensitivity: CaseSensitivity) -> bool { unsafe fn has_class_for_layout(&self, name: &Atom, case_sensitivity: CaseSensitivity) -> bool {
@ -913,7 +912,7 @@ impl Element {
*self.prefix.borrow_mut() = prefix; *self.prefix.borrow_mut() = prefix;
} }
pub fn attrs(&self) -> Ref<[JS<Attr>]> { pub fn attrs(&self) -> Ref<[Dom<Attr>]> {
Ref::map(self.attrs.borrow(), |attrs| &**attrs) Ref::map(self.attrs.borrow(), |attrs| &**attrs)
} }
@ -924,7 +923,7 @@ impl Element {
let inclusive_ancestor_elements = let inclusive_ancestor_elements =
self.upcast::<Node>() self.upcast::<Node>()
.inclusive_ancestors() .inclusive_ancestors()
.filter_map(Root::downcast::<Self>); .filter_map(DomRoot::downcast::<Self>);
// Steps 3-4. // Steps 3-4.
for element in inclusive_ancestor_elements { for element in inclusive_ancestor_elements {
@ -959,7 +958,7 @@ impl Element {
ns!() ns!()
} }
pub fn style_attribute(&self) -> &DOMRefCell<Option<Arc<Locked<PropertyDeclarationBlock>>>> { pub fn style_attribute(&self) -> &DomRefCell<Option<Arc<Locked<PropertyDeclarationBlock>>>> {
&self.style_attribute &self.style_attribute
} }
@ -1003,7 +1002,7 @@ impl Element {
} }
} }
pub fn root_element(&self) -> Root<Element> { pub fn root_element(&self) -> DomRoot<Element> {
if self.node.is_in_doc() { if self.node.is_in_doc() {
self.upcast::<Node>() self.upcast::<Node>()
.owner_doc() .owner_doc()
@ -1012,7 +1011,7 @@ impl Element {
} else { } else {
self.upcast::<Node>() self.upcast::<Node>()
.inclusive_ancestors() .inclusive_ancestors()
.filter_map(Root::downcast) .filter_map(DomRoot::downcast)
.last() .last()
.expect("We know inclusive_ancestors will return `self` which is an element") .expect("We know inclusive_ancestors will return `self` which is an element")
} }
@ -1119,24 +1118,24 @@ impl Element {
assert!(attr.GetOwnerElement().r() == Some(self)); assert!(attr.GetOwnerElement().r() == Some(self));
self.will_mutate_attr(attr); self.will_mutate_attr(attr);
self.attrs.borrow_mut().push(JS::from_ref(attr)); self.attrs.borrow_mut().push(Dom::from_ref(attr));
if attr.namespace() == &ns!() { if attr.namespace() == &ns!() {
vtable_for(self.upcast()).attribute_mutated(attr, AttributeMutation::Set(None)); vtable_for(self.upcast()).attribute_mutated(attr, AttributeMutation::Set(None));
} }
} }
pub fn get_attribute(&self, namespace: &Namespace, local_name: &LocalName) -> Option<Root<Attr>> { pub fn get_attribute(&self, namespace: &Namespace, local_name: &LocalName) -> Option<DomRoot<Attr>> {
self.attrs self.attrs
.borrow() .borrow()
.iter() .iter()
.find(|attr| attr.local_name() == local_name && attr.namespace() == namespace) .find(|attr| attr.local_name() == local_name && attr.namespace() == namespace)
.map(|js| Root::from_ref(&**js)) .map(|js| DomRoot::from_ref(&**js))
} }
// https://dom.spec.whatwg.org/#concept-element-attributes-get-by-name // https://dom.spec.whatwg.org/#concept-element-attributes-get-by-name
pub fn get_attribute_by_name(&self, name: DOMString) -> Option<Root<Attr>> { pub fn get_attribute_by_name(&self, name: DOMString) -> Option<DomRoot<Attr>> {
let name = &self.parsed_name(name); let name = &self.parsed_name(name);
self.attrs.borrow().iter().find(|a| a.name() == name).map(|js| Root::from_ref(&**js)) self.attrs.borrow().iter().find(|a| a.name() == name).map(|js| DomRoot::from_ref(&**js))
} }
pub fn set_attribute_from_parser(&self, pub fn set_attribute_from_parser(&self,
@ -1208,7 +1207,7 @@ impl Element {
.borrow() .borrow()
.iter() .iter()
.find(|attr| find(&attr)) .find(|attr| find(&attr))
.map(|js| Root::from_ref(&**js)); .map(|js| DomRoot::from_ref(&**js));
if let Some(attr) = attr { if let Some(attr) = attr {
attr.set_value(value, self); attr.set_value(value, self);
} else { } else {
@ -1228,21 +1227,21 @@ impl Element {
} }
} }
pub fn remove_attribute(&self, namespace: &Namespace, local_name: &LocalName) -> Option<Root<Attr>> { pub fn remove_attribute(&self, namespace: &Namespace, local_name: &LocalName) -> Option<DomRoot<Attr>> {
self.remove_first_matching_attribute(|attr| { self.remove_first_matching_attribute(|attr| {
attr.namespace() == namespace && attr.local_name() == local_name attr.namespace() == namespace && attr.local_name() == local_name
}) })
} }
pub fn remove_attribute_by_name(&self, name: &LocalName) -> Option<Root<Attr>> { pub fn remove_attribute_by_name(&self, name: &LocalName) -> Option<DomRoot<Attr>> {
self.remove_first_matching_attribute(|attr| attr.name() == name) self.remove_first_matching_attribute(|attr| attr.name() == name)
} }
fn remove_first_matching_attribute<F>(&self, find: F) -> Option<Root<Attr>> fn remove_first_matching_attribute<F>(&self, find: F) -> Option<DomRoot<Attr>>
where F: Fn(&Attr) -> bool { where F: Fn(&Attr) -> bool {
let idx = self.attrs.borrow().iter().position(|attr| find(&attr)); let idx = self.attrs.borrow().iter().position(|attr| find(&attr));
idx.map(|idx| { idx.map(|idx| {
let attr = Root::from_ref(&*(*self.attrs.borrow())[idx]); let attr = DomRoot::from_ref(&*(*self.attrs.borrow())[idx]);
self.will_mutate_attr(&attr); self.will_mutate_attr(&attr);
let name = attr.local_name().clone(); let name = attr.local_name().clone();
@ -1397,7 +1396,7 @@ impl Element {
// https://dom.spec.whatwg.org/#insert-adjacent // https://dom.spec.whatwg.org/#insert-adjacent
pub fn insert_adjacent(&self, where_: AdjacentPosition, node: &Node) pub fn insert_adjacent(&self, where_: AdjacentPosition, node: &Node)
-> Fallible<Option<Root<Node>>> { -> Fallible<Option<DomRoot<Node>>> {
let self_node = self.upcast::<Node>(); let self_node = self.upcast::<Node>();
match where_ { match where_ {
AdjacentPosition::BeforeBegin => { AdjacentPosition::BeforeBegin => {
@ -1469,7 +1468,7 @@ impl Element {
} }
// https://w3c.github.io/DOM-Parsing/#parsing // https://w3c.github.io/DOM-Parsing/#parsing
pub fn parse_fragment(&self, markup: DOMString) -> Fallible<Root<DocumentFragment>> { pub fn parse_fragment(&self, markup: DOMString) -> Fallible<DomRoot<DocumentFragment>> {
// Steps 1-2. // Steps 1-2.
let context_document = document_from_node(self); let context_document = document_from_node(self);
// TODO(#11995): XML case. // TODO(#11995): XML case.
@ -1484,13 +1483,13 @@ impl Element {
Ok(fragment) Ok(fragment)
} }
pub fn fragment_parsing_context(owner_doc: &Document, element: Option<&Self>) -> Root<Self> { pub fn fragment_parsing_context(owner_doc: &Document, element: Option<&Self>) -> DomRoot<Self> {
match element { match element {
Some(elem) if elem.local_name() != &local_name!("html") || !elem.html_element_in_html_document() => { Some(elem) if elem.local_name() != &local_name!("html") || !elem.html_element_in_html_document() => {
Root::from_ref(elem) DomRoot::from_ref(elem)
}, },
_ => { _ => {
Root::upcast(HTMLBodyElement::new(local_name!("body"), None, owner_doc)) DomRoot::upcast(HTMLBodyElement::new(local_name!("body"), None, owner_doc))
} }
} }
} }
@ -1569,12 +1568,12 @@ impl ElementMethods for Element {
} }
// https://dom.spec.whatwg.org/#dom-element-classlist // https://dom.spec.whatwg.org/#dom-element-classlist
fn ClassList(&self) -> Root<DOMTokenList> { fn ClassList(&self) -> DomRoot<DOMTokenList> {
self.class_list.or_init(|| DOMTokenList::new(self, &local_name!("class"))) self.class_list.or_init(|| DOMTokenList::new(self, &local_name!("class")))
} }
// https://dom.spec.whatwg.org/#dom-element-attributes // https://dom.spec.whatwg.org/#dom-element-attributes
fn Attributes(&self) -> Root<NamedNodeMap> { fn Attributes(&self) -> DomRoot<NamedNodeMap> {
self.attr_list.or_init(|| NamedNodeMap::new(&window_from_node(self), self)) self.attr_list.or_init(|| NamedNodeMap::new(&window_from_node(self), self))
} }
@ -1604,7 +1603,7 @@ impl ElementMethods for Element {
} }
// https://dom.spec.whatwg.org/#dom-element-getattributenode // https://dom.spec.whatwg.org/#dom-element-getattributenode
fn GetAttributeNode(&self, name: DOMString) -> Option<Root<Attr>> { fn GetAttributeNode(&self, name: DOMString) -> Option<DomRoot<Attr>> {
self.get_attribute_by_name(name) self.get_attribute_by_name(name)
} }
@ -1612,7 +1611,7 @@ impl ElementMethods for Element {
fn GetAttributeNodeNS(&self, fn GetAttributeNodeNS(&self,
namespace: Option<DOMString>, namespace: Option<DOMString>,
local_name: DOMString) local_name: DOMString)
-> Option<Root<Attr>> { -> Option<DomRoot<Attr>> {
let namespace = &namespace_from_domstring(namespace); let namespace = &namespace_from_domstring(namespace);
self.get_attribute(namespace, &LocalName::from(local_name)) self.get_attribute(namespace, &LocalName::from(local_name))
} }
@ -1651,7 +1650,7 @@ impl ElementMethods for Element {
} }
// https://dom.spec.whatwg.org/#dom-element-setattributenode // https://dom.spec.whatwg.org/#dom-element-setattributenode
fn SetAttributeNode(&self, attr: &Attr) -> Fallible<Option<Root<Attr>>> { fn SetAttributeNode(&self, attr: &Attr) -> Fallible<Option<DomRoot<Attr>>> {
// Step 1. // Step 1.
if let Some(owner) = attr.GetOwnerElement() { if let Some(owner) = attr.GetOwnerElement() {
if &*owner != self { if &*owner != self {
@ -1674,11 +1673,11 @@ impl ElementMethods for Element {
}); });
if let Some(position) = position { if let Some(position) = position {
let old_attr = Root::from_ref(&*self.attrs.borrow()[position]); let old_attr = DomRoot::from_ref(&*self.attrs.borrow()[position]);
// Step 3. // Step 3.
if &*old_attr == attr { if &*old_attr == attr {
return Ok(Some(Root::from_ref(attr))); return Ok(Some(DomRoot::from_ref(attr)));
} }
// Step 4. // Step 4.
@ -1693,7 +1692,7 @@ impl ElementMethods for Element {
} }
self.will_mutate_attr(attr); self.will_mutate_attr(attr);
attr.set_owner(Some(self)); attr.set_owner(Some(self));
self.attrs.borrow_mut()[position] = JS::from_ref(attr); self.attrs.borrow_mut()[position] = Dom::from_ref(attr);
old_attr.set_owner(None); old_attr.set_owner(None);
if attr.namespace() == &ns!() { if attr.namespace() == &ns!() {
vtable.attribute_mutated( vtable.attribute_mutated(
@ -1713,7 +1712,7 @@ impl ElementMethods for Element {
} }
// https://dom.spec.whatwg.org/#dom-element-setattributenodens // https://dom.spec.whatwg.org/#dom-element-setattributenodens
fn SetAttributeNodeNS(&self, attr: &Attr) -> Fallible<Option<Root<Attr>>> { fn SetAttributeNodeNS(&self, attr: &Attr) -> Fallible<Option<DomRoot<Attr>>> {
self.SetAttributeNode(attr) self.SetAttributeNode(attr)
} }
@ -1731,7 +1730,7 @@ impl ElementMethods for Element {
} }
// https://dom.spec.whatwg.org/#dom-element-removeattributenode // https://dom.spec.whatwg.org/#dom-element-removeattributenode
fn RemoveAttributeNode(&self, attr: &Attr) -> Fallible<Root<Attr>> { fn RemoveAttributeNode(&self, attr: &Attr) -> Fallible<DomRoot<Attr>> {
self.remove_first_matching_attribute(|a| a == attr) self.remove_first_matching_attribute(|a| a == attr)
.ok_or(Error::NotFound) .ok_or(Error::NotFound)
} }
@ -1747,7 +1746,7 @@ impl ElementMethods for Element {
} }
// https://dom.spec.whatwg.org/#dom-element-getelementsbytagname // https://dom.spec.whatwg.org/#dom-element-getelementsbytagname
fn GetElementsByTagName(&self, localname: DOMString) -> Root<HTMLCollection> { fn GetElementsByTagName(&self, localname: DOMString) -> DomRoot<HTMLCollection> {
let window = window_from_node(self); let window = window_from_node(self);
HTMLCollection::by_qualified_name(&window, self.upcast(), LocalName::from(&*localname)) HTMLCollection::by_qualified_name(&window, self.upcast(), LocalName::from(&*localname))
} }
@ -1756,19 +1755,19 @@ impl ElementMethods for Element {
fn GetElementsByTagNameNS(&self, fn GetElementsByTagNameNS(&self,
maybe_ns: Option<DOMString>, maybe_ns: Option<DOMString>,
localname: DOMString) localname: DOMString)
-> Root<HTMLCollection> { -> DomRoot<HTMLCollection> {
let window = window_from_node(self); let window = window_from_node(self);
HTMLCollection::by_tag_name_ns(&window, self.upcast(), localname, maybe_ns) HTMLCollection::by_tag_name_ns(&window, self.upcast(), localname, maybe_ns)
} }
// https://dom.spec.whatwg.org/#dom-element-getelementsbyclassname // https://dom.spec.whatwg.org/#dom-element-getelementsbyclassname
fn GetElementsByClassName(&self, classes: DOMString) -> Root<HTMLCollection> { fn GetElementsByClassName(&self, classes: DOMString) -> DomRoot<HTMLCollection> {
let window = window_from_node(self); let window = window_from_node(self);
HTMLCollection::by_class_name(&window, self.upcast(), classes) HTMLCollection::by_class_name(&window, self.upcast(), classes)
} }
// https://drafts.csswg.org/cssom-view/#dom-element-getclientrects // https://drafts.csswg.org/cssom-view/#dom-element-getclientrects
fn GetClientRects(&self) -> Vec<Root<DOMRect>> { fn GetClientRects(&self) -> Vec<DomRoot<DOMRect>> {
let win = window_from_node(self); let win = window_from_node(self);
let raw_rects = self.upcast::<Node>().content_boxes(); let raw_rects = self.upcast::<Node>().content_boxes();
raw_rects.iter().map(|rect| { raw_rects.iter().map(|rect| {
@ -1781,7 +1780,7 @@ impl ElementMethods for Element {
} }
// https://drafts.csswg.org/cssom-view/#dom-element-getboundingclientrect // https://drafts.csswg.org/cssom-view/#dom-element-getboundingclientrect
fn GetBoundingClientRect(&self) -> Root<DOMRect> { fn GetBoundingClientRect(&self) -> DomRoot<DOMRect> {
let win = window_from_node(self); let win = window_from_node(self);
let rect = self.upcast::<Node>().bounding_content_box_or_zero(); let rect = self.upcast::<Node>().bounding_content_box_or_zero();
DOMRect::new(win.upcast(), DOMRect::new(win.upcast(),
@ -2060,9 +2059,9 @@ impl ElementMethods for Element {
// Step 2. // Step 2.
// https://github.com/w3c/DOM-Parsing/issues/1 // https://github.com/w3c/DOM-Parsing/issues/1
let target = if let Some(template) = self.downcast::<HTMLTemplateElement>() { let target = if let Some(template) = self.downcast::<HTMLTemplateElement>() {
Root::upcast(template.Content()) DomRoot::upcast(template.Content())
} else { } else {
Root::from_ref(self.upcast()) DomRoot::from_ref(self.upcast())
}; };
Node::replace_all(Some(frag.upcast()), &target); Node::replace_all(Some(frag.upcast()), &target);
Ok(()) Ok(())
@ -2097,7 +2096,7 @@ impl ElementMethods for Element {
&context_document, &context_document,
ElementCreator::ScriptCreated, ElementCreator::ScriptCreated,
CustomElementCreationMode::Synchronous); CustomElementCreationMode::Synchronous);
Root::upcast(body_elem) DomRoot::upcast(body_elem)
}, },
_ => context_node.GetParentElement().unwrap() _ => context_node.GetParentElement().unwrap()
}; };
@ -2110,29 +2109,29 @@ impl ElementMethods for Element {
} }
// https://dom.spec.whatwg.org/#dom-nondocumenttypechildnode-previouselementsibling // https://dom.spec.whatwg.org/#dom-nondocumenttypechildnode-previouselementsibling
fn GetPreviousElementSibling(&self) -> Option<Root<Element>> { fn GetPreviousElementSibling(&self) -> Option<DomRoot<Element>> {
self.upcast::<Node>().preceding_siblings().filter_map(Root::downcast).next() self.upcast::<Node>().preceding_siblings().filter_map(DomRoot::downcast).next()
} }
// https://dom.spec.whatwg.org/#dom-nondocumenttypechildnode-nextelementsibling // https://dom.spec.whatwg.org/#dom-nondocumenttypechildnode-nextelementsibling
fn GetNextElementSibling(&self) -> Option<Root<Element>> { fn GetNextElementSibling(&self) -> Option<DomRoot<Element>> {
self.upcast::<Node>().following_siblings().filter_map(Root::downcast).next() self.upcast::<Node>().following_siblings().filter_map(DomRoot::downcast).next()
} }
// https://dom.spec.whatwg.org/#dom-parentnode-children // https://dom.spec.whatwg.org/#dom-parentnode-children
fn Children(&self) -> Root<HTMLCollection> { fn Children(&self) -> DomRoot<HTMLCollection> {
let window = window_from_node(self); let window = window_from_node(self);
HTMLCollection::children(&window, self.upcast()) HTMLCollection::children(&window, self.upcast())
} }
// https://dom.spec.whatwg.org/#dom-parentnode-firstelementchild // https://dom.spec.whatwg.org/#dom-parentnode-firstelementchild
fn GetFirstElementChild(&self) -> Option<Root<Element>> { fn GetFirstElementChild(&self) -> Option<DomRoot<Element>> {
self.upcast::<Node>().child_elements().next() self.upcast::<Node>().child_elements().next()
} }
// https://dom.spec.whatwg.org/#dom-parentnode-lastelementchild // https://dom.spec.whatwg.org/#dom-parentnode-lastelementchild
fn GetLastElementChild(&self) -> Option<Root<Element>> { fn GetLastElementChild(&self) -> Option<DomRoot<Element>> {
self.upcast::<Node>().rev_children().filter_map(Root::downcast::<Element>).next() self.upcast::<Node>().rev_children().filter_map(DomRoot::downcast::<Element>).next()
} }
// https://dom.spec.whatwg.org/#dom-parentnode-childelementcount // https://dom.spec.whatwg.org/#dom-parentnode-childelementcount
@ -2151,13 +2150,13 @@ impl ElementMethods for Element {
} }
// https://dom.spec.whatwg.org/#dom-parentnode-queryselector // https://dom.spec.whatwg.org/#dom-parentnode-queryselector
fn QuerySelector(&self, selectors: DOMString) -> Fallible<Option<Root<Element>>> { fn QuerySelector(&self, selectors: DOMString) -> Fallible<Option<DomRoot<Element>>> {
let root = self.upcast::<Node>(); let root = self.upcast::<Node>();
root.query_selector(selectors) root.query_selector(selectors)
} }
// https://dom.spec.whatwg.org/#dom-parentnode-queryselectorall // https://dom.spec.whatwg.org/#dom-parentnode-queryselectorall
fn QuerySelectorAll(&self, selectors: DOMString) -> Fallible<Root<NodeList>> { fn QuerySelectorAll(&self, selectors: DOMString) -> Fallible<DomRoot<NodeList>> {
let root = self.upcast::<Node>(); let root = self.upcast::<Node>();
root.query_selector_all(selectors) root.query_selector_all(selectors)
} }
@ -2191,7 +2190,7 @@ impl ElementMethods for Element {
// FIXME(bholley): Consider an nth-index cache here. // FIXME(bholley): Consider an nth-index cache here.
let mut ctx = MatchingContext::new(MatchingMode::Normal, None, None, let mut ctx = MatchingContext::new(MatchingMode::Normal, None, None,
quirks_mode); quirks_mode);
Ok(matches_selector_list(&selectors, &Root::from_ref(self), &mut ctx)) Ok(matches_selector_list(&selectors, &DomRoot::from_ref(self), &mut ctx))
} }
} }
} }
@ -2202,13 +2201,13 @@ impl ElementMethods for Element {
} }
// https://dom.spec.whatwg.org/#dom-element-closest // https://dom.spec.whatwg.org/#dom-element-closest
fn Closest(&self, selectors: DOMString) -> Fallible<Option<Root<Element>>> { fn Closest(&self, selectors: DOMString) -> Fallible<Option<DomRoot<Element>>> {
match SelectorParser::parse_author_origin_no_namespace(&selectors) { match SelectorParser::parse_author_origin_no_namespace(&selectors) {
Err(_) => Err(Error::Syntax), Err(_) => Err(Error::Syntax),
Ok(selectors) => { Ok(selectors) => {
let root = self.upcast::<Node>(); let root = self.upcast::<Node>();
for element in root.inclusive_ancestors() { for element in root.inclusive_ancestors() {
if let Some(element) = Root::downcast::<Element>(element) { if let Some(element) = DomRoot::downcast::<Element>(element) {
let quirks_mode = document_from_node(self).quirks_mode(); let quirks_mode = document_from_node(self).quirks_mode();
// FIXME(bholley): Consider an nth-index cache here. // FIXME(bholley): Consider an nth-index cache here.
let mut ctx = MatchingContext::new(MatchingMode::Normal, None, None, let mut ctx = MatchingContext::new(MatchingMode::Normal, None, None,
@ -2225,10 +2224,10 @@ impl ElementMethods for Element {
// https://dom.spec.whatwg.org/#dom-element-insertadjacentelement // https://dom.spec.whatwg.org/#dom-element-insertadjacentelement
fn InsertAdjacentElement(&self, where_: DOMString, element: &Element) fn InsertAdjacentElement(&self, where_: DOMString, element: &Element)
-> Fallible<Option<Root<Element>>> { -> Fallible<Option<DomRoot<Element>>> {
let where_ = AdjacentPosition::try_from(&*where_)?; let where_ = AdjacentPosition::try_from(&*where_)?;
let inserted_node = self.insert_adjacent(where_, element.upcast())?; let inserted_node = self.insert_adjacent(where_, element.upcast())?;
Ok(inserted_node.map(|node| Root::downcast(node).unwrap())) Ok(inserted_node.map(|node| DomRoot::downcast(node).unwrap()))
} }
// https://dom.spec.whatwg.org/#dom-element-insertadjacenttext // https://dom.spec.whatwg.org/#dom-element-insertadjacenttext
@ -2259,7 +2258,7 @@ impl ElementMethods for Element {
} }
} }
AdjacentPosition::AfterBegin | AdjacentPosition::BeforeEnd => { AdjacentPosition::AfterBegin | AdjacentPosition::BeforeEnd => {
Root::from_ref(self.upcast::<Node>()) DomRoot::from_ref(self.upcast::<Node>())
} }
}; };
@ -2497,14 +2496,14 @@ impl VirtualMethods for Element {
} }
} }
impl<'a> ::selectors::Element for Root<Element> { impl<'a> ::selectors::Element for DomRoot<Element> {
type Impl = SelectorImpl; type Impl = SelectorImpl;
fn opaque(&self) -> ::selectors::OpaqueElement { fn opaque(&self) -> ::selectors::OpaqueElement {
::selectors::OpaqueElement::new(self.reflector().get_jsobject().get()) ::selectors::OpaqueElement::new(self.reflector().get_jsobject().get())
} }
fn parent_element(&self) -> Option<Root<Element>> { fn parent_element(&self) -> Option<DomRoot<Element>> {
self.upcast::<Node>().GetParentElement() self.upcast::<Node>().GetParentElement()
} }
@ -2517,20 +2516,20 @@ impl<'a> ::selectors::Element for Root<Element> {
} }
fn first_child_element(&self) -> Option<Root<Element>> { fn first_child_element(&self) -> Option<DomRoot<Element>> {
self.node.child_elements().next() self.node.child_elements().next()
} }
fn last_child_element(&self) -> Option<Root<Element>> { fn last_child_element(&self) -> Option<DomRoot<Element>> {
self.node.rev_children().filter_map(Root::downcast).next() self.node.rev_children().filter_map(DomRoot::downcast).next()
} }
fn prev_sibling_element(&self) -> Option<Root<Element>> { fn prev_sibling_element(&self) -> Option<DomRoot<Element>> {
self.node.preceding_siblings().filter_map(Root::downcast).next() self.node.preceding_siblings().filter_map(DomRoot::downcast).next()
} }
fn next_sibling_element(&self) -> Option<Root<Element>> { fn next_sibling_element(&self) -> Option<DomRoot<Element>> {
self.node.following_siblings().filter_map(Root::downcast).next() self.node.following_siblings().filter_map(DomRoot::downcast).next()
} }
fn attr_matches(&self, fn attr_matches(&self,
@ -2740,15 +2739,15 @@ impl Element {
} }
// https://html.spec.whatwg.org/multipage/#nearest-activatable-element // https://html.spec.whatwg.org/multipage/#nearest-activatable-element
pub fn nearest_activable_element(&self) -> Option<Root<Element>> { pub fn nearest_activable_element(&self) -> Option<DomRoot<Element>> {
match self.as_maybe_activatable() { match self.as_maybe_activatable() {
Some(el) => Some(Root::from_ref(el.as_element())), Some(el) => Some(DomRoot::from_ref(el.as_element())),
None => { None => {
let node = self.upcast::<Node>(); let node = self.upcast::<Node>();
for node in node.ancestors() { for node in node.ancestors() {
if let Some(node) = node.downcast::<Element>() { if let Some(node) = node.downcast::<Element>() {
if node.as_maybe_activatable().is_some() { if node.as_maybe_activatable().is_some() {
return Some(Root::from_ref(node)); return Some(DomRoot::from_ref(node));
} }
} }
} }
@ -3007,12 +3006,12 @@ impl<'a> AttributeMutation<'a> {
/// owner changes. /// owner changes.
#[derive(HeapSizeOf, JSTraceable)] #[derive(HeapSizeOf, JSTraceable)]
struct TagName { struct TagName {
ptr: DOMRefCell<Option<LocalName>>, ptr: DomRefCell<Option<LocalName>>,
} }
impl TagName { impl TagName {
fn new() -> TagName { fn new() -> TagName {
TagName { ptr: DOMRefCell::new(None) } TagName { ptr: DomRefCell::new(None) }
} }
/// Retrieve a copy of the current inner value. If it is `None`, it is /// Retrieve a copy of the current inner value. If it is `None`, it is

View file

@ -2,14 +2,14 @@
* License, v. 2.0. If a copy of the MPL was not distributed with this * 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/. */ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use dom::bindings::cell::DOMRefCell; use dom::bindings::cell::DomRefCell;
use dom::bindings::codegen::Bindings::ErrorEventBinding; use dom::bindings::codegen::Bindings::ErrorEventBinding;
use dom::bindings::codegen::Bindings::ErrorEventBinding::ErrorEventMethods; use dom::bindings::codegen::Bindings::ErrorEventBinding::ErrorEventMethods;
use dom::bindings::codegen::Bindings::EventBinding::EventMethods; use dom::bindings::codegen::Bindings::EventBinding::EventMethods;
use dom::bindings::error::Fallible; use dom::bindings::error::Fallible;
use dom::bindings::inheritance::Castable; use dom::bindings::inheritance::Castable;
use dom::bindings::js::Root;
use dom::bindings::reflector::reflect_dom_object; use dom::bindings::reflector::reflect_dom_object;
use dom::bindings::root::DomRoot;
use dom::bindings::str::DOMString; use dom::bindings::str::DOMString;
use dom::bindings::trace::RootedTraceableBox; use dom::bindings::trace::RootedTraceableBox;
use dom::event::{Event, EventBubbles, EventCancelable}; use dom::event::{Event, EventBubbles, EventCancelable};
@ -23,8 +23,8 @@ use std::cell::Cell;
#[dom_struct] #[dom_struct]
pub struct ErrorEvent { pub struct ErrorEvent {
event: Event, event: Event,
message: DOMRefCell<DOMString>, message: DomRefCell<DOMString>,
filename: DOMRefCell<DOMString>, filename: DomRefCell<DOMString>,
lineno: Cell<u32>, lineno: Cell<u32>,
colno: Cell<u32>, colno: Cell<u32>,
#[ignore_heap_size_of = "Defined in rust-mozjs"] #[ignore_heap_size_of = "Defined in rust-mozjs"]
@ -35,15 +35,15 @@ impl ErrorEvent {
fn new_inherited() -> ErrorEvent { fn new_inherited() -> ErrorEvent {
ErrorEvent { ErrorEvent {
event: Event::new_inherited(), event: Event::new_inherited(),
message: DOMRefCell::new(DOMString::new()), message: DomRefCell::new(DOMString::new()),
filename: DOMRefCell::new(DOMString::new()), filename: DomRefCell::new(DOMString::new()),
lineno: Cell::new(0), lineno: Cell::new(0),
colno: Cell::new(0), colno: Cell::new(0),
error: Heap::default() error: Heap::default()
} }
} }
pub fn new_uninitialized(global: &GlobalScope) -> Root<ErrorEvent> { pub fn new_uninitialized(global: &GlobalScope) -> DomRoot<ErrorEvent> {
reflect_dom_object(box ErrorEvent::new_inherited(), reflect_dom_object(box ErrorEvent::new_inherited(),
global, global,
ErrorEventBinding::Wrap) ErrorEventBinding::Wrap)
@ -57,7 +57,7 @@ impl ErrorEvent {
filename: DOMString, filename: DOMString,
lineno: u32, lineno: u32,
colno: u32, colno: u32,
error: HandleValue) -> Root<ErrorEvent> { error: HandleValue) -> DomRoot<ErrorEvent> {
let ev = ErrorEvent::new_uninitialized(global); let ev = ErrorEvent::new_uninitialized(global);
{ {
let event = ev.upcast::<Event>(); let event = ev.upcast::<Event>();
@ -75,7 +75,7 @@ impl ErrorEvent {
pub fn Constructor(global: &GlobalScope, pub fn Constructor(global: &GlobalScope,
type_: DOMString, type_: DOMString,
init: RootedTraceableBox<ErrorEventBinding::ErrorEventInit>) init: RootedTraceableBox<ErrorEventBinding::ErrorEventInit>)
-> Fallible<Root<ErrorEvent>>{ -> Fallible<DomRoot<ErrorEvent>>{
let msg = match init.message.as_ref() { let msg = match init.message.as_ref() {
Some(message) => message.clone(), Some(message) => message.clone(),
None => DOMString::new(), None => DOMString::new(),

View file

@ -4,14 +4,14 @@
use devtools_traits::{TimelineMarker, TimelineMarkerType}; use devtools_traits::{TimelineMarker, TimelineMarkerType};
use dom::bindings::callback::ExceptionHandling; use dom::bindings::callback::ExceptionHandling;
use dom::bindings::cell::DOMRefCell; use dom::bindings::cell::DomRefCell;
use dom::bindings::codegen::Bindings::EventBinding; use dom::bindings::codegen::Bindings::EventBinding;
use dom::bindings::codegen::Bindings::EventBinding::{EventConstants, EventMethods}; use dom::bindings::codegen::Bindings::EventBinding::{EventConstants, EventMethods};
use dom::bindings::error::Fallible; use dom::bindings::error::Fallible;
use dom::bindings::inheritance::Castable; use dom::bindings::inheritance::Castable;
use dom::bindings::js::{JS, MutNullableJS, Root, RootedReference};
use dom::bindings::refcounted::Trusted; use dom::bindings::refcounted::Trusted;
use dom::bindings::reflector::{DomObject, Reflector, reflect_dom_object}; use dom::bindings::reflector::{DomObject, Reflector, reflect_dom_object};
use dom::bindings::root::{Dom, DomRoot, MutNullableDom, RootedReference};
use dom::bindings::str::DOMString; use dom::bindings::str::DOMString;
use dom::document::Document; use dom::document::Document;
use dom::eventtarget::{CompiledEventListener, EventTarget, ListenerPhase}; use dom::eventtarget::{CompiledEventListener, EventTarget, ListenerPhase};
@ -29,9 +29,9 @@ use time;
#[dom_struct] #[dom_struct]
pub struct Event { pub struct Event {
reflector_: Reflector, reflector_: Reflector,
current_target: MutNullableJS<EventTarget>, current_target: MutNullableDom<EventTarget>,
target: MutNullableJS<EventTarget>, target: MutNullableDom<EventTarget>,
type_: DOMRefCell<Atom>, type_: DomRefCell<Atom>,
phase: Cell<EventPhase>, phase: Cell<EventPhase>,
canceled: Cell<EventDefault>, canceled: Cell<EventDefault>,
stop_propagation: Cell<bool>, stop_propagation: Cell<bool>,
@ -50,7 +50,7 @@ impl Event {
reflector_: Reflector::new(), reflector_: Reflector::new(),
current_target: Default::default(), current_target: Default::default(),
target: Default::default(), target: Default::default(),
type_: DOMRefCell::new(atom!("")), type_: DomRefCell::new(atom!("")),
phase: Cell::new(EventPhase::None), phase: Cell::new(EventPhase::None),
canceled: Cell::new(EventDefault::Allowed), canceled: Cell::new(EventDefault::Allowed),
stop_propagation: Cell::new(false), stop_propagation: Cell::new(false),
@ -64,7 +64,7 @@ impl Event {
} }
} }
pub fn new_uninitialized(global: &GlobalScope) -> Root<Event> { pub fn new_uninitialized(global: &GlobalScope) -> DomRoot<Event> {
reflect_dom_object(box Event::new_inherited(), reflect_dom_object(box Event::new_inherited(),
global, global,
EventBinding::Wrap) EventBinding::Wrap)
@ -73,7 +73,7 @@ impl Event {
pub fn new(global: &GlobalScope, pub fn new(global: &GlobalScope,
type_: Atom, type_: Atom,
bubbles: EventBubbles, bubbles: EventBubbles,
cancelable: EventCancelable) -> Root<Event> { cancelable: EventCancelable) -> DomRoot<Event> {
let event = Event::new_uninitialized(global); let event = Event::new_uninitialized(global);
event.init_event(type_, bool::from(bubbles), bool::from(cancelable)); event.init_event(type_, bool::from(bubbles), bool::from(cancelable));
event event
@ -81,7 +81,7 @@ impl Event {
pub fn Constructor(global: &GlobalScope, pub fn Constructor(global: &GlobalScope,
type_: DOMString, type_: DOMString,
init: &EventBinding::EventInit) -> Fallible<Root<Event>> { init: &EventBinding::EventInit) -> Fallible<DomRoot<Event>> {
let bubbles = EventBubbles::from(init.bubbles); let bubbles = EventBubbles::from(init.bubbles);
let cancelable = EventCancelable::from(init.cancelable); let cancelable = EventCancelable::from(init.cancelable);
Ok(Event::new(global, Atom::from(type_), bubbles, cancelable)) Ok(Event::new(global, Atom::from(type_), bubbles, cancelable))
@ -137,13 +137,13 @@ impl Event {
// Step 4. // Step 4.
if let Some(target_node) = target.downcast::<Node>() { if let Some(target_node) = target.downcast::<Node>() {
for ancestor in target_node.ancestors() { for ancestor in target_node.ancestors() {
event_path.push(JS::from_ref(ancestor.upcast::<EventTarget>())); event_path.push(Dom::from_ref(ancestor.upcast::<EventTarget>()));
} }
let top_most_ancestor_or_target = let top_most_ancestor_or_target =
Root::from_ref(event_path.r().last().cloned().unwrap_or(target)); DomRoot::from_ref(event_path.r().last().cloned().unwrap_or(target));
if let Some(document) = Root::downcast::<Document>(top_most_ancestor_or_target) { if let Some(document) = DomRoot::downcast::<Document>(top_most_ancestor_or_target) {
if self.type_() != atom!("load") && document.browsing_context().is_some() { if self.type_() != atom!("load") && document.browsing_context().is_some() {
event_path.push(JS::from_ref(document.window().upcast())); event_path.push(Dom::from_ref(document.window().upcast()));
} }
} }
} }
@ -233,12 +233,12 @@ impl EventMethods for Event {
} }
// https://dom.spec.whatwg.org/#dom-event-target // https://dom.spec.whatwg.org/#dom-event-target
fn GetTarget(&self) -> Option<Root<EventTarget>> { fn GetTarget(&self) -> Option<DomRoot<EventTarget>> {
self.target.get() self.target.get()
} }
// https://dom.spec.whatwg.org/#dom-event-currenttarget // https://dom.spec.whatwg.org/#dom-event-currenttarget
fn GetCurrentTarget(&self) -> Option<Root<EventTarget>> { fn GetCurrentTarget(&self) -> Option<DomRoot<EventTarget>> {
self.current_target.get() self.current_target.get()
} }
@ -416,7 +416,7 @@ fn dispatch_to_listeners(event: &Event, target: &EventTarget, event_path: &[&Eve
assert!(!event.stop_propagation.get()); assert!(!event.stop_propagation.get());
assert!(!event.stop_immediate.get()); assert!(!event.stop_immediate.get());
let window = match Root::downcast::<Window>(target.global()) { let window = match DomRoot::downcast::<Window>(target.global()) {
Some(window) => { Some(window) => {
if window.need_emit_timeline_marker(TimelineMarkerType::DOMEvent) { if window.need_emit_timeline_marker(TimelineMarkerType::DOMEvent) {
Some(window) Some(window)

View file

@ -2,13 +2,13 @@
* License, v. 2.0. If a copy of the MPL was not distributed with this * 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/. */ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use dom::bindings::cell::DOMRefCell; use dom::bindings::cell::DomRefCell;
use dom::bindings::codegen::Bindings::EventSourceBinding::{EventSourceInit, EventSourceMethods, Wrap}; use dom::bindings::codegen::Bindings::EventSourceBinding::{EventSourceInit, EventSourceMethods, Wrap};
use dom::bindings::error::{Error, Fallible}; use dom::bindings::error::{Error, Fallible};
use dom::bindings::inheritance::Castable; use dom::bindings::inheritance::Castable;
use dom::bindings::js::Root;
use dom::bindings::refcounted::Trusted; use dom::bindings::refcounted::Trusted;
use dom::bindings::reflector::{DomObject, reflect_dom_object}; use dom::bindings::reflector::{DomObject, reflect_dom_object};
use dom::bindings::root::DomRoot;
use dom::bindings::str::DOMString; use dom::bindings::str::DOMString;
use dom::event::Event; use dom::event::Event;
use dom::eventtarget::EventTarget; use dom::eventtarget::EventTarget;
@ -56,8 +56,8 @@ enum ReadyState {
pub struct EventSource { pub struct EventSource {
eventtarget: EventTarget, eventtarget: EventTarget,
url: ServoUrl, url: ServoUrl,
request: DOMRefCell<Option<RequestInit>>, request: DomRefCell<Option<RequestInit>>,
last_event_id: DOMRefCell<DOMString>, last_event_id: DomRefCell<DOMString>,
reconnection_time: Cell<u64>, reconnection_time: Cell<u64>,
generation_id: Cell<GenerationId>, generation_id: Cell<GenerationId>,
@ -402,8 +402,8 @@ impl EventSource {
EventSource { EventSource {
eventtarget: EventTarget::new_inherited(), eventtarget: EventTarget::new_inherited(),
url: url, url: url,
request: DOMRefCell::new(None), request: DomRefCell::new(None),
last_event_id: DOMRefCell::new(DOMString::from("")), last_event_id: DomRefCell::new(DOMString::from("")),
reconnection_time: Cell::new(DEFAULT_RECONNECTION_TIME), reconnection_time: Cell::new(DEFAULT_RECONNECTION_TIME),
generation_id: Cell::new(GenerationId(0)), generation_id: Cell::new(GenerationId(0)),
@ -412,7 +412,7 @@ impl EventSource {
} }
} }
fn new(global: &GlobalScope, url: ServoUrl, with_credentials: bool) -> Root<EventSource> { fn new(global: &GlobalScope, url: ServoUrl, with_credentials: bool) -> DomRoot<EventSource> {
reflect_dom_object(box EventSource::new_inherited(url, with_credentials), reflect_dom_object(box EventSource::new_inherited(url, with_credentials),
global, global,
Wrap) Wrap)
@ -424,7 +424,7 @@ impl EventSource {
pub fn Constructor(global: &GlobalScope, pub fn Constructor(global: &GlobalScope,
url: DOMString, url: DOMString,
event_source_init: &EventSourceInit) -> Fallible<Root<EventSource>> { event_source_init: &EventSourceInit) -> Fallible<DomRoot<EventSource>> {
// TODO: Step 2 relevant settings object // TODO: Step 2 relevant settings object
// Step 3 // Step 3
let base_url = global.api_base_url(); let base_url = global.api_base_url();

View file

@ -4,7 +4,7 @@
use dom::beforeunloadevent::BeforeUnloadEvent; use dom::beforeunloadevent::BeforeUnloadEvent;
use dom::bindings::callback::{CallbackContainer, ExceptionHandling, CallbackFunction}; use dom::bindings::callback::{CallbackContainer, ExceptionHandling, CallbackFunction};
use dom::bindings::cell::DOMRefCell; use dom::bindings::cell::DomRefCell;
use dom::bindings::codegen::Bindings::BeforeUnloadEventBinding::BeforeUnloadEventMethods; use dom::bindings::codegen::Bindings::BeforeUnloadEventBinding::BeforeUnloadEventMethods;
use dom::bindings::codegen::Bindings::ErrorEventBinding::ErrorEventMethods; use dom::bindings::codegen::Bindings::ErrorEventBinding::ErrorEventMethods;
use dom::bindings::codegen::Bindings::EventBinding::EventMethods; use dom::bindings::codegen::Bindings::EventBinding::EventMethods;
@ -17,8 +17,8 @@ use dom::bindings::codegen::Bindings::WindowBinding::WindowMethods;
use dom::bindings::codegen::UnionTypes::EventOrString; use dom::bindings::codegen::UnionTypes::EventOrString;
use dom::bindings::error::{Error, Fallible, report_pending_exception}; use dom::bindings::error::{Error, Fallible, report_pending_exception};
use dom::bindings::inheritance::Castable; use dom::bindings::inheritance::Castable;
use dom::bindings::js::Root;
use dom::bindings::reflector::{DomObject, Reflector}; use dom::bindings::reflector::{DomObject, Reflector};
use dom::bindings::root::DomRoot;
use dom::bindings::str::DOMString; use dom::bindings::str::DOMString;
use dom::element::Element; use dom::element::Element;
use dom::errorevent::ErrorEvent; use dom::errorevent::ErrorEvent;
@ -174,7 +174,7 @@ impl CompiledEventListener {
return; return;
} }
let _ = handler.Call_(object, EventOrString::Event(Root::from_ref(event)), let _ = handler.Call_(object, EventOrString::Event(DomRoot::from_ref(event)),
None, None, None, None, exception_handle); None, None, None, None, exception_handle);
} }
@ -276,14 +276,14 @@ impl EventListeners {
#[dom_struct] #[dom_struct]
pub struct EventTarget { pub struct EventTarget {
reflector_: Reflector, reflector_: Reflector,
handlers: DOMRefCell<HashMap<Atom, EventListeners, BuildHasherDefault<FnvHasher>>>, handlers: DomRefCell<HashMap<Atom, EventListeners, BuildHasherDefault<FnvHasher>>>,
} }
impl EventTarget { impl EventTarget {
pub fn new_inherited() -> EventTarget { pub fn new_inherited() -> EventTarget {
EventTarget { EventTarget {
reflector_: Reflector::new(), reflector_: Reflector::new(),
handlers: DOMRefCell::new(Default::default()), handlers: DomRefCell::new(Default::default()),
} }
} }
@ -506,28 +506,28 @@ impl EventTarget {
} }
// https://dom.spec.whatwg.org/#concept-event-fire // https://dom.spec.whatwg.org/#concept-event-fire
pub fn fire_event(&self, name: Atom) -> Root<Event> { pub fn fire_event(&self, name: Atom) -> DomRoot<Event> {
self.fire_event_with_params(name, self.fire_event_with_params(name,
EventBubbles::DoesNotBubble, EventBubbles::DoesNotBubble,
EventCancelable::NotCancelable) EventCancelable::NotCancelable)
} }
// https://dom.spec.whatwg.org/#concept-event-fire // https://dom.spec.whatwg.org/#concept-event-fire
pub fn fire_bubbling_event(&self, name: Atom) -> Root<Event> { pub fn fire_bubbling_event(&self, name: Atom) -> DomRoot<Event> {
self.fire_event_with_params(name, self.fire_event_with_params(name,
EventBubbles::Bubbles, EventBubbles::Bubbles,
EventCancelable::NotCancelable) EventCancelable::NotCancelable)
} }
// https://dom.spec.whatwg.org/#concept-event-fire // https://dom.spec.whatwg.org/#concept-event-fire
pub fn fire_cancelable_event(&self, name: Atom) -> Root<Event> { pub fn fire_cancelable_event(&self, name: Atom) -> DomRoot<Event> {
self.fire_event_with_params(name, self.fire_event_with_params(name,
EventBubbles::DoesNotBubble, EventBubbles::DoesNotBubble,
EventCancelable::Cancelable) EventCancelable::Cancelable)
} }
// https://dom.spec.whatwg.org/#concept-event-fire // https://dom.spec.whatwg.org/#concept-event-fire
pub fn fire_bubbling_cancelable_event(&self, name: Atom) -> Root<Event> { pub fn fire_bubbling_cancelable_event(&self, name: Atom) -> DomRoot<Event> {
self.fire_event_with_params(name, self.fire_event_with_params(name,
EventBubbles::Bubbles, EventBubbles::Bubbles,
EventCancelable::Cancelable) EventCancelable::Cancelable)
@ -538,7 +538,7 @@ impl EventTarget {
name: Atom, name: Atom,
bubbles: EventBubbles, bubbles: EventBubbles,
cancelable: EventCancelable) cancelable: EventCancelable)
-> Root<Event> { -> DomRoot<Event> {
let event = Event::new(&self.global(), name, bubbles, cancelable); let event = Event::new(&self.global(), name, bubbles, cancelable);
event.fire(self); event.fire(self);
event event

View file

@ -6,8 +6,8 @@ use dom::bindings::codegen::Bindings::EventBinding::{self, EventMethods};
use dom::bindings::codegen::Bindings::ExtendableEventBinding; use dom::bindings::codegen::Bindings::ExtendableEventBinding;
use dom::bindings::error::{Error, ErrorResult, Fallible}; use dom::bindings::error::{Error, ErrorResult, Fallible};
use dom::bindings::inheritance::Castable; use dom::bindings::inheritance::Castable;
use dom::bindings::js::Root;
use dom::bindings::reflector::reflect_dom_object; use dom::bindings::reflector::reflect_dom_object;
use dom::bindings::root::DomRoot;
use dom::bindings::str::DOMString; use dom::bindings::str::DOMString;
use dom::event::Event; use dom::event::Event;
use dom::serviceworkerglobalscope::ServiceWorkerGlobalScope; use dom::serviceworkerglobalscope::ServiceWorkerGlobalScope;
@ -33,7 +33,7 @@ impl ExtendableEvent {
type_: Atom, type_: Atom,
bubbles: bool, bubbles: bool,
cancelable: bool) cancelable: bool)
-> Root<ExtendableEvent> { -> DomRoot<ExtendableEvent> {
let ev = reflect_dom_object(box ExtendableEvent::new_inherited(), worker, ExtendableEventBinding::Wrap); let ev = reflect_dom_object(box ExtendableEvent::new_inherited(), worker, ExtendableEventBinding::Wrap);
{ {
let event = ev.upcast::<Event>(); let event = ev.upcast::<Event>();
@ -44,7 +44,7 @@ impl ExtendableEvent {
pub fn Constructor(worker: &ServiceWorkerGlobalScope, pub fn Constructor(worker: &ServiceWorkerGlobalScope,
type_: DOMString, type_: DOMString,
init: &ExtendableEventBinding::ExtendableEventInit) -> Fallible<Root<ExtendableEvent>> { init: &ExtendableEventBinding::ExtendableEventInit) -> Fallible<DomRoot<ExtendableEvent>> {
Ok(ExtendableEvent::new(worker, Ok(ExtendableEvent::new(worker,
Atom::from(type_), Atom::from(type_),
init.parent.bubbles, init.parent.bubbles,

View file

@ -6,8 +6,8 @@ use dom::bindings::codegen::Bindings::ExtendableMessageEventBinding;
use dom::bindings::codegen::Bindings::ExtendableMessageEventBinding::ExtendableMessageEventMethods; use dom::bindings::codegen::Bindings::ExtendableMessageEventBinding::ExtendableMessageEventMethods;
use dom::bindings::error::Fallible; use dom::bindings::error::Fallible;
use dom::bindings::inheritance::Castable; use dom::bindings::inheritance::Castable;
use dom::bindings::js::Root;
use dom::bindings::reflector::reflect_dom_object; use dom::bindings::reflector::reflect_dom_object;
use dom::bindings::root::DomRoot;
use dom::bindings::str::DOMString; use dom::bindings::str::DOMString;
use dom::bindings::trace::RootedTraceableBox; use dom::bindings::trace::RootedTraceableBox;
use dom::event::Event; use dom::event::Event;
@ -32,7 +32,7 @@ impl ExtendableMessageEvent {
pub fn new(global: &GlobalScope, type_: Atom, pub fn new(global: &GlobalScope, type_: Atom,
bubbles: bool, cancelable: bool, bubbles: bool, cancelable: bool,
data: HandleValue, origin: DOMString, lastEventId: DOMString) data: HandleValue, origin: DOMString, lastEventId: DOMString)
-> Root<ExtendableMessageEvent> { -> DomRoot<ExtendableMessageEvent> {
let ev = box ExtendableMessageEvent { let ev = box ExtendableMessageEvent {
event: ExtendableEvent::new_inherited(), event: ExtendableEvent::new_inherited(),
data: Heap::default(), data: Heap::default(),
@ -52,7 +52,7 @@ impl ExtendableMessageEvent {
pub fn Constructor(worker: &ServiceWorkerGlobalScope, pub fn Constructor(worker: &ServiceWorkerGlobalScope,
type_: DOMString, type_: DOMString,
init: RootedTraceableBox<ExtendableMessageEventBinding::ExtendableMessageEventInit>) init: RootedTraceableBox<ExtendableMessageEventBinding::ExtendableMessageEventInit>)
-> Fallible<Root<ExtendableMessageEvent>> { -> Fallible<DomRoot<ExtendableMessageEvent>> {
let global = worker.upcast::<GlobalScope>(); let global = worker.upcast::<GlobalScope>();
let ev = ExtendableMessageEvent::new(global, let ev = ExtendableMessageEvent::new(global,
Atom::from(type_), Atom::from(type_),

View file

@ -7,8 +7,8 @@ use dom::bindings::codegen::Bindings::FileBinding::FileMethods;
use dom::bindings::codegen::UnionTypes::BlobOrString; use dom::bindings::codegen::UnionTypes::BlobOrString;
use dom::bindings::error::{Error, Fallible}; use dom::bindings::error::{Error, Fallible};
use dom::bindings::inheritance::Castable; use dom::bindings::inheritance::Castable;
use dom::bindings::js::Root;
use dom::bindings::reflector::reflect_dom_object; use dom::bindings::reflector::reflect_dom_object;
use dom::bindings::root::DomRoot;
use dom::bindings::str::DOMString; use dom::bindings::str::DOMString;
use dom::blob::{Blob, BlobImpl, blob_parts_to_bytes}; use dom::blob::{Blob, BlobImpl, blob_parts_to_bytes};
use dom::globalscope::GlobalScope; use dom::globalscope::GlobalScope;
@ -44,14 +44,14 @@ impl File {
#[allow(unrooted_must_root)] #[allow(unrooted_must_root)]
pub fn new(global: &GlobalScope, blob_impl: BlobImpl, pub fn new(global: &GlobalScope, blob_impl: BlobImpl,
name: DOMString, modified: Option<i64>, typeString: &str) -> Root<File> { name: DOMString, modified: Option<i64>, typeString: &str) -> DomRoot<File> {
reflect_dom_object(box File::new_inherited(blob_impl, name, modified, typeString), reflect_dom_object(box File::new_inherited(blob_impl, name, modified, typeString),
global, global,
FileBinding::Wrap) FileBinding::Wrap)
} }
// Construct from selected file message from file manager thread // Construct from selected file message from file manager thread
pub fn new_from_selected(window: &Window, selected: SelectedFile) -> Root<File> { pub fn new_from_selected(window: &Window, selected: SelectedFile) -> DomRoot<File> {
let name = DOMString::from(selected.filename.to_str().expect("File name encoding error")); let name = DOMString::from(selected.filename.to_str().expect("File name encoding error"));
File::new(window.upcast(), BlobImpl::new_from_file(selected.id, selected.filename, selected.size), File::new(window.upcast(), BlobImpl::new_from_file(selected.id, selected.filename, selected.size),
@ -63,7 +63,7 @@ impl File {
fileBits: Vec<BlobOrString>, fileBits: Vec<BlobOrString>,
filename: DOMString, filename: DOMString,
filePropertyBag: &FileBinding::FilePropertyBag) filePropertyBag: &FileBinding::FilePropertyBag)
-> Fallible<Root<File>> { -> Fallible<DomRoot<File>> {
let bytes: Vec<u8> = match blob_parts_to_bytes(fileBits) { let bytes: Vec<u8> = match blob_parts_to_bytes(fileBits) {
Ok(bytes) => bytes, Ok(bytes) => bytes,
Err(_) => return Err(Error::InvalidCharacter), Err(_) => return Err(Error::InvalidCharacter),

View file

@ -4,8 +4,8 @@
use dom::bindings::codegen::Bindings::FileListBinding; use dom::bindings::codegen::Bindings::FileListBinding;
use dom::bindings::codegen::Bindings::FileListBinding::FileListMethods; use dom::bindings::codegen::Bindings::FileListBinding::FileListMethods;
use dom::bindings::js::{JS, Root};
use dom::bindings::reflector::{Reflector, reflect_dom_object}; use dom::bindings::reflector::{Reflector, reflect_dom_object};
use dom::bindings::root::{Dom, DomRoot};
use dom::file::File; use dom::file::File;
use dom::window::Window; use dom::window::Window;
use dom_struct::dom_struct; use dom_struct::dom_struct;
@ -15,12 +15,12 @@ use std::slice::Iter;
#[dom_struct] #[dom_struct]
pub struct FileList { pub struct FileList {
reflector_: Reflector, reflector_: Reflector,
list: Vec<JS<File>> list: Vec<Dom<File>>
} }
impl FileList { impl FileList {
#[allow(unrooted_must_root)] #[allow(unrooted_must_root)]
fn new_inherited(files: Vec<JS<File>>) -> FileList { fn new_inherited(files: Vec<Dom<File>>) -> FileList {
FileList { FileList {
reflector_: Reflector::new(), reflector_: Reflector::new(),
list: files list: files
@ -28,13 +28,13 @@ impl FileList {
} }
#[allow(unrooted_must_root)] #[allow(unrooted_must_root)]
pub fn new(window: &Window, files: Vec<Root<File>>) -> Root<FileList> { pub fn new(window: &Window, files: Vec<DomRoot<File>>) -> DomRoot<FileList> {
reflect_dom_object(box FileList::new_inherited(files.iter().map(|r| JS::from_ref(&**r)).collect()), reflect_dom_object(box FileList::new_inherited(files.iter().map(|r| Dom::from_ref(&**r)).collect()),
window, window,
FileListBinding::Wrap) FileListBinding::Wrap)
} }
pub fn iter_files(&self) -> Iter<JS<File>> { pub fn iter_files(&self) -> Iter<Dom<File>> {
self.list.iter() self.list.iter()
} }
} }
@ -46,16 +46,16 @@ impl FileListMethods for FileList {
} }
// https://w3c.github.io/FileAPI/#dfn-item // https://w3c.github.io/FileAPI/#dfn-item
fn Item(&self, index: u32) -> Option<Root<File>> { fn Item(&self, index: u32) -> Option<DomRoot<File>> {
if (index as usize) < self.list.len() { if (index as usize) < self.list.len() {
Some(Root::from_ref(&*(self.list[index as usize]))) Some(DomRoot::from_ref(&*(self.list[index as usize])))
} else { } else {
None None
} }
} }
// check-tidy: no specs after this line // check-tidy: no specs after this line
fn IndexedGetter(&self, index: u32) -> Option<Root<File>> { fn IndexedGetter(&self, index: u32) -> Option<DomRoot<File>> {
self.Item(index) self.Item(index)
} }
} }

View file

@ -3,15 +3,15 @@
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use base64; use base64;
use dom::bindings::cell::DOMRefCell; use dom::bindings::cell::DomRefCell;
use dom::bindings::codegen::Bindings::BlobBinding::BlobMethods; use dom::bindings::codegen::Bindings::BlobBinding::BlobMethods;
use dom::bindings::codegen::Bindings::FileReaderBinding::{self, FileReaderConstants, FileReaderMethods}; use dom::bindings::codegen::Bindings::FileReaderBinding::{self, FileReaderConstants, FileReaderMethods};
use dom::bindings::codegen::UnionTypes::StringOrObject; use dom::bindings::codegen::UnionTypes::StringOrObject;
use dom::bindings::error::{Error, ErrorResult, Fallible}; use dom::bindings::error::{Error, ErrorResult, Fallible};
use dom::bindings::inheritance::Castable; use dom::bindings::inheritance::Castable;
use dom::bindings::js::{MutNullableJS, Root};
use dom::bindings::refcounted::Trusted; use dom::bindings::refcounted::Trusted;
use dom::bindings::reflector::{DomObject, reflect_dom_object}; use dom::bindings::reflector::{DomObject, reflect_dom_object};
use dom::bindings::root::{DomRoot, MutNullableDom};
use dom::bindings::str::DOMString; use dom::bindings::str::DOMString;
use dom::bindings::trace::RootedTraceableBox; use dom::bindings::trace::RootedTraceableBox;
use dom::blob::Blob; use dom::blob::Blob;
@ -87,8 +87,8 @@ pub enum FileReaderResult {
pub struct FileReader { pub struct FileReader {
eventtarget: EventTarget, eventtarget: EventTarget,
ready_state: Cell<FileReaderReadyState>, ready_state: Cell<FileReaderReadyState>,
error: MutNullableJS<DOMException>, error: MutNullableDom<DOMException>,
result: DOMRefCell<Option<FileReaderResult>>, result: DomRefCell<Option<FileReaderResult>>,
generation_id: Cell<GenerationId>, generation_id: Cell<GenerationId>,
} }
@ -97,18 +97,18 @@ impl FileReader {
FileReader { FileReader {
eventtarget: EventTarget::new_inherited(), eventtarget: EventTarget::new_inherited(),
ready_state: Cell::new(FileReaderReadyState::Empty), ready_state: Cell::new(FileReaderReadyState::Empty),
error: MutNullableJS::new(None), error: MutNullableDom::new(None),
result: DOMRefCell::new(None), result: DomRefCell::new(None),
generation_id: Cell::new(GenerationId(0)), generation_id: Cell::new(GenerationId(0)),
} }
} }
pub fn new(global: &GlobalScope) -> Root<FileReader> { pub fn new(global: &GlobalScope) -> DomRoot<FileReader> {
reflect_dom_object(box FileReader::new_inherited(), reflect_dom_object(box FileReader::new_inherited(),
global, FileReaderBinding::Wrap) global, FileReaderBinding::Wrap)
} }
pub fn Constructor(global: &GlobalScope) -> Fallible<Root<FileReader>> { pub fn Constructor(global: &GlobalScope) -> Fallible<DomRoot<FileReader>> {
Ok(FileReader::new(global)) Ok(FileReader::new(global))
} }
@ -216,7 +216,7 @@ impl FileReader {
} }
// https://w3c.github.io/FileAPI/#dfn-readAsText // https://w3c.github.io/FileAPI/#dfn-readAsText
fn perform_readastext(result: &DOMRefCell<Option<FileReaderResult>>, data: ReadMetaData, blob_bytes: &[u8]) { fn perform_readastext(result: &DomRefCell<Option<FileReaderResult>>, data: ReadMetaData, blob_bytes: &[u8]) {
let blob_label = &data.label; let blob_label = &data.label;
let blob_type = &data.blobtype; let blob_type = &data.blobtype;
@ -246,7 +246,7 @@ impl FileReader {
} }
//https://w3c.github.io/FileAPI/#dfn-readAsDataURL //https://w3c.github.io/FileAPI/#dfn-readAsDataURL
fn perform_readasdataurl(result: &DOMRefCell<Option<FileReaderResult>>, data: ReadMetaData, bytes: &[u8]) { fn perform_readasdataurl(result: &DomRefCell<Option<FileReaderResult>>, data: ReadMetaData, bytes: &[u8]) {
let base64 = base64::encode(bytes); let base64 = base64::encode(bytes);
let output = if data.blobtype.is_empty() { let output = if data.blobtype.is_empty() {
@ -260,7 +260,7 @@ impl FileReader {
// https://w3c.github.io/FileAPI/#dfn-readAsArrayBuffer // https://w3c.github.io/FileAPI/#dfn-readAsArrayBuffer
#[allow(unsafe_code)] #[allow(unsafe_code)]
fn perform_readasarraybuffer(result: &DOMRefCell<Option<FileReaderResult>>, fn perform_readasarraybuffer(result: &DomRefCell<Option<FileReaderResult>>,
cx: *mut JSContext, _: ReadMetaData, bytes: &[u8]) { cx: *mut JSContext, _: ReadMetaData, bytes: &[u8]) {
unsafe { unsafe {
rooted!(in(cx) let mut array_buffer = ptr::null_mut()); rooted!(in(cx) let mut array_buffer = ptr::null_mut());
@ -328,7 +328,7 @@ impl FileReaderMethods for FileReader {
} }
// https://w3c.github.io/FileAPI/#dfn-error // https://w3c.github.io/FileAPI/#dfn-error
fn GetError(&self) -> Option<Root<DOMException>> { fn GetError(&self) -> Option<DomRoot<DOMException>> {
self.error.get() self.error.get()
} }

View file

@ -4,8 +4,8 @@
use dom::bindings::codegen::Bindings::FileReaderSyncBinding; use dom::bindings::codegen::Bindings::FileReaderSyncBinding;
use dom::bindings::error::Fallible; use dom::bindings::error::Fallible;
use dom::bindings::js::Root;
use dom::bindings::reflector::reflect_dom_object; use dom::bindings::reflector::reflect_dom_object;
use dom::bindings::root::DomRoot;
use dom::eventtarget::EventTarget; use dom::eventtarget::EventTarget;
use dom::globalscope::GlobalScope; use dom::globalscope::GlobalScope;
use dom_struct::dom_struct; use dom_struct::dom_struct;
@ -22,12 +22,12 @@ impl FileReaderSync {
} }
} }
pub fn new(global: &GlobalScope) -> Root<FileReaderSync> { pub fn new(global: &GlobalScope) -> DomRoot<FileReaderSync> {
reflect_dom_object(box FileReaderSync::new_inherited(), reflect_dom_object(box FileReaderSync::new_inherited(),
global, FileReaderSyncBinding::Wrap) global, FileReaderSyncBinding::Wrap)
} }
pub fn Constructor(global: &GlobalScope) -> Fallible<Root<FileReaderSync>> { pub fn Constructor(global: &GlobalScope) -> Fallible<DomRoot<FileReaderSync>> {
Ok(FileReaderSync::new(global)) Ok(FileReaderSync::new(global))
} }
} }

View file

@ -7,8 +7,8 @@ use dom::bindings::codegen::Bindings::FocusEventBinding::FocusEventMethods;
use dom::bindings::codegen::Bindings::UIEventBinding::UIEventMethods; use dom::bindings::codegen::Bindings::UIEventBinding::UIEventMethods;
use dom::bindings::error::Fallible; use dom::bindings::error::Fallible;
use dom::bindings::inheritance::Castable; use dom::bindings::inheritance::Castable;
use dom::bindings::js::{MutNullableJS, Root, RootedReference};
use dom::bindings::reflector::reflect_dom_object; use dom::bindings::reflector::reflect_dom_object;
use dom::bindings::root::{DomRoot, MutNullableDom, RootedReference};
use dom::bindings::str::DOMString; use dom::bindings::str::DOMString;
use dom::event::{EventBubbles, EventCancelable}; use dom::event::{EventBubbles, EventCancelable};
use dom::eventtarget::EventTarget; use dom::eventtarget::EventTarget;
@ -20,7 +20,7 @@ use std::default::Default;
#[dom_struct] #[dom_struct]
pub struct FocusEvent { pub struct FocusEvent {
uievent: UIEvent, uievent: UIEvent,
related_target: MutNullableJS<EventTarget>, related_target: MutNullableDom<EventTarget>,
} }
impl FocusEvent { impl FocusEvent {
@ -31,7 +31,7 @@ impl FocusEvent {
} }
} }
pub fn new_uninitialized(window: &Window) -> Root<FocusEvent> { pub fn new_uninitialized(window: &Window) -> DomRoot<FocusEvent> {
reflect_dom_object(box FocusEvent::new_inherited(), reflect_dom_object(box FocusEvent::new_inherited(),
window, window,
FocusEventBinding::Wrap) FocusEventBinding::Wrap)
@ -43,7 +43,7 @@ impl FocusEvent {
cancelable: EventCancelable, cancelable: EventCancelable,
view: Option<&Window>, view: Option<&Window>,
detail: i32, detail: i32,
related_target: Option<&EventTarget>) -> Root<FocusEvent> { related_target: Option<&EventTarget>) -> DomRoot<FocusEvent> {
let ev = FocusEvent::new_uninitialized(window); let ev = FocusEvent::new_uninitialized(window);
ev.upcast::<UIEvent>().InitUIEvent(type_, ev.upcast::<UIEvent>().InitUIEvent(type_,
bool::from(can_bubble), bool::from(can_bubble),
@ -55,7 +55,7 @@ impl FocusEvent {
pub fn Constructor(window: &Window, pub fn Constructor(window: &Window,
type_: DOMString, type_: DOMString,
init: &FocusEventBinding::FocusEventInit) -> Fallible<Root<FocusEvent>> { init: &FocusEventBinding::FocusEventInit) -> Fallible<DomRoot<FocusEvent>> {
let bubbles = EventBubbles::from(init.parent.parent.bubbles); let bubbles = EventBubbles::from(init.parent.parent.bubbles);
let cancelable = EventCancelable::from(init.parent.parent.cancelable); let cancelable = EventCancelable::from(init.parent.parent.cancelable);
let event = FocusEvent::new(window, let event = FocusEvent::new(window,
@ -71,7 +71,7 @@ impl FocusEvent {
impl FocusEventMethods for FocusEvent { impl FocusEventMethods for FocusEvent {
// https://w3c.github.io/uievents/#widl-FocusEvent-relatedTarget // https://w3c.github.io/uievents/#widl-FocusEvent-relatedTarget
fn GetRelatedTarget(&self) -> Option<Root<EventTarget>> { fn GetRelatedTarget(&self) -> Option<DomRoot<EventTarget>> {
self.related_target.get() self.related_target.get()
} }

View file

@ -6,9 +6,9 @@ use dom::bindings::codegen::Bindings::ForceTouchEventBinding;
use dom::bindings::codegen::Bindings::ForceTouchEventBinding::ForceTouchEventMethods; use dom::bindings::codegen::Bindings::ForceTouchEventBinding::ForceTouchEventMethods;
use dom::bindings::codegen::Bindings::UIEventBinding::UIEventMethods; use dom::bindings::codegen::Bindings::UIEventBinding::UIEventMethods;
use dom::bindings::inheritance::Castable; use dom::bindings::inheritance::Castable;
use dom::bindings::js::Root;
use dom::bindings::num::Finite; use dom::bindings::num::Finite;
use dom::bindings::reflector::reflect_dom_object; use dom::bindings::reflector::reflect_dom_object;
use dom::bindings::root::DomRoot;
use dom::bindings::str::DOMString; use dom::bindings::str::DOMString;
use dom::uievent::UIEvent; use dom::uievent::UIEvent;
use dom::window::Window; use dom::window::Window;
@ -30,7 +30,7 @@ impl ForceTouchEvent {
pub fn new(window: &Window, pub fn new(window: &Window,
type_: DOMString, type_: DOMString,
force: f32) -> Root<ForceTouchEvent> { force: f32) -> DomRoot<ForceTouchEvent> {
let event = box ForceTouchEvent::new_inherited(force); let event = box ForceTouchEvent::new_inherited(force);
let ev = reflect_dom_object(event, window, ForceTouchEventBinding::Wrap); let ev = reflect_dom_object(event, window, ForceTouchEventBinding::Wrap);
ev.upcast::<UIEvent>().InitUIEvent(type_, true, true, Some(window), 0); ev.upcast::<UIEvent>().InitUIEvent(type_, true, true, Some(window), 0);

View file

@ -2,15 +2,15 @@
* License, v. 2.0. If a copy of the MPL was not distributed with this * 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/. */ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use dom::bindings::cell::DOMRefCell; use dom::bindings::cell::DomRefCell;
use dom::bindings::codegen::Bindings::FormDataBinding::FormDataMethods; use dom::bindings::codegen::Bindings::FormDataBinding::FormDataMethods;
use dom::bindings::codegen::Bindings::FormDataBinding::FormDataWrap; use dom::bindings::codegen::Bindings::FormDataBinding::FormDataWrap;
use dom::bindings::codegen::UnionTypes::FileOrUSVString; use dom::bindings::codegen::UnionTypes::FileOrUSVString;
use dom::bindings::error::Fallible; use dom::bindings::error::Fallible;
use dom::bindings::inheritance::Castable; use dom::bindings::inheritance::Castable;
use dom::bindings::iterable::Iterable; use dom::bindings::iterable::Iterable;
use dom::bindings::js::Root;
use dom::bindings::reflector::{DomObject, Reflector, reflect_dom_object}; use dom::bindings::reflector::{DomObject, Reflector, reflect_dom_object};
use dom::bindings::root::DomRoot;
use dom::bindings::str::{DOMString, USVString}; use dom::bindings::str::{DOMString, USVString};
use dom::blob::{Blob, BlobImpl}; use dom::blob::{Blob, BlobImpl};
use dom::file::File; use dom::file::File;
@ -25,7 +25,7 @@ use std::iter;
#[dom_struct] #[dom_struct]
pub struct FormData { pub struct FormData {
reflector_: Reflector, reflector_: Reflector,
data: DOMRefCell<HashMap<LocalName, Vec<FormDatum>>>, data: DomRefCell<HashMap<LocalName, Vec<FormDatum>>>,
} }
impl FormData { impl FormData {
@ -43,16 +43,16 @@ impl FormData {
FormData { FormData {
reflector_: Reflector::new(), reflector_: Reflector::new(),
data: DOMRefCell::new(hashmap), data: DomRefCell::new(hashmap),
} }
} }
pub fn new(form: Option<&HTMLFormElement>, global: &GlobalScope) -> Root<FormData> { pub fn new(form: Option<&HTMLFormElement>, global: &GlobalScope) -> DomRoot<FormData> {
reflect_dom_object(box FormData::new_inherited(form), reflect_dom_object(box FormData::new_inherited(form),
global, FormDataWrap) global, FormDataWrap)
} }
pub fn Constructor(global: &GlobalScope, form: Option<&HTMLFormElement>) -> Fallible<Root<FormData>> { pub fn Constructor(global: &GlobalScope, form: Option<&HTMLFormElement>) -> Fallible<DomRoot<FormData>> {
// TODO: Construct form data set for form if it is supplied // TODO: Construct form data set for form if it is supplied
Ok(FormData::new(form, global)) Ok(FormData::new(form, global))
} }
@ -80,7 +80,7 @@ impl FormDataMethods for FormData {
let datum = FormDatum { let datum = FormDatum {
ty: DOMString::from("file"), ty: DOMString::from("file"),
name: DOMString::from(name.0.clone()), name: DOMString::from(name.0.clone()),
value: FormDatumValue::File(Root::from_ref(&*self.create_an_entry(blob, filename))), value: FormDatumValue::File(DomRoot::from_ref(&*self.create_an_entry(blob, filename))),
}; };
let mut data = self.data.borrow_mut(); let mut data = self.data.borrow_mut();
@ -102,7 +102,7 @@ impl FormDataMethods for FormData {
.get(&LocalName::from(name.0)) .get(&LocalName::from(name.0))
.map(|entry| match entry[0].value { .map(|entry| match entry[0].value {
FormDatumValue::String(ref s) => FileOrUSVString::USVString(USVString(s.to_string())), FormDatumValue::String(ref s) => FileOrUSVString::USVString(USVString(s.to_string())),
FormDatumValue::File(ref b) => FileOrUSVString::File(Root::from_ref(&*b)), FormDatumValue::File(ref b) => FileOrUSVString::File(DomRoot::from_ref(&*b)),
}) })
} }
@ -113,7 +113,7 @@ impl FormDataMethods for FormData {
.map_or(vec![], |data| .map_or(vec![], |data|
data.iter().map(|item| match item.value { data.iter().map(|item| match item.value {
FormDatumValue::String(ref s) => FileOrUSVString::USVString(USVString(s.to_string())), FormDatumValue::String(ref s) => FileOrUSVString::USVString(USVString(s.to_string())),
FormDatumValue::File(ref b) => FileOrUSVString::File(Root::from_ref(&*b)), FormDatumValue::File(ref b) => FileOrUSVString::File(DomRoot::from_ref(&*b)),
}).collect() }).collect()
) )
} }
@ -138,7 +138,7 @@ impl FormDataMethods for FormData {
self.data.borrow_mut().insert(LocalName::from(name.0.clone()), vec![FormDatum { self.data.borrow_mut().insert(LocalName::from(name.0.clone()), vec![FormDatum {
ty: DOMString::from("file"), ty: DOMString::from("file"),
name: DOMString::from(name.0), name: DOMString::from(name.0),
value: FormDatumValue::File(Root::from_ref(&*self.create_an_entry(blob, filename))), value: FormDatumValue::File(DomRoot::from_ref(&*self.create_an_entry(blob, filename))),
}]); }]);
} }
@ -148,7 +148,7 @@ impl FormDataMethods for FormData {
impl FormData { impl FormData {
// https://xhr.spec.whatwg.org/#create-an-entry // https://xhr.spec.whatwg.org/#create-an-entry
// Steps 3-4. // Steps 3-4.
fn create_an_entry(&self, blob: &Blob, opt_filename: Option<USVString>) -> Root<File> { fn create_an_entry(&self, blob: &Blob, opt_filename: Option<USVString>) -> DomRoot<File> {
let name = match opt_filename { let name = match opt_filename {
Some(filename) => DOMString::from(filename.0), Some(filename) => DOMString::from(filename.0),
None if blob.downcast::<File>().is_none() => DOMString::from("blob"), None if blob.downcast::<File>().is_none() => DOMString::from("blob"),
@ -185,7 +185,7 @@ impl Iterable for FormData {
.value; .value;
match *value { match *value {
FormDatumValue::String(ref s) => FileOrUSVString::USVString(USVString(s.to_string())), FormDatumValue::String(ref s) => FileOrUSVString::USVString(USVString(s.to_string())),
FormDatumValue::File(ref b) => FileOrUSVString::File(Root::from_ref(&*b)), FormDatumValue::File(ref b) => FileOrUSVString::File(DomRoot::from_ref(&*b)),
} }
} }

View file

@ -6,9 +6,9 @@ use core::nonzero::NonZero;
use dom::bindings::codegen::Bindings::GamepadBinding; use dom::bindings::codegen::Bindings::GamepadBinding;
use dom::bindings::codegen::Bindings::GamepadBinding::GamepadMethods; use dom::bindings::codegen::Bindings::GamepadBinding::GamepadMethods;
use dom::bindings::inheritance::Castable; use dom::bindings::inheritance::Castable;
use dom::bindings::js::{JS, Root};
use dom::bindings::num::Finite; use dom::bindings::num::Finite;
use dom::bindings::reflector::{DomObject, Reflector, reflect_dom_object}; use dom::bindings::reflector::{DomObject, Reflector, reflect_dom_object};
use dom::bindings::root::{Dom, DomRoot};
use dom::bindings::str::DOMString; use dom::bindings::str::DOMString;
use dom::event::Event; use dom::event::Event;
use dom::eventtarget::EventTarget; use dom::eventtarget::EventTarget;
@ -33,8 +33,8 @@ pub struct Gamepad {
timestamp: Cell<f64>, timestamp: Cell<f64>,
mapping_type: String, mapping_type: String,
axes: Heap<*mut JSObject>, axes: Heap<*mut JSObject>,
buttons: JS<GamepadButtonList>, buttons: Dom<GamepadButtonList>,
pose: Option<JS<VRPose>>, pose: Option<Dom<VRPose>>,
#[ignore_heap_size_of = "Defined in rust-webvr"] #[ignore_heap_size_of = "Defined in rust-webvr"]
hand: WebVRGamepadHand, hand: WebVRGamepadHand,
display_id: u32 display_id: u32
@ -60,8 +60,8 @@ impl Gamepad {
timestamp: Cell::new(timestamp), timestamp: Cell::new(timestamp),
mapping_type: mapping_type, mapping_type: mapping_type,
axes: Heap::default(), axes: Heap::default(),
buttons: JS::from_ref(buttons), buttons: Dom::from_ref(buttons),
pose: pose.map(JS::from_ref), pose: pose.map(Dom::from_ref),
hand: hand, hand: hand,
display_id: display_id display_id: display_id
} }
@ -71,7 +71,7 @@ impl Gamepad {
pub fn new_from_vr(global: &GlobalScope, pub fn new_from_vr(global: &GlobalScope,
index: i32, index: i32,
data: &WebVRGamepadData, data: &WebVRGamepadData,
state: &WebVRGamepadState) -> Root<Gamepad> { state: &WebVRGamepadState) -> DomRoot<Gamepad> {
let buttons = GamepadButtonList::new_from_vr(&global, &state.buttons); let buttons = GamepadButtonList::new_from_vr(&global, &state.buttons);
let pose = VRPose::new(&global, &state.pose); let pose = VRPose::new(&global, &state.pose);
@ -132,8 +132,8 @@ impl GamepadMethods for Gamepad {
} }
// https://w3c.github.io/gamepad/#dom-gamepad-buttons // https://w3c.github.io/gamepad/#dom-gamepad-buttons
fn Buttons(&self) -> Root<GamepadButtonList> { fn Buttons(&self) -> DomRoot<GamepadButtonList> {
Root::from_ref(&*self.buttons) DomRoot::from_ref(&*self.buttons)
} }
// https://w3c.github.io/gamepad/extensions.html#gamepadhand-enum // https://w3c.github.io/gamepad/extensions.html#gamepadhand-enum
@ -147,8 +147,8 @@ impl GamepadMethods for Gamepad {
} }
// https://w3c.github.io/gamepad/extensions.html#dom-gamepad-pose // https://w3c.github.io/gamepad/extensions.html#dom-gamepad-pose
fn GetPose(&self) -> Option<Root<VRPose>> { fn GetPose(&self) -> Option<DomRoot<VRPose>> {
self.pose.as_ref().map(|p| Root::from_ref(&**p)) self.pose.as_ref().map(|p| DomRoot::from_ref(&**p))
} }
// https://w3c.github.io/webvr/spec/1.1/#gamepad-getvrdisplays-attribute // https://w3c.github.io/webvr/spec/1.1/#gamepad-getvrdisplays-attribute

View file

@ -4,9 +4,9 @@
use dom::bindings::codegen::Bindings::GamepadButtonBinding; use dom::bindings::codegen::Bindings::GamepadButtonBinding;
use dom::bindings::codegen::Bindings::GamepadButtonBinding::GamepadButtonMethods; use dom::bindings::codegen::Bindings::GamepadButtonBinding::GamepadButtonMethods;
use dom::bindings::js::Root;
use dom::bindings::num::Finite; use dom::bindings::num::Finite;
use dom::bindings::reflector::{Reflector, reflect_dom_object}; use dom::bindings::reflector::{Reflector, reflect_dom_object};
use dom::bindings::root::DomRoot;
use dom::globalscope::GlobalScope; use dom::globalscope::GlobalScope;
use dom_struct::dom_struct; use dom_struct::dom_struct;
use std::cell::Cell; use std::cell::Cell;
@ -29,7 +29,7 @@ impl GamepadButton {
} }
} }
pub fn new(global: &GlobalScope, pressed: bool, touched: bool) -> Root<GamepadButton> { pub fn new(global: &GlobalScope, pressed: bool, touched: bool) -> DomRoot<GamepadButton> {
reflect_dom_object(box GamepadButton::new_inherited(pressed, touched), reflect_dom_object(box GamepadButton::new_inherited(pressed, touched),
global, global,
GamepadButtonBinding::Wrap) GamepadButtonBinding::Wrap)

View file

@ -4,8 +4,8 @@
use dom::bindings::codegen::Bindings::GamepadButtonListBinding; use dom::bindings::codegen::Bindings::GamepadButtonListBinding;
use dom::bindings::codegen::Bindings::GamepadButtonListBinding::GamepadButtonListMethods; use dom::bindings::codegen::Bindings::GamepadButtonListBinding::GamepadButtonListMethods;
use dom::bindings::js::{JS, Root, RootedReference};
use dom::bindings::reflector::{Reflector, reflect_dom_object}; use dom::bindings::reflector::{Reflector, reflect_dom_object};
use dom::bindings::root::{Dom, DomRoot, RootedReference};
use dom::gamepadbutton::GamepadButton; use dom::gamepadbutton::GamepadButton;
use dom::globalscope::GlobalScope; use dom::globalscope::GlobalScope;
use dom_struct::dom_struct; use dom_struct::dom_struct;
@ -15,7 +15,7 @@ use webvr_traits::WebVRGamepadButton;
#[dom_struct] #[dom_struct]
pub struct GamepadButtonList { pub struct GamepadButtonList {
reflector_: Reflector, reflector_: Reflector,
list: Vec<JS<GamepadButton>> list: Vec<Dom<GamepadButton>>
} }
impl GamepadButtonList { impl GamepadButtonList {
@ -23,11 +23,11 @@ impl GamepadButtonList {
fn new_inherited(list: &[&GamepadButton]) -> GamepadButtonList { fn new_inherited(list: &[&GamepadButton]) -> GamepadButtonList {
GamepadButtonList { GamepadButtonList {
reflector_: Reflector::new(), reflector_: Reflector::new(),
list: list.iter().map(|button| JS::from_ref(*button)).collect(), list: list.iter().map(|button| Dom::from_ref(*button)).collect(),
} }
} }
pub fn new_from_vr(global: &GlobalScope, buttons: &[WebVRGamepadButton]) -> Root<GamepadButtonList> { pub fn new_from_vr(global: &GlobalScope, buttons: &[WebVRGamepadButton]) -> DomRoot<GamepadButtonList> {
rooted_vec!(let list <- buttons.iter() rooted_vec!(let list <- buttons.iter()
.map(|btn| GamepadButton::new(&global, btn.pressed, btn.touched))); .map(|btn| GamepadButton::new(&global, btn.pressed, btn.touched)));
@ -52,12 +52,12 @@ impl GamepadButtonListMethods for GamepadButtonList {
} }
// https://w3c.github.io/gamepad/#dom-gamepad-buttons // https://w3c.github.io/gamepad/#dom-gamepad-buttons
fn Item(&self, index: u32) -> Option<Root<GamepadButton>> { fn Item(&self, index: u32) -> Option<DomRoot<GamepadButton>> {
self.list.get(index as usize).map(|button| Root::from_ref(&**button)) self.list.get(index as usize).map(|button| DomRoot::from_ref(&**button))
} }
// https://w3c.github.io/gamepad/#dom-gamepad-buttons // https://w3c.github.io/gamepad/#dom-gamepad-buttons
fn IndexedGetter(&self, index: u32) -> Option<Root<GamepadButton>> { fn IndexedGetter(&self, index: u32) -> Option<DomRoot<GamepadButton>> {
self.Item(index) self.Item(index)
} }
} }

View file

@ -7,8 +7,8 @@ use dom::bindings::codegen::Bindings::GamepadEventBinding;
use dom::bindings::codegen::Bindings::GamepadEventBinding::GamepadEventMethods; use dom::bindings::codegen::Bindings::GamepadEventBinding::GamepadEventMethods;
use dom::bindings::error::Fallible; use dom::bindings::error::Fallible;
use dom::bindings::inheritance::Castable; use dom::bindings::inheritance::Castable;
use dom::bindings::js::{JS, Root};
use dom::bindings::reflector::{DomObject, reflect_dom_object}; use dom::bindings::reflector::{DomObject, reflect_dom_object};
use dom::bindings::root::{Dom, DomRoot};
use dom::bindings::str::DOMString; use dom::bindings::str::DOMString;
use dom::event::Event; use dom::event::Event;
use dom::gamepad::Gamepad; use dom::gamepad::Gamepad;
@ -20,7 +20,7 @@ use servo_atoms::Atom;
#[dom_struct] #[dom_struct]
pub struct GamepadEvent { pub struct GamepadEvent {
event: Event, event: Event,
gamepad: JS<Gamepad>, gamepad: Dom<Gamepad>,
} }
pub enum GamepadEventType { pub enum GamepadEventType {
@ -32,7 +32,7 @@ impl GamepadEvent {
fn new_inherited(gamepad: &Gamepad) -> GamepadEvent { fn new_inherited(gamepad: &Gamepad) -> GamepadEvent {
GamepadEvent { GamepadEvent {
event: Event::new_inherited(), event: Event::new_inherited(),
gamepad: JS::from_ref(gamepad), gamepad: Dom::from_ref(gamepad),
} }
} }
@ -41,7 +41,7 @@ impl GamepadEvent {
bubbles: bool, bubbles: bool,
cancelable: bool, cancelable: bool,
gamepad: &Gamepad) gamepad: &Gamepad)
-> Root<GamepadEvent> { -> DomRoot<GamepadEvent> {
let ev = reflect_dom_object(box GamepadEvent::new_inherited(&gamepad), let ev = reflect_dom_object(box GamepadEvent::new_inherited(&gamepad),
global, global,
GamepadEventBinding::Wrap); GamepadEventBinding::Wrap);
@ -53,7 +53,7 @@ impl GamepadEvent {
} }
pub fn new_with_type(global: &GlobalScope, event_type: GamepadEventType, gamepad: &Gamepad) pub fn new_with_type(global: &GlobalScope, event_type: GamepadEventType, gamepad: &Gamepad)
-> Root<GamepadEvent> { -> DomRoot<GamepadEvent> {
let name = match event_type { let name = match event_type {
GamepadEventType::Connected => "gamepadconnected", GamepadEventType::Connected => "gamepadconnected",
GamepadEventType::Disconnected => "gamepaddisconnected" GamepadEventType::Disconnected => "gamepaddisconnected"
@ -70,7 +70,7 @@ impl GamepadEvent {
pub fn Constructor(window: &Window, pub fn Constructor(window: &Window,
type_: DOMString, type_: DOMString,
init: &GamepadEventBinding::GamepadEventInit) init: &GamepadEventBinding::GamepadEventInit)
-> Fallible<Root<GamepadEvent>> { -> Fallible<DomRoot<GamepadEvent>> {
Ok(GamepadEvent::new(&window.global(), Ok(GamepadEvent::new(&window.global(),
Atom::from(type_), Atom::from(type_),
init.parent.bubbles, init.parent.bubbles,
@ -81,8 +81,8 @@ impl GamepadEvent {
impl GamepadEventMethods for GamepadEvent { impl GamepadEventMethods for GamepadEvent {
// https://w3c.github.io/gamepad/#gamepadevent-interface // https://w3c.github.io/gamepad/#gamepadevent-interface
fn Gamepad(&self) -> Root<Gamepad> { fn Gamepad(&self) -> DomRoot<Gamepad> {
Root::from_ref(&*self.gamepad) DomRoot::from_ref(&*self.gamepad)
} }
// https://dom.spec.whatwg.org/#dom-event-istrusted // https://dom.spec.whatwg.org/#dom-event-istrusted

View file

@ -2,11 +2,11 @@
* License, v. 2.0. If a copy of the MPL was not distributed with this * 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/. */ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use dom::bindings::cell::DOMRefCell; use dom::bindings::cell::DomRefCell;
use dom::bindings::codegen::Bindings::GamepadListBinding; use dom::bindings::codegen::Bindings::GamepadListBinding;
use dom::bindings::codegen::Bindings::GamepadListBinding::GamepadListMethods; use dom::bindings::codegen::Bindings::GamepadListBinding::GamepadListMethods;
use dom::bindings::js::{JS, Root};
use dom::bindings::reflector::{Reflector, reflect_dom_object}; use dom::bindings::reflector::{Reflector, reflect_dom_object};
use dom::bindings::root::{Dom, DomRoot};
use dom::gamepad::Gamepad; use dom::gamepad::Gamepad;
use dom::globalscope::GlobalScope; use dom::globalscope::GlobalScope;
use dom_struct::dom_struct; use dom_struct::dom_struct;
@ -15,27 +15,27 @@ use dom_struct::dom_struct;
#[dom_struct] #[dom_struct]
pub struct GamepadList { pub struct GamepadList {
reflector_: Reflector, reflector_: Reflector,
list: DOMRefCell<Vec<JS<Gamepad>>> list: DomRefCell<Vec<Dom<Gamepad>>>
} }
impl GamepadList { impl GamepadList {
fn new_inherited(list: &[&Gamepad]) -> GamepadList { fn new_inherited(list: &[&Gamepad]) -> GamepadList {
GamepadList { GamepadList {
reflector_: Reflector::new(), reflector_: Reflector::new(),
list: DOMRefCell::new(list.iter().map(|g| JS::from_ref(&**g)).collect()) list: DomRefCell::new(list.iter().map(|g| Dom::from_ref(&**g)).collect())
} }
} }
pub fn new(global: &GlobalScope, list: &[&Gamepad]) -> Root<GamepadList> { pub fn new(global: &GlobalScope, list: &[&Gamepad]) -> DomRoot<GamepadList> {
reflect_dom_object(box GamepadList::new_inherited(list), reflect_dom_object(box GamepadList::new_inherited(list),
global, global,
GamepadListBinding::Wrap) GamepadListBinding::Wrap)
} }
pub fn add_if_not_exists(&self, gamepads: &[Root<Gamepad>]) { pub fn add_if_not_exists(&self, gamepads: &[DomRoot<Gamepad>]) {
for gamepad in gamepads { for gamepad in gamepads {
if !self.list.borrow().iter().any(|g| g.gamepad_id() == gamepad.gamepad_id()) { if !self.list.borrow().iter().any(|g| g.gamepad_id() == gamepad.gamepad_id()) {
self.list.borrow_mut().push(JS::from_ref(&*gamepad)); self.list.borrow_mut().push(Dom::from_ref(&*gamepad));
// Ensure that the gamepad has the correct index // Ensure that the gamepad has the correct index
gamepad.update_index(self.list.borrow().len() as i32 - 1); gamepad.update_index(self.list.borrow().len() as i32 - 1);
} }
@ -50,12 +50,12 @@ impl GamepadListMethods for GamepadList {
} }
// https://w3c.github.io/gamepad/#dom-navigator-getgamepads // https://w3c.github.io/gamepad/#dom-navigator-getgamepads
fn Item(&self, index: u32) -> Option<Root<Gamepad>> { fn Item(&self, index: u32) -> Option<DomRoot<Gamepad>> {
self.list.borrow().get(index as usize).map(|gamepad| Root::from_ref(&**gamepad)) self.list.borrow().get(index as usize).map(|gamepad| DomRoot::from_ref(&**gamepad))
} }
// https://w3c.github.io/gamepad/#dom-navigator-getgamepads // https://w3c.github.io/gamepad/#dom-navigator-getgamepads
fn IndexedGetter(&self, index: u32) -> Option<Root<Gamepad>> { fn IndexedGetter(&self, index: u32) -> Option<DomRoot<Gamepad>> {
self.Item(index) self.Item(index)
} }
} }

View file

@ -3,14 +3,14 @@
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use devtools_traits::{ScriptToDevtoolsControlMsg, WorkerId}; use devtools_traits::{ScriptToDevtoolsControlMsg, WorkerId};
use dom::bindings::cell::DOMRefCell; use dom::bindings::cell::DomRefCell;
use dom::bindings::codegen::Bindings::WindowBinding::WindowMethods; use dom::bindings::codegen::Bindings::WindowBinding::WindowMethods;
use dom::bindings::codegen::Bindings::WorkerGlobalScopeBinding::WorkerGlobalScopeMethods; use dom::bindings::codegen::Bindings::WorkerGlobalScopeBinding::WorkerGlobalScopeMethods;
use dom::bindings::conversions::root_from_object; use dom::bindings::conversions::root_from_object;
use dom::bindings::error::{ErrorInfo, report_pending_exception}; use dom::bindings::error::{ErrorInfo, report_pending_exception};
use dom::bindings::inheritance::Castable; use dom::bindings::inheritance::Castable;
use dom::bindings::js::{MutNullableJS, Root};
use dom::bindings::reflector::DomObject; use dom::bindings::reflector::DomObject;
use dom::bindings::root::{DomRoot, MutNullableDom};
use dom::bindings::settings_stack::{AutoEntryScript, entry_global, incumbent_global}; use dom::bindings::settings_stack::{AutoEntryScript, entry_global, incumbent_global};
use dom::bindings::str::DOMString; use dom::bindings::str::DOMString;
use dom::crypto::Crypto; use dom::crypto::Crypto;
@ -58,7 +58,7 @@ use timers::{OneshotTimers, TimerCallback};
#[dom_struct] #[dom_struct]
pub struct GlobalScope { pub struct GlobalScope {
eventtarget: EventTarget, eventtarget: EventTarget,
crypto: MutNullableJS<Crypto>, crypto: MutNullableDom<Crypto>,
next_worker_id: Cell<WorkerId>, next_worker_id: Cell<WorkerId>,
/// Pipeline id associated with this global. /// Pipeline id associated with this global.
@ -69,7 +69,7 @@ pub struct GlobalScope {
devtools_wants_updates: Cell<bool>, devtools_wants_updates: Cell<bool>,
/// Timers used by the Console API. /// Timers used by the Console API.
console_timers: DOMRefCell<HashMap<DOMString, u64>>, console_timers: DomRefCell<HashMap<DOMString, u64>>,
/// For providing instructions to an optional devtools server. /// For providing instructions to an optional devtools server.
#[ignore_heap_size_of = "channels are hard"] #[ignore_heap_size_of = "channels are hard"]
@ -131,7 +131,7 @@ impl GlobalScope {
next_worker_id: Cell::new(WorkerId(0)), next_worker_id: Cell::new(WorkerId(0)),
pipeline_id, pipeline_id,
devtools_wants_updates: Default::default(), devtools_wants_updates: Default::default(),
console_timers: DOMRefCell::new(Default::default()), console_timers: DomRefCell::new(Default::default()),
devtools_chan, devtools_chan,
mem_profiler_chan, mem_profiler_chan,
time_profiler_chan, time_profiler_chan,
@ -148,13 +148,13 @@ impl GlobalScope {
/// Returns the global scope of the realm that the given DOM object's reflector /// Returns the global scope of the realm that the given DOM object's reflector
/// was created in. /// was created in.
#[allow(unsafe_code)] #[allow(unsafe_code)]
pub fn from_reflector<T: DomObject>(reflector: &T) -> Root<Self> { pub fn from_reflector<T: DomObject>(reflector: &T) -> DomRoot<Self> {
unsafe { GlobalScope::from_object(*reflector.reflector().get_jsobject()) } unsafe { GlobalScope::from_object(*reflector.reflector().get_jsobject()) }
} }
/// Returns the global scope of the realm that the given JS object was created in. /// Returns the global scope of the realm that the given JS object was created in.
#[allow(unsafe_code)] #[allow(unsafe_code)]
pub unsafe fn from_object(obj: *mut JSObject) -> Root<Self> { pub unsafe fn from_object(obj: *mut JSObject) -> DomRoot<Self> {
assert!(!obj.is_null()); assert!(!obj.is_null());
let global = GetGlobalForObjectCrossCompartment(obj); let global = GetGlobalForObjectCrossCompartment(obj);
global_scope_from_global(global) global_scope_from_global(global)
@ -162,7 +162,7 @@ impl GlobalScope {
/// Returns the global scope for the given JSContext /// Returns the global scope for the given JSContext
#[allow(unsafe_code)] #[allow(unsafe_code)]
pub unsafe fn from_context(cx: *mut JSContext) -> Root<Self> { pub unsafe fn from_context(cx: *mut JSContext) -> DomRoot<Self> {
let global = CurrentGlobalOrNull(cx); let global = CurrentGlobalOrNull(cx);
global_scope_from_global(global) global_scope_from_global(global)
} }
@ -170,7 +170,7 @@ impl GlobalScope {
/// Returns the global object of the realm that the given JS object /// Returns the global object of the realm that the given JS object
/// was created in, after unwrapping any wrappers. /// was created in, after unwrapping any wrappers.
#[allow(unsafe_code)] #[allow(unsafe_code)]
pub unsafe fn from_object_maybe_wrapped(mut obj: *mut JSObject) -> Root<Self> { pub unsafe fn from_object_maybe_wrapped(mut obj: *mut JSObject) -> DomRoot<Self> {
if IsWrapper(obj) { if IsWrapper(obj) {
obj = UnwrapObject(obj, /* stopAtWindowProxy = */ 0); obj = UnwrapObject(obj, /* stopAtWindowProxy = */ 0);
assert!(!obj.is_null()); assert!(!obj.is_null());
@ -190,7 +190,7 @@ impl GlobalScope {
} }
} }
pub fn crypto(&self) -> Root<Crypto> { pub fn crypto(&self) -> DomRoot<Crypto> {
self.crypto.or_init(|| Crypto::new(self)) self.crypto.or_init(|| Crypto::new(self))
} }
@ -409,7 +409,7 @@ impl GlobalScope {
let _aes = AutoEntryScript::new(self); let _aes = AutoEntryScript::new(self);
let options = CompileOptionsWrapper::new(cx, filename.as_ptr(), line_number); let options = CompileOptionsWrapper::new(cx, filename.as_ptr(), line_number);
debug!("evaluating JS string"); debug!("evaluating Dom string");
let result = unsafe { let result = unsafe {
Evaluate2(cx, options.ptr, code.as_ptr(), Evaluate2(cx, options.ptr, code.as_ptr(),
code.len() as libc::size_t, code.len() as libc::size_t,
@ -417,7 +417,7 @@ impl GlobalScope {
}; };
if !result { if !result {
debug!("error evaluating JS string"); debug!("error evaluating Dom string");
unsafe { report_pending_exception(cx, true) }; unsafe { report_pending_exception(cx, true) };
} }
@ -496,7 +496,7 @@ impl GlobalScope {
/// Perform a microtask checkpoint. /// Perform a microtask checkpoint.
pub fn perform_a_microtask_checkpoint(&self) { pub fn perform_a_microtask_checkpoint(&self) {
self.microtask_queue.checkpoint(|_| Some(Root::from_ref(self))); self.microtask_queue.checkpoint(|_| Some(DomRoot::from_ref(self)));
} }
/// Enqueue a microtask for subsequent execution. /// Enqueue a microtask for subsequent execution.
@ -550,7 +550,7 @@ impl GlobalScope {
/// ///
/// ["current"]: https://html.spec.whatwg.org/multipage/#current /// ["current"]: https://html.spec.whatwg.org/multipage/#current
#[allow(unsafe_code)] #[allow(unsafe_code)]
pub fn current() -> Option<Root<Self>> { pub fn current() -> Option<DomRoot<Self>> {
unsafe { unsafe {
let cx = Runtime::get(); let cx = Runtime::get();
assert!(!cx.is_null()); assert!(!cx.is_null());
@ -566,18 +566,18 @@ impl GlobalScope {
/// Returns the ["entry"] global object. /// Returns the ["entry"] global object.
/// ///
/// ["entry"]: https://html.spec.whatwg.org/multipage/#entry /// ["entry"]: https://html.spec.whatwg.org/multipage/#entry
pub fn entry() -> Root<Self> { pub fn entry() -> DomRoot<Self> {
entry_global() entry_global()
} }
/// Returns the ["incumbent"] global object. /// Returns the ["incumbent"] global object.
/// ///
/// ["incumbent"]: https://html.spec.whatwg.org/multipage/#incumbent /// ["incumbent"]: https://html.spec.whatwg.org/multipage/#incumbent
pub fn incumbent() -> Option<Root<Self>> { pub fn incumbent() -> Option<DomRoot<Self>> {
incumbent_global() incumbent_global()
} }
pub fn performance(&self) -> Root<Performance> { pub fn performance(&self) -> DomRoot<Performance> {
if let Some(window) = self.downcast::<Window>() { if let Some(window) = self.downcast::<Window>() {
return window.Performance(); return window.Performance();
} }
@ -607,7 +607,7 @@ fn timestamp_in_ms(time: Timespec) -> u64 {
/// Returns the Rust global scope from a JS global object. /// Returns the Rust global scope from a JS global object.
#[allow(unsafe_code)] #[allow(unsafe_code)]
unsafe fn global_scope_from_global(global: *mut JSObject) -> Root<GlobalScope> { unsafe fn global_scope_from_global(global: *mut JSObject) -> DomRoot<GlobalScope> {
assert!(!global.is_null()); assert!(!global.is_null());
let clasp = get_object_class(global); let clasp = get_object_class(global);
assert!(((*clasp).flags & (JSCLASS_IS_DOMJSCLASS | JSCLASS_IS_GLOBAL)) != 0); assert!(((*clasp).flags & (JSCLASS_IS_DOMJSCLASS | JSCLASS_IS_GLOBAL)) != 0);

View file

@ -7,8 +7,8 @@ use dom::bindings::codegen::Bindings::HashChangeEventBinding;
use dom::bindings::codegen::Bindings::HashChangeEventBinding::HashChangeEventMethods; use dom::bindings::codegen::Bindings::HashChangeEventBinding::HashChangeEventMethods;
use dom::bindings::error::Fallible; use dom::bindings::error::Fallible;
use dom::bindings::inheritance::Castable; use dom::bindings::inheritance::Castable;
use dom::bindings::js::Root;
use dom::bindings::reflector::reflect_dom_object; use dom::bindings::reflector::reflect_dom_object;
use dom::bindings::root::DomRoot;
use dom::bindings::str::{DOMString, USVString}; use dom::bindings::str::{DOMString, USVString};
use dom::event::Event; use dom::event::Event;
use dom::window::Window; use dom::window::Window;
@ -32,7 +32,7 @@ impl HashChangeEvent {
} }
} }
pub fn new_uninitialized(window: &Window) -> Root<HashChangeEvent> { pub fn new_uninitialized(window: &Window) -> DomRoot<HashChangeEvent> {
reflect_dom_object(box HashChangeEvent::new_inherited(String::new(), String::new()), reflect_dom_object(box HashChangeEvent::new_inherited(String::new(), String::new()),
window, window,
HashChangeEventBinding::Wrap) HashChangeEventBinding::Wrap)
@ -44,7 +44,7 @@ impl HashChangeEvent {
cancelable: bool, cancelable: bool,
old_url: String, old_url: String,
new_url: String) new_url: String)
-> Root<HashChangeEvent> { -> DomRoot<HashChangeEvent> {
let ev = reflect_dom_object(box HashChangeEvent::new_inherited(old_url, new_url), let ev = reflect_dom_object(box HashChangeEvent::new_inherited(old_url, new_url),
window, window,
HashChangeEventBinding::Wrap); HashChangeEventBinding::Wrap);
@ -58,7 +58,7 @@ impl HashChangeEvent {
pub fn Constructor(window: &Window, pub fn Constructor(window: &Window,
type_: DOMString, type_: DOMString,
init: &HashChangeEventBinding::HashChangeEventInit) init: &HashChangeEventBinding::HashChangeEventInit)
-> Fallible<Root<HashChangeEvent>> { -> Fallible<DomRoot<HashChangeEvent>> {
Ok(HashChangeEvent::new(window, Ok(HashChangeEvent::new(window,
Atom::from(type_), Atom::from(type_),
init.parent.bubbles, init.parent.bubbles,

View file

@ -2,12 +2,12 @@
* License, v. 2.0. If a copy of the MPL was not distributed with this * 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/. */ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use dom::bindings::cell::DOMRefCell; use dom::bindings::cell::DomRefCell;
use dom::bindings::codegen::Bindings::HeadersBinding::{HeadersInit, HeadersMethods, HeadersWrap}; use dom::bindings::codegen::Bindings::HeadersBinding::{HeadersInit, HeadersMethods, HeadersWrap};
use dom::bindings::error::{Error, ErrorResult, Fallible}; use dom::bindings::error::{Error, ErrorResult, Fallible};
use dom::bindings::iterable::Iterable; use dom::bindings::iterable::Iterable;
use dom::bindings::js::Root;
use dom::bindings::reflector::{Reflector, reflect_dom_object}; use dom::bindings::reflector::{Reflector, reflect_dom_object};
use dom::bindings::root::DomRoot;
use dom::bindings::str::{ByteString, is_token}; use dom::bindings::str::{ByteString, is_token};
use dom::globalscope::GlobalScope; use dom::globalscope::GlobalScope;
use dom_struct::dom_struct; use dom_struct::dom_struct;
@ -22,7 +22,7 @@ pub struct Headers {
reflector_: Reflector, reflector_: Reflector,
guard: Cell<Guard>, guard: Cell<Guard>,
#[ignore_heap_size_of = "Defined in hyper"] #[ignore_heap_size_of = "Defined in hyper"]
header_list: DOMRefCell<HyperHeaders> header_list: DomRefCell<HyperHeaders>
} }
// https://fetch.spec.whatwg.org/#concept-headers-guard // https://fetch.spec.whatwg.org/#concept-headers-guard
@ -40,17 +40,17 @@ impl Headers {
Headers { Headers {
reflector_: Reflector::new(), reflector_: Reflector::new(),
guard: Cell::new(Guard::None), guard: Cell::new(Guard::None),
header_list: DOMRefCell::new(HyperHeaders::new()), header_list: DomRefCell::new(HyperHeaders::new()),
} }
} }
pub fn new(global: &GlobalScope) -> Root<Headers> { pub fn new(global: &GlobalScope) -> DomRoot<Headers> {
reflect_dom_object(box Headers::new_inherited(), global, HeadersWrap) reflect_dom_object(box Headers::new_inherited(), global, HeadersWrap)
} }
// https://fetch.spec.whatwg.org/#dom-headers // https://fetch.spec.whatwg.org/#dom-headers
pub fn Constructor(global: &GlobalScope, init: Option<HeadersInit>) pub fn Constructor(global: &GlobalScope, init: Option<HeadersInit>)
-> Fallible<Root<Headers>> { -> Fallible<DomRoot<Headers>> {
let dom_headers_new = Headers::new(global); let dom_headers_new = Headers::new(global);
dom_headers_new.fill(init)?; dom_headers_new.fill(init)?;
Ok(dom_headers_new) Ok(dom_headers_new)
@ -206,13 +206,13 @@ impl Headers {
} }
} }
pub fn for_request(global: &GlobalScope) -> Root<Headers> { pub fn for_request(global: &GlobalScope) -> DomRoot<Headers> {
let headers_for_request = Headers::new(global); let headers_for_request = Headers::new(global);
headers_for_request.guard.set(Guard::Request); headers_for_request.guard.set(Guard::Request);
headers_for_request headers_for_request
} }
pub fn for_response(global: &GlobalScope) -> Root<Headers> { pub fn for_response(global: &GlobalScope) -> DomRoot<Headers> {
let headers_for_response = Headers::new(global); let headers_for_response = Headers::new(global);
headers_for_response.guard.set(Guard::Response); headers_for_response.guard.set(Guard::Response);
headers_for_response headers_for_response

Some files were not shown because too many files have changed in this diff Show more