auto merge of #4526 : servo/servo/deref-1, r=Manishearth

This is a start towards fixing #3868. Not all callers have been fixed yet, so the `Deref` implementation remains for now.
This commit is contained in:
bors-servo 2015-01-02 09:22:51 -07:00
commit 141b5d038f
71 changed files with 592 additions and 568 deletions

View file

@ -25,8 +25,8 @@ pub fn handle_evaluate_js(page: &Rc<Page>, pipeline: PipelineId, eval: String, r
let page = get_page(&*page, pipeline); let page = get_page(&*page, pipeline);
let frame = page.frame(); let frame = page.frame();
let window = frame.as_ref().unwrap().window.root(); let window = frame.as_ref().unwrap().window.root();
let cx = window.get_cx(); let cx = window.r().get_cx();
let rval = window.evaluate_js_with_result(eval.as_slice()); let rval = window.r().evaluate_js_with_result(eval.as_slice());
reply.send(if rval.is_undefined() { reply.send(if rval.is_undefined() {
devtools_traits::VoidValue devtools_traits::VoidValue
@ -51,7 +51,7 @@ pub fn handle_get_root_node(page: &Rc<Page>, pipeline: PipelineId, reply: Sender
let frame = page.frame(); let frame = page.frame();
let document = frame.as_ref().unwrap().document.root(); let document = frame.as_ref().unwrap().document.root();
let node: JSRef<Node> = NodeCast::from_ref(*document); let node: JSRef<Node> = NodeCast::from_ref(document.r());
reply.send(node.summarize()); reply.send(node.summarize());
} }
@ -59,9 +59,9 @@ pub fn handle_get_document_element(page: &Rc<Page>, pipeline: PipelineId, reply:
let page = get_page(&*page, pipeline); let page = get_page(&*page, pipeline);
let frame = page.frame(); let frame = page.frame();
let document = frame.as_ref().unwrap().document.root(); let document = frame.as_ref().unwrap().document.root();
let document_element = document.GetDocumentElement().root().unwrap(); let document_element = document.r().GetDocumentElement().root().unwrap();
let node: JSRef<Node> = NodeCast::from_ref(*document_element); let node: JSRef<Node> = NodeCast::from_ref(document_element.r());
reply.send(node.summarize()); reply.send(node.summarize());
} }
@ -69,7 +69,7 @@ fn find_node_by_unique_id(page: &Rc<Page>, pipeline: PipelineId, node_id: String
let page = get_page(&*page, pipeline); let page = get_page(&*page, pipeline);
let frame = page.frame(); let frame = page.frame();
let document = frame.as_ref().unwrap().document.root(); let document = frame.as_ref().unwrap().document.root();
let node: JSRef<Node> = NodeCast::from_ref(*document); let node: JSRef<Node> = NodeCast::from_ref(document.r());
for candidate in node.traverse_preorder() { for candidate in node.traverse_preorder() {
if candidate.get_unique_id().as_slice() == node_id.as_slice() { if candidate.get_unique_id().as_slice() == node_id.as_slice() {
@ -82,20 +82,20 @@ fn find_node_by_unique_id(page: &Rc<Page>, pipeline: PipelineId, node_id: String
pub fn handle_get_children(page: &Rc<Page>, pipeline: PipelineId, node_id: String, reply: Sender<Vec<NodeInfo>>) { pub fn handle_get_children(page: &Rc<Page>, pipeline: PipelineId, node_id: String, reply: Sender<Vec<NodeInfo>>) {
let parent = find_node_by_unique_id(&*page, pipeline, node_id).root(); let parent = find_node_by_unique_id(&*page, pipeline, node_id).root();
let children = parent.children().map(|child| child.summarize()).collect(); let children = parent.r().children().map(|child| child.summarize()).collect();
reply.send(children); reply.send(children);
} }
pub fn handle_get_layout(page: &Rc<Page>, pipeline: PipelineId, node_id: String, reply: Sender<(f32, f32)>) { pub fn handle_get_layout(page: &Rc<Page>, pipeline: PipelineId, node_id: String, reply: Sender<(f32, f32)>) {
let node = find_node_by_unique_id(&*page, pipeline, node_id).root(); let node = find_node_by_unique_id(&*page, pipeline, node_id).root();
let elem: JSRef<Element> = ElementCast::to_ref(*node).expect("should be getting layout of element"); let elem: JSRef<Element> = ElementCast::to_ref(node.r()).expect("should be getting layout of element");
let rect = elem.GetBoundingClientRect().root(); let rect = elem.GetBoundingClientRect().root();
reply.send((rect.Width(), rect.Height())); reply.send((rect.r().Width(), rect.r().Height()));
} }
pub fn handle_modify_attribute(page: &Rc<Page>, pipeline: PipelineId, node_id: String, modifications: Vec<Modification>) { pub fn handle_modify_attribute(page: &Rc<Page>, pipeline: PipelineId, node_id: String, modifications: Vec<Modification>) {
let node = find_node_by_unique_id(&*page, pipeline, node_id).root(); let node = find_node_by_unique_id(&*page, pipeline, node_id).root();
let elem: JSRef<Element> = ElementCast::to_ref(*node).expect("should be getting layout of element"); let elem: JSRef<Element> = ElementCast::to_ref(node.r()).expect("should be getting layout of element");
for modification in modifications.iter(){ for modification in modifications.iter(){
match modification.newValue { match modification.newValue {

View file

@ -32,22 +32,23 @@ pub trait Activatable : Copy {
fn synthetic_click_activation(&self, ctrlKey: bool, shiftKey: bool, altKey: bool, metaKey: bool) { fn synthetic_click_activation(&self, ctrlKey: bool, shiftKey: bool, altKey: bool, metaKey: bool) {
let element = self.as_element().root(); let element = self.as_element().root();
// Step 1 // Step 1
if element.click_in_progress() { if element.r().click_in_progress() {
return; return;
} }
// Step 2 // Step 2
element.set_click_in_progress(true); element.r().set_click_in_progress(true);
// Step 3 // Step 3
self.pre_click_activation(); self.pre_click_activation();
// Step 4 // Step 4
// https://html.spec.whatwg.org/multipage/webappapis.html#fire-a-synthetic-mouse-event // https://html.spec.whatwg.org/multipage/webappapis.html#fire-a-synthetic-mouse-event
let win = window_from_node(*element).root(); let win = window_from_node(element.r()).root();
let target: JSRef<EventTarget> = EventTargetCast::from_ref(*element); let target: JSRef<EventTarget> = EventTargetCast::from_ref(element.r());
let mouse = MouseEvent::new(*win, "click".into_string(), false, false, Some(*win), 1, let mouse = MouseEvent::new(win.r(), "click".into_string(),
false, false, Some(win.r()), 1,
0, 0, 0, 0, ctrlKey, shiftKey, altKey, metaKey, 0, 0, 0, 0, ctrlKey, shiftKey, altKey, metaKey,
0, None).root(); 0, None).root();
let event: JSRef<Event> = EventCast::from_ref(*mouse); let event: JSRef<Event> = EventCast::from_ref(mouse.r());
event.set_trusted(true); event.set_trusted(true);
target.dispatch_event(event); target.dispatch_event(event);
@ -60,6 +61,6 @@ pub trait Activatable : Copy {
} }
// Step 6 // Step 6
element.set_click_in_progress(false); element.r().set_click_in_progress(false);
} }
} }

View file

@ -8,6 +8,7 @@ use dom::bindings::codegen::Bindings::AttrBinding::AttrMethods;
use dom::bindings::codegen::InheritTypes::NodeCast; use dom::bindings::codegen::InheritTypes::NodeCast;
use dom::bindings::global::GlobalRef; use dom::bindings::global::GlobalRef;
use dom::bindings::js::{JS, JSRef, Temporary}; use dom::bindings::js::{JS, JSRef, Temporary};
use dom::bindings::js::{OptionalRootedRootable, RootedReference};
use dom::bindings::utils::{Reflector, reflect_dom_object}; use dom::bindings::utils::{Reflector, reflect_dom_object};
use dom::element::{Element, AttributeHandlers}; use dom::element::{Element, AttributeHandlers};
use dom::node::Node; use dom::node::Node;
@ -151,8 +152,8 @@ impl<'a> AttrMethods for JSRef<'a, Attr> {
} }
Some(o) => { Some(o) => {
let owner = o.root(); let owner = o.root();
let value = owner.parse_attribute(&self.namespace, self.local_name(), value); let value = owner.r().parse_attribute(&self.namespace, self.local_name(), value);
self.set_value(AttrSettingType::ReplacedAttr, value, *owner); self.set_value(AttrSettingType::ReplacedAttr, value, owner.r());
} }
} }
} }
@ -207,7 +208,7 @@ pub trait AttrHelpers<'a> {
impl<'a> AttrHelpers<'a> for JSRef<'a, Attr> { impl<'a> AttrHelpers<'a> for JSRef<'a, Attr> {
fn set_value(self, set_type: AttrSettingType, value: AttrValue, owner: JSRef<Element>) { fn set_value(self, set_type: AttrSettingType, value: AttrValue, owner: JSRef<Element>) {
assert!(Some(owner) == self.owner.map(|o| *o.root())); assert!(Some(owner) == self.owner.root().r());
let node: JSRef<Node> = NodeCast::from_ref(owner); let node: JSRef<Node> = NodeCast::from_ref(owner);
let namespace_is_null = self.namespace == ns!(""); let namespace_is_null = self.namespace == ns!("");

View file

@ -147,7 +147,7 @@ impl CallSetup {
pub fn new<T: CallbackContainer>(callback: T, handling: ExceptionHandling) -> CallSetup { pub fn new<T: CallbackContainer>(callback: T, handling: ExceptionHandling) -> CallSetup {
let global = global_object_for_js_object(callback.callback()); let global = global_object_for_js_object(callback.callback());
let global = global.root(); let global = global.root();
let cx = global.root_ref().get_cx(); let cx = global.r().get_cx();
CallSetup { CallSetup {
cx: cx, cx: cx,
_handling: handling _handling: handling

View file

@ -2199,7 +2199,7 @@ class CGCallGenerator(CGThing):
if static: if static:
call = CGWrapper(call, pre="%s::" % descriptorProvider.interface.identifier.name) call = CGWrapper(call, pre="%s::" % descriptorProvider.interface.identifier.name)
else: else:
call = CGWrapper(call, pre="%s." % object) call = CGWrapper(call, pre="%s.r()." % object)
call = CGList([call, CGWrapper(args, pre="(", post=")")]) call = CGList([call, CGWrapper(args, pre="(", post=")")])
self.cgRoot.append(CGList([ self.cgRoot.append(CGList([
@ -2214,7 +2214,7 @@ class CGCallGenerator(CGThing):
if static: if static:
glob = "" glob = ""
else: else:
glob = " let global = global_object_for_js_object(this.reflector().get_jsobject());\n"\ glob = " let global = global_object_for_js_object(this.r().reflector().get_jsobject());\n"\
" let global = global.root();\n" " let global = global.root();\n"
self.cgRoot.append(CGGeneric( self.cgRoot.append(CGGeneric(
@ -2222,7 +2222,7 @@ class CGCallGenerator(CGThing):
" Ok(result) => result,\n" " Ok(result) => result,\n"
" Err(e) => {\n" " Err(e) => {\n"
"%s" "%s"
" throw_dom_exception(cx, global.root_ref(), e);\n" " throw_dom_exception(cx, global.r(), e);\n"
" return%s;\n" " return%s;\n"
" },\n" " },\n"
"};" % (glob, errorResult))) "};" % (glob, errorResult)))
@ -2307,7 +2307,7 @@ class CGPerSignatureCall(CGThing):
def process(arg, i): def process(arg, i):
argVal = "arg" + str(i) argVal = "arg" + str(i)
if arg.type.isGeckoInterface() and not arg.type.unroll().inner.isCallback(): if arg.type.isGeckoInterface() and not arg.type.unroll().inner.isCallback():
argVal += ".root_ref()" argVal += ".r()"
return argVal return argVal
return [(a, process(a, i)) for (i, a) in enumerate(self.arguments)] return [(a, process(a, i)) for (i, a) in enumerate(self.arguments)]
@ -3540,7 +3540,7 @@ class CGProxySpecialOperation(CGPerSignatureCall):
def process(arg): def process(arg):
argVal = arg.identifier.name argVal = arg.identifier.name
if arg.type.isGeckoInterface() and not arg.type.unroll().inner.isCallback(): if arg.type.isGeckoInterface() and not arg.type.unroll().inner.isCallback():
argVal += ".root_ref()" argVal += ".r()"
return argVal return argVal
args = [(a, process(a)) for a in self.arguments] args = [(a, process(a)) for a in self.arguments]
if self.idlNode.isGetter(): if self.idlNode.isGetter():
@ -4014,7 +4014,7 @@ let global = global_object_for_js_object(JS_CALLEE(cx, vp).to_object());
let global = global.root(); let global = global.root();
""") """)
nativeName = MakeNativeName(self._ctor.identifier.name) nativeName = MakeNativeName(self._ctor.identifier.name)
callGenerator = CGMethodCall(["&global.root_ref()"], nativeName, True, callGenerator = CGMethodCall(["&global.r()"], nativeName, True,
self.descriptor, self._ctor) self.descriptor, self._ctor)
return CGList([preamble, callGenerator]) return CGList([preamble, callGenerator])

View file

@ -156,7 +156,7 @@ class Descriptor(DescriptorProvider):
self.needsRooting = True self.needsRooting = True
self.returnType = "Temporary<%s>" % ifaceName self.returnType = "Temporary<%s>" % ifaceName
self.argumentType = "JSRef<%s>" % ifaceName self.argumentType = "JSRef<%s>" % ifaceName
self.memberType = "Root<'a, 'b, %s>" % ifaceName self.memberType = "Root<%s>" % ifaceName
self.nativeType = "JS<%s>" % ifaceName self.nativeType = "JS<%s>" % ifaceName
self.concreteType = ifaceName self.concreteType = ifaceName

View file

@ -471,9 +471,9 @@ impl<T: Reflectable+IDLInterface> FromJSValConvertible<()> for JS<T> {
} }
} }
impl<'a, 'b, T: Reflectable> ToJSValConvertible for Root<'a, 'b, T> { impl<T: Reflectable> ToJSValConvertible for Root<T> {
fn to_jsval(&self, cx: *mut JSContext) -> JSVal { fn to_jsval(&self, cx: *mut JSContext) -> JSVal {
self.reflector().to_jsval(cx) self.r().reflector().to_jsval(cx)
} }
} }

View file

@ -32,9 +32,9 @@ pub enum GlobalRef<'a> {
} }
/// A stack-based rooted reference to a global object. /// A stack-based rooted reference to a global object.
pub enum GlobalRoot<'a, 'b> { pub enum GlobalRoot {
Window(Root<'a, 'b, window::Window>), Window(Root<window::Window>),
Worker(Root<'a, 'b, WorkerGlobalScope>), Worker(Root<WorkerGlobalScope>),
} }
/// A traced reference to a global object, for use in fields of traced Rust /// A traced reference to a global object, for use in fields of traced Rust
@ -98,13 +98,13 @@ impl<'a> Reflectable for GlobalRef<'a> {
} }
} }
impl<'a, 'b> GlobalRoot<'a, 'b> { impl GlobalRoot {
/// Obtain a safe reference to the global object that cannot outlive the /// Obtain a safe reference to the global object that cannot outlive the
/// lifetime of this root. /// lifetime of this root.
pub fn root_ref<'c>(&'c self) -> GlobalRef<'c> { pub fn r<'c>(&'c self) -> GlobalRef<'c> {
match *self { match *self {
GlobalRoot::Window(ref window) => GlobalRef::Window(window.root_ref()), GlobalRoot::Window(ref window) => GlobalRef::Window(window.r()),
GlobalRoot::Worker(ref worker) => GlobalRef::Worker(worker.root_ref()), GlobalRoot::Worker(ref worker) => GlobalRef::Worker(worker.r()),
} }
} }
} }

View file

@ -31,11 +31,11 @@
//! Both `Temporary<T>` and `JS<T>` do not allow access to their inner value without explicitly //! Both `Temporary<T>` and `JS<T>` do not allow access to their inner value without explicitly
//! creating a stack-based root via the `root` method. This returns a `Root<T>`, which causes //! creating a stack-based root via the `root` method. This returns a `Root<T>`, which causes
//! the JS-owned value to be uncollectable for the duration of the `Root` object's lifetime. //! the JS-owned value to be uncollectable for the duration of the `Root` object's lifetime.
//! A `JSRef<T>` can be obtained from a `Root<T>` either by dereferencing the `Root<T>` (`*rooted`) //! A `JSRef<T>` can be obtained from a `Root<T>` by calling the `r` method. (Dereferencing the
//! or explicitly calling the `root_ref` method. These `JSRef<T>` values are not allowed to //! object is still supported, but as it is unsafe, this is deprecated.) These `JSRef<T>` values
//! outlive their originating `Root<T>`, to ensure that all interactions with the enclosed value //! are not allowed to outlive their originating `Root<T>`, to ensure that all interactions with
//! only occur when said value is uncollectable, and will cause static lifetime errors if //! the enclosed value only occur when said value is uncollectable, and will cause static lifetime
//! misused. //! errors if misused.
//! //!
//! Other miscellaneous helper traits: //! Other miscellaneous helper traits:
//! //!
@ -91,7 +91,7 @@ impl<T: Reflectable> Temporary<T> {
} }
/// Create a stack-bounded root for this value. /// Create a stack-bounded root for this value.
pub fn root<'a, 'b>(self) -> Root<'a, 'b, T> { pub fn root(self) -> Root<T> {
let collection = StackRoots.get().unwrap(); let collection = StackRoots.get().unwrap();
unsafe { unsafe {
Root::new(&**collection, &self.inner) Root::new(&**collection, &self.inner)
@ -150,7 +150,7 @@ impl<T: Reflectable> JS<T> {
/// Root this JS-owned value to prevent its collection as garbage. /// Root this JS-owned value to prevent its collection as garbage.
pub fn root<'a, 'b>(&self) -> Root<'a, 'b, T> { pub fn root(&self) -> Root<T> {
let collection = StackRoots.get().unwrap(); let collection = StackRoots.get().unwrap();
unsafe { unsafe {
Root::new(&**collection, self) Root::new(&**collection, self)
@ -307,23 +307,23 @@ impl<From, To> JS<From> {
/// Get an `Option<JSRef<T>>` out of an `Option<Root<T>>` /// Get an `Option<JSRef<T>>` out of an `Option<Root<T>>`
pub trait RootedReference<T> { pub trait RootedReference<T> {
fn root_ref<'a>(&'a self) -> Option<JSRef<'a, T>>; fn r<'a>(&'a self) -> Option<JSRef<'a, T>>;
} }
impl<'a, 'b, T: Reflectable> RootedReference<T> for Option<Root<'a, 'b, T>> { impl<T: Reflectable> RootedReference<T> for Option<Root<T>> {
fn root_ref<'a>(&'a self) -> Option<JSRef<'a, T>> { fn r<'a>(&'a self) -> Option<JSRef<'a, T>> {
self.as_ref().map(|root| root.root_ref()) self.as_ref().map(|root| root.r())
} }
} }
/// Get an `Option<Option<JSRef<T>>>` out of an `Option<Option<Root<T>>>` /// Get an `Option<Option<JSRef<T>>>` out of an `Option<Option<Root<T>>>`
pub trait OptionalRootedReference<T> { pub trait OptionalRootedReference<T> {
fn root_ref<'a>(&'a self) -> Option<Option<JSRef<'a, T>>>; fn r<'a>(&'a self) -> Option<Option<JSRef<'a, T>>>;
} }
impl<'a, 'b, T: Reflectable> OptionalRootedReference<T> for Option<Option<Root<'a, 'b, T>>> { impl<T: Reflectable> OptionalRootedReference<T> for Option<Option<Root<T>>> {
fn root_ref<'a>(&'a self) -> Option<Option<JSRef<'a, T>>> { fn r<'a>(&'a self) -> Option<Option<JSRef<'a, T>>> {
self.as_ref().map(|inner| inner.root_ref()) self.as_ref().map(|inner| inner.r())
} }
} }
@ -367,11 +367,11 @@ impl<T: Assignable<U>, U: Reflectable> OptionalSettable<T> for Cell<Option<JS<U>
/// Root a rootable `Option` type (used for `Option<Temporary<T>>`) /// Root a rootable `Option` type (used for `Option<Temporary<T>>`)
pub trait OptionalRootable<T> { pub trait OptionalRootable<T> {
fn root<'a, 'b>(self) -> Option<Root<'a, 'b, T>>; fn root(self) -> Option<Root<T>>;
} }
impl<T: Reflectable> OptionalRootable<T> for Option<Temporary<T>> { impl<T: Reflectable> OptionalRootable<T> for Option<Temporary<T>> {
fn root<'a, 'b>(self) -> Option<Root<'a, 'b, T>> { fn root(self) -> Option<Root<T>> {
self.map(|inner| inner.root()) self.map(|inner| inner.root())
} }
} }
@ -389,22 +389,22 @@ impl<'a, T: Reflectable> OptionalUnrootable<T> for Option<JSRef<'a, T>> {
/// Root a rootable `Option` type (used for `Option<JS<T>>`) /// Root a rootable `Option` type (used for `Option<JS<T>>`)
pub trait OptionalRootedRootable<T> { pub trait OptionalRootedRootable<T> {
fn root<'a, 'b>(&self) -> Option<Root<'a, 'b, T>>; fn root(&self) -> Option<Root<T>>;
} }
impl<T: Reflectable> OptionalRootedRootable<T> for Option<JS<T>> { impl<T: Reflectable> OptionalRootedRootable<T> for Option<JS<T>> {
fn root<'a, 'b>(&self) -> Option<Root<'a, 'b, T>> { fn root(&self) -> Option<Root<T>> {
self.as_ref().map(|inner| inner.root()) self.as_ref().map(|inner| inner.root())
} }
} }
/// Root a rootable `Option<Option>` type (used for `Option<Option<JS<T>>>`) /// Root a rootable `Option<Option>` type (used for `Option<Option<JS<T>>>`)
pub trait OptionalOptionalRootedRootable<T> { pub trait OptionalOptionalRootedRootable<T> {
fn root<'a, 'b>(&self) -> Option<Option<Root<'a, 'b, T>>>; fn root(&self) -> Option<Option<Root<T>>>;
} }
impl<T: Reflectable> OptionalOptionalRootedRootable<T> for Option<Option<JS<T>>> { impl<T: Reflectable> OptionalOptionalRootedRootable<T> for Option<Option<JS<T>>> {
fn root<'a, 'b>(&self) -> Option<Option<Root<'a, 'b, T>>> { fn root(&self) -> Option<Option<Root<T>>> {
self.as_ref().map(|inner| inner.root()) self.as_ref().map(|inner| inner.root())
} }
} }
@ -412,17 +412,17 @@ impl<T: Reflectable> OptionalOptionalRootedRootable<T> for Option<Option<JS<T>>>
/// Root a rootable `Result` type (any of `Temporary<T>` or `JS<T>`) /// Root a rootable `Result` type (any of `Temporary<T>` or `JS<T>`)
pub trait ResultRootable<T,U> { pub trait ResultRootable<T,U> {
fn root<'a, 'b>(self) -> Result<Root<'a, 'b, T>, U>; fn root(self) -> Result<Root<T>, U>;
} }
impl<T: Reflectable, U> ResultRootable<T, U> for Result<Temporary<T>, U> { impl<T: Reflectable, U> ResultRootable<T, U> for Result<Temporary<T>, U> {
fn root<'a, 'b>(self) -> Result<Root<'a, 'b, T>, U> { fn root(self) -> Result<Root<T>, U> {
self.map(|inner| inner.root()) self.map(|inner| inner.root())
} }
} }
impl<T: Reflectable, U> ResultRootable<T, U> for Result<JS<T>, U> { impl<T: Reflectable, U> ResultRootable<T, U> for Result<JS<T>, U> {
fn root<'a, 'b>(self) -> Result<Root<'a, 'b, T>, U> { fn root(self) -> Result<Root<T>, U> {
self.map(|inner| inner.root()) self.map(|inner| inner.root())
} }
} }
@ -459,7 +459,7 @@ impl RootCollection {
} }
/// Track a stack-based root to ensure LIFO root ordering /// Track a stack-based root to ensure LIFO root ordering
fn root<'a, 'b, T: Reflectable>(&self, untracked: &Root<'a, 'b, T>) { fn root<'b, T: Reflectable>(&self, untracked: &Root<T>) {
unsafe { unsafe {
let roots = self.roots.get(); let roots = self.roots.get();
(*roots).push(untracked.js_ptr); (*roots).push(untracked.js_ptr);
@ -468,7 +468,7 @@ impl RootCollection {
} }
/// Stop tracking a stack-based root, asserting if LIFO root ordering has been violated /// Stop tracking a stack-based root, asserting if LIFO root ordering has been violated
fn unroot<'a, 'b, T: Reflectable>(&self, rooted: &Root<'a, 'b, T>) { fn unroot<'b, T: Reflectable>(&self, rooted: &Root<T>) {
unsafe { unsafe {
let roots = self.roots.get(); let roots = self.roots.get();
debug!("unrooting {} (expecting {}", debug!("unrooting {} (expecting {}",
@ -485,20 +485,20 @@ impl RootCollection {
/// for the same JS value. `Root`s cannot outlive the associated `RootCollection` object. /// for the same JS value. `Root`s cannot outlive the associated `RootCollection` object.
/// Attempts to transfer ownership of a `Root` via moving will trigger dynamic unrooting /// Attempts to transfer ownership of a `Root` via moving will trigger dynamic unrooting
/// failures due to incorrect ordering. /// failures due to incorrect ordering.
pub struct Root<'a, 'b, T> { pub struct Root<T> {
/// List that ensures correct dynamic root ordering /// List that ensures correct dynamic root ordering
root_list: &'a RootCollection, root_list: &'static RootCollection,
/// Reference to rooted value that must not outlive this container /// Reference to rooted value that must not outlive this container
jsref: JSRef<'b, T>, jsref: JSRef<'static, T>,
/// On-stack JS pointer to assuage conservative stack scanner /// On-stack JS pointer to assuage conservative stack scanner
js_ptr: *mut JSObject, js_ptr: *mut JSObject,
} }
impl<'b, 'a: 'b, T: Reflectable> Root<'a, 'b, T> { impl<T: Reflectable> Root<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 not outlive its associated `RootCollection`, and it contains a `JSRef` /// It cannot not outlive its associated `RootCollection`, and it contains a `JSRef`
/// which cannot outlive this new `Root`. /// which cannot outlive this new `Root`.
fn new(roots: &'a RootCollection, unrooted: &JS<T>) -> Root<'a, 'b, T> { fn new(roots: &'static RootCollection, unrooted: &JS<T>) -> Root<T> {
let root = Root { let root = Root {
root_list: roots, root_list: roots,
jsref: JSRef { jsref: JSRef {
@ -513,19 +513,22 @@ impl<'b, 'a: 'b, T: Reflectable> Root<'a, 'b, T> {
/// Obtain a safe reference to the wrapped JS owned-value that cannot outlive /// Obtain a safe reference to the wrapped JS owned-value that cannot outlive
/// the lifetime of this root. /// the lifetime of this root.
pub fn root_ref<'b>(&'b self) -> JSRef<'b,T> { pub fn r<'b>(&'b self) -> JSRef<'b, T> {
self.jsref.clone() JSRef {
ptr: self.jsref.ptr,
chain: ContravariantLifetime,
}
} }
} }
#[unsafe_destructor] #[unsafe_destructor]
impl<'b, 'a: 'b, T: Reflectable> Drop for Root<'a, 'b, T> { impl<T: Reflectable> Drop for Root<T> {
fn drop(&mut self) { fn drop(&mut self) {
self.root_list.unroot(self); self.root_list.unroot(self);
} }
} }
impl<'b, 'a: 'b, T: Reflectable> Deref<JSRef<'b, T>> for Root<'a, 'b, T> { impl<'b, T: Reflectable> Deref<JSRef<'b, T>> for Root<T> {
fn deref<'c>(&'c self) -> &'c JSRef<'b, T> { fn deref<'c>(&'c self) -> &'c JSRef<'b, T> {
&self.jsref &self.jsref
} }

View file

@ -552,7 +552,7 @@ pub extern fn outerize_global(_cx: *mut JSContext, obj: JSHandleObject) -> *mut
debug!("outerizing"); debug!("outerizing");
let obj = *obj.unnamed_field1; let obj = *obj.unnamed_field1;
let win: Root<window::Window> = unwrap_jsmanaged(obj).unwrap().root(); let win: Root<window::Window> = unwrap_jsmanaged(obj).unwrap().root();
win.browser_context().as_ref().unwrap().window_proxy() win.r().browser_context().as_ref().unwrap().window_proxy()
} }
} }

View file

@ -121,13 +121,13 @@ impl<'a> BlobMethods for JSRef<'a, Blob> {
let span: i64 = max(relativeEnd - relativeStart, 0); let span: i64 = max(relativeEnd - relativeStart, 0);
let global = self.global.root(); let global = self.global.root();
match self.bytes { match self.bytes {
None => Blob::new(&global.root_ref(), None, relativeContentType.as_slice()), None => Blob::new(&global.r(), None, relativeContentType.as_slice()),
Some(ref vec) => { Some(ref vec) => {
let start = relativeStart.to_uint().unwrap(); let start = relativeStart.to_uint().unwrap();
let end = (relativeStart + span).to_uint().unwrap(); let end = (relativeStart + span).to_uint().unwrap();
let mut bytes: Vec<u8> = Vec::new(); let mut bytes: Vec<u8> = Vec::new();
bytes.push_all(vec.slice(start, end)); bytes.push_all(vec.slice(start, end));
Blob::new(&global.root_ref(), Some(bytes), relativeContentType.as_slice()) Blob::new(&global.r(), Some(bytes), relativeContentType.as_slice())
} }
} }
} }

View file

@ -39,7 +39,7 @@ impl BrowserContext {
pub fn active_window(&self) -> Temporary<Window> { pub fn active_window(&self) -> Temporary<Window> {
let doc = self.active_document().root(); let doc = self.active_document().root();
doc.window() doc.r().window()
} }
pub fn window_proxy(&self) -> *mut JSObject { pub fn window_proxy(&self) -> *mut JSObject {
@ -49,6 +49,7 @@ impl BrowserContext {
fn create_window_proxy(&mut self) { fn create_window_proxy(&mut self) {
let win = self.active_window().root(); let win = self.active_window().root();
let win = win.r();
let page = win.page(); let page = win.page();
let js_info = page.js_info(); let js_info = page.js_info();

View file

@ -40,7 +40,7 @@ impl Comment {
pub fn Constructor(global: &GlobalRef, data: DOMString) -> Fallible<Temporary<Comment>> { pub fn Constructor(global: &GlobalRef, data: DOMString) -> Fallible<Temporary<Comment>> {
let document = global.as_window().Document().root(); let document = global.as_window().Document().root();
Ok(Comment::new(data, *document)) Ok(Comment::new(data, document.r()))
} }
#[inline] #[inline]

View file

@ -85,13 +85,13 @@ trait PrivateCSSStyleDeclarationHelpers {
impl<'a> PrivateCSSStyleDeclarationHelpers for JSRef<'a, CSSStyleDeclaration> { impl<'a> PrivateCSSStyleDeclarationHelpers for JSRef<'a, CSSStyleDeclaration> {
fn get_declaration(self, property: &Atom) -> Option<PropertyDeclaration> { fn get_declaration(self, property: &Atom) -> Option<PropertyDeclaration> {
let owner = self.owner.root(); let owner = self.owner.root();
let element: JSRef<Element> = ElementCast::from_ref(*owner); let element: JSRef<Element> = ElementCast::from_ref(owner.r());
element.get_inline_style_declaration(property).map(|decl| decl.clone()) element.get_inline_style_declaration(property).map(|decl| decl.clone())
} }
fn get_important_declaration(self, property: &Atom) -> Option<PropertyDeclaration> { fn get_important_declaration(self, property: &Atom) -> Option<PropertyDeclaration> {
let owner = self.owner.root(); let owner = self.owner.root();
let element: JSRef<Element> = ElementCast::from_ref(*owner); let element: JSRef<Element> = ElementCast::from_ref(owner.r());
element.get_important_inline_style_declaration(property).map(|decl| decl.clone()) element.get_important_inline_style_declaration(property).map(|decl| decl.clone())
} }
} }
@ -99,7 +99,7 @@ impl<'a> PrivateCSSStyleDeclarationHelpers for JSRef<'a, CSSStyleDeclaration> {
impl<'a> CSSStyleDeclarationMethods for JSRef<'a, CSSStyleDeclaration> { impl<'a> CSSStyleDeclarationMethods for JSRef<'a, CSSStyleDeclaration> {
fn Length(self) -> u32 { fn Length(self) -> u32 {
let owner = self.owner.root(); let owner = self.owner.root();
let elem: JSRef<Element> = ElementCast::from_ref(*owner); let elem: JSRef<Element> = ElementCast::from_ref(owner.r());
let len = match *elem.style_attribute().borrow() { let len = match *elem.style_attribute().borrow() {
Some(ref declarations) => declarations.normal.len() + declarations.important.len(), Some(ref declarations) => declarations.normal.len() + declarations.important.len(),
None => 0 None => 0
@ -109,7 +109,7 @@ impl<'a> CSSStyleDeclarationMethods for JSRef<'a, CSSStyleDeclaration> {
fn Item(self, index: u32) -> DOMString { fn Item(self, index: u32) -> DOMString {
let owner = self.owner.root(); let owner = self.owner.root();
let elem: JSRef<Element> = ElementCast::from_ref(*owner); let elem: JSRef<Element> = ElementCast::from_ref(owner.r());
let style_attribute = elem.style_attribute().borrow(); let style_attribute = elem.style_attribute().borrow();
let result = style_attribute.as_ref().and_then(|declarations| { let result = style_attribute.as_ref().and_then(|declarations| {
if index as uint > declarations.normal.len() { if index as uint > declarations.normal.len() {
@ -218,7 +218,8 @@ impl<'a> CSSStyleDeclarationMethods for JSRef<'a, CSSStyleDeclaration> {
synthesized_declaration.push_str(value.as_slice()); synthesized_declaration.push_str(value.as_slice());
let owner = self.owner.root(); let owner = self.owner.root();
let window = window_from_node(*owner).root(); let window = window_from_node(owner.r()).root();
let window = window.r();
let page = window.page(); let page = window.page();
let decl_block = parse_style_attribute(synthesized_declaration.as_slice(), let decl_block = parse_style_attribute(synthesized_declaration.as_slice(),
&page.get_url()); &page.get_url());
@ -229,7 +230,7 @@ impl<'a> CSSStyleDeclarationMethods for JSRef<'a, CSSStyleDeclaration> {
} }
let owner = self.owner.root(); let owner = self.owner.root();
let element: JSRef<Element> = ElementCast::from_ref(*owner); let element: JSRef<Element> = ElementCast::from_ref(owner.r());
// Step 8 // Step 8
for decl in decl_block.normal.iter() { for decl in decl_block.normal.iter() {
@ -240,7 +241,7 @@ impl<'a> CSSStyleDeclarationMethods for JSRef<'a, CSSStyleDeclaration> {
let document = document_from_node(element).root(); let document = document_from_node(element).root();
let node: JSRef<Node> = NodeCast::from_ref(element); let node: JSRef<Node> = NodeCast::from_ref(element);
document.content_changed(node, NodeDamage::NodeStyleDamaged); document.r().content_changed(node, NodeDamage::NodeStyleDamaged);
Ok(()) Ok(())
} }
@ -266,11 +267,12 @@ impl<'a> CSSStyleDeclarationMethods for JSRef<'a, CSSStyleDeclaration> {
} }
let owner = self.owner.root(); let owner = self.owner.root();
let window = window_from_node(*owner).root(); let window = window_from_node(owner.r()).root();
let window = window.r();
let page = window.page(); let page = window.page();
let decl_block = parse_style_attribute(property.as_slice(), let decl_block = parse_style_attribute(property.as_slice(),
&page.get_url()); &page.get_url());
let element: JSRef<Element> = ElementCast::from_ref(*owner); let element: JSRef<Element> = ElementCast::from_ref(owner.r());
// Step 5 // Step 5
for decl in decl_block.normal.iter() { for decl in decl_block.normal.iter() {
@ -281,7 +283,7 @@ impl<'a> CSSStyleDeclarationMethods for JSRef<'a, CSSStyleDeclaration> {
let document = document_from_node(element).root(); let document = document_from_node(element).root();
let node: JSRef<Node> = NodeCast::from_ref(element); let node: JSRef<Node> = NodeCast::from_ref(element);
document.content_changed(node, NodeDamage::NodeStyleDamaged); document.r().content_changed(node, NodeDamage::NodeStyleDamaged);
Ok(()) Ok(())
} }
@ -315,7 +317,7 @@ impl<'a> CSSStyleDeclarationMethods for JSRef<'a, CSSStyleDeclaration> {
None => { None => {
// Step 5 // Step 5
let owner = self.owner.root(); let owner = self.owner.root();
let elem: JSRef<Element> = ElementCast::from_ref(*owner); let elem: JSRef<Element> = ElementCast::from_ref(owner.r());
elem.remove_inline_style_property(property) elem.remove_inline_style_property(property)
} }
} }

View file

@ -42,8 +42,8 @@ impl CustomEvent {
} }
pub fn new(global: &GlobalRef, type_: DOMString, bubbles: bool, cancelable: bool, detail: JSVal) -> Temporary<CustomEvent> { pub fn new(global: &GlobalRef, type_: DOMString, bubbles: bool, cancelable: bool, detail: JSVal) -> Temporary<CustomEvent> {
let ev = CustomEvent::new_uninitialized(*global).root(); let ev = CustomEvent::new_uninitialized(*global).root();
ev.InitCustomEvent(global.get_cx(), type_, bubbles, cancelable, detail); ev.r().InitCustomEvent(global.get_cx(), type_, bubbles, cancelable, detail);
Temporary::from_rooted(*ev) Temporary::from_rooted(ev.r())
} }
pub fn Constructor(global: &GlobalRef, pub fn Constructor(global: &GlobalRef,
type_: DOMString, type_: DOMString,

View file

@ -158,20 +158,20 @@ impl DedicatedWorkerGlobalScope {
parent_sender, own_sender, receiver).root(); parent_sender, own_sender, receiver).root();
{ {
let _ar = AutoWorkerReset::new(*global, worker); let _ar = AutoWorkerReset::new(global.r(), worker);
match js_context.evaluate_script( match js_context.evaluate_script(
global.reflector().get_jsobject(), source, url.serialize(), 1) { global.r().reflector().get_jsobject(), source, url.serialize(), 1) {
Ok(_) => (), Ok(_) => (),
Err(_) => println!("evaluate_script failed") Err(_) => println!("evaluate_script failed")
} }
} }
loop { loop {
match global.receiver.recv_opt() { match global.r().receiver.recv_opt() {
Ok((linked_worker, msg)) => { Ok((linked_worker, msg)) => {
let _ar = AutoWorkerReset::new(*global, linked_worker); let _ar = AutoWorkerReset::new(global.r(), linked_worker);
global.handle_event(msg); global.r().handle_event(msg);
} }
Err(_) => break, Err(_) => break,
} }

View file

@ -24,7 +24,7 @@ use dom::bindings::error::Error::{NotSupported, InvalidCharacter};
use dom::bindings::error::Error::{HierarchyRequest, NamespaceError}; use dom::bindings::error::Error::{HierarchyRequest, NamespaceError};
use dom::bindings::global::GlobalRef; use dom::bindings::global::GlobalRef;
use dom::bindings::js::{MutNullableJS, JS, JSRef, Temporary, OptionalSettable, TemporaryPushable}; use dom::bindings::js::{MutNullableJS, JS, JSRef, Temporary, OptionalSettable, TemporaryPushable};
use dom::bindings::js::OptionalRootable; use dom::bindings::js::{OptionalRootable, RootedReference};
use dom::bindings::utils::reflect_dom_object; use dom::bindings::utils::reflect_dom_object;
use dom::bindings::utils::xml_name_type; use dom::bindings::utils::xml_name_type;
use dom::bindings::utils::XMLName::{QName, Name, InvalidXMLName}; use dom::bindings::utils::XMLName::{QName, Name, InvalidXMLName};
@ -220,6 +220,7 @@ impl<'a> DocumentHelpers<'a> for JSRef<'a, Document> {
match mode { match mode {
Quirks => { Quirks => {
let window = self.window.root(); let window = self.window.root();
let window = window.r();
let LayoutChan(ref layout_chan) = window.page().layout_chan; let LayoutChan(ref layout_chan) = window.page().layout_chan;
layout_chan.send(Msg::SetQuirksMode); layout_chan.send(Msg::SetQuirksMode);
} }
@ -255,7 +256,7 @@ impl<'a> DocumentHelpers<'a> for JSRef<'a, Document> {
Some(elements) => { Some(elements) => {
let position = elements.iter() let position = elements.iter()
.map(|elem| elem.root()) .map(|elem| elem.root())
.position(|element| *element == to_unregister) .position(|element| element.r() == to_unregister)
.expect("This element should be in registered."); .expect("This element should be in registered.");
elements.remove(position); elements.remove(position);
elements.is_empty() elements.is_empty()
@ -289,13 +290,13 @@ impl<'a> DocumentHelpers<'a> for JSRef<'a, Document> {
let new_node: JSRef<Node> = NodeCast::from_ref(element); let new_node: JSRef<Node> = NodeCast::from_ref(element);
let mut head: uint = 0u; let mut head: uint = 0u;
let root: JSRef<Node> = NodeCast::from_ref(*root); let root: JSRef<Node> = NodeCast::from_ref(root.r());
for node in root.traverse_preorder() { for node in root.traverse_preorder() {
let elem: Option<JSRef<Element>> = ElementCast::to_ref(node); let elem: Option<JSRef<Element>> = ElementCast::to_ref(node);
match elem { match elem {
None => {}, None => {},
Some(elem) => { Some(elem) => {
if *(*elements)[head].root() == elem { if (*elements)[head].root().r() == elem {
head += 1; head += 1;
} }
if new_node == node || head == elements.len() { if new_node == node || head == elements.len() {
@ -312,7 +313,7 @@ impl<'a> DocumentHelpers<'a> for JSRef<'a, Document> {
fn load_anchor_href(self, href: DOMString) { fn load_anchor_href(self, href: DOMString) {
let window = self.window.root(); let window = self.window.root();
window.load_url(href); window.r().load_url(href);
} }
/// Attempt to find a named element in this page's document. /// Attempt to find a named element in this page's document.
@ -322,7 +323,7 @@ impl<'a> DocumentHelpers<'a> for JSRef<'a, Document> {
let check_anchor = |&node: &JSRef<HTMLAnchorElement>| { let check_anchor = |&node: &JSRef<HTMLAnchorElement>| {
let elem: JSRef<Element> = ElementCast::from_ref(node); let elem: JSRef<Element> = ElementCast::from_ref(node);
elem.get_attribute(ns!(""), &atom!("name")).root().map_or(false, |attr| { elem.get_attribute(ns!(""), &atom!("name")).root().map_or(false, |attr| {
attr.value().as_slice() == fragid.as_slice() attr.r().value().as_slice() == fragid.as_slice()
}) })
}; };
let doc_node: JSRef<Node> = NodeCast::from_ref(self); let doc_node: JSRef<Node> = NodeCast::from_ref(self);
@ -338,11 +339,11 @@ impl<'a> DocumentHelpers<'a> for JSRef<'a, Document> {
self.ready_state.set(state); self.ready_state.set(state);
let window = self.window.root(); let window = self.window.root();
let event = Event::new(GlobalRef::Window(*window), "readystatechange".into_string(), let event = Event::new(GlobalRef::Window(window.r()), "readystatechange".into_string(),
EventBubbles::DoesNotBubble, EventBubbles::DoesNotBubble,
EventCancelable::NotCancelable).root(); EventCancelable::NotCancelable).root();
let target: JSRef<EventTarget> = EventTargetCast::from_ref(self); let target: JSRef<EventTarget> = EventTargetCast::from_ref(self);
let _ = target.DispatchEvent(*event); let _ = target.DispatchEvent(event.r());
} }
/// Return the element that currently has focus. /// Return the element that currently has focus.
@ -372,7 +373,7 @@ impl<'a> DocumentHelpers<'a> for JSRef<'a, Document> {
/// Sends this document's title to the compositor. /// Sends this document's title to the compositor.
fn send_title_to_compositor(self) { fn send_title_to_compositor(self) {
let window = self.window().root(); let window = self.window().root();
window.page().send_title_to_compositor(); window.r().page().send_title_to_compositor();
} }
fn dirty_all_nodes(self) { fn dirty_all_nodes(self) {
@ -466,9 +467,9 @@ impl Document {
GlobalRef::Window(window), GlobalRef::Window(window),
DocumentBinding::Wrap).root(); DocumentBinding::Wrap).root();
let node: JSRef<Node> = NodeCast::from_ref(*document); let node: JSRef<Node> = NodeCast::from_ref(document.r());
node.set_owner_doc(*document); node.set_owner_doc(document.r());
Temporary::from_rooted(*document) Temporary::from_rooted(document.r())
} }
} }
@ -480,20 +481,23 @@ trait PrivateDocumentHelpers {
impl<'a> PrivateDocumentHelpers for JSRef<'a, Document> { impl<'a> PrivateDocumentHelpers for JSRef<'a, Document> {
fn createNodeList(self, callback: |node: JSRef<Node>| -> bool) -> Temporary<NodeList> { fn createNodeList(self, callback: |node: JSRef<Node>| -> bool) -> Temporary<NodeList> {
let window = self.window.root(); let window = self.window.root();
let nodes = match self.GetDocumentElement().root() { let document_element = self.GetDocumentElement().root();
let nodes = match document_element {
None => vec!(), None => vec!(),
Some(root) => { Some(ref root) => {
let root: JSRef<Node> = NodeCast::from_ref(*root); let root: JSRef<Node> = NodeCast::from_ref(root.r());
root.traverse_preorder().filter(|&node| callback(node)).collect() root.traverse_preorder().filter(|&node| callback(node)).collect()
} }
}; };
NodeList::new_simple_list(*window, nodes) NodeList::new_simple_list(window.r(), nodes)
} }
fn get_html_element(self) -> Option<Temporary<HTMLHtmlElement>> { fn get_html_element(self) -> Option<Temporary<HTMLHtmlElement>> {
self.GetDocumentElement().root().and_then(|element| { self.GetDocumentElement()
HTMLHtmlElementCast::to_ref(*element) .root()
}).map(Temporary::from_rooted) .r()
.and_then(HTMLHtmlElementCast::to_ref)
.map(Temporary::from_rooted)
} }
} }
@ -554,20 +558,20 @@ impl<'a> DocumentMethods for JSRef<'a, Document> {
// http://dom.spec.whatwg.org/#dom-document-getelementsbytagname // http://dom.spec.whatwg.org/#dom-document-getelementsbytagname
fn GetElementsByTagName(self, tag_name: DOMString) -> Temporary<HTMLCollection> { fn GetElementsByTagName(self, tag_name: DOMString) -> Temporary<HTMLCollection> {
let window = self.window.root(); let window = self.window.root();
HTMLCollection::by_tag_name(*window, NodeCast::from_ref(self), tag_name) HTMLCollection::by_tag_name(window.r(), NodeCast::from_ref(self), tag_name)
} }
// http://dom.spec.whatwg.org/#dom-document-getelementsbytagnamens // http://dom.spec.whatwg.org/#dom-document-getelementsbytagnamens
fn GetElementsByTagNameNS(self, maybe_ns: Option<DOMString>, tag_name: DOMString) -> Temporary<HTMLCollection> { fn GetElementsByTagNameNS(self, maybe_ns: Option<DOMString>, tag_name: DOMString) -> Temporary<HTMLCollection> {
let window = self.window.root(); let window = self.window.root();
HTMLCollection::by_tag_name_ns(*window, NodeCast::from_ref(self), tag_name, maybe_ns) HTMLCollection::by_tag_name_ns(window.r(), NodeCast::from_ref(self), tag_name, maybe_ns)
} }
// http://dom.spec.whatwg.org/#dom-document-getelementsbyclassname // http://dom.spec.whatwg.org/#dom-document-getelementsbyclassname
fn GetElementsByClassName(self, classes: DOMString) -> Temporary<HTMLCollection> { fn GetElementsByClassName(self, classes: DOMString) -> Temporary<HTMLCollection> {
let window = self.window.root(); let window = self.window.root();
HTMLCollection::by_class_name(*window, NodeCast::from_ref(self), classes) HTMLCollection::by_class_name(window.r(), NodeCast::from_ref(self), classes)
} }
// http://dom.spec.whatwg.org/#dom-nonelementparentnode-getelementbyid // http://dom.spec.whatwg.org/#dom-nonelementparentnode-getelementbyid
@ -652,7 +656,7 @@ impl<'a> DocumentMethods for JSRef<'a, Document> {
let l_name = Atom::from_slice(local_name.as_slice()); let l_name = Atom::from_slice(local_name.as_slice());
let value = AttrValue::String("".into_string()); let value = AttrValue::String("".into_string());
Ok(Attr::new(*window, name, value, l_name, ns!(""), None, None)) Ok(Attr::new(window.r(), name, value, l_name, ns!(""), None, None))
} }
// http://dom.spec.whatwg.org/#dom-document-createdocumentfragment // http://dom.spec.whatwg.org/#dom-document-createdocumentfragment
@ -724,17 +728,17 @@ impl<'a> DocumentMethods for JSRef<'a, Document> {
match interface.as_slice().to_ascii_lower().as_slice() { match interface.as_slice().to_ascii_lower().as_slice() {
"uievents" | "uievent" => Ok(EventCast::from_temporary( "uievents" | "uievent" => Ok(EventCast::from_temporary(
UIEvent::new_uninitialized(*window))), UIEvent::new_uninitialized(window.r()))),
"mouseevents" | "mouseevent" => Ok(EventCast::from_temporary( "mouseevents" | "mouseevent" => Ok(EventCast::from_temporary(
MouseEvent::new_uninitialized(*window))), MouseEvent::new_uninitialized(window.r()))),
"customevent" => Ok(EventCast::from_temporary( "customevent" => Ok(EventCast::from_temporary(
CustomEvent::new_uninitialized(GlobalRef::Window(*window)))), CustomEvent::new_uninitialized(GlobalRef::Window(window.r())))),
"htmlevents" | "events" | "event" => Ok(Event::new_uninitialized( "htmlevents" | "events" | "event" => Ok(Event::new_uninitialized(
GlobalRef::Window(*window))), GlobalRef::Window(window.r()))),
"keyboardevent" | "keyevents" => Ok(EventCast::from_temporary( "keyboardevent" | "keyevents" => Ok(EventCast::from_temporary(
KeyboardEvent::new_uninitialized(*window))), KeyboardEvent::new_uninitialized(window.r()))),
"messageevent" => Ok(EventCast::from_temporary( "messageevent" => Ok(EventCast::from_temporary(
MessageEvent::new_uninitialized(GlobalRef::Window(*window)))), MessageEvent::new_uninitialized(GlobalRef::Window(window.r())))),
_ => Err(NotSupported) _ => Err(NotSupported)
} }
} }
@ -762,7 +766,7 @@ impl<'a> DocumentMethods for JSRef<'a, Document> {
fn Title(self) -> DOMString { fn Title(self) -> DOMString {
let mut title = String::new(); let mut title = String::new();
self.GetDocumentElement().root().map(|root| { self.GetDocumentElement().root().map(|root| {
let root: JSRef<Node> = NodeCast::from_ref(*root); let root: JSRef<Node> = NodeCast::from_ref(root.r());
root.traverse_preorder() root.traverse_preorder()
.find(|node| node.type_id() == NodeTypeId::Element(ElementTypeId::HTMLTitleElement)) .find(|node| node.type_id() == NodeTypeId::Element(ElementTypeId::HTMLTitleElement))
.map(|title_elem| { .map(|title_elem| {
@ -778,7 +782,7 @@ impl<'a> DocumentMethods for JSRef<'a, Document> {
// http://www.whatwg.org/specs/web-apps/current-work/#document.title // http://www.whatwg.org/specs/web-apps/current-work/#document.title
fn SetTitle(self, title: DOMString) -> ErrorResult { fn SetTitle(self, title: DOMString) -> ErrorResult {
self.GetDocumentElement().root().map(|root| { self.GetDocumentElement().root().map(|root| {
let root: JSRef<Node> = NodeCast::from_ref(*root); let root: JSRef<Node> = NodeCast::from_ref(root.r());
let head_node = root.traverse_preorder().find(|child| { let head_node = root.traverse_preorder().find(|child| {
child.type_id() == NodeTypeId::Element(ElementTypeId::HTMLHeadElement) child.type_id() == NodeTypeId::Element(ElementTypeId::HTMLHeadElement)
}); });
@ -794,16 +798,16 @@ impl<'a> DocumentMethods for JSRef<'a, Document> {
} }
if !title.is_empty() { if !title.is_empty() {
let new_text = self.CreateTextNode(title.clone()).root(); let new_text = self.CreateTextNode(title.clone()).root();
assert!(title_node.AppendChild(NodeCast::from_ref(*new_text)).is_ok()); assert!(title_node.AppendChild(NodeCast::from_ref(new_text.r())).is_ok());
} }
}, },
None => { None => {
let new_title = HTMLTitleElement::new("title".into_string(), None, self).root(); let new_title = HTMLTitleElement::new("title".into_string(), None, self).root();
let new_title: JSRef<Node> = NodeCast::from_ref(*new_title); let new_title: JSRef<Node> = NodeCast::from_ref(new_title.r());
if !title.is_empty() { if !title.is_empty() {
let new_text = self.CreateTextNode(title.clone()).root(); let new_text = self.CreateTextNode(title.clone()).root();
assert!(new_title.AppendChild(NodeCast::from_ref(*new_text)).is_ok()); assert!(new_title.AppendChild(NodeCast::from_ref(new_text.r())).is_ok());
} }
assert!(head.AppendChild(new_title).is_ok()); assert!(head.AppendChild(new_title).is_ok());
}, },
@ -817,7 +821,7 @@ impl<'a> DocumentMethods for JSRef<'a, Document> {
fn GetHead(self) -> Option<Temporary<HTMLHeadElement>> { fn GetHead(self) -> Option<Temporary<HTMLHeadElement>> {
self.get_html_element().and_then(|root| { self.get_html_element().and_then(|root| {
let root = root.root(); let root = root.root();
let node: JSRef<Node> = NodeCast::from_ref(*root); let node: JSRef<Node> = NodeCast::from_ref(root.r());
node.children().filter_map(HTMLHeadElementCast::to_ref).next().map(Temporary::from_rooted) node.children().filter_map(HTMLHeadElementCast::to_ref).next().map(Temporary::from_rooted)
}) })
} }
@ -826,7 +830,7 @@ impl<'a> DocumentMethods for JSRef<'a, Document> {
fn GetBody(self) -> Option<Temporary<HTMLElement>> { fn GetBody(self) -> Option<Temporary<HTMLElement>> {
self.get_html_element().and_then(|root| { self.get_html_element().and_then(|root| {
let root = root.root(); let root = root.root();
let node: JSRef<Node> = NodeCast::from_ref(*root); let node: JSRef<Node> = NodeCast::from_ref(root.r());
node.children().find(|child| { node.children().find(|child| {
match child.type_id() { match child.type_id() {
NodeTypeId::Element(ElementTypeId::HTMLBodyElement) | NodeTypeId::Element(ElementTypeId::HTMLBodyElement) |
@ -856,7 +860,7 @@ impl<'a> DocumentMethods for JSRef<'a, Document> {
// Step 2. // Step 2.
let old_body = self.GetBody().root(); let old_body = self.GetBody().root();
if old_body.as_ref().map(|body| **body) == Some(new_body) { if old_body.as_ref().map(|body| body.r()) == Some(new_body) {
return Ok(()); return Ok(());
} }
@ -867,10 +871,10 @@ impl<'a> DocumentMethods for JSRef<'a, Document> {
Some(ref root) => { Some(ref root) => {
let new_body: JSRef<Node> = NodeCast::from_ref(new_body); let new_body: JSRef<Node> = NodeCast::from_ref(new_body);
let root: JSRef<Node> = NodeCast::from_ref(**root); let root: JSRef<Node> = NodeCast::from_ref(root.r());
match old_body { match old_body {
Some(ref child) => { Some(ref child) => {
let child: JSRef<Node> = NodeCast::from_ref(**child); let child: JSRef<Node> = NodeCast::from_ref(child.r());
assert!(root.ReplaceChild(new_body, child).is_ok()) assert!(root.ReplaceChild(new_body, child).is_ok())
} }
@ -889,7 +893,7 @@ impl<'a> DocumentMethods for JSRef<'a, Document> {
None => return false, None => return false,
}; };
element.get_attribute(ns!(""), &atom!("name")).root().map_or(false, |attr| { element.get_attribute(ns!(""), &atom!("name")).root().map_or(false, |attr| {
attr.value().as_slice() == name.as_slice() attr.r().value().as_slice() == name.as_slice()
}) })
}) })
} }
@ -899,7 +903,7 @@ impl<'a> DocumentMethods for JSRef<'a, Document> {
let window = self.window.root(); let window = self.window.root();
let root = NodeCast::from_ref(self); let root = NodeCast::from_ref(self);
let filter = box ImagesFilter; let filter = box ImagesFilter;
HTMLCollection::create(*window, root, filter) HTMLCollection::create(window.r(), root, filter)
}) })
} }
@ -908,7 +912,7 @@ impl<'a> DocumentMethods for JSRef<'a, Document> {
let window = self.window.root(); let window = self.window.root();
let root = NodeCast::from_ref(self); let root = NodeCast::from_ref(self);
let filter = box EmbedsFilter; let filter = box EmbedsFilter;
HTMLCollection::create(*window, root, filter) HTMLCollection::create(window.r(), root, filter)
}) })
} }
@ -921,7 +925,7 @@ impl<'a> DocumentMethods for JSRef<'a, Document> {
let window = self.window.root(); let window = self.window.root();
let root = NodeCast::from_ref(self); let root = NodeCast::from_ref(self);
let filter = box LinksFilter; let filter = box LinksFilter;
HTMLCollection::create(*window, root, filter) HTMLCollection::create(window.r(), root, filter)
}) })
} }
@ -930,7 +934,7 @@ impl<'a> DocumentMethods for JSRef<'a, Document> {
let window = self.window.root(); let window = self.window.root();
let root = NodeCast::from_ref(self); let root = NodeCast::from_ref(self);
let filter = box FormsFilter; let filter = box FormsFilter;
HTMLCollection::create(*window, root, filter) HTMLCollection::create(window.r(), root, filter)
}) })
} }
@ -939,7 +943,7 @@ impl<'a> DocumentMethods for JSRef<'a, Document> {
let window = self.window.root(); let window = self.window.root();
let root = NodeCast::from_ref(self); let root = NodeCast::from_ref(self);
let filter = box ScriptsFilter; let filter = box ScriptsFilter;
HTMLCollection::create(*window, root, filter) HTMLCollection::create(window.r(), root, filter)
}) })
} }
@ -948,7 +952,7 @@ impl<'a> DocumentMethods for JSRef<'a, Document> {
let window = self.window.root(); let window = self.window.root();
let root = NodeCast::from_ref(self); let root = NodeCast::from_ref(self);
let filter = box AnchorsFilter; let filter = box AnchorsFilter;
HTMLCollection::create(*window, root, filter) HTMLCollection::create(window.r(), root, filter)
}) })
} }
@ -958,19 +962,19 @@ impl<'a> DocumentMethods for JSRef<'a, Document> {
let window = self.window.root(); let window = self.window.root();
let root = NodeCast::from_ref(self); let root = NodeCast::from_ref(self);
let filter = box AppletsFilter; let filter = box AppletsFilter;
HTMLCollection::create(*window, root, filter) HTMLCollection::create(window.r(), root, filter)
}) })
} }
fn Location(self) -> Temporary<Location> { fn Location(self) -> Temporary<Location> {
let window = self.window.root(); let window = self.window.root();
window.Location() window.r().Location()
} }
// http://dom.spec.whatwg.org/#dom-parentnode-children // http://dom.spec.whatwg.org/#dom-parentnode-children
fn Children(self) -> Temporary<HTMLCollection> { fn Children(self) -> Temporary<HTMLCollection> {
let window = self.window.root(); let window = self.window.root();
HTMLCollection::children(*window, NodeCast::from_ref(self)) HTMLCollection::children(window.r(), NodeCast::from_ref(self))
} }
// http://dom.spec.whatwg.org/#dom-parentnode-queryselector // http://dom.spec.whatwg.org/#dom-parentnode-queryselector

View file

@ -45,7 +45,7 @@ impl DocumentFragment {
let document = global.as_window().Document(); let document = global.as_window().Document();
let document = document.root(); let document = document.root();
Ok(DocumentFragment::new(*document)) Ok(DocumentFragment::new(document.r()))
} }
} }
@ -53,7 +53,7 @@ impl<'a> DocumentFragmentMethods for JSRef<'a, DocumentFragment> {
// http://dom.spec.whatwg.org/#dom-parentnode-children // http://dom.spec.whatwg.org/#dom-parentnode-children
fn Children(self) -> Temporary<HTMLCollection> { fn Children(self) -> Temporary<HTMLCollection> {
let window = window_from_node(self).root(); let window = window_from_node(self).root();
HTMLCollection::children(*window, NodeCast::from_ref(self)) HTMLCollection::children(window.r(), NodeCast::from_ref(self))
} }
// http://dom.spec.whatwg.org/#dom-parentnode-queryselector // http://dom.spec.whatwg.org/#dom-parentnode-queryselector

View file

@ -42,7 +42,7 @@ impl DOMImplementation {
pub fn new(document: JSRef<Document>) -> Temporary<DOMImplementation> { pub fn new(document: JSRef<Document>) -> Temporary<DOMImplementation> {
let window = document.window().root(); let window = document.window().root();
reflect_dom_object(box DOMImplementation::new_inherited(document), reflect_dom_object(box DOMImplementation::new_inherited(document),
GlobalRef::Window(*window), GlobalRef::Window(window.r()),
DOMImplementationBinding::Wrap) DOMImplementationBinding::Wrap)
} }
} }
@ -59,7 +59,7 @@ impl<'a> DOMImplementationMethods for JSRef<'a, DOMImplementation> {
// Step 3. // Step 3.
QName => { QName => {
let document = self.document.root(); let document = self.document.root();
Ok(DocumentType::new(qname, Some(pubid), Some(sysid), *document)) Ok(DocumentType::new(qname, Some(pubid), Some(sysid), document.r()))
} }
} }
} }
@ -68,23 +68,23 @@ impl<'a> DOMImplementationMethods for JSRef<'a, DOMImplementation> {
fn CreateDocument(self, namespace: Option<DOMString>, qname: DOMString, fn CreateDocument(self, namespace: Option<DOMString>, qname: DOMString,
maybe_doctype: Option<JSRef<DocumentType>>) -> Fallible<Temporary<Document>> { maybe_doctype: Option<JSRef<DocumentType>>) -> Fallible<Temporary<Document>> {
let doc = self.document.root(); let doc = self.document.root();
let win = doc.window().root(); let win = doc.r().window().root();
// Step 1. // Step 1.
let doc = Document::new(*win, None, IsHTMLDocument::NonHTMLDocument, let doc = Document::new(win.r(), None, IsHTMLDocument::NonHTMLDocument,
None, DocumentSource::NotFromParser).root(); None, DocumentSource::NotFromParser).root();
// Step 2-3. // Step 2-3.
let maybe_elem = if qname.is_empty() { let maybe_elem = if qname.is_empty() {
None None
} else { } else {
match doc.CreateElementNS(namespace, qname) { match doc.r().CreateElementNS(namespace, qname) {
Err(error) => return Err(error), Err(error) => return Err(error),
Ok(elem) => Some(elem) Ok(elem) => Some(elem)
} }
}; };
{ {
let doc_node: JSRef<Node> = NodeCast::from_ref(*doc); let doc_node: JSRef<Node> = NodeCast::from_ref(doc.r());
// Step 4. // Step 4.
match maybe_doctype { match maybe_doctype {
@ -99,7 +99,7 @@ impl<'a> DOMImplementationMethods for JSRef<'a, DOMImplementation> {
match maybe_elem.root() { match maybe_elem.root() {
None => (), None => (),
Some(elem) => { Some(elem) => {
assert!(doc_node.AppendChild(NodeCast::from_ref(*elem)).is_ok()) assert!(doc_node.AppendChild(NodeCast::from_ref(elem.r())).is_ok())
} }
} }
} }
@ -108,60 +108,60 @@ impl<'a> DOMImplementationMethods for JSRef<'a, DOMImplementation> {
// FIXME: https://github.com/mozilla/servo/issues/1522 // FIXME: https://github.com/mozilla/servo/issues/1522
// Step 7. // Step 7.
Ok(Temporary::from_rooted(*doc)) Ok(Temporary::from_rooted(doc.r()))
} }
// http://dom.spec.whatwg.org/#dom-domimplementation-createhtmldocument // http://dom.spec.whatwg.org/#dom-domimplementation-createhtmldocument
fn CreateHTMLDocument(self, title: Option<DOMString>) -> Temporary<Document> { fn CreateHTMLDocument(self, title: Option<DOMString>) -> Temporary<Document> {
let document = self.document.root(); let document = self.document.root();
let win = document.window().root(); let win = document.r().window().root();
// Step 1-2. // Step 1-2.
let doc = Document::new(*win, None, IsHTMLDocument::HTMLDocument, None, let doc = Document::new(win.r(), None, IsHTMLDocument::HTMLDocument, None,
DocumentSource::NotFromParser).root(); DocumentSource::NotFromParser).root();
let doc_node: JSRef<Node> = NodeCast::from_ref(*doc); let doc_node: JSRef<Node> = NodeCast::from_ref(doc.r());
{ {
// Step 3. // Step 3.
let doc_type = DocumentType::new("html".into_string(), None, None, *doc).root(); let doc_type = DocumentType::new("html".into_string(), None, None, doc.r()).root();
assert!(doc_node.AppendChild(NodeCast::from_ref(*doc_type)).is_ok()); assert!(doc_node.AppendChild(NodeCast::from_ref(doc_type.r())).is_ok());
} }
{ {
// Step 4. // Step 4.
let doc_html: Root<Node> = NodeCast::from_temporary(HTMLHtmlElement::new("html".into_string(), None, *doc)).root(); let doc_html: Root<Node> = NodeCast::from_temporary(HTMLHtmlElement::new("html".into_string(), None, doc.r())).root();
assert!(doc_node.AppendChild(*doc_html).is_ok()); assert!(doc_node.AppendChild(doc_html.r()).is_ok());
{ {
// Step 5. // Step 5.
let doc_head: Root<Node> = NodeCast::from_temporary(HTMLHeadElement::new("head".into_string(), None, *doc)).root(); let doc_head: Root<Node> = NodeCast::from_temporary(HTMLHeadElement::new("head".into_string(), None, doc.r())).root();
assert!(doc_html.AppendChild(*doc_head).is_ok()); assert!(doc_html.r().AppendChild(doc_head.r()).is_ok());
// Step 6. // Step 6.
match title { match title {
None => (), None => (),
Some(title_str) => { Some(title_str) => {
// Step 6.1. // Step 6.1.
let doc_title: Root<Node> = NodeCast::from_temporary(HTMLTitleElement::new("title".into_string(), None, *doc)).root(); let doc_title: Root<Node> = NodeCast::from_temporary(HTMLTitleElement::new("title".into_string(), None, doc.r())).root();
assert!(doc_head.AppendChild(*doc_title).is_ok()); assert!(doc_head.r().AppendChild(doc_title.r()).is_ok());
// Step 6.2. // Step 6.2.
let title_text: Root<Text> = Text::new(title_str, *doc).root(); let title_text: Root<Text> = Text::new(title_str, doc.r()).root();
assert!(doc_title.AppendChild(NodeCast::from_ref(*title_text)).is_ok()); assert!(doc_title.r().AppendChild(NodeCast::from_ref(title_text.r())).is_ok());
} }
} }
} }
// Step 7. // Step 7.
let doc_body: Root<HTMLBodyElement> = HTMLBodyElement::new("body".into_string(), None, *doc).root(); let doc_body: Root<HTMLBodyElement> = HTMLBodyElement::new("body".into_string(), None, doc.r()).root();
assert!(doc_html.AppendChild(NodeCast::from_ref(*doc_body)).is_ok()); assert!(doc_html.r().AppendChild(NodeCast::from_ref(doc_body.r())).is_ok());
} }
// Step 8. // Step 8.
// FIXME: https://github.com/mozilla/servo/issues/1522 // FIXME: https://github.com/mozilla/servo/issues/1522
// Step 9. // Step 9.
Temporary::from_rooted(*doc) Temporary::from_rooted(doc.r())
} }
// https://dom.spec.whatwg.org/#dom-domimplementation-hasfeature // https://dom.spec.whatwg.org/#dom-domimplementation-hasfeature

View file

@ -47,22 +47,22 @@ impl<'a> DOMParserMethods for JSRef<'a, DOMParser> {
s: DOMString, s: DOMString,
ty: DOMParserBinding::SupportedType) ty: DOMParserBinding::SupportedType)
-> Fallible<Temporary<Document>> { -> Fallible<Temporary<Document>> {
let window = self.window.root().clone(); let window = self.window.root();
let url = window.get_url(); let url = window.r().get_url();
let content_type = DOMParserBinding::SupportedTypeValues::strings[ty as uint].into_string(); let content_type = DOMParserBinding::SupportedTypeValues::strings[ty as uint].into_string();
match ty { match ty {
Text_html => { Text_html => {
let document = Document::new(window, Some(url.clone()), let document = Document::new(window.r(), Some(url.clone()),
IsHTMLDocument::HTMLDocument, IsHTMLDocument::HTMLDocument,
Some(content_type), Some(content_type),
DocumentSource::FromParser).root().clone(); DocumentSource::FromParser).root();
parse_html(document, HTMLInput::InputString(s), &url); parse_html(document.r(), HTMLInput::InputString(s), &url);
document.set_ready_state(DocumentReadyState::Complete); document.r().set_ready_state(DocumentReadyState::Complete);
Ok(Temporary::from_rooted(document)) Ok(Temporary::from_rooted(document.r()))
} }
Text_xml => { Text_xml => {
//FIXME: this should probably be FromParser when we actually parse the string (#3756). //FIXME: this should probably be FromParser when we actually parse the string (#3756).
Ok(Document::new(window, Some(url.clone()), Ok(Document::new(window.r(), Some(url.clone()),
IsHTMLDocument::NonHTMLDocument, IsHTMLDocument::NonHTMLDocument,
Some(content_type), Some(content_type),
DocumentSource::NotFromParser)) DocumentSource::NotFromParser))

View file

@ -29,7 +29,7 @@ impl DOMStringMap {
pub fn new(element: JSRef<HTMLElement>) -> Temporary<DOMStringMap> { pub fn new(element: JSRef<HTMLElement>) -> Temporary<DOMStringMap> {
let window = window_from_node(element).root(); let window = window_from_node(element).root();
reflect_dom_object(box DOMStringMap::new_inherited(element), reflect_dom_object(box DOMStringMap::new_inherited(element),
GlobalRef::Window(window.root_ref()), DOMStringMapBinding::Wrap) GlobalRef::Window(window.r()), DOMStringMapBinding::Wrap)
} }
} }
@ -41,17 +41,17 @@ impl<'a> DOMStringMapMethods for JSRef<'a, DOMStringMap> {
fn NamedDeleter(self, name: DOMString) { fn NamedDeleter(self, name: DOMString) {
let element = self.element.root(); let element = self.element.root();
element.delete_custom_attr(name) element.r().delete_custom_attr(name)
} }
fn NamedSetter(self, name: DOMString, value: DOMString) -> ErrorResult { fn NamedSetter(self, name: DOMString, value: DOMString) -> ErrorResult {
let element = self.element.root(); let element = self.element.root();
element.set_custom_attr(name, value) element.r().set_custom_attr(name, value)
} }
fn NamedGetter(self, name: DOMString, found: &mut bool) -> DOMString { fn NamedGetter(self, name: DOMString, found: &mut bool) -> DOMString {
let element = self.element.root(); let element = self.element.root();
match element.get_custom_attr(name) { match element.r().get_custom_attr(name) {
Some(value) => { Some(value) => {
*found = true; *found = true;
value.clone() value.clone()

View file

@ -35,7 +35,7 @@ impl DOMTokenList {
pub fn new(element: JSRef<Element>, local_name: &Atom) -> Temporary<DOMTokenList> { pub fn new(element: JSRef<Element>, local_name: &Atom) -> Temporary<DOMTokenList> {
let window = window_from_node(element).root(); let window = window_from_node(element).root();
reflect_dom_object(box DOMTokenList::new_inherited(element, local_name.clone()), reflect_dom_object(box DOMTokenList::new_inherited(element, local_name.clone()),
GlobalRef::Window(*window), GlobalRef::Window(window.r()),
DOMTokenListBinding::Wrap) DOMTokenListBinding::Wrap)
} }
} }
@ -48,7 +48,7 @@ trait PrivateDOMTokenListHelpers {
impl<'a> PrivateDOMTokenListHelpers for JSRef<'a, DOMTokenList> { impl<'a> PrivateDOMTokenListHelpers for JSRef<'a, DOMTokenList> {
fn attribute(self) -> Option<Temporary<Attr>> { fn attribute(self) -> Option<Temporary<Attr>> {
let element = self.element.root(); let element = self.element.root();
element.get_attribute(ns!(""), &self.local_name) element.r().get_attribute(ns!(""), &self.local_name)
} }
fn check_token_exceptions<'a>(self, token: &'a str) -> Fallible<Atom> { fn check_token_exceptions<'a>(self, token: &'a str) -> Fallible<Atom> {
@ -65,13 +65,13 @@ impl<'a> DOMTokenListMethods for JSRef<'a, DOMTokenList> {
// http://dom.spec.whatwg.org/#dom-domtokenlist-length // http://dom.spec.whatwg.org/#dom-domtokenlist-length
fn Length(self) -> u32 { fn Length(self) -> u32 {
self.attribute().root().map(|attr| { self.attribute().root().map(|attr| {
attr.value().tokens().map(|tokens| tokens.len()).unwrap_or(0) attr.r().value().tokens().map(|tokens| tokens.len()).unwrap_or(0)
}).unwrap_or(0) as u32 }).unwrap_or(0) as u32
} }
// http://dom.spec.whatwg.org/#dom-domtokenlist-item // http://dom.spec.whatwg.org/#dom-domtokenlist-item
fn Item(self, index: u32) -> Option<DOMString> { fn Item(self, index: u32) -> Option<DOMString> {
self.attribute().root().and_then(|attr| attr.value().tokens().and_then(|tokens| { self.attribute().root().and_then(|attr| attr.r().value().tokens().and_then(|tokens| {
tokens.get(index as uint).map(|token| token.as_slice().into_string()) tokens.get(index as uint).map(|token| token.as_slice().into_string())
})) }))
} }
@ -86,7 +86,8 @@ impl<'a> DOMTokenListMethods for JSRef<'a, DOMTokenList> {
fn Contains(self, token: DOMString) -> Fallible<bool> { fn Contains(self, token: DOMString) -> Fallible<bool> {
self.check_token_exceptions(token.as_slice()).map(|token| { self.check_token_exceptions(token.as_slice()).map(|token| {
self.attribute().root().map(|attr| { self.attribute().root().map(|attr| {
attr.value() attr.r()
.value()
.tokens() .tokens()
.expect("Should have parsed this attribute") .expect("Should have parsed this attribute")
.iter() .iter()
@ -98,42 +99,42 @@ impl<'a> DOMTokenListMethods for JSRef<'a, DOMTokenList> {
// https://dom.spec.whatwg.org/#dom-domtokenlist-add // https://dom.spec.whatwg.org/#dom-domtokenlist-add
fn Add(self, tokens: Vec<DOMString>) -> ErrorResult { fn Add(self, tokens: Vec<DOMString>) -> ErrorResult {
let element = self.element.root(); let element = self.element.root();
let mut atoms = element.get_tokenlist_attribute(&self.local_name); let mut atoms = element.r().get_tokenlist_attribute(&self.local_name);
for token in tokens.iter() { for token in tokens.iter() {
let token = try!(self.check_token_exceptions(token.as_slice())); let token = try!(self.check_token_exceptions(token.as_slice()));
if !atoms.iter().any(|atom| *atom == token) { if !atoms.iter().any(|atom| *atom == token) {
atoms.push(token); atoms.push(token);
} }
} }
element.set_atomic_tokenlist_attribute(&self.local_name, atoms); element.r().set_atomic_tokenlist_attribute(&self.local_name, atoms);
Ok(()) Ok(())
} }
// https://dom.spec.whatwg.org/#dom-domtokenlist-remove // https://dom.spec.whatwg.org/#dom-domtokenlist-remove
fn Remove(self, tokens: Vec<DOMString>) -> ErrorResult { fn Remove(self, tokens: Vec<DOMString>) -> ErrorResult {
let element = self.element.root(); let element = self.element.root();
let mut atoms = element.get_tokenlist_attribute(&self.local_name); let mut atoms = element.r().get_tokenlist_attribute(&self.local_name);
for token in tokens.iter() { for token in tokens.iter() {
let token = try!(self.check_token_exceptions(token.as_slice())); let token = try!(self.check_token_exceptions(token.as_slice()));
atoms.iter().position(|atom| *atom == token).and_then(|index| { atoms.iter().position(|atom| *atom == token).and_then(|index| {
atoms.remove(index) atoms.remove(index)
}); });
} }
element.set_atomic_tokenlist_attribute(&self.local_name, atoms); element.r().set_atomic_tokenlist_attribute(&self.local_name, atoms);
Ok(()) Ok(())
} }
// https://dom.spec.whatwg.org/#dom-domtokenlist-toggle // https://dom.spec.whatwg.org/#dom-domtokenlist-toggle
fn Toggle(self, token: DOMString, force: Option<bool>) -> Fallible<bool> { fn Toggle(self, token: DOMString, force: Option<bool>) -> Fallible<bool> {
let element = self.element.root(); let element = self.element.root();
let mut atoms = element.get_tokenlist_attribute(&self.local_name); let mut atoms = element.r().get_tokenlist_attribute(&self.local_name);
let token = try!(self.check_token_exceptions(token.as_slice())); let token = try!(self.check_token_exceptions(token.as_slice()));
match atoms.iter().position(|atom| *atom == token) { match atoms.iter().position(|atom| *atom == token) {
Some(index) => match force { Some(index) => match force {
Some(true) => Ok(true), Some(true) => Ok(true),
_ => { _ => {
atoms.remove(index); atoms.remove(index);
element.set_atomic_tokenlist_attribute(&self.local_name, atoms); element.r().set_atomic_tokenlist_attribute(&self.local_name, atoms);
Ok(false) Ok(false)
} }
}, },
@ -141,7 +142,7 @@ impl<'a> DOMTokenListMethods for JSRef<'a, DOMTokenList> {
Some(false) => Ok(false), Some(false) => Ok(false),
_ => { _ => {
atoms.push(token); atoms.push(token);
element.set_atomic_tokenlist_attribute(&self.local_name, atoms); element.r().set_atomic_tokenlist_attribute(&self.local_name, atoms);
Ok(true) Ok(true)
} }
} }

View file

@ -515,9 +515,9 @@ impl<'a> ElementHelpers<'a> for JSRef<'a, Element> {
let attrs = self.Attributes().root(); let attrs = self.Attributes().root();
let mut i = 0; let mut i = 0;
let mut summarized = vec!(); let mut summarized = vec!();
while i < attrs.Length() { while i < attrs.r().Length() {
let attr = attrs.Item(i).unwrap().root(); let attr = attrs.r().Item(i).unwrap().root();
summarized.push(attr.summarize()); summarized.push(attr.r().summarize());
i += 1; i += 1;
} }
summarized summarized
@ -658,14 +658,14 @@ pub trait AttributeHandlers {
impl<'a> AttributeHandlers for JSRef<'a, Element> { impl<'a> AttributeHandlers for JSRef<'a, Element> {
fn get_attribute(self, namespace: Namespace, local_name: &Atom) -> Option<Temporary<Attr>> { fn get_attribute(self, namespace: Namespace, local_name: &Atom) -> Option<Temporary<Attr>> {
self.get_attributes(local_name).iter().map(|attr| attr.root()) self.get_attributes(local_name).iter().map(|attr| attr.root())
.find(|attr| *attr.namespace() == namespace) .find(|attr| *attr.r().namespace() == namespace)
.map(|x| Temporary::from_rooted(*x)) .map(|x| Temporary::from_rooted(x.r()))
} }
fn get_attributes(self, local_name: &Atom) -> Vec<Temporary<Attr>> { fn get_attributes(self, local_name: &Atom) -> Vec<Temporary<Attr>> {
self.attrs.borrow().iter().map(|attr| attr.root()).filter_map(|attr| { self.attrs.borrow().iter().map(|attr| attr.root()).filter_map(|attr| {
if *attr.local_name() == *local_name { if *attr.r().local_name() == *local_name {
Some(Temporary::from_rooted(*attr)) Some(Temporary::from_rooted(attr.r()))
} else { } else {
None None
} }
@ -678,7 +678,7 @@ impl<'a> AttributeHandlers for JSRef<'a, Element> {
prefix: Option<DOMString>) { prefix: Option<DOMString>) {
// Don't set if the attribute already exists, so we can handle add_attrs_if_missing // Don't set if the attribute already exists, so we can handle add_attrs_if_missing
if self.attrs.borrow().iter().map(|attr| attr.root()) if self.attrs.borrow().iter().map(|attr| attr.root())
.any(|a| *a.local_name() == qname.local && *a.namespace() == qname.ns) { .any(|a| *a.r().local_name() == qname.local && *a.r().namespace() == qname.ns) {
return; return;
} }
@ -723,19 +723,19 @@ impl<'a> AttributeHandlers for JSRef<'a, Element> {
prefix: Option<DOMString>, cb: |JSRef<Attr>| -> bool) { prefix: Option<DOMString>, cb: |JSRef<Attr>| -> bool) {
let idx = self.attrs.borrow().iter() let idx = self.attrs.borrow().iter()
.map(|attr| attr.root()) .map(|attr| attr.root())
.position(|attr| cb(*attr)); .position(|attr| cb(attr.r()));
let (idx, set_type) = match idx { let (idx, set_type) = match idx {
Some(idx) => (idx, AttrSettingType::ReplacedAttr), Some(idx) => (idx, AttrSettingType::ReplacedAttr),
None => { None => {
let window = window_from_node(self).root(); let window = window_from_node(self).root();
let attr = Attr::new(*window, local_name, value.clone(), let attr = Attr::new(window.r(), local_name, value.clone(),
name, namespace.clone(), prefix, Some(self)); name, namespace.clone(), prefix, Some(self));
self.attrs.borrow_mut().push_unrooted(&attr); self.attrs.borrow_mut().push_unrooted(&attr);
(self.attrs.borrow().len() - 1, AttrSettingType::FirstSetAttr) (self.attrs.borrow().len() - 1, AttrSettingType::FirstSetAttr)
} }
}; };
(*self.attrs.borrow())[idx].root().set_value(set_type, value, self); (*self.attrs.borrow())[idx].root().r().set_value(set_type, value, self);
} }
fn parse_attribute(self, namespace: &Namespace, local_name: &Atom, fn parse_attribute(self, namespace: &Namespace, local_name: &Atom,
@ -753,7 +753,7 @@ impl<'a> AttributeHandlers for JSRef<'a, Element> {
let local_name = Atom::from_slice(local_name); let local_name = Atom::from_slice(local_name);
let idx = self.attrs.borrow().iter().map(|attr| attr.root()).position(|attr| { let idx = self.attrs.borrow().iter().map(|attr| attr.root()).position(|attr| {
*attr.local_name() == local_name *attr.r().local_name() == local_name
}); });
match idx { match idx {
@ -761,7 +761,7 @@ impl<'a> AttributeHandlers for JSRef<'a, Element> {
Some(idx) => { Some(idx) => {
if namespace == ns!("") { if namespace == ns!("") {
let attr = (*self.attrs.borrow())[idx].root(); let attr = (*self.attrs.borrow())[idx].root();
vtable_for(&NodeCast::from_ref(self)).before_remove_attr(*attr); vtable_for(&NodeCast::from_ref(self)).before_remove_attr(attr.r());
} }
self.attrs.borrow_mut().remove(idx); self.attrs.borrow_mut().remove(idx);
@ -770,9 +770,9 @@ impl<'a> AttributeHandlers for JSRef<'a, Element> {
if node.is_in_doc() { if node.is_in_doc() {
let document = document_from_node(self).root(); let document = document_from_node(self).root();
if local_name == atom!("style") { if local_name == atom!("style") {
document.content_changed(node, NodeDamage::NodeStyleDamaged); document.r().content_changed(node, NodeDamage::NodeStyleDamaged);
} else { } else {
document.content_changed(node, NodeDamage::OtherNodeDamage); document.r().content_changed(node, NodeDamage::OtherNodeDamage);
} }
} }
} }
@ -781,7 +781,7 @@ impl<'a> AttributeHandlers for JSRef<'a, Element> {
fn has_class(&self, name: &Atom) -> bool { fn has_class(&self, name: &Atom) -> bool {
self.get_attribute(ns!(""), &atom!("class")).root().map(|attr| { self.get_attribute(ns!(""), &atom!("class")).root().map(|attr| {
attr.value().tokens().map(|tokens| { attr.r().value().tokens().map(|tokens| {
tokens.iter().any(|atom| atom == name) tokens.iter().any(|atom| atom == name)
}).unwrap_or(false) }).unwrap_or(false)
}).unwrap_or(false) }).unwrap_or(false)
@ -798,7 +798,7 @@ impl<'a> AttributeHandlers for JSRef<'a, Element> {
!ch.is_ascii() || ch.to_ascii().to_lowercase() == ch.to_ascii() !ch.is_ascii() || ch.to_ascii().to_lowercase() == ch.to_ascii()
})); }));
self.attrs.borrow().iter().map(|attr| attr.root()).any(|attr| { self.attrs.borrow().iter().map(|attr| attr.root()).any(|attr| {
*attr.local_name() == *name && *attr.namespace() == ns!("") *attr.r().local_name() == *name && *attr.r().namespace() == ns!("")
}) })
} }
@ -818,7 +818,7 @@ impl<'a> AttributeHandlers for JSRef<'a, Element> {
} }
let url = self.get_string_attribute(name); let url = self.get_string_attribute(name);
let doc = document_from_node(self).root(); let doc = document_from_node(self).root();
let base = doc.url(); let base = doc.r().url();
// https://html.spec.whatwg.org/multipage/infrastructure.html#reflect // https://html.spec.whatwg.org/multipage/infrastructure.html#reflect
// XXXManishearth this doesn't handle `javascript:` urls properly // XXXManishearth this doesn't handle `javascript:` urls properly
match UrlParser::new().base_url(base).parse(url.as_slice()) { match UrlParser::new().base_url(base).parse(url.as_slice()) {
@ -832,7 +832,7 @@ impl<'a> AttributeHandlers for JSRef<'a, Element> {
fn get_string_attribute(self, name: &Atom) -> DOMString { fn get_string_attribute(self, name: &Atom) -> DOMString {
match self.get_attribute(ns!(""), name) { match self.get_attribute(ns!(""), name) {
Some(x) => x.root().Value(), Some(x) => x.root().r().Value(),
None => "".into_string() None => "".into_string()
} }
} }
@ -843,7 +843,8 @@ impl<'a> AttributeHandlers for JSRef<'a, Element> {
fn get_tokenlist_attribute(self, name: &Atom) -> Vec<Atom> { fn get_tokenlist_attribute(self, name: &Atom) -> Vec<Atom> {
self.get_attribute(ns!(""), name).root().map(|attr| { self.get_attribute(ns!(""), name).root().map(|attr| {
attr.value() attr.r()
.value()
.tokens() .tokens()
.expect("Expected a TokenListAttrValue") .expect("Expected a TokenListAttrValue")
.to_vec() .to_vec()
@ -867,7 +868,7 @@ impl<'a> AttributeHandlers for JSRef<'a, Element> {
let attribute = self.get_attribute(ns!(""), name).root(); let attribute = self.get_attribute(ns!(""), name).root();
match attribute { match attribute {
Some(attribute) => { Some(attribute) => {
match *attribute.value() { match *attribute.r().value() {
AttrValue::UInt(_, value) => value, AttrValue::UInt(_, value) => value,
_ => panic!("Expected an AttrValue::UInt: \ _ => panic!("Expected an AttrValue::UInt: \
implement parse_plain_attribute"), implement parse_plain_attribute"),
@ -949,8 +950,8 @@ impl<'a> ElementMethods for JSRef<'a, Element> {
let node: JSRef<Node> = NodeCast::from_ref(self); let node: JSRef<Node> = NodeCast::from_ref(self);
node.owner_doc().root() node.owner_doc().root()
}; };
let window = doc.window().root(); let window = doc.r().window().root();
NamedNodeMap::new(*window, self) NamedNodeMap::new(window.r(), self)
}) })
} }
@ -958,7 +959,7 @@ impl<'a> ElementMethods for JSRef<'a, Element> {
fn GetAttribute(self, name: DOMString) -> Option<DOMString> { fn GetAttribute(self, name: DOMString) -> Option<DOMString> {
let name = self.parsed_name(name); let name = self.parsed_name(name);
self.get_attribute(ns!(""), &Atom::from_slice(name.as_slice())).root() self.get_attribute(ns!(""), &Atom::from_slice(name.as_slice())).root()
.map(|s| s.Value()) .map(|s| s.r().Value())
} }
// http://dom.spec.whatwg.org/#dom-element-getattributens // http://dom.spec.whatwg.org/#dom-element-getattributens
@ -967,7 +968,7 @@ impl<'a> ElementMethods for JSRef<'a, Element> {
local_name: DOMString) -> Option<DOMString> { local_name: DOMString) -> Option<DOMString> {
let namespace = namespace::from_domstring(namespace); let namespace = namespace::from_domstring(namespace);
self.get_attribute(namespace, &Atom::from_slice(local_name.as_slice())).root() self.get_attribute(namespace, &Atom::from_slice(local_name.as_slice())).root()
.map(|attr| attr.Value()) .map(|attr| attr.r().Value())
} }
// http://dom.spec.whatwg.org/#dom-element-setattribute // http://dom.spec.whatwg.org/#dom-element-setattribute
@ -1084,18 +1085,18 @@ impl<'a> ElementMethods for JSRef<'a, Element> {
fn GetElementsByTagName(self, localname: DOMString) -> Temporary<HTMLCollection> { fn GetElementsByTagName(self, localname: DOMString) -> Temporary<HTMLCollection> {
let window = window_from_node(self).root(); let window = window_from_node(self).root();
HTMLCollection::by_tag_name(*window, NodeCast::from_ref(self), localname) HTMLCollection::by_tag_name(window.r(), NodeCast::from_ref(self), localname)
} }
fn GetElementsByTagNameNS(self, maybe_ns: Option<DOMString>, fn GetElementsByTagNameNS(self, maybe_ns: Option<DOMString>,
localname: DOMString) -> Temporary<HTMLCollection> { localname: DOMString) -> Temporary<HTMLCollection> {
let window = window_from_node(self).root(); let window = window_from_node(self).root();
HTMLCollection::by_tag_name_ns(*window, NodeCast::from_ref(self), localname, maybe_ns) HTMLCollection::by_tag_name_ns(window.r(), NodeCast::from_ref(self), localname, maybe_ns)
} }
fn GetElementsByClassName(self, classes: DOMString) -> Temporary<HTMLCollection> { fn GetElementsByClassName(self, classes: DOMString) -> Temporary<HTMLCollection> {
let window = window_from_node(self).root(); let window = window_from_node(self).root();
HTMLCollection::by_class_name(*window, NodeCast::from_ref(self), classes) HTMLCollection::by_class_name(window.r(), NodeCast::from_ref(self), classes)
} }
// http://dev.w3.org/csswg/cssom-view/#dom-element-getclientrects // http://dev.w3.org/csswg/cssom-view/#dom-element-getclientrects
@ -1105,14 +1106,14 @@ impl<'a> ElementMethods for JSRef<'a, Element> {
let rects = node.get_content_boxes(); let rects = node.get_content_boxes();
let rects: Vec<Root<DOMRect>> = rects.iter().map(|r| { let rects: Vec<Root<DOMRect>> = rects.iter().map(|r| {
DOMRect::new( DOMRect::new(
*win, win.r(),
r.origin.y, r.origin.y,
r.origin.y + r.size.height, r.origin.y + r.size.height,
r.origin.x, r.origin.x,
r.origin.x + r.size.width).root() r.origin.x + r.size.width).root()
}).collect(); }).collect();
DOMRectList::new(*win, rects.iter().map(|rect| rect.deref().clone()).collect()) DOMRectList::new(win.r(), rects.iter().map(|rect| rect.r()).collect())
} }
// http://dev.w3.org/csswg/cssom-view/#dom-element-getboundingclientrect // http://dev.w3.org/csswg/cssom-view/#dom-element-getboundingclientrect
@ -1121,7 +1122,7 @@ impl<'a> ElementMethods for JSRef<'a, Element> {
let node: JSRef<Node> = NodeCast::from_ref(self); let node: JSRef<Node> = NodeCast::from_ref(self);
let rect = node.get_bounding_content_box(); let rect = node.get_bounding_content_box();
DOMRect::new( DOMRect::new(
*win, win.r(),
rect.origin.y, rect.origin.y,
rect.origin.y + rect.size.height, rect.origin.y + rect.size.height,
rect.origin.x, rect.origin.x,
@ -1140,7 +1141,7 @@ impl<'a> ElementMethods for JSRef<'a, Element> {
// http://dom.spec.whatwg.org/#dom-parentnode-children // http://dom.spec.whatwg.org/#dom-parentnode-children
fn Children(self) -> Temporary<HTMLCollection> { fn Children(self) -> Temporary<HTMLCollection> {
let window = window_from_node(self).root(); let window = window_from_node(self).root();
HTMLCollection::children(*window, NodeCast::from_ref(self)) HTMLCollection::children(window.r(), NodeCast::from_ref(self))
} }
// http://dom.spec.whatwg.org/#dom-parentnode-queryselector // http://dom.spec.whatwg.org/#dom-parentnode-queryselector
@ -1206,13 +1207,13 @@ impl<'a> VirtualMethods for JSRef<'a, Element> {
// Modifying the `style` attribute might change style. // Modifying the `style` attribute might change style.
let node: JSRef<Node> = NodeCast::from_ref(*self); let node: JSRef<Node> = NodeCast::from_ref(*self);
let doc = document_from_node(*self).root(); let doc = document_from_node(*self).root();
let base_url = doc.url().clone(); let base_url = doc.r().url().clone();
let value = attr.value(); let value = attr.value();
let style = Some(style::parse_style_attribute(value.as_slice(), &base_url)); let style = Some(style::parse_style_attribute(value.as_slice(), &base_url));
*self.style_attribute.borrow_mut() = style; *self.style_attribute.borrow_mut() = style;
if node.is_in_doc() { if node.is_in_doc() {
doc.content_changed(node, NodeDamage::NodeStyleDamaged); doc.r().content_changed(node, NodeDamage::NodeStyleDamaged);
} }
} }
&atom!("class") => { &atom!("class") => {
@ -1220,7 +1221,7 @@ impl<'a> VirtualMethods for JSRef<'a, Element> {
let node: JSRef<Node> = NodeCast::from_ref(*self); let node: JSRef<Node> = NodeCast::from_ref(*self);
if node.is_in_doc() { if node.is_in_doc() {
let document = document_from_node(*self).root(); let document = document_from_node(*self).root();
document.content_changed(node, NodeDamage::NodeStyleDamaged); document.r().content_changed(node, NodeDamage::NodeStyleDamaged);
} }
} }
&atom!("id") => { &atom!("id") => {
@ -1231,9 +1232,9 @@ impl<'a> VirtualMethods for JSRef<'a, Element> {
let doc = document_from_node(*self).root(); let doc = document_from_node(*self).root();
if !value.as_slice().is_empty() { if !value.as_slice().is_empty() {
let value = Atom::from_slice(value.as_slice()); let value = Atom::from_slice(value.as_slice());
doc.register_named_element(*self, value); doc.r().register_named_element(*self, value);
} }
doc.content_changed(node, NodeDamage::NodeStyleDamaged); doc.r().content_changed(node, NodeDamage::NodeStyleDamaged);
} }
} }
_ => { _ => {
@ -1241,7 +1242,7 @@ impl<'a> VirtualMethods for JSRef<'a, Element> {
let node: JSRef<Node> = NodeCast::from_ref(*self); let node: JSRef<Node> = NodeCast::from_ref(*self);
if node.is_in_doc() { if node.is_in_doc() {
let document = document_from_node(*self).root(); let document = document_from_node(*self).root();
document.content_changed(node, NodeDamage::OtherNodeDamage); document.r().content_changed(node, NodeDamage::OtherNodeDamage);
} }
} }
} }
@ -1261,7 +1262,7 @@ impl<'a> VirtualMethods for JSRef<'a, Element> {
let node: JSRef<Node> = NodeCast::from_ref(*self); let node: JSRef<Node> = NodeCast::from_ref(*self);
if node.is_in_doc() { if node.is_in_doc() {
let doc = document_from_node(*self).root(); let doc = document_from_node(*self).root();
doc.content_changed(node, NodeDamage::NodeStyleDamaged); doc.r().content_changed(node, NodeDamage::NodeStyleDamaged);
} }
} }
&atom!("id") => { &atom!("id") => {
@ -1272,9 +1273,9 @@ impl<'a> VirtualMethods for JSRef<'a, Element> {
let doc = document_from_node(*self).root(); let doc = document_from_node(*self).root();
if !value.as_slice().is_empty() { if !value.as_slice().is_empty() {
let value = Atom::from_slice(value.as_slice()); let value = Atom::from_slice(value.as_slice());
doc.unregister_named_element(*self, value); doc.r().unregister_named_element(*self, value);
} }
doc.content_changed(node, NodeDamage::NodeStyleDamaged); doc.r().content_changed(node, NodeDamage::NodeStyleDamaged);
} }
} }
&atom!("class") => { &atom!("class") => {
@ -1282,7 +1283,7 @@ impl<'a> VirtualMethods for JSRef<'a, Element> {
let node: JSRef<Node> = NodeCast::from_ref(*self); let node: JSRef<Node> = NodeCast::from_ref(*self);
if node.is_in_doc() { if node.is_in_doc() {
let document = document_from_node(*self).root(); let document = document_from_node(*self).root();
document.content_changed(node, NodeDamage::NodeStyleDamaged); document.r().content_changed(node, NodeDamage::NodeStyleDamaged);
} }
} }
_ => { _ => {
@ -1290,7 +1291,7 @@ impl<'a> VirtualMethods for JSRef<'a, Element> {
let node: JSRef<Node> = NodeCast::from_ref(*self); let node: JSRef<Node> = NodeCast::from_ref(*self);
if node.is_in_doc() { if node.is_in_doc() {
let doc = document_from_node(*self).root(); let doc = document_from_node(*self).root();
doc.content_changed(node, NodeDamage::OtherNodeDamage); doc.r().content_changed(node, NodeDamage::OtherNodeDamage);
} }
} }
} }
@ -1315,10 +1316,10 @@ impl<'a> VirtualMethods for JSRef<'a, Element> {
match self.get_attribute(ns!(""), &atom!("id")).root() { match self.get_attribute(ns!(""), &atom!("id")).root() {
Some(attr) => { Some(attr) => {
let doc = document_from_node(*self).root(); let doc = document_from_node(*self).root();
let value = attr.Value(); let value = attr.r().Value();
if !value.is_empty() { if !value.is_empty() {
let value = Atom::from_slice(value.as_slice()); let value = Atom::from_slice(value.as_slice());
doc.register_named_element(*self, value); doc.r().register_named_element(*self, value);
} }
} }
_ => () _ => ()
@ -1336,10 +1337,10 @@ impl<'a> VirtualMethods for JSRef<'a, Element> {
match self.get_attribute(ns!(""), &atom!("id")).root() { match self.get_attribute(ns!(""), &atom!("id")).root() {
Some(attr) => { Some(attr) => {
let doc = document_from_node(*self).root(); let doc = document_from_node(*self).root();
let value = attr.Value(); let value = attr.r().Value();
if !value.is_empty() { if !value.is_empty() {
let value = Atom::from_slice(value.as_slice()); let value = Atom::from_slice(value.as_slice());
doc.unregister_named_element(*self, value); doc.r().unregister_named_element(*self, value);
} }
} }
_ => () _ => ()
@ -1351,13 +1352,13 @@ impl<'a> style::TElement<'a> for JSRef<'a, Element> {
fn get_attr(self, namespace: &Namespace, attr: &Atom) -> Option<&'a str> { fn get_attr(self, namespace: &Namespace, attr: &Atom) -> Option<&'a str> {
self.get_attribute(namespace.clone(), attr).root().map(|attr| { self.get_attribute(namespace.clone(), attr).root().map(|attr| {
// This transmute is used to cheat the lifetime restriction. // This transmute is used to cheat the lifetime restriction.
unsafe { mem::transmute(attr.value().as_slice()) } unsafe { mem::transmute(attr.r().value().as_slice()) }
}) })
} }
fn get_attrs(self, attr: &Atom) -> Vec<&'a str> { fn get_attrs(self, attr: &Atom) -> Vec<&'a str> {
self.get_attributes(attr).iter().map(|attr| attr.root()).map(|attr| { self.get_attributes(attr).iter().map(|attr| attr.root()).map(|attr| {
// This transmute is used to cheat the lifetime restriction. // This transmute is used to cheat the lifetime restriction.
unsafe { mem::transmute(attr.value().as_slice()) } unsafe { mem::transmute(attr.r().value().as_slice()) }
}).collect() }).collect()
} }
fn get_link(self) -> Option<&'a str> { fn get_link(self) -> Option<&'a str> {
@ -1397,7 +1398,7 @@ impl<'a> style::TElement<'a> for JSRef<'a, Element> {
fn get_id(self) -> Option<Atom> { fn get_id(self) -> Option<Atom> {
self.get_attribute(ns!(""), &atom!("id")).map(|attr| { self.get_attribute(ns!(""), &atom!("id")).map(|attr| {
let attr = attr.root(); let attr = attr.root();
match *attr.value() { match *attr.r().value() {
AttrValue::Atom(ref val) => val.clone(), AttrValue::Atom(ref val) => val.clone(),
_ => panic!("`id` attribute should be AttrValue::Atom"), _ => panic!("`id` attribute should be AttrValue::Atom"),
} }
@ -1436,7 +1437,7 @@ impl<'a> style::TElement<'a> for JSRef<'a, Element> {
match self.get_attribute(ns!(""), &atom!("class")).root() { match self.get_attribute(ns!(""), &atom!("class")).root() {
None => {} None => {}
Some(ref attr) => { Some(ref attr) => {
match attr.value().tokens() { match attr.r().value().tokens() {
None => {} None => {}
Some(tokens) => { Some(tokens) => {
for token in tokens.iter() { for token in tokens.iter() {
@ -1495,7 +1496,7 @@ impl<'a> ActivationElementHelpers<'a> for JSRef<'a, Element> {
// https://html.spec.whatwg.org/multipage/interaction.html#nearest-activatable-element // https://html.spec.whatwg.org/multipage/interaction.html#nearest-activatable-element
fn nearest_activable_element(self) -> Option<Temporary<Element>> { fn nearest_activable_element(self) -> Option<Temporary<Element>> {
match self.as_maybe_activatable() { match self.as_maybe_activatable() {
Some(el) => Some(Temporary::from_rooted(*el.as_element().root())), Some(el) => Some(Temporary::from_rooted(el.as_element().root().r())),
None => { None => {
let node: JSRef<Node> = NodeCast::from_ref(self); let node: JSRef<Node> = NodeCast::from_ref(self);
node.ancestors() node.ancestors()
@ -1526,7 +1527,7 @@ impl<'a> ActivationElementHelpers<'a> for JSRef<'a, Element> {
// Step 4 // Step 4
let e = self.nearest_activable_element().root(); let e = self.nearest_activable_element().root();
match e { match e {
Some(el) => match el.as_maybe_activatable() { Some(el) => match el.r().as_maybe_activatable() {
Some(elem) => { Some(elem) => {
// Step 5-6 // Step 5-6
elem.pre_click_activation(); elem.pre_click_activation();

View file

@ -64,15 +64,15 @@ impl ErrorEvent {
colno: u32, colno: u32,
error: JSVal) -> Temporary<ErrorEvent> { error: JSVal) -> Temporary<ErrorEvent> {
let ev = ErrorEvent::new_uninitialized(global).root(); let ev = ErrorEvent::new_uninitialized(global).root();
let event: JSRef<Event> = EventCast::from_ref(*ev); let event: JSRef<Event> = EventCast::from_ref(ev.r());
event.InitEvent(type_, bubbles == EventBubbles::Bubbles, event.InitEvent(type_, bubbles == EventBubbles::Bubbles,
cancelable == EventCancelable::Cancelable); cancelable == EventCancelable::Cancelable);
*ev.message.borrow_mut() = message; *ev.r().message.borrow_mut() = message;
*ev.filename.borrow_mut() = filename; *ev.r().filename.borrow_mut() = filename;
ev.lineno.set(lineno); ev.r().lineno.set(lineno);
ev.colno.set(colno); ev.r().colno.set(colno);
ev.error.set(error); ev.r().error.set(error);
Temporary::from_rooted(*ev) Temporary::from_rooted(ev.r())
} }
pub fn Constructor(global: &GlobalRef, pub fn Constructor(global: &GlobalRef,

View file

@ -100,8 +100,8 @@ impl Event {
bubbles: EventBubbles, bubbles: EventBubbles,
cancelable: EventCancelable) -> Temporary<Event> { cancelable: EventCancelable) -> Temporary<Event> {
let event = Event::new_uninitialized(global).root(); let event = Event::new_uninitialized(global).root();
event.InitEvent(type_, bubbles == EventBubbles::Bubbles, cancelable == EventCancelable::Cancelable); event.r().InitEvent(type_, bubbles == EventBubbles::Bubbles, cancelable == EventCancelable::Cancelable);
Temporary::from_rooted(*event) Temporary::from_rooted(event.r())
} }
pub fn Constructor(global: &GlobalRef, pub fn Constructor(global: &GlobalRef,

View file

@ -43,12 +43,12 @@ pub fn dispatch_event<'a, 'b>(target: JSRef<'a, EventTarget>,
/* capturing */ /* capturing */
for cur_target in chain.as_slice().iter().rev() { for cur_target in chain.as_slice().iter().rev() {
let stopped = match cur_target.get_listeners_for(type_.as_slice(), ListenerPhase::Capturing) { let stopped = match cur_target.r().get_listeners_for(type_.as_slice(), ListenerPhase::Capturing) {
Some(listeners) => { Some(listeners) => {
event.set_current_target(cur_target.deref().clone()); event.set_current_target(cur_target.r());
for listener in listeners.iter() { for listener in listeners.iter() {
// Explicitly drop any exception on the floor. // Explicitly drop any exception on the floor.
let _ = listener.HandleEvent_(**cur_target, event, ReportExceptions); let _ = listener.HandleEvent_(cur_target.r(), event, ReportExceptions);
if event.stop_immediate() { if event.stop_immediate() {
break; break;
@ -88,12 +88,12 @@ pub fn dispatch_event<'a, 'b>(target: JSRef<'a, EventTarget>,
event.set_phase(EventPhase::Bubbling); event.set_phase(EventPhase::Bubbling);
for cur_target in chain.iter() { for cur_target in chain.iter() {
let stopped = match cur_target.get_listeners_for(type_.as_slice(), ListenerPhase::Bubbling) { let stopped = match cur_target.r().get_listeners_for(type_.as_slice(), ListenerPhase::Bubbling) {
Some(listeners) => { Some(listeners) => {
event.set_current_target(cur_target.deref().clone()); event.set_current_target(cur_target.r());
for listener in listeners.iter() { for listener in listeners.iter() {
// Explicitly drop any exception on the floor. // Explicitly drop any exception on the floor.
let _ = listener.HandleEvent_(**cur_target, event, ReportExceptions); let _ = listener.HandleEvent_(cur_target.r(), event, ReportExceptions);
if event.stop_immediate() { if event.stop_immediate() {
break; break;
@ -114,7 +114,7 @@ pub fn dispatch_event<'a, 'b>(target: JSRef<'a, EventTarget>,
let target = event.GetTarget().root(); let target = event.GetTarget().root();
match target { match target {
Some(target) => { Some(target) => {
let node: Option<JSRef<Node>> = NodeCast::to_ref(*target); let node: Option<JSRef<Node>> = NodeCast::to_ref(target.r());
match node { match node {
Some(node) => { Some(node) => {
let vtable = vtable_for(&node); let vtable = vtable_for(&node);

View file

@ -116,6 +116,6 @@ impl PrivateFormDataHelpers for FormData {
let global = self.global.root(); let global = self.global.root();
let f: Option<JSRef<File>> = FileCast::to_ref(value); let f: Option<JSRef<File>> = FileCast::to_ref(value);
let name = filename.unwrap_or(f.map(|inner| inner.name().clone()).unwrap_or("blob".into_string())); let name = filename.unwrap_or(f.map(|inner| inner.name().clone()).unwrap_or("blob".into_string()));
File::new(&global.root_ref(), value, name) File::new(&global.r(), value, name)
} }
} }

View file

@ -62,11 +62,11 @@ impl<'a> PrivateHTMLAnchorElementHelpers for JSRef<'a, HTMLAnchorElement> {
let attr = element.get_attribute(ns!(""), &atom!("href")).root(); let attr = element.get_attribute(ns!(""), &atom!("href")).root();
match attr { match attr {
Some(ref href) => { Some(ref href) => {
let value = href.Value(); let value = href.r().Value();
debug!("clicked on link to {:s}", value); debug!("clicked on link to {:s}", value);
let node: JSRef<Node> = NodeCast::from_ref(self); let node: JSRef<Node> = NodeCast::from_ref(self);
let doc = node.owner_doc().root(); let doc = node.owner_doc().root();
doc.load_anchor_href(value); doc.r().load_anchor_href(value);
} }
None => () None => ()
} }

View file

@ -56,12 +56,12 @@ impl HTMLBodyElement {
impl<'a> HTMLBodyElementMethods for JSRef<'a, HTMLBodyElement> { impl<'a> HTMLBodyElementMethods for JSRef<'a, HTMLBodyElement> {
fn GetOnunload(self) -> Option<EventHandlerNonNull> { fn GetOnunload(self) -> Option<EventHandlerNonNull> {
let win = window_from_node(self).root(); let win = window_from_node(self).root();
win.GetOnunload() win.r().GetOnunload()
} }
fn SetOnunload(self, listener: Option<EventHandlerNonNull>) { fn SetOnunload(self, listener: Option<EventHandlerNonNull>) {
let win = window_from_node(self).root(); let win = window_from_node(self).root();
win.SetOnunload(listener) win.r().SetOnunload(listener)
} }
} }
@ -95,12 +95,12 @@ impl<'a> VirtualMethods for JSRef<'a, HTMLBodyElement> {
"onoffline", "ononline", "onpagehide", "onpageshow", "onpopstate", "onoffline", "ononline", "onpagehide", "onpageshow", "onpopstate",
"onstorage", "onresize", "onunload", "onerror"]; "onstorage", "onresize", "onunload", "onerror"];
let window = window_from_node(*self).root(); let window = window_from_node(*self).root();
let (cx, url, reflector) = (window.get_cx(), let (cx, url, reflector) = (window.r().get_cx(),
window.get_url(), window.r().get_url(),
window.reflector().get_jsobject()); window.r().reflector().get_jsobject());
let evtarget: JSRef<EventTarget> = let evtarget: JSRef<EventTarget> =
if FORWARDED_EVENTS.iter().any(|&event| name == event) { if FORWARDED_EVENTS.iter().any(|&event| name == event) {
EventTargetCast::from_ref(*window) EventTargetCast::from_ref(window.r())
} else { } else {
EventTargetCast::from_ref(*self) EventTargetCast::from_ref(*self)
}; };

View file

@ -49,7 +49,7 @@ impl HTMLButtonElement {
impl<'a> HTMLButtonElementMethods for JSRef<'a, HTMLButtonElement> { impl<'a> HTMLButtonElementMethods for JSRef<'a, HTMLButtonElement> {
fn Validity(self) -> Temporary<ValidityState> { fn Validity(self) -> Temporary<ValidityState> {
let window = window_from_node(self).root(); let window = window_from_node(self).root();
ValidityState::new(*window) ValidityState::new(window.r())
} }
// http://www.whatwg.org/html/#dom-fe-disabled // http://www.whatwg.org/html/#dom-fe-disabled

View file

@ -86,7 +86,7 @@ impl<'a> HTMLCanvasElementMethods for JSRef<'a, HTMLCanvasElement> {
Some(self.context.or_init(|| { Some(self.context.or_init(|| {
let window = window_from_node(self).root(); let window = window_from_node(self).root();
let (w, h) = (self.width.get() as i32, self.height.get() as i32); let (w, h) = (self.width.get() as i32, self.height.get() as i32);
CanvasRenderingContext2D::new(&GlobalRef::Window(*window), self, Size2D(w, h)) CanvasRenderingContext2D::new(&GlobalRef::Window(window.r()), self, Size2D(w, h))
})) }))
} }
} }
@ -118,7 +118,7 @@ impl<'a> VirtualMethods for JSRef<'a, HTMLCanvasElement> {
if recreate { if recreate {
let (w, h) = (self.width.get() as i32, self.height.get() as i32); let (w, h) = (self.width.get() as i32, self.height.get() as i32);
match self.context.get() { match self.context.get() {
Some(ref context) => context.root().recreate(Size2D(w, h)), Some(ref context) => context.root().r().recreate(Size2D(w, h)),
None => () None => ()
} }
} }
@ -146,7 +146,7 @@ impl<'a> VirtualMethods for JSRef<'a, HTMLCanvasElement> {
if recreate { if recreate {
let (w, h) = (self.width.get() as i32, self.height.get() as i32); let (w, h) = (self.width.get() as i32, self.height.get() as i32);
match self.context.get() { match self.context.get() {
Some(ref context) => context.root().recreate(Size2D(w, h)), Some(ref context) => context.root().r().recreate(Size2D(w, h)),
None => () None => ()
} }
} }

View file

@ -181,8 +181,8 @@ impl<'a> HTMLCollectionMethods for JSRef<'a, HTMLCollection> {
CollectionTypeId::Static(ref elems) => elems.len() as u32, CollectionTypeId::Static(ref elems) => elems.len() as u32,
CollectionTypeId::Live(ref root, ref filter) => { CollectionTypeId::Live(ref root, ref filter) => {
let root = root.root(); let root = root.root();
HTMLCollection::traverse(*root) HTMLCollection::traverse(root.r())
.filter(|element| filter.filter(*element, *root)) .filter(|element| filter.filter(*element, root.r()))
.count() as u32 .count() as u32
} }
} }
@ -197,8 +197,8 @@ impl<'a> HTMLCollectionMethods for JSRef<'a, HTMLCollection> {
.map(|elem| Temporary::new(elem.clone())), .map(|elem| Temporary::new(elem.clone())),
CollectionTypeId::Live(ref root, ref filter) => { CollectionTypeId::Live(ref root, ref filter) => {
let root = root.root(); let root = root.root();
HTMLCollection::traverse(*root) HTMLCollection::traverse(root.r())
.filter(|element| filter.filter(*element, *root)) .filter(|element| filter.filter(*element, root.r()))
.nth(index as uint) .nth(index as uint)
.clone() .clone()
.map(Temporary::from_rooted) .map(Temporary::from_rooted)
@ -218,13 +218,13 @@ impl<'a> HTMLCollectionMethods for JSRef<'a, HTMLCollection> {
CollectionTypeId::Static(ref elems) => elems.iter() CollectionTypeId::Static(ref elems) => elems.iter()
.map(|elem| elem.root()) .map(|elem| elem.root())
.find(|elem| { .find(|elem| {
elem.get_string_attribute(&atom!("name")) == key || elem.r().get_string_attribute(&atom!("name")) == key ||
elem.get_string_attribute(&atom!("id")) == key }) elem.r().get_string_attribute(&atom!("id")) == key })
.map(|maybe_elem| Temporary::from_rooted(*maybe_elem)), .map(|maybe_elem| Temporary::from_rooted(maybe_elem.r())),
CollectionTypeId::Live(ref root, ref filter) => { CollectionTypeId::Live(ref root, ref filter) => {
let root = root.root(); let root = root.root();
HTMLCollection::traverse(*root) HTMLCollection::traverse(root.r())
.filter(|element| filter.filter(*element, *root)) .filter(|element| filter.filter(*element, root.r()))
.find(|elem| { .find(|elem| {
elem.get_string_attribute(&atom!("name")) == key || elem.get_string_attribute(&atom!("name")) == key ||
elem.get_string_attribute(&atom!("id")) == key }) elem.get_string_attribute(&atom!("id")) == key })

View file

@ -52,7 +52,7 @@ impl<'a> HTMLDataListElementMethods for JSRef<'a, HTMLDataListElement> {
let node: JSRef<Node> = NodeCast::from_ref(self); let node: JSRef<Node> = NodeCast::from_ref(self);
let filter = box HTMLDataListOptionsFilter; let filter = box HTMLDataListOptionsFilter;
let window = window_from_node(node).root(); let window = window_from_node(node).root();
HTMLCollection::create(*window, node, filter) HTMLCollection::create(window.r(), node, filter)
} }
} }

View file

@ -78,7 +78,7 @@ impl<'a> HTMLElementMethods for JSRef<'a, HTMLElement> {
fn Style(self) -> Temporary<CSSStyleDeclaration> { fn Style(self) -> Temporary<CSSStyleDeclaration> {
self.style_decl.or_init(|| { self.style_decl.or_init(|| {
let global = window_from_node(self).root(); let global = window_from_node(self).root();
CSSStyleDeclaration::new(*global, self, CSSModificationAccess::ReadWrite) CSSStyleDeclaration::new(global.r(), self, CSSModificationAccess::ReadWrite)
}) })
} }
@ -102,7 +102,7 @@ impl<'a> HTMLElementMethods for JSRef<'a, HTMLElement> {
fn GetOnload(self) -> Option<EventHandlerNonNull> { fn GetOnload(self) -> Option<EventHandlerNonNull> {
if self.is_body_or_frameset() { if self.is_body_or_frameset() {
let win = window_from_node(self).root(); let win = window_from_node(self).root();
win.GetOnload() win.r().GetOnload()
} else { } else {
let target: JSRef<EventTarget> = EventTargetCast::from_ref(self); let target: JSRef<EventTarget> = EventTargetCast::from_ref(self);
target.get_event_handler_common("load") target.get_event_handler_common("load")
@ -112,7 +112,7 @@ impl<'a> HTMLElementMethods for JSRef<'a, HTMLElement> {
fn SetOnload(self, listener: Option<EventHandlerNonNull>) { fn SetOnload(self, listener: Option<EventHandlerNonNull>) {
if self.is_body_or_frameset() { if self.is_body_or_frameset() {
let win = window_from_node(self).root(); let win = window_from_node(self).root();
win.SetOnload(listener) win.r().SetOnload(listener)
} else { } else {
let target: JSRef<EventTarget> = EventTargetCast::from_ref(self); let target: JSRef<EventTarget> = EventTargetCast::from_ref(self);
target.set_event_handler_common("load", listener) target.set_event_handler_common("load", listener)
@ -167,7 +167,7 @@ impl<'a> HTMLElementCustomAttributeHelpers for JSRef<'a, HTMLElement> {
let element: JSRef<Element> = ElementCast::from_ref(self); let element: JSRef<Element> = ElementCast::from_ref(self);
element.get_attribute(ns!(""), &Atom::from_slice(to_snake_case(name).as_slice())).map(|attr| { element.get_attribute(ns!(""), &Atom::from_slice(to_snake_case(name).as_slice())).map(|attr| {
let attr = attr.root(); let attr = attr.root();
attr.value().as_slice().into_string() attr.r().value().as_slice().into_string()
}) })
} }
@ -192,9 +192,9 @@ impl<'a> VirtualMethods for JSRef<'a, HTMLElement> {
let name = attr.local_name().as_slice(); let name = attr.local_name().as_slice();
if name.starts_with("on") { if name.starts_with("on") {
let window = window_from_node(*self).root(); let window = window_from_node(*self).root();
let (cx, url, reflector) = (window.get_cx(), let (cx, url, reflector) = (window.r().get_cx(),
window.get_url(), window.r().get_url(),
window.reflector().get_jsobject()); window.r().reflector().get_jsobject());
let evtarget: JSRef<EventTarget> = EventTargetCast::from_ref(*self); let evtarget: JSRef<EventTarget> = EventTargetCast::from_ref(*self);
evtarget.set_event_handler_uncompiled(cx, url, reflector, evtarget.set_event_handler_uncompiled(cx, url, reflector,
name.slice_from(2), name.slice_from(2),

View file

@ -61,12 +61,12 @@ impl<'a> HTMLFieldSetElementMethods for JSRef<'a, HTMLFieldSetElement> {
let node: JSRef<Node> = NodeCast::from_ref(self); let node: JSRef<Node> = NodeCast::from_ref(self);
let filter = box ElementsFilter; let filter = box ElementsFilter;
let window = window_from_node(node).root(); let window = window_from_node(node).root();
HTMLCollection::create(*window, node, filter) HTMLCollection::create(window.r(), node, filter)
} }
fn Validity(self) -> Temporary<ValidityState> { fn Validity(self) -> Temporary<ValidityState> {
let window = window_from_node(self).root(); let window = window_from_node(self).root();
ValidityState::new(*window) ValidityState::new(window.r())
} }
// http://www.whatwg.org/html/#dom-fieldset-disabled // http://www.whatwg.org/html/#dom-fieldset-disabled

View file

@ -152,17 +152,17 @@ impl<'a> HTMLFormElementHelpers for JSRef<'a, HTMLFormElement> {
// Step 1 // Step 1
let doc = document_from_node(self).root(); let doc = document_from_node(self).root();
let win = window_from_node(self).root(); let win = window_from_node(self).root();
let base = doc.url(); let base = doc.r().url();
// TODO: Handle browsing contexts // TODO: Handle browsing contexts
// TODO: Handle validation // TODO: Handle validation
let event = Event::new(GlobalRef::Window(*win), let event = Event::new(GlobalRef::Window(win.r()),
"submit".into_string(), "submit".into_string(),
EventBubbles::Bubbles, EventBubbles::Bubbles,
EventCancelable::Cancelable).root(); EventCancelable::Cancelable).root();
event.set_trusted(true); event.r().set_trusted(true);
let target: JSRef<EventTarget> = EventTargetCast::from_ref(self); let target: JSRef<EventTarget> = EventTargetCast::from_ref(self);
target.DispatchEvent(*event).ok(); target.DispatchEvent(event.r()).ok();
if event.DefaultPrevented() { if event.r().DefaultPrevented() {
return; return;
} }
// Step 6 // Step 6
@ -204,7 +204,7 @@ impl<'a> HTMLFormElementHelpers for JSRef<'a, HTMLFormElement> {
} }
// This is wrong. https://html.spec.whatwg.org/multipage/forms.html#planned-navigation // This is wrong. https://html.spec.whatwg.org/multipage/forms.html#planned-navigation
win.script_chan().send(ScriptMsg::TriggerLoad(win.page().id, load_data)); win.r().script_chan().send(ScriptMsg::TriggerLoad(win.r().page().id, load_data));
} }
fn get_form_dataset<'b>(self, submitter: Option<FormSubmitter<'b>>) -> Vec<FormDatum> { fn get_form_dataset<'b>(self, submitter: Option<FormSubmitter<'b>>) -> Vec<FormDatum> {
@ -342,13 +342,13 @@ impl<'a> HTMLFormElementHelpers for JSRef<'a, HTMLFormElement> {
} }
let win = window_from_node(self).root(); let win = window_from_node(self).root();
let event = Event::new(GlobalRef::Window(*win), let event = Event::new(GlobalRef::Window(win.r()),
"reset".into_string(), "reset".into_string(),
EventBubbles::Bubbles, EventBubbles::Bubbles,
EventCancelable::Cancelable).root(); EventCancelable::Cancelable).root();
let target: JSRef<EventTarget> = EventTargetCast::from_ref(self); let target: JSRef<EventTarget> = EventTargetCast::from_ref(self);
target.DispatchEvent(*event).ok(); target.DispatchEvent(event.r()).ok();
if event.DefaultPrevented() { if event.r().DefaultPrevented() {
return; return;
} }
@ -484,10 +484,10 @@ pub trait FormControl<'a> : Copy {
let owner = elem.get_string_attribute(&atom!("form")); let owner = elem.get_string_attribute(&atom!("form"));
if !owner.is_empty() { if !owner.is_empty() {
let doc = document_from_node(elem).root(); let doc = document_from_node(elem).root();
let owner = doc.GetElementById(owner).root(); let owner = doc.r().GetElementById(owner).root();
match owner { match owner {
Some(o) => { Some(o) => {
let maybe_form: Option<JSRef<HTMLFormElement>> = HTMLFormElementCast::to_ref(*o); let maybe_form: Option<JSRef<HTMLFormElement>> = HTMLFormElementCast::to_ref(o.r());
if maybe_form.is_some() { if maybe_form.is_some() {
return maybe_form.map(Temporary::from_rooted); return maybe_form.map(Temporary::from_rooted);
} }
@ -507,7 +507,7 @@ pub trait FormControl<'a> : Copy {
if self.to_element().has_attribute(attr) { if self.to_element().has_attribute(attr) {
input(self) input(self)
} else { } else {
self.form_owner().map_or("".into_string(), |t| owner(*t.root())) self.form_owner().map_or("".into_string(), |t| owner(t.root().r()))
} }
} }
fn to_element(self) -> JSRef<'a, Element>; fn to_element(self) -> JSRef<'a, Element>;

View file

@ -87,12 +87,12 @@ impl<'a> HTMLIFrameElementHelpers for JSRef<'a, HTMLIFrameElement> {
fn get_url(self) -> Option<Url> { fn get_url(self) -> Option<Url> {
let element: JSRef<Element> = ElementCast::from_ref(self); let element: JSRef<Element> = ElementCast::from_ref(self);
element.get_attribute(ns!(""), &atom!("src")).root().and_then(|src| { element.get_attribute(ns!(""), &atom!("src")).root().and_then(|src| {
let url = src.value(); let url = src.r().value();
if url.as_slice().is_empty() { if url.as_slice().is_empty() {
None None
} else { } else {
let window = window_from_node(self).root(); let window = window_from_node(self).root();
UrlParser::new().base_url(&window.page().get_url()) UrlParser::new().base_url(&window.r().page().get_url())
.parse(url.as_slice()).ok() .parse(url.as_slice()).ok()
} }
}) })
@ -112,6 +112,7 @@ impl<'a> HTMLIFrameElementHelpers for JSRef<'a, HTMLIFrameElement> {
// Subpage Id // Subpage Id
let window = window_from_node(self).root(); let window = window_from_node(self).root();
let window = window.r();
let page = window.page(); let page = window.page();
let subpage_id = page.get_next_subpage_id(); let subpage_id = page.get_next_subpage_id();
@ -188,10 +189,10 @@ impl<'a> HTMLIFrameElementMethods for JSRef<'a, HTMLIFrameElement> {
Some(self_url) => self_url, Some(self_url) => self_url,
None => return None, None => return None,
}; };
let win_url = window_from_node(self).root().page().get_url(); let win_url = window_from_node(self).root().r().page().get_url();
if UrlHelper::SameOrigin(&self_url, &win_url) { if UrlHelper::SameOrigin(&self_url, &win_url) {
Some(window.Document()) Some(window.r().Document())
} else { } else {
None None
} }

View file

@ -45,7 +45,8 @@ impl<'a> PrivateHTMLImageElementHelpers for JSRef<'a, HTMLImageElement> {
fn update_image(self, value: Option<(DOMString, &Url)>) { fn update_image(self, value: Option<(DOMString, &Url)>) {
let node: JSRef<Node> = NodeCast::from_ref(self); let node: JSRef<Node> = NodeCast::from_ref(self);
let document = node.owner_doc().root(); let document = node.owner_doc().root();
let window = document.window().root(); let window = document.r().window().root();
let window = window.r();
let image_cache = window.image_cache_task(); let image_cache = window.image_cache_task();
match value { match value {
None => { None => {
@ -186,7 +187,7 @@ impl<'a> VirtualMethods for JSRef<'a, HTMLImageElement> {
match attr.local_name() { match attr.local_name() {
&atom!("src") => { &atom!("src") => {
let window = window_from_node(*self).root(); let window = window_from_node(*self).root();
let url = window.get_url(); let url = window.r().get_url();
self.update_image(Some((attr.value().as_slice().into_string(), &url))); self.update_image(Some((attr.value().as_slice().into_string(), &url)));
}, },
_ => () _ => ()

View file

@ -307,13 +307,13 @@ fn broadcast_radio_checked(broadcaster: JSRef<HTMLInputElement>, group: Option<&
//TODO: if not in document, use root ancestor instead of document //TODO: if not in document, use root ancestor instead of document
let owner = broadcaster.form_owner().root(); let owner = broadcaster.form_owner().root();
let doc = document_from_node(broadcaster).root(); let doc = document_from_node(broadcaster).root();
let doc_node: JSRef<Node> = NodeCast::from_ref(*doc); let doc_node: JSRef<Node> = NodeCast::from_ref(doc.r());
// There is no DOM tree manipulation here, so this is safe // There is no DOM tree manipulation here, so this is safe
let mut iter = unsafe { let mut iter = unsafe {
doc_node.query_selector_iter("input[type=radio]".into_string()).unwrap() doc_node.query_selector_iter("input[type=radio]".into_string()).unwrap()
.filter_map(|t| HTMLInputElementCast::to_ref(t)) .filter_map(|t| HTMLInputElementCast::to_ref(t))
.filter(|&r| in_same_group(r, owner.root_ref(), group) && broadcaster != r) .filter(|&r| in_same_group(r, owner.r(), group) && broadcaster != r)
}; };
for r in iter { for r in iter {
if r.Checked() { if r.Checked() {
@ -326,7 +326,7 @@ fn in_same_group<'a,'b>(other: JSRef<'a, HTMLInputElement>,
owner: Option<JSRef<'b, HTMLFormElement>>, owner: Option<JSRef<'b, HTMLFormElement>>,
group: Option<&str>) -> bool { group: Option<&str>) -> bool {
let other_owner = other.form_owner().root(); let other_owner = other.form_owner().root();
let other_owner = other_owner.root_ref(); let other_owner = other_owner.r();
other.input_type.get() == InputType::InputRadio && other.input_type.get() == InputType::InputRadio &&
// TODO Both a and b are in the same home subtree. // TODO Both a and b are in the same home subtree.
other_owner.equals(owner) && other_owner.equals(owner) &&
@ -342,7 +342,7 @@ impl<'a> HTMLInputElementHelpers for JSRef<'a, HTMLInputElement> {
fn force_relayout(self) { fn force_relayout(self) {
let doc = document_from_node(self).root(); let doc = document_from_node(self).root();
let node: JSRef<Node> = NodeCast::from_ref(self); let node: JSRef<Node> = NodeCast::from_ref(self);
doc.content_changed(node, NodeDamage::OtherNodeDamage) doc.r().content_changed(node, NodeDamage::OtherNodeDamage)
} }
fn radio_group_updated(self, group: Option<&str>) { fn radio_group_updated(self, group: Option<&str>) {
@ -356,7 +356,7 @@ impl<'a> HTMLInputElementHelpers for JSRef<'a, HTMLInputElement> {
let elem: JSRef<Element> = ElementCast::from_ref(self); let elem: JSRef<Element> = ElementCast::from_ref(self);
elem.get_attribute(ns!(""), &atom!("name")) elem.get_attribute(ns!(""), &atom!("name"))
.root() .root()
.map(|name| name.Value()) .map(|name| name.r().Value())
} }
fn update_checked_state(self, checked: bool, dirty: bool) { fn update_checked_state(self, checked: bool, dirty: bool) {
@ -550,7 +550,7 @@ impl<'a> VirtualMethods for JSRef<'a, HTMLInputElement> {
//TODO: set the editing position for text inputs //TODO: set the editing position for text inputs
let doc = document_from_node(*self).root(); let doc = document_from_node(*self).root();
doc.request_focus(ElementCast::from_ref(*self)); doc.r().request_focus(ElementCast::from_ref(*self));
} else if "keydown" == event.Type().as_slice() && !event.DefaultPrevented() && } else if "keydown" == event.Type().as_slice() && !event.DefaultPrevented() &&
(self.input_type.get() == InputType::InputText || (self.input_type.get() == InputType::InputText ||
self.input_type.get() == InputType::InputPassword) { self.input_type.get() == InputType::InputPassword) {
@ -631,14 +631,14 @@ impl<'a> Activatable for JSRef<'a, HTMLInputElement> {
//TODO: if not in document, use root ancestor instead of document //TODO: if not in document, use root ancestor instead of document
let owner = self.form_owner().root(); let owner = self.form_owner().root();
let doc = document_from_node(*self).root(); let doc = document_from_node(*self).root();
let doc_node: JSRef<Node> = NodeCast::from_ref(*doc); let doc_node: JSRef<Node> = NodeCast::from_ref(doc.r());
let group = self.get_radio_group_name();; let group = self.get_radio_group_name();;
// Safe since we only manipulate the DOM tree after finding an element // Safe since we only manipulate the DOM tree after finding an element
let checked_member = unsafe { let checked_member = unsafe {
doc_node.query_selector_iter("input[type=radio]".into_string()).unwrap() doc_node.query_selector_iter("input[type=radio]".into_string()).unwrap()
.filter_map(|t| HTMLInputElementCast::to_ref(t)) .filter_map(|t| HTMLInputElementCast::to_ref(t))
.filter(|&r| in_same_group(r, owner.root_ref(), .filter(|&r| in_same_group(r, owner.r(),
group.as_ref().map(|gr| gr.as_slice()))) group.as_ref().map(|gr| gr.as_slice())))
.find(|r| r.Checked()) .find(|r| r.Checked())
}; };
@ -684,11 +684,11 @@ impl<'a> Activatable for JSRef<'a, HTMLInputElement> {
Some(o) => { Some(o) => {
// Avoiding iterating through the whole tree here, instead // Avoiding iterating through the whole tree here, instead
// we can check if the conditions for radio group siblings apply // we can check if the conditions for radio group siblings apply
if name == o.get_radio_group_name() && // TODO should be compatibility caseless if name == o.r().get_radio_group_name() && // TODO should be compatibility caseless
self.form_owner() == o.form_owner() && self.form_owner() == o.r().form_owner() &&
// TODO Both a and b are in the same home subtree // TODO Both a and b are in the same home subtree
o.input_type.get() == InputType::InputRadio { o.r().input_type.get() == InputType::InputRadio {
o.SetChecked(true); o.r().SetChecked(true);
} else { } else {
self.SetChecked(false); self.SetChecked(false);
} }
@ -716,8 +716,8 @@ impl<'a> Activatable for JSRef<'a, HTMLInputElement> {
// FIXME (Manishearth): support document owners (needs ability to get parent browsing context) // FIXME (Manishearth): support document owners (needs ability to get parent browsing context)
if self.mutable() /* and document owner is fully active */ { if self.mutable() /* and document owner is fully active */ {
self.form_owner().map(|o| { self.form_owner().map(|o| {
o.root().submit(SubmittedFrom::NotFromFormSubmitMethod, o.root().r().submit(SubmittedFrom::NotFromFormSubmitMethod,
FormSubmitter::InputElement(self.clone())) FormSubmitter::InputElement(self.clone()))
}); });
} }
}, },
@ -726,7 +726,7 @@ impl<'a> Activatable for JSRef<'a, HTMLInputElement> {
// FIXME (Manishearth): support document owners (needs ability to get parent browsing context) // FIXME (Manishearth): support document owners (needs ability to get parent browsing context)
if self.mutable() /* and document owner is fully active */ { if self.mutable() /* and document owner is fully active */ {
self.form_owner().map(|o| { self.form_owner().map(|o| {
o.root().reset(ResetFrom::NotFromFormResetMethod) o.root().r().reset(ResetFrom::NotFromFormResetMethod)
}); });
} }
}, },
@ -735,21 +735,21 @@ impl<'a> Activatable for JSRef<'a, HTMLInputElement> {
// https://html.spec.whatwg.org/multipage/forms.html#radio-button-state-(type=radio):activation-behavior // https://html.spec.whatwg.org/multipage/forms.html#radio-button-state-(type=radio):activation-behavior
if self.mutable() { if self.mutable() {
let win = window_from_node(*self).root(); let win = window_from_node(*self).root();
let event = Event::new(GlobalRef::Window(*win), let event = Event::new(GlobalRef::Window(win.r()),
"input".into_string(), "input".into_string(),
EventBubbles::Bubbles, EventBubbles::Bubbles,
EventCancelable::NotCancelable).root(); EventCancelable::NotCancelable).root();
event.set_trusted(true); event.r().set_trusted(true);
let target: JSRef<EventTarget> = EventTargetCast::from_ref(*self); let target: JSRef<EventTarget> = EventTargetCast::from_ref(*self);
target.DispatchEvent(*event).ok(); target.DispatchEvent(event.r()).ok();
let event = Event::new(GlobalRef::Window(*win), let event = Event::new(GlobalRef::Window(win.r()),
"change".into_string(), "change".into_string(),
EventBubbles::Bubbles, EventBubbles::Bubbles,
EventCancelable::NotCancelable).root(); EventCancelable::NotCancelable).root();
event.set_trusted(true); event.r().set_trusted(true);
let target: JSRef<EventTarget> = EventTargetCast::from_ref(*self); let target: JSRef<EventTarget> = EventTargetCast::from_ref(*self);
target.DispatchEvent(*event).ok(); target.DispatchEvent(event.r()).ok();
} }
}, },
_ => () _ => ()
@ -759,7 +759,7 @@ impl<'a> Activatable for JSRef<'a, HTMLInputElement> {
// https://html.spec.whatwg.org/multipage/forms.html#implicit-submission // https://html.spec.whatwg.org/multipage/forms.html#implicit-submission
fn implicit_submission(&self, ctrlKey: bool, shiftKey: bool, altKey: bool, metaKey: bool) { fn implicit_submission(&self, ctrlKey: bool, shiftKey: bool, altKey: bool, metaKey: bool) {
let doc = document_from_node(*self).root(); let doc = document_from_node(*self).root();
let node: JSRef<Node> = NodeCast::from_ref(*doc); let node: JSRef<Node> = NodeCast::from_ref(doc.r());
let owner = self.form_owner(); let owner = self.form_owner();
if owner.is_none() || ElementCast::from_ref(*self).click_in_progress() { if owner.is_none() || ElementCast::from_ref(*self).click_in_progress() {
return; return;

View file

@ -53,7 +53,7 @@ impl HTMLLinkElement {
fn get_attr(element: JSRef<Element>, name: &Atom) -> Option<String> { fn get_attr(element: JSRef<Element>, name: &Atom) -> Option<String> {
let elem = element.get_attribute(ns!(""), name).root(); let elem = element.get_attribute(ns!(""), name).root();
elem.map(|e| e.value().as_slice().into_string()) elem.map(|e| e.r().value().as_slice().into_string())
} }
fn is_stylesheet(value: &Option<String>) -> bool { fn is_stylesheet(value: &Option<String>) -> bool {
@ -127,6 +127,7 @@ trait PrivateHTMLLinkElementHelpers {
impl<'a> PrivateHTMLLinkElementHelpers for JSRef<'a, HTMLLinkElement> { impl<'a> PrivateHTMLLinkElementHelpers for JSRef<'a, HTMLLinkElement> {
fn handle_stylesheet_url(self, href: &str) { fn handle_stylesheet_url(self, href: &str) {
let window = window_from_node(self).root(); let window = window_from_node(self).root();
let window = window.r();
match UrlParser::new().base_url(&window.page().get_url()).parse(href) { match UrlParser::new().base_url(&window.page().get_url()).parse(href) {
Ok(url) => { Ok(url) => {
let LayoutChan(ref layout_chan) = window.page().layout_chan; let LayoutChan(ref layout_chan) = window.page().layout_chan;

View file

@ -62,8 +62,8 @@ impl<'a> ProcessDataURL for JSRef<'a, HTMLObjectElement> {
let elem: JSRef<Element> = ElementCast::from_ref(*self); let elem: JSRef<Element> = ElementCast::from_ref(*self);
// TODO: support other values // TODO: support other values
match (elem.get_attribute(ns!(""), &atom!("type")).map(|x| x.root().Value()), match (elem.get_attribute(ns!(""), &atom!("type")).map(|x| x.root().r().Value()),
elem.get_attribute(ns!(""), &atom!("data")).map(|x| x.root().Value())) { elem.get_attribute(ns!(""), &atom!("data")).map(|x| x.root().r().Value())) {
(None, Some(uri)) => { (None, Some(uri)) => {
if is_image_data(uri.as_slice()) { if is_image_data(uri.as_slice()) {
let data_url = Url::parse(uri.as_slice()).unwrap(); let data_url = Url::parse(uri.as_slice()).unwrap();
@ -84,7 +84,7 @@ pub fn is_image_data(uri: &str) -> bool {
impl<'a> HTMLObjectElementMethods for JSRef<'a, HTMLObjectElement> { impl<'a> HTMLObjectElementMethods for JSRef<'a, HTMLObjectElement> {
fn Validity(self) -> Temporary<ValidityState> { fn Validity(self) -> Temporary<ValidityState> {
let window = window_from_node(self).root(); let window = window_from_node(self).root();
ValidityState::new(*window) ValidityState::new(window.r())
} }
// https://html.spec.whatwg.org/multipage/embedded-content.html#dom-object-type // https://html.spec.whatwg.org/multipage/embedded-content.html#dom-object-type
@ -109,7 +109,7 @@ impl<'a> VirtualMethods for JSRef<'a, HTMLObjectElement> {
match attr.local_name() { match attr.local_name() {
&atom!("data") => { &atom!("data") => {
let window = window_from_node(*self).root(); let window = window_from_node(*self).root();
self.process_data_url(window.image_cache_task().clone()); self.process_data_url(window.r().image_cache_task().clone());
}, },
_ => () _ => ()
} }

View file

@ -42,7 +42,7 @@ impl HTMLOutputElement {
impl<'a> HTMLOutputElementMethods for JSRef<'a, HTMLOutputElement> { impl<'a> HTMLOutputElementMethods for JSRef<'a, HTMLOutputElement> {
fn Validity(self) -> Temporary<ValidityState> { fn Validity(self) -> Temporary<ValidityState> {
let window = window_from_node(self).root(); let window = window_from_node(self).root();
ValidityState::new(*window) ValidityState::new(window.r())
} }
} }

View file

@ -170,16 +170,17 @@ impl<'a> HTMLScriptElementHelpers for JSRef<'a, HTMLScriptElement> {
// TODO: Add support for the `defer` and `async` attributes. (For now, we fetch all // TODO: Add support for the `defer` and `async` attributes. (For now, we fetch all
// scripts synchronously and execute them immediately.) // scripts synchronously and execute them immediately.)
let window = window_from_node(self).root(); let window = window_from_node(self).root();
let window = window.r();
let page = window.page(); let page = window.page();
let base_url = page.get_url(); let base_url = page.get_url();
let (source, url) = match element.get_attribute(ns!(""), &atom!("src")).root() { let (source, url) = match element.get_attribute(ns!(""), &atom!("src")).root() {
Some(src) => { Some(src) => {
if src.deref().Value().is_empty() { if src.r().Value().is_empty() {
// TODO: queue a task to fire a simple event named `error` at the element // TODO: queue a task to fire a simple event named `error` at the element
return; return;
} }
match UrlParser::new().base_url(&base_url).parse(src.deref().Value().as_slice()) { match UrlParser::new().base_url(&base_url).parse(src.r().Value().as_slice()) {
Ok(url) => { Ok(url) => {
// TODO: Do a potentially CORS-enabled fetch with the mode being the current // TODO: Do a potentially CORS-enabled fetch with the mode being the current
// state of the element's `crossorigin` content attribute, the origin being // state of the element's `crossorigin` content attribute, the origin being
@ -192,14 +193,14 @@ impl<'a> HTMLScriptElementHelpers for JSRef<'a, HTMLScriptElement> {
(source, metadata.final_url) (source, metadata.final_url)
} }
Err(_) => { Err(_) => {
error!("error loading script {}", src.deref().Value()); error!("error loading script {}", src.r().Value());
return; return;
} }
} }
} }
Err(_) => { Err(_) => {
// TODO: queue a task to fire a simple event named `error` at the element // TODO: queue a task to fire a simple event named `error` at the element
error!("error parsing URL for script {}", src.deref().Value()); error!("error parsing URL for script {}", src.r().Value());
return; return;
} }
} }
@ -209,18 +210,18 @@ impl<'a> HTMLScriptElementHelpers for JSRef<'a, HTMLScriptElement> {
window.evaluate_script_with_result(source.as_slice(), url.serialize().as_slice()); window.evaluate_script_with_result(source.as_slice(), url.serialize().as_slice());
let event = Event::new(GlobalRef::Window(*window), let event = Event::new(GlobalRef::Window(window),
"load".into_string(), "load".into_string(),
EventBubbles::DoesNotBubble, EventBubbles::DoesNotBubble,
EventCancelable::NotCancelable).root(); EventCancelable::NotCancelable).root();
event.set_trusted(true); event.r().set_trusted(true);
let target: JSRef<EventTarget> = EventTargetCast::from_ref(self); let target: JSRef<EventTarget> = EventTargetCast::from_ref(self);
target.dispatch_event(*event); target.dispatch_event(event.r());
} }
fn is_javascript(self) -> bool { fn is_javascript(self) -> bool {
let element: JSRef<Element> = ElementCast::from_ref(self); let element: JSRef<Element> = ElementCast::from_ref(self);
match element.get_attribute(ns!(""), &atom!("type")).root().map(|s| s.Value()) { match element.get_attribute(ns!(""), &atom!("type")).root().map(|s| s.r().Value()) {
Some(ref s) if s.is_empty() => { Some(ref s) if s.is_empty() => {
// type attr exists, but empty means js // type attr exists, but empty means js
debug!("script type empty, inferring js"); debug!("script type empty, inferring js");
@ -234,7 +235,7 @@ impl<'a> HTMLScriptElementHelpers for JSRef<'a, HTMLScriptElement> {
debug!("no script type"); debug!("no script type");
match element.get_attribute(ns!(""), &atom!("language")) match element.get_attribute(ns!(""), &atom!("language"))
.root() .root()
.map(|s| s.Value()) { .map(|s| s.r().Value()) {
Some(ref s) if s.is_empty() => { Some(ref s) if s.is_empty() => {
debug!("script language empty, inferring js"); debug!("script language empty, inferring js");
true true

View file

@ -50,7 +50,7 @@ impl HTMLSelectElement {
impl<'a> HTMLSelectElementMethods for JSRef<'a, HTMLSelectElement> { impl<'a> HTMLSelectElementMethods for JSRef<'a, HTMLSelectElement> {
fn Validity(self) -> Temporary<ValidityState> { fn Validity(self) -> Temporary<ValidityState> {
let window = window_from_node(self).root(); let window = window_from_node(self).root();
ValidityState::new(*window) ValidityState::new(window.r())
} }
// Note: this function currently only exists for test_union.html. // Note: this function currently only exists for test_union.html.

View file

@ -71,8 +71,8 @@ fn serialize_comment(comment: JSRef<Comment>, html: &mut String) {
fn serialize_text(text: JSRef<Text>, html: &mut String) { fn serialize_text(text: JSRef<Text>, html: &mut String) {
let text_node: JSRef<Node> = NodeCast::from_ref(text); let text_node: JSRef<Node> = NodeCast::from_ref(text);
match text_node.parent_node().map(|node| node.root()) { match text_node.parent_node().map(|node| node.root()) {
Some(ref parent) if parent.is_element() => { Some(ref parent) if parent.r().is_element() => {
let elem: JSRef<Element> = ElementCast::to_ref(**parent).unwrap(); let elem: JSRef<Element> = ElementCast::to_ref(parent.r()).unwrap();
match elem.local_name().as_slice() { match elem.local_name().as_slice() {
"style" | "script" | "xmp" | "iframe" | "style" | "script" | "xmp" | "iframe" |
"noembed" | "noframes" | "plaintext" | "noembed" | "noframes" | "plaintext" |
@ -105,7 +105,7 @@ fn serialize_elem(elem: JSRef<Element>, open_elements: &mut Vec<String>, html: &
html.push_str(elem.local_name().as_slice()); html.push_str(elem.local_name().as_slice());
for attr in elem.attrs().iter() { for attr in elem.attrs().iter() {
let attr = attr.root(); let attr = attr.root();
serialize_attr(*attr, html); serialize_attr(attr.r(), html);
}; };
html.push('>'); html.push('>');
@ -113,8 +113,8 @@ fn serialize_elem(elem: JSRef<Element>, open_elements: &mut Vec<String>, html: &
"pre" | "listing" | "textarea" if *elem.namespace() == ns!(HTML) => { "pre" | "listing" | "textarea" if *elem.namespace() == ns!(HTML) => {
let node: JSRef<Node> = NodeCast::from_ref(elem); let node: JSRef<Node> = NodeCast::from_ref(elem);
match node.first_child().map(|child| child.root()) { match node.first_child().map(|child| child.root()) {
Some(ref child) if child.is_text() => { Some(ref child) if child.r().is_text() => {
let text: JSRef<CharacterData> = CharacterDataCast::to_ref(**child).unwrap(); let text: JSRef<CharacterData> = CharacterDataCast::to_ref(child.r()).unwrap();
if text.data().len() > 0 && text.data().as_slice().char_at(0) == '\n' { if text.data().len() > 0 && text.data().as_slice().char_at(0) == '\n' {
html.push('\x0A'); html.push('\x0A');
} }

View file

@ -51,6 +51,7 @@ impl<'a> StyleElementHelpers for JSRef<'a, HTMLStyleElement> {
assert!(node.is_in_doc()); assert!(node.is_in_doc());
let win = window_from_node(node).root(); let win = window_from_node(node).root();
let win = win.r();
let url = win.page().get_url(); let url = win.page().get_url();
let data = node.GetTextContent().expect("Element.textContent must be a string"); let data = node.GetTextContent().expect("Element.textContent must be a string");

View file

@ -75,7 +75,7 @@ impl<'a> HTMLTableElementMethods for JSRef<'a, HTMLTableElement> {
match old_caption { match old_caption {
Some(htmlelem) => { Some(htmlelem) => {
let htmlelem_root = htmlelem.root(); let htmlelem_root = htmlelem.root();
let old_caption_node: JSRef<Node> = NodeCast::from_ref(*htmlelem_root); let old_caption_node: JSRef<Node> = NodeCast::from_ref(htmlelem_root.r());
assert!(node.RemoveChild(old_caption_node).is_ok()); assert!(node.RemoveChild(old_caption_node).is_ok());
} }
None => () None => ()

View file

@ -193,7 +193,7 @@ impl<'a> PrivateHTMLTextAreaElementHelpers for JSRef<'a, HTMLTextAreaElement> {
fn force_relayout(self) { fn force_relayout(self) {
let doc = document_from_node(self).root(); let doc = document_from_node(self).root();
let node: JSRef<Node> = NodeCast::from_ref(self); let node: JSRef<Node> = NodeCast::from_ref(self);
doc.content_changed(node, NodeDamage::OtherNodeDamage) doc.r().content_changed(node, NodeDamage::OtherNodeDamage)
} }
} }
@ -312,7 +312,7 @@ impl<'a> VirtualMethods for JSRef<'a, HTMLTextAreaElement> {
//TODO: set the editing position for text inputs //TODO: set the editing position for text inputs
let doc = document_from_node(*self).root(); let doc = document_from_node(*self).root();
doc.request_focus(ElementCast::from_ref(*self)); doc.r().request_focus(ElementCast::from_ref(*self));
} else if "keydown" == event.Type().as_slice() && !event.DefaultPrevented() { } else if "keydown" == event.Type().as_slice() && !event.DefaultPrevented() {
let keyevent: Option<JSRef<KeyboardEvent>> = KeyboardEventCast::to_ref(event); let keyevent: Option<JSRef<KeyboardEvent>> = KeyboardEventCast::to_ref(event);
keyevent.map(|event| { keyevent.map(|event| {

View file

@ -74,7 +74,7 @@ impl<'a> VirtualMethods for JSRef<'a, HTMLTitleElement> {
let node: JSRef<Node> = NodeCast::from_ref(*self); let node: JSRef<Node> = NodeCast::from_ref(*self);
if is_in_doc { if is_in_doc {
let document = node.owner_doc().root(); let document = node.owner_doc().root();
document.send_title_to_compositor() document.r().send_title_to_compositor()
} }
} }
} }

View file

@ -82,17 +82,17 @@ impl KeyboardEvent {
char_code: Option<u32>, char_code: Option<u32>,
key_code: u32) -> Temporary<KeyboardEvent> { key_code: u32) -> Temporary<KeyboardEvent> {
let ev = KeyboardEvent::new_uninitialized(window).root(); let ev = KeyboardEvent::new_uninitialized(window).root();
ev.deref().InitKeyboardEvent(type_, canBubble, cancelable, view, key, location, ev.r().InitKeyboardEvent(type_, canBubble, cancelable, view, key, location,
"".into_string(), repeat, "".into_string()); "".into_string(), repeat, "".into_string());
*ev.code.borrow_mut() = code; *ev.r().code.borrow_mut() = code;
ev.ctrl.set(ctrlKey); ev.r().ctrl.set(ctrlKey);
ev.alt.set(altKey); ev.r().alt.set(altKey);
ev.shift.set(shiftKey); ev.r().shift.set(shiftKey);
ev.meta.set(metaKey); ev.r().meta.set(metaKey);
ev.char_code.set(char_code); ev.r().char_code.set(char_code);
ev.key_code.set(key_code); ev.r().key_code.set(key_code);
ev.is_composing.set(isComposing); ev.r().is_composing.set(isComposing);
Temporary::from_rooted(*ev) Temporary::from_rooted(ev.r())
} }
pub fn Constructor(global: &GlobalRef, pub fn Constructor(global: &GlobalRef,
@ -101,7 +101,7 @@ impl KeyboardEvent {
let event = KeyboardEvent::new(global.as_window(), type_, let event = KeyboardEvent::new(global.as_window(), type_,
init.parent.parent.parent.bubbles, init.parent.parent.parent.bubbles,
init.parent.parent.parent.cancelable, init.parent.parent.parent.cancelable,
init.parent.parent.view.root_ref(), init.parent.parent.view.r(),
init.parent.parent.detail, init.parent.parent.detail,
init.key.clone(), init.code.clone(), init.location, init.key.clone(), init.code.clone(), init.location,
init.repeat, init.isComposing, init.parent.ctrlKey, init.repeat, init.isComposing, init.parent.ctrlKey,

View file

@ -87,7 +87,7 @@ macro_rules! make_url_or_base_getter(
match url.as_slice() { match url.as_slice() {
"" => { "" => {
let window = window_from_node(self).root(); let window = window_from_node(self).root();
window.get_url().serialize() window.r().get_url().serialize()
}, },
_ => url _ => url
} }

View file

@ -58,9 +58,9 @@ impl MessageEvent {
data: JSVal, origin: DOMString, lastEventId: DOMString) data: JSVal, origin: DOMString, lastEventId: DOMString)
-> Temporary<MessageEvent> { -> Temporary<MessageEvent> {
let ev = MessageEvent::new_initialized(global, data, origin, lastEventId).root(); let ev = MessageEvent::new_initialized(global, data, origin, lastEventId).root();
let event: JSRef<Event> = EventCast::from_ref(*ev); let event: JSRef<Event> = EventCast::from_ref(ev.r());
event.InitEvent(type_, bubbles, cancelable); event.InitEvent(type_, bubbles, cancelable);
Temporary::from_rooted(*ev) Temporary::from_rooted(ev.r())
} }
pub fn Constructor(global: &GlobalRef, pub fn Constructor(global: &GlobalRef,
@ -80,7 +80,7 @@ impl MessageEvent {
let messageevent = MessageEvent::new( let messageevent = MessageEvent::new(
scope, "message".into_string(), false, false, message, scope, "message".into_string(), false, false, message,
"".into_string(), "".into_string()).root(); "".into_string(), "".into_string()).root();
let event: JSRef<Event> = EventCast::from_ref(*messageevent); let event: JSRef<Event> = EventCast::from_ref(messageevent.r());
target.dispatch_event(event); target.dispatch_event(event);
} }
} }

View file

@ -79,11 +79,11 @@ impl MouseEvent {
button: i16, button: i16,
relatedTarget: Option<JSRef<EventTarget>>) -> Temporary<MouseEvent> { relatedTarget: Option<JSRef<EventTarget>>) -> Temporary<MouseEvent> {
let ev = MouseEvent::new_uninitialized(window).root(); let ev = MouseEvent::new_uninitialized(window).root();
ev.InitMouseEvent(type_, canBubble, cancelable, view, detail, ev.r().InitMouseEvent(type_, canBubble, cancelable, view, detail,
screenX, screenY, clientX, clientY, screenX, screenY, clientX, clientY,
ctrlKey, altKey, shiftKey, metaKey, ctrlKey, altKey, shiftKey, metaKey,
button, relatedTarget); button, relatedTarget);
Temporary::from_rooted(*ev) Temporary::from_rooted(ev.r())
} }
pub fn Constructor(global: &GlobalRef, pub fn Constructor(global: &GlobalRef,
@ -92,12 +92,12 @@ impl MouseEvent {
let event = MouseEvent::new(global.as_window(), type_, let event = MouseEvent::new(global.as_window(), type_,
init.parent.parent.parent.bubbles, init.parent.parent.parent.bubbles,
init.parent.parent.parent.cancelable, init.parent.parent.parent.cancelable,
init.parent.parent.view.root_ref(), init.parent.parent.view.r(),
init.parent.parent.detail, init.parent.parent.detail,
init.screenX, init.screenY, init.screenX, init.screenY,
init.clientX, init.clientY, init.parent.ctrlKey, init.clientX, init.clientY, init.parent.ctrlKey,
init.parent.altKey, init.parent.shiftKey, init.parent.metaKey, init.parent.altKey, init.parent.shiftKey, init.parent.metaKey,
init.button, init.relatedTarget.root_ref()); init.button, init.relatedTarget.r());
Ok(event) Ok(event)
} }
} }

View file

@ -33,11 +33,11 @@ impl NamedNodeMap {
impl<'a> NamedNodeMapMethods for JSRef<'a, NamedNodeMap> { impl<'a> NamedNodeMapMethods for JSRef<'a, NamedNodeMap> {
fn Length(self) -> u32 { fn Length(self) -> u32 {
self.owner.root().attrs().len() as u32 self.owner.root().r().attrs().len() as u32
} }
fn Item(self, index: u32) -> Option<Temporary<Attr>> { fn Item(self, index: u32) -> Option<Temporary<Attr>> {
self.owner.root().attrs().as_slice().get(index as uint).map(|x| Temporary::new(x.clone())) self.owner.root().r().attrs().as_slice().get(index as uint).map(|x| Temporary::new(x.clone()))
} }
fn IndexedGetter(self, index: u32, found: &mut bool) -> Option<Temporary<Attr>> { fn IndexedGetter(self, index: u32, found: &mut bool) -> Option<Temporary<Attr>> {

View file

@ -282,8 +282,8 @@ impl<'a> PrivateNodeHelpers for JSRef<'a, Node> {
} }
let parent = self.parent_node().root(); let parent = self.parent_node().root();
parent.map(|parent| vtable_for(&*parent).child_inserted(self)); parent.map(|parent| vtable_for(&parent.r()).child_inserted(self));
document.content_and_heritage_changed(self, NodeDamage::OtherNodeDamage); document.r().content_and_heritage_changed(self, NodeDamage::OtherNodeDamage);
} }
// http://dom.spec.whatwg.org/#node-is-removed // http://dom.spec.whatwg.org/#node-is-removed
@ -307,15 +307,15 @@ impl<'a> PrivateNodeHelpers for JSRef<'a, Node> {
assert!(new_child.next_sibling().is_none()); assert!(new_child.next_sibling().is_none());
match before { match before {
Some(ref before) => { Some(ref before) => {
assert!(before.parent_node().root().root_ref() == Some(self)); assert!(before.parent_node().root().r() == Some(self));
match before.prev_sibling().root() { match before.prev_sibling().root() {
None => { None => {
assert!(Some(*before) == self.first_child().root().root_ref()); assert!(Some(*before) == self.first_child().root().r());
self.first_child.assign(Some(new_child)); self.first_child.assign(Some(new_child));
}, },
Some(prev_sibling) => { Some(prev_sibling) => {
prev_sibling.next_sibling.assign(Some(new_child)); prev_sibling.r().next_sibling.assign(Some(new_child));
new_child.prev_sibling.assign(Some(*prev_sibling)); new_child.prev_sibling.assign(Some(prev_sibling.r()));
}, },
} }
before.prev_sibling.assign(Some(new_child)); before.prev_sibling.assign(Some(new_child));
@ -325,9 +325,9 @@ impl<'a> PrivateNodeHelpers for JSRef<'a, Node> {
match self.last_child().root() { match self.last_child().root() {
None => self.first_child.assign(Some(new_child)), None => self.first_child.assign(Some(new_child)),
Some(last_child) => { Some(last_child) => {
assert!(last_child.next_sibling().is_none()); assert!(last_child.r().next_sibling().is_none());
last_child.next_sibling.assign(Some(new_child)); last_child.r().next_sibling.assign(Some(new_child));
new_child.prev_sibling.assign(Some(*last_child)); new_child.prev_sibling.assign(Some(last_child.r()));
} }
} }
@ -342,14 +342,14 @@ impl<'a> PrivateNodeHelpers for JSRef<'a, Node> {
/// ///
/// Fails unless `child` is a child of this node. /// Fails unless `child` is a child of this node.
fn remove_child(self, child: JSRef<Node>) { fn remove_child(self, child: JSRef<Node>) {
assert!(child.parent_node().root().root_ref() == Some(self)); assert!(child.parent_node().root().r() == Some(self));
match child.prev_sibling.get().root() { match child.prev_sibling.get().root() {
None => { None => {
self.first_child.assign(child.next_sibling.get()); self.first_child.assign(child.next_sibling.get());
} }
Some(prev_sibling) => { Some(prev_sibling) => {
prev_sibling.next_sibling.assign(child.next_sibling.get()); prev_sibling.r().next_sibling.assign(child.next_sibling.get());
} }
} }
@ -358,7 +358,7 @@ impl<'a> PrivateNodeHelpers for JSRef<'a, Node> {
self.last_child.assign(child.prev_sibling.get()); self.last_child.assign(child.prev_sibling.get());
} }
Some(next_sibling) => { Some(next_sibling) => {
next_sibling.prev_sibling.assign(child.prev_sibling.get()); next_sibling.r().prev_sibling.assign(child.prev_sibling.get());
} }
} }
@ -682,7 +682,7 @@ impl<'a> NodeHelpers<'a> for JSRef<'a, Node> {
Some(parent) => parent, Some(parent) => parent,
}; };
for sibling in parent.root().children() { for sibling in parent.root().r().children() {
sibling.set_has_dirty_siblings(true); sibling.set_has_dirty_siblings(true);
} }
@ -726,11 +726,11 @@ impl<'a> NodeHelpers<'a> for JSRef<'a, Node> {
} }
fn get_bounding_content_box(self) -> Rect<Au> { fn get_bounding_content_box(self) -> Rect<Au> {
window_from_node(self).root().page().content_box_query(self.to_trusted_node_address()) window_from_node(self).root().r().page().content_box_query(self.to_trusted_node_address())
} }
fn get_content_boxes(self) -> Vec<Rect<Au>> { fn get_content_boxes(self) -> Vec<Rect<Au>> {
window_from_node(self).root().page().content_boxes_query(self.to_trusted_node_address()) window_from_node(self).root().r().page().content_boxes_query(self.to_trusted_node_address())
} }
// http://dom.spec.whatwg.org/#dom-parentnode-queryselector // http://dom.spec.whatwg.org/#dom-parentnode-queryselector
@ -781,7 +781,7 @@ impl<'a> NodeHelpers<'a> for JSRef<'a, Node> {
unsafe { unsafe {
self.query_selector_iter(selectors).map(|mut iter| { self.query_selector_iter(selectors).map(|mut iter| {
let window = window_from_node(self).root(); let window = window_from_node(self).root();
NodeList::new_simple_list(*window, iter.collect()) NodeList::new_simple_list(window.r(), iter.collect())
}) })
} }
} }
@ -802,7 +802,7 @@ impl<'a> NodeHelpers<'a> for JSRef<'a, Node> {
} }
fn is_in_html_doc(self) -> bool { fn is_in_html_doc(self) -> bool {
self.owner_doc().root().is_html_document() self.owner_doc().root().r().is_html_document()
} }
fn children(self) -> NodeChildrenIterator<'a> { fn children(self) -> NodeChildrenIterator<'a> {
@ -825,7 +825,7 @@ impl<'a> NodeHelpers<'a> for JSRef<'a, Node> {
fn remove_self(self) { fn remove_self(self) {
match self.parent_node().root() { match self.parent_node().root() {
Some(parent) => parent.remove_child(self), Some(parent) => parent.r().remove_child(self),
None => () None => ()
} }
} }
@ -843,11 +843,11 @@ impl<'a> NodeHelpers<'a> for JSRef<'a, Node> {
NodeInfo { NodeInfo {
uniqueId: self.unique_id.borrow().clone(), uniqueId: self.unique_id.borrow().clone(),
baseURI: self.GetBaseURI().unwrap_or("".into_string()), baseURI: self.GetBaseURI().unwrap_or("".into_string()),
parent: self.GetParentNode().root().map(|node| node.get_unique_id()).unwrap_or("".into_string()), parent: self.GetParentNode().root().map(|node| node.r().get_unique_id()).unwrap_or("".into_string()),
nodeType: self.NodeType() as uint, nodeType: self.NodeType() as uint,
namespaceURI: "".into_string(), //FIXME namespaceURI: "".into_string(), //FIXME
nodeName: self.NodeName(), nodeName: self.NodeName(),
numChildren: self.ChildNodes().root().Length() as uint, numChildren: self.ChildNodes().root().r().Length() as uint,
//FIXME doctype nodes only //FIXME doctype nodes only
name: "".into_string(), name: "".into_string(),
@ -861,8 +861,9 @@ impl<'a> NodeHelpers<'a> for JSRef<'a, Node> {
isDocumentElement: isDocumentElement:
self.owner_doc().root() self.owner_doc().root()
.r()
.GetDocumentElement() .GetDocumentElement()
.map(|elem| NodeCast::from_ref(*elem.root()) == self) .map(|elem| NodeCast::from_ref(elem.root().r()) == self)
.unwrap_or(false), .unwrap_or(false),
shortValue: self.GetNodeValue().unwrap_or("".into_string()), //FIXME: truncate shortValue: self.GetNodeValue().unwrap_or("".into_string()), //FIXME: truncate
@ -1159,7 +1160,7 @@ impl Node {
wrap_fn: extern "Rust" fn(*mut JSContext, GlobalRef, Box<N>) -> Temporary<N>) wrap_fn: extern "Rust" fn(*mut JSContext, GlobalRef, Box<N>) -> Temporary<N>)
-> Temporary<N> { -> Temporary<N> {
let window = document.window().root(); let window = document.window().root();
reflect_dom_object(node, GlobalRef::Window(*window), wrap_fn) reflect_dom_object(node, GlobalRef::Window(window.r()), wrap_fn)
} }
pub fn new_inherited(type_id: NodeTypeId, doc: JSRef<Document>) -> Node { pub fn new_inherited(type_id: NodeTypeId, doc: JSRef<Document>) -> Node {
@ -1210,14 +1211,14 @@ impl Node {
// Step 1. // Step 1.
match node.parent_node().root() { match node.parent_node().root() {
Some(parent) => { Some(parent) => {
Node::remove(node, *parent, SuppressObserver::Unsuppressed); Node::remove(node, parent.r(), SuppressObserver::Unsuppressed);
} }
None => (), None => (),
} }
// Step 2. // Step 2.
let node_doc = document_from_node(node).root(); let node_doc = document_from_node(node).root();
if *node_doc != document { if node_doc.r() != document {
for descendant in node.traverse_preorder() { for descendant in node.traverse_preorder() {
descendant.set_owner_doc(document); descendant.set_owner_doc(document);
} }
@ -1429,7 +1430,7 @@ impl Node {
match node { match node {
Some(node) => { Some(node) => {
let document = document_from_node(parent).root(); let document = document_from_node(parent).root();
Node::adopt(node, *document); Node::adopt(node, document.r());
} }
None => (), None => (),
} }
@ -1519,16 +1520,16 @@ impl Node {
let doctype: JSRef<DocumentType> = DocumentTypeCast::to_ref(node).unwrap(); let doctype: JSRef<DocumentType> = DocumentTypeCast::to_ref(node).unwrap();
let doctype = DocumentType::new(doctype.name().clone(), let doctype = DocumentType::new(doctype.name().clone(),
Some(doctype.public_id().clone()), Some(doctype.public_id().clone()),
Some(doctype.system_id().clone()), *document); Some(doctype.system_id().clone()), document.r());
NodeCast::from_temporary(doctype) NodeCast::from_temporary(doctype)
}, },
NodeTypeId::DocumentFragment => { NodeTypeId::DocumentFragment => {
let doc_fragment = DocumentFragment::new(*document); let doc_fragment = DocumentFragment::new(document.r());
NodeCast::from_temporary(doc_fragment) NodeCast::from_temporary(doc_fragment)
}, },
NodeTypeId::Comment => { NodeTypeId::Comment => {
let comment: JSRef<Comment> = CommentCast::to_ref(node).unwrap(); let comment: JSRef<Comment> = CommentCast::to_ref(node).unwrap();
let comment = Comment::new(comment.characterdata().data().clone(), *document); let comment = Comment::new(comment.characterdata().data().clone(), document.r());
NodeCast::from_temporary(comment) NodeCast::from_temporary(comment)
}, },
NodeTypeId::Document => { NodeTypeId::Document => {
@ -1538,7 +1539,7 @@ impl Node {
false => IsHTMLDocument::NonHTMLDocument, false => IsHTMLDocument::NonHTMLDocument,
}; };
let window = document.window().root(); let window = document.window().root();
let document = Document::new(*window, Some(document.url().clone()), let document = Document::new(window.r(), Some(document.url().clone()),
is_html_doc, None, is_html_doc, None,
DocumentSource::NotFromParser); DocumentSource::NotFromParser);
NodeCast::from_temporary(document) NodeCast::from_temporary(document)
@ -1551,67 +1552,67 @@ impl Node {
}; };
let element = Element::create(name, let element = Element::create(name,
element.prefix().as_ref().map(|p| p.as_slice().into_string()), element.prefix().as_ref().map(|p| p.as_slice().into_string()),
*document, ElementCreator::ScriptCreated); document.r(), ElementCreator::ScriptCreated);
NodeCast::from_temporary(element) NodeCast::from_temporary(element)
}, },
NodeTypeId::Text => { NodeTypeId::Text => {
let text: JSRef<Text> = TextCast::to_ref(node).unwrap(); let text: JSRef<Text> = TextCast::to_ref(node).unwrap();
let text = Text::new(text.characterdata().data().clone(), *document); let text = Text::new(text.characterdata().data().clone(), document.r());
NodeCast::from_temporary(text) NodeCast::from_temporary(text)
}, },
NodeTypeId::ProcessingInstruction => { NodeTypeId::ProcessingInstruction => {
let pi: JSRef<ProcessingInstruction> = ProcessingInstructionCast::to_ref(node).unwrap(); let pi: JSRef<ProcessingInstruction> = ProcessingInstructionCast::to_ref(node).unwrap();
let pi = ProcessingInstruction::new(pi.target().clone(), let pi = ProcessingInstruction::new(pi.target().clone(),
pi.characterdata().data().clone(), *document); pi.characterdata().data().clone(), document.r());
NodeCast::from_temporary(pi) NodeCast::from_temporary(pi)
}, },
}.root(); }.root();
// Step 3. // Step 3.
let document = match DocumentCast::to_ref(*copy) { let document = match DocumentCast::to_ref(copy.r()) {
Some(doc) => doc, Some(doc) => doc,
None => *document, None => document.r(),
}; };
assert!(*copy.owner_doc().root() == document); assert!(copy.r().owner_doc().root().r() == document);
// Step 4 (some data already copied in step 2). // Step 4 (some data already copied in step 2).
match node.type_id() { match node.type_id() {
NodeTypeId::Document => { NodeTypeId::Document => {
let node_doc: JSRef<Document> = DocumentCast::to_ref(node).unwrap(); let node_doc: JSRef<Document> = DocumentCast::to_ref(node).unwrap();
let copy_doc: JSRef<Document> = DocumentCast::to_ref(*copy).unwrap(); let copy_doc: JSRef<Document> = DocumentCast::to_ref(copy.r()).unwrap();
copy_doc.set_encoding_name(node_doc.encoding_name().clone()); copy_doc.set_encoding_name(node_doc.encoding_name().clone());
copy_doc.set_quirks_mode(node_doc.quirks_mode()); copy_doc.set_quirks_mode(node_doc.quirks_mode());
}, },
NodeTypeId::Element(..) => { NodeTypeId::Element(..) => {
let node_elem: JSRef<Element> = ElementCast::to_ref(node).unwrap(); let node_elem: JSRef<Element> = ElementCast::to_ref(node).unwrap();
let copy_elem: JSRef<Element> = ElementCast::to_ref(*copy).unwrap(); let copy_elem: JSRef<Element> = ElementCast::to_ref(copy.r()).unwrap();
// FIXME: https://github.com/mozilla/servo/issues/1737 // FIXME: https://github.com/mozilla/servo/issues/1737
let window = document.window().root(); let window = document.window().root();
for attr in node_elem.attrs().iter().map(|attr| attr.root()) { for attr in node_elem.attrs().iter().map(|attr| attr.root()) {
copy_elem.attrs_mut().push_unrooted( copy_elem.attrs_mut().push_unrooted(
&Attr::new(*window, &Attr::new(window.r(),
attr.local_name().clone(), attr.value().clone(), attr.r().local_name().clone(), attr.r().value().clone(),
attr.name().clone(), attr.namespace().clone(), attr.r().name().clone(), attr.r().namespace().clone(),
attr.prefix().clone(), Some(copy_elem))); attr.r().prefix().clone(), Some(copy_elem)));
} }
}, },
_ => () _ => ()
} }
// Step 5: cloning steps. // Step 5: cloning steps.
vtable_for(&node).cloning_steps(*copy, maybe_doc, clone_children); vtable_for(&node).cloning_steps(copy.r(), maybe_doc, clone_children);
// Step 6. // Step 6.
if clone_children == CloneChildrenFlag::CloneChildren { if clone_children == CloneChildrenFlag::CloneChildren {
for child in node.children() { for child in node.children() {
let child_copy = Node::clone(child, Some(document), clone_children).root(); let child_copy = Node::clone(child, Some(document), clone_children).root();
let _inserted_node = Node::pre_insert(*child_copy, *copy, None); let _inserted_node = Node::pre_insert(child_copy.r(), copy.r(), None);
} }
} }
// Step 7. // Step 7.
Temporary::from_rooted(*copy) Temporary::from_rooted(copy.r())
} }
/// Sends layout data, if any, back to the layout task to be destroyed. /// Sends layout data, if any, back to the layout task to be destroyed.
@ -1708,7 +1709,7 @@ impl<'a> NodeMethods for JSRef<'a, Node> {
self.parent_node.get() self.parent_node.get()
.and_then(|parent| { .and_then(|parent| {
let parent = parent.root(); let parent = parent.root();
ElementCast::to_ref(*parent).map(|elem| { ElementCast::to_ref(parent.r()).map(|elem| {
Temporary::from_rooted(elem) Temporary::from_rooted(elem)
}) })
}) })
@ -1723,8 +1724,8 @@ impl<'a> NodeMethods for JSRef<'a, Node> {
fn ChildNodes(self) -> Temporary<NodeList> { fn ChildNodes(self) -> Temporary<NodeList> {
self.child_list.or_init(|| { self.child_list.or_init(|| {
let doc = self.owner_doc().root(); let doc = self.owner_doc().root();
let window = doc.window().root(); let window = doc.r().window().root();
NodeList::new_child_list(*window, self) NodeList::new_child_list(window.r(), self)
}) })
} }
@ -1807,11 +1808,11 @@ impl<'a> NodeMethods for JSRef<'a, Node> {
None None
} else { } else {
let document = self.owner_doc().root(); let document = self.owner_doc().root();
Some(NodeCast::from_temporary(document.CreateTextNode(value))) Some(NodeCast::from_temporary(document.r().CreateTextNode(value)))
}.root(); }.root();
// Step 3. // Step 3.
Node::replace_all(node.root_ref(), self); Node::replace_all(node.r(), self);
} }
NodeTypeId::Comment | NodeTypeId::Comment |
NodeTypeId::Text | NodeTypeId::Text |
@ -1821,7 +1822,7 @@ impl<'a> NodeMethods for JSRef<'a, Node> {
// Notify the document that the content of this node is different // Notify the document that the content of this node is different
let document = self.owner_doc().root(); let document = self.owner_doc().root();
document.content_changed(self, NodeDamage::OtherNodeDamage); document.r().content_changed(self, NodeDamage::OtherNodeDamage);
} }
NodeTypeId::DocumentType | NodeTypeId::DocumentType |
NodeTypeId::Document => {} NodeTypeId::Document => {}
@ -1942,7 +1943,7 @@ impl<'a> NodeMethods for JSRef<'a, Node> {
// Step 9. // Step 9.
let document = document_from_node(self).root(); let document = document_from_node(self).root();
Node::adopt(node, *document); Node::adopt(node, document.r());
{ {
// Step 10. // Step 10.
@ -2044,9 +2045,9 @@ impl<'a> NodeMethods for JSRef<'a, Node> {
assert!(element.attrs().len() == other_element.attrs().len()); assert!(element.attrs().len() == other_element.attrs().len());
element.attrs().iter().map(|attr| attr.root()).all(|attr| { element.attrs().iter().map(|attr| attr.root()).all(|attr| {
other_element.attrs().iter().map(|attr| attr.root()).any(|other_attr| { other_element.attrs().iter().map(|attr| attr.root()).any(|other_attr| {
(*attr.namespace() == *other_attr.namespace()) && (*attr.r().namespace() == *other_attr.r().namespace()) &&
(attr.local_name() == other_attr.local_name()) && (attr.r().local_name() == other_attr.r().local_name()) &&
(attr.value().as_slice() == other_attr.value().as_slice()) (attr.r().value().as_slice() == other_attr.r().value().as_slice())
}) })
}) })
} }
@ -2183,7 +2184,7 @@ pub fn document_from_node<T: NodeBase+Reflectable>(derived: JSRef<T>) -> Tempora
pub fn window_from_node<T: NodeBase+Reflectable>(derived: JSRef<T>) -> Temporary<Window> { pub fn window_from_node<T: NodeBase+Reflectable>(derived: JSRef<T>) -> Temporary<Window> {
let document = document_from_node(derived).root(); let document = document_from_node(derived).root();
document.window() document.r().window()
} }
impl<'a> VirtualMethods for JSRef<'a, Node> { impl<'a> VirtualMethods for JSRef<'a, Node> {
@ -2279,12 +2280,12 @@ impl<'a> style::TNode<'a, JSRef<'a, Element>> for JSRef<'a, Node> {
match attr.namespace { match attr.namespace {
style::NamespaceConstraint::Specific(ref ns) => { style::NamespaceConstraint::Specific(ref ns) => {
self.as_element().get_attribute(ns.clone(), name).root() self.as_element().get_attribute(ns.clone(), name).root()
.map_or(false, |attr| test(attr.value().as_slice())) .map_or(false, |attr| test(attr.r().value().as_slice()))
}, },
style::NamespaceConstraint::Any => { style::NamespaceConstraint::Any => {
self.as_element().get_attributes(name).iter() self.as_element().get_attributes(name).iter()
.map(|attr| attr.root()) .map(|attr| attr.root())
.any(|attr| test(attr.value().as_slice())) .any(|attr| test(attr.r().value().as_slice()))
} }
} }
} }
@ -2338,7 +2339,7 @@ impl<'a> DisabledStateHelpers for JSRef<'a, Node> {
fn check_parent_disabled_state_for_option(self) { fn check_parent_disabled_state_for_option(self) {
if self.get_disabled_state() { return; } if self.get_disabled_state() { return; }
match self.parent_node().root() { match self.parent_node().root() {
Some(ref parent) if parent.is_htmloptgroupelement() && parent.get_disabled_state() => { Some(ref parent) if parent.r().is_htmloptgroupelement() && parent.r().get_disabled_state() => {
self.set_disabled_state(true); self.set_disabled_state(true);
self.set_enabled_state(false); self.set_enabled_state(false);
}, },

View file

@ -52,7 +52,7 @@ impl<'a> NodeListMethods for JSRef<'a, NodeList> {
NodeListType::Simple(ref elems) => elems.len() as u32, NodeListType::Simple(ref elems) => elems.len() as u32,
NodeListType::Children(ref node) => { NodeListType::Children(ref node) => {
let node = node.root(); let node = node.root();
node.children().count() as u32 node.r().children().count() as u32
} }
} }
} }
@ -63,8 +63,8 @@ impl<'a> NodeListMethods for JSRef<'a, NodeList> {
NodeListType::Simple(ref elems) => Some(Temporary::new(elems[index as uint].clone())), NodeListType::Simple(ref elems) => Some(Temporary::new(elems[index as uint].clone())),
NodeListType::Children(ref node) => { NodeListType::Children(ref node) => {
let node = node.root(); let node = node.root();
node.children().nth(index as uint) node.r().children().nth(index as uint)
.map(|child| Temporary::from_rooted(child)) .map(|child| Temporary::from_rooted(child))
} }
} }
} }

View file

@ -49,7 +49,7 @@ impl<'a> PerformanceMethods for JSRef<'a, Performance> {
// https://dvcs.w3.org/hg/webperf/raw-file/tip/specs/HighResolutionTime/Overview.html#dom-performance-now // https://dvcs.w3.org/hg/webperf/raw-file/tip/specs/HighResolutionTime/Overview.html#dom-performance-now
fn Now(self) -> DOMHighResTimeStamp { fn Now(self) -> DOMHighResTimeStamp {
let navStart = self.timing.root().NavigationStartPrecise(); let navStart = self.timing.root().r().NavigationStartPrecise();
(time::precise_time_ns() as f64 - navStart) * 1000000u as DOMHighResTimeStamp (time::precise_time_ns() as f64 - navStart) * 1000000u as DOMHighResTimeStamp
} }
} }

View file

@ -42,9 +42,9 @@ impl ProgressEvent {
let ev = reflect_dom_object(box ProgressEvent::new_inherited(length_computable, loaded, total), let ev = reflect_dom_object(box ProgressEvent::new_inherited(length_computable, loaded, total),
global, global,
ProgressEventBinding::Wrap).root(); ProgressEventBinding::Wrap).root();
let event: JSRef<Event> = EventCast::from_ref(*ev); let event: JSRef<Event> = EventCast::from_ref(ev.r());
event.InitEvent(type_, can_bubble, cancelable); event.InitEvent(type_, can_bubble, cancelable);
Temporary::from_rooted(*ev) Temporary::from_rooted(ev.r())
} }
pub fn Constructor(global: &GlobalRef, pub fn Constructor(global: &GlobalRef,
type_: DOMString, type_: DOMString,

View file

@ -26,13 +26,13 @@ impl Range {
pub fn new(document: JSRef<Document>) -> Temporary<Range> { pub fn new(document: JSRef<Document>) -> Temporary<Range> {
let window = document.window().root(); let window = document.window().root();
reflect_dom_object(box Range::new_inherited(), reflect_dom_object(box Range::new_inherited(),
GlobalRef::Window(*window), GlobalRef::Window(window.r()),
RangeBinding::Wrap) RangeBinding::Wrap)
} }
pub fn Constructor(global: &GlobalRef) -> Fallible<Temporary<Range>> { pub fn Constructor(global: &GlobalRef) -> Fallible<Temporary<Range>> {
let document = global.as_window().Document().root(); let document = global.as_window().Document().root();
Ok(Range::new(*document)) Ok(Range::new(document.r()))
} }
} }

View file

@ -72,7 +72,8 @@ impl ServoHTMLParser {
tokenizer: DOMRefCell::new(tok), tokenizer: DOMRefCell::new(tok),
}; };
reflect_dom_object(box parser, GlobalRef::Window(*window), ServoHTMLParserBinding::Wrap) reflect_dom_object(box parser, GlobalRef::Window(window.r()),
ServoHTMLParserBinding::Wrap)
} }
#[inline] #[inline]

View file

@ -38,13 +38,13 @@ impl Storage {
fn get_url(&self) -> Url { fn get_url(&self) -> Url {
let global_root = self.global.root(); let global_root = self.global.root();
let global_ref = global_root.root_ref(); let global_ref = global_root.r();
global_ref.get_url() global_ref.get_url()
} }
fn get_storage_task(&self) -> StorageTask { fn get_storage_task(&self) -> StorageTask {
let global_root = self.global.root(); let global_root = self.global.root();
let global_ref = global_root.root_ref(); let global_ref = global_root.r();
global_ref.as_window().storage_task() global_ref.as_window().storage_task()
} }

View file

@ -59,7 +59,7 @@ impl<'a> TestBindingMethods for JSRef<'a, TestBinding> {
fn SetEnumAttribute(self, _: TestEnum) {} fn SetEnumAttribute(self, _: TestEnum) {}
fn InterfaceAttribute(self) -> Temporary<Blob> { fn InterfaceAttribute(self) -> Temporary<Blob> {
let global = self.global.root(); let global = self.global.root();
Blob::new(&global.root_ref(), None, "") Blob::new(&global.r(), None, "")
} }
fn SetInterfaceAttribute(self, _: JSRef<Blob>) {} fn SetInterfaceAttribute(self, _: JSRef<Blob>) {}
fn UnionAttribute(self) -> HTMLElementOrLong { eLong(0) } fn UnionAttribute(self) -> HTMLElementOrLong { eLong(0) }
@ -99,7 +99,7 @@ impl<'a> TestBindingMethods for JSRef<'a, TestBinding> {
fn GetEnumAttributeNullable(self) -> Option<TestEnum> { Some(_empty) } fn GetEnumAttributeNullable(self) -> Option<TestEnum> { Some(_empty) }
fn GetInterfaceAttributeNullable(self) -> Option<Temporary<Blob>> { fn GetInterfaceAttributeNullable(self) -> Option<Temporary<Blob>> {
let global = self.global.root(); let global = self.global.root();
Some(Blob::new(&global.root_ref(), None, "")) Some(Blob::new(&global.r(), None, ""))
} }
fn SetInterfaceAttributeNullable(self, _: Option<JSRef<Blob>>) {} fn SetInterfaceAttributeNullable(self, _: Option<JSRef<Blob>>) {}
fn GetUnionAttributeNullable(self) -> Option<HTMLElementOrLong> { Some(eLong(0)) } fn GetUnionAttributeNullable(self) -> Option<HTMLElementOrLong> { Some(eLong(0)) }
@ -123,7 +123,7 @@ impl<'a> TestBindingMethods for JSRef<'a, TestBinding> {
fn ReceiveEnum(self) -> TestEnum { _empty } fn ReceiveEnum(self) -> TestEnum { _empty }
fn ReceiveInterface(self) -> Temporary<Blob> { fn ReceiveInterface(self) -> Temporary<Blob> {
let global = self.global.root(); let global = self.global.root();
Blob::new(&global.root_ref(), None, "") Blob::new(&global.r(), None, "")
} }
fn ReceiveAny(self, _: *mut JSContext) -> JSVal { NullValue() } fn ReceiveAny(self, _: *mut JSContext) -> JSVal { NullValue() }
fn ReceiveUnion(self) -> HTMLElementOrLong { eLong(0) } fn ReceiveUnion(self) -> HTMLElementOrLong { eLong(0) }
@ -145,7 +145,7 @@ impl<'a> TestBindingMethods for JSRef<'a, TestBinding> {
fn ReceiveNullableEnum(self) -> Option<TestEnum> { Some(_empty) } fn ReceiveNullableEnum(self) -> Option<TestEnum> { Some(_empty) }
fn ReceiveNullableInterface(self) -> Option<Temporary<Blob>> { fn ReceiveNullableInterface(self) -> Option<Temporary<Blob>> {
let global = self.global.root(); let global = self.global.root();
Some(Blob::new(&global.root_ref(), None, "")) Some(Blob::new(&global.r(), None, ""))
} }
fn ReceiveNullableUnion(self) -> Option<HTMLElementOrLong> { Some(eLong(0)) } fn ReceiveNullableUnion(self) -> Option<HTMLElementOrLong> { Some(eLong(0)) }
fn ReceiveNullableUnion2(self) -> Option<EventOrString> { Some(eString("".into_string())) } fn ReceiveNullableUnion2(self) -> Option<EventOrString> { Some(eString("".into_string())) }

View file

@ -40,7 +40,7 @@ impl Text {
pub fn Constructor(global: &GlobalRef, text: DOMString) -> Fallible<Temporary<Text>> { pub fn Constructor(global: &GlobalRef, text: DOMString) -> Fallible<Temporary<Text>> {
let document = global.as_window().Document().root(); let document = global.as_window().Document().root();
Ok(Text::new(text, *document)) Ok(Text::new(text, document.r()))
} }
#[inline] #[inline]

View file

@ -47,7 +47,7 @@ impl TreeWalker {
filter: Filter) -> Temporary<TreeWalker> { filter: Filter) -> Temporary<TreeWalker> {
let window = document.window().root(); let window = document.window().root();
reflect_dom_object(box TreeWalker::new_inherited(root_node, what_to_show, filter), reflect_dom_object(box TreeWalker::new_inherited(root_node, what_to_show, filter),
GlobalRef::Window(*window), GlobalRef::Window(window.r()),
TreeWalkerBinding::Wrap) TreeWalkerBinding::Wrap)
} }

View file

@ -53,8 +53,8 @@ impl UIEvent {
view: Option<JSRef<Window>>, view: Option<JSRef<Window>>,
detail: i32) -> Temporary<UIEvent> { detail: i32) -> Temporary<UIEvent> {
let ev = UIEvent::new_uninitialized(window).root(); let ev = UIEvent::new_uninitialized(window).root();
ev.InitUIEvent(type_, can_bubble, cancelable, view, detail); ev.r().InitUIEvent(type_, can_bubble, cancelable, view, detail);
Temporary::from_rooted(*ev) Temporary::from_rooted(ev.r())
} }
pub fn Constructor(global: &GlobalRef, pub fn Constructor(global: &GlobalRef,
@ -62,7 +62,7 @@ impl UIEvent {
init: &UIEventBinding::UIEventInit) -> Fallible<Temporary<UIEvent>> { init: &UIEventBinding::UIEventInit) -> Fallible<Temporary<UIEvent>> {
let event = UIEvent::new(global.as_window(), type_, let event = UIEvent::new(global.as_window(), type_,
init.parent.bubbles, init.parent.cancelable, init.parent.bubbles, init.parent.cancelable,
init.view.root_ref(), init.detail); init.view.r(), init.detail);
Ok(event) Ok(event)
} }
} }

View file

@ -52,7 +52,7 @@ impl URLSearchParams {
Some(eURLSearchParams(u)) => { Some(eURLSearchParams(u)) => {
let u = u.root(); let u = u.root();
let mut map = usp.data.borrow_mut(); let mut map = usp.data.borrow_mut();
*map = u.data.borrow().clone(); *map = u.r().data.borrow().clone();
}, },
None => {} None => {}
} }

View file

@ -71,31 +71,31 @@ impl Worker {
let (sender, receiver) = channel(); let (sender, receiver) = channel();
let worker = Worker::new(global, sender.clone()).root(); let worker = Worker::new(global, sender.clone()).root();
let worker_ref = Trusted::new(global.get_cx(), *worker, global.script_chan()); let worker_ref = Trusted::new(global.get_cx(), worker.r(), global.script_chan());
DedicatedWorkerGlobalScope::run_worker_scope( DedicatedWorkerGlobalScope::run_worker_scope(
worker_url, worker_ref, resource_task, global.script_chan(), worker_url, worker_ref, resource_task, global.script_chan(),
sender, receiver); sender, receiver);
Ok(Temporary::from_rooted(*worker)) Ok(Temporary::from_rooted(worker.r()))
} }
pub fn handle_message(address: TrustedWorkerAddress, pub fn handle_message(address: TrustedWorkerAddress,
data: *mut u64, nbytes: size_t) { data: *mut u64, nbytes: size_t) {
let worker = address.to_temporary().root(); let worker = address.to_temporary().root();
let global = worker.global.root(); let global = worker.r().global.root();
let mut message = UndefinedValue(); let mut message = UndefinedValue();
unsafe { unsafe {
assert!(JS_ReadStructuredClone( assert!(JS_ReadStructuredClone(
global.root_ref().get_cx(), data as *const u64, nbytes, global.r().get_cx(), data as *const u64, nbytes,
JS_STRUCTURED_CLONE_VERSION, &mut message, JS_STRUCTURED_CLONE_VERSION, &mut message,
ptr::null(), ptr::null_mut()) != 0); ptr::null(), ptr::null_mut()) != 0);
} }
let target: JSRef<EventTarget> = EventTargetCast::from_ref(*worker); let target: JSRef<EventTarget> = EventTargetCast::from_ref(worker.r());
MessageEvent::dispatch_jsval(target, global.root_ref(), message); MessageEvent::dispatch_jsval(target, global.r(), message);
} }
} }
@ -112,7 +112,7 @@ impl<'a> WorkerMethods for JSRef<'a, Worker> {
return Err(DataClone); return Err(DataClone);
} }
let address = Trusted::new(cx, self, self.global.root().root_ref().script_chan().clone()); let address = Trusted::new(cx, self, self.global.root().r().script_chan().clone());
self.sender.send((address, ScriptMsg::DOMMessage(data, nbytes))); self.sender.send((address, ScriptMsg::DOMMessage(data, nbytes)));
Ok(()) Ok(())
} }

View file

@ -201,7 +201,7 @@ impl XMLHttpRequest {
pub fn handle_progress(addr: TrustedXHRAddress, progress: XHRProgress) { pub fn handle_progress(addr: TrustedXHRAddress, progress: XHRProgress) {
let xhr = addr.to_temporary().root(); let xhr = addr.to_temporary().root();
xhr.process_partial_response(progress); xhr.r().process_partial_response(progress);
} }
fn fetch(fetch_type: &SyncOrAsync, resource_task: ResourceTask, fn fetch(fetch_type: &SyncOrAsync, resource_task: ResourceTask,
@ -367,7 +367,7 @@ impl<'a> XMLHttpRequestMethods for JSRef<'a, XMLHttpRequest> {
*self.request_method.borrow_mut() = maybe_method.unwrap(); *self.request_method.borrow_mut() = maybe_method.unwrap();
// Step 6 // Step 6
let base = self.global.root().root_ref().get_url(); let base = self.global.root().r().get_url();
let parsed_url = match UrlParser::new().base_url(&base).parse(url.as_slice()) { let parsed_url = match UrlParser::new().base_url(&base).parse(url.as_slice()) {
Ok(parsed) => parsed, Ok(parsed) => parsed,
Err(_) => return Err(Syntax) // Step 7 Err(_) => return Err(Syntax) // Step 7
@ -510,8 +510,8 @@ impl<'a> XMLHttpRequestMethods for JSRef<'a, XMLHttpRequest> {
if !self.sync.get() { if !self.sync.get() {
// Step 8 // Step 8
let upload_target = *self.upload.root(); let upload_target = self.upload.root();
let event_target: JSRef<EventTarget> = EventTargetCast::from_ref(upload_target); let event_target: JSRef<EventTarget> = EventTargetCast::from_ref(upload_target.r());
if event_target.has_handlers() { if event_target.has_handlers() {
self.upload_events.set(true); self.upload_events.set(true);
} }
@ -535,7 +535,7 @@ impl<'a> XMLHttpRequestMethods for JSRef<'a, XMLHttpRequest> {
} }
let global = self.global.root(); let global = self.global.root();
let resource_task = global.root_ref().resource_task(); let resource_task = global.r().resource_task();
let (start_chan, start_port) = channel(); let (start_chan, start_port) = channel();
let mut load_data = LoadData::new(self.request_url.borrow().clone().unwrap(), start_chan); let mut load_data = LoadData::new(self.request_url.borrow().clone().unwrap(), start_chan);
load_data.data = extracted; load_data.data = extracted;
@ -579,7 +579,7 @@ impl<'a> XMLHttpRequestMethods for JSRef<'a, XMLHttpRequest> {
*self.terminate_sender.borrow_mut() = Some(terminate_sender); *self.terminate_sender.borrow_mut() = Some(terminate_sender);
// CORS stuff // CORS stuff
let referer_url = self.global.root().root_ref().get_url(); let referer_url = self.global.root().r().get_url();
let mode = if self.upload_events.get() { let mode = if self.upload_events.get() {
RequestMode::ForcedPreflight RequestMode::ForcedPreflight
} else { } else {
@ -613,11 +613,11 @@ impl<'a> XMLHttpRequestMethods for JSRef<'a, XMLHttpRequest> {
terminate_receiver, cors_request, gen_id, start_port); terminate_receiver, cors_request, gen_id, start_port);
} else { } else {
self.fetch_time.set(time::now().to_timespec().sec); self.fetch_time.set(time::now().to_timespec().sec);
let script_chan = global.root_ref().script_chan(); let script_chan = global.r().script_chan();
// Pin the object before launching the fetch task. This is to ensure that // Pin the object before launching the fetch task. This is to ensure that
// the object will stay alive as long as there are (possibly cancelled) // the object will stay alive as long as there are (possibly cancelled)
// inflight events queued up in the script task's port. // inflight events queued up in the script task's port.
let addr = Trusted::new(self.global.root().root_ref().get_cx(), self, let addr = Trusted::new(self.global.root().r().get_cx(), self,
script_chan.clone()); script_chan.clone());
spawn_named("XHRTask", proc() { spawn_named("XHRTask", proc() {
let _ = XMLHttpRequest::fetch(&mut SyncOrAsync::Async(addr, script_chan), let _ = XMLHttpRequest::fetch(&mut SyncOrAsync::Async(addr, script_chan),
@ -764,12 +764,12 @@ impl<'a> PrivateXMLHttpRequestHelpers for JSRef<'a, XMLHttpRequest> {
assert!(self.ready_state.get() != rs) assert!(self.ready_state.get() != rs)
self.ready_state.set(rs); self.ready_state.set(rs);
let global = self.global.root(); let global = self.global.root();
let event = Event::new(global.root_ref(), let event = Event::new(global.r(),
"readystatechange".into_string(), "readystatechange".into_string(),
EventBubbles::DoesNotBubble, EventBubbles::DoesNotBubble,
EventCancelable::Cancelable).root(); EventCancelable::Cancelable).root();
let target: JSRef<EventTarget> = EventTargetCast::from_ref(self); let target: JSRef<EventTarget> = EventTargetCast::from_ref(self);
target.dispatch_event(*event); target.dispatch_event(event.r());
} }
fn process_partial_response(self, progress: XHRProgress) { fn process_partial_response(self, progress: XHRProgress) {
@ -898,17 +898,17 @@ impl<'a> PrivateXMLHttpRequestHelpers for JSRef<'a, XMLHttpRequest> {
fn dispatch_progress_event(self, upload: bool, type_: DOMString, loaded: u64, total: Option<u64>) { fn dispatch_progress_event(self, upload: bool, type_: DOMString, loaded: u64, total: Option<u64>) {
let global = self.global.root(); let global = self.global.root();
let upload_target = *self.upload.root(); let upload_target = self.upload.root();
let progressevent = ProgressEvent::new(global.root_ref(), let progressevent = ProgressEvent::new(global.r(),
type_, false, false, type_, false, false,
total.is_some(), loaded, total.is_some(), loaded,
total.unwrap_or(0)).root(); total.unwrap_or(0)).root();
let target: JSRef<EventTarget> = if upload { let target: JSRef<EventTarget> = if upload {
EventTargetCast::from_ref(upload_target) EventTargetCast::from_ref(upload_target.r())
} else { } else {
EventTargetCast::from_ref(self) EventTargetCast::from_ref(self)
}; };
let event: JSRef<Event> = EventCast::from_ref(*progressevent); let event: JSRef<Event> = EventCast::from_ref(progressevent.r());
target.dispatch_event(event); target.dispatch_event(event);
} }
@ -1008,7 +1008,7 @@ impl Extractable for SendParam {
let encoding = UTF_8 as EncodingRef; let encoding = UTF_8 as EncodingRef;
match *self { match *self {
eString(ref s) => encoding.encode(s.as_slice(), EncoderTrap::Replace).unwrap(), eString(ref s) => encoding.encode(s.as_slice(), EncoderTrap::Replace).unwrap(),
eURLSearchParams(ref usp) => usp.root().serialize(None) // Default encoding is UTF8 eURLSearchParams(ref usp) => usp.root().r().serialize(None) // Default encoding is UTF8
} }
} }
} }

View file

@ -166,7 +166,7 @@ impl Page {
pub fn flush_layout(&self, goal: ReflowGoal, query: ReflowQueryType) { pub fn flush_layout(&self, goal: ReflowGoal, query: ReflowQueryType) {
let frame = self.frame(); let frame = self.frame();
let window = frame.as_ref().unwrap().window.root(); let window = frame.as_ref().unwrap().window.root();
self.reflow(goal, window.control_chan().clone(), &mut **window.compositor(), query); self.reflow(goal, window.r().control_chan().clone(), &mut **window.r().compositor(), query);
} }
pub fn layout(&self) -> &LayoutRPC { pub fn layout(&self) -> &LayoutRPC {
@ -238,7 +238,7 @@ impl Page {
Some(ref frame) => { Some(ref frame) => {
let window = frame.window.root(); let window = frame.window.root();
let document = frame.document.root(); let document = frame.document.root();
window.compositor().set_title(self.id, Some(document.Title())); window.r().compositor().set_title(self.id, Some(document.r().Title()));
} }
} }
} }
@ -246,7 +246,7 @@ impl Page {
pub fn dirty_all_nodes(&self) { pub fn dirty_all_nodes(&self) {
match *self.frame.borrow() { match *self.frame.borrow() {
None => {} None => {}
Some(ref frame) => frame.document.root().dirty_all_nodes(), Some(ref frame) => frame.document.root().r().dirty_all_nodes(),
} }
} }
} }
@ -344,7 +344,7 @@ impl Page {
let root = match *self.frame() { let root = match *self.frame() {
None => return, None => return,
Some(ref frame) => { Some(ref frame) => {
frame.document.root().GetDocumentElement() frame.document.root().r().GetDocumentElement()
} }
}; };
@ -355,7 +355,7 @@ impl Page {
debug!("script: performing reflow for goal {}", goal); debug!("script: performing reflow for goal {}", goal);
let root: JSRef<Node> = NodeCast::from_ref(*root); let root: JSRef<Node> = NodeCast::from_ref(root.r());
if !root.get_has_dirty_descendants() { if !root.get_has_dirty_descendants() {
debug!("root has no dirty descendants; avoiding reflow"); debug!("root has no dirty descendants; avoiding reflow");
return return
@ -401,17 +401,17 @@ impl Page {
/// Attempt to find a named element in this page's document. /// Attempt to find a named element in this page's document.
pub fn find_fragment_node(&self, fragid: DOMString) -> Option<Temporary<Element>> { pub fn find_fragment_node(&self, fragid: DOMString) -> Option<Temporary<Element>> {
let document = self.frame().as_ref().unwrap().document.root(); let document = self.frame().as_ref().unwrap().document.root();
document.find_fragment_node(fragid) document.r().find_fragment_node(fragid)
} }
pub fn hit_test(&self, point: &Point2D<f32>) -> Option<UntrustedNodeAddress> { pub fn hit_test(&self, point: &Point2D<f32>) -> Option<UntrustedNodeAddress> {
let frame = self.frame(); let frame = self.frame();
let document = frame.as_ref().unwrap().document.root(); let document = frame.as_ref().unwrap().document.root();
let root = match document.GetDocumentElement().root() { let root = match document.r().GetDocumentElement().root() {
None => return None, None => return None,
Some(root) => root, Some(root) => root,
}; };
let root: JSRef<Node> = NodeCast::from_ref(*root); let root: JSRef<Node> = NodeCast::from_ref(root.r());
let address = match self.layout().hit_test(root.to_trusted_node_address(), *point) { let address = match self.layout().hit_test(root.to_trusted_node_address(), *point) {
Ok(HitTestResponse(node_address)) => { Ok(HitTestResponse(node_address)) => {
Some(node_address) Some(node_address)
@ -427,11 +427,11 @@ impl Page {
pub fn get_nodes_under_mouse(&self, point: &Point2D<f32>) -> Option<Vec<UntrustedNodeAddress>> { pub fn get_nodes_under_mouse(&self, point: &Point2D<f32>) -> Option<Vec<UntrustedNodeAddress>> {
let frame = self.frame(); let frame = self.frame();
let document = frame.as_ref().unwrap().document.root(); let document = frame.as_ref().unwrap().document.root();
let root = match document.GetDocumentElement().root() { let root = match document.r().GetDocumentElement().root() {
None => return None, None => return None,
Some(root) => root, Some(root) => root,
}; };
let root: JSRef<Node> = NodeCast::from_ref(*root); let root: JSRef<Node> = NodeCast::from_ref(root.r());
let address = match self.layout().mouse_over(root.to_trusted_node_address(), *point) { let address = match self.layout().mouse_over(root.to_trusted_node_address(), *point) {
Ok(MouseOverResponse(node_address)) => { Ok(MouseOverResponse(node_address)) => {
Some(node_address) Some(node_address)

View file

@ -46,7 +46,7 @@ impl SinkHelpers for servohtmlparser::Sink {
AppendNode(n) => Temporary::new(unsafe { JS::from_trusted_node_address(n) }), AppendNode(n) => Temporary::new(unsafe { JS::from_trusted_node_address(n) }),
AppendText(t) => { AppendText(t) => {
let doc = self.document.root(); let doc = self.document.root();
let text = Text::new(t, *doc); let text = Text::new(t, doc.r());
NodeCast::from_temporary(text) NodeCast::from_temporary(text)
} }
} }
@ -56,7 +56,7 @@ impl SinkHelpers for servohtmlparser::Sink {
impl<'a> TreeSink<TrustedNodeAddress> for servohtmlparser::Sink { impl<'a> TreeSink<TrustedNodeAddress> for servohtmlparser::Sink {
fn get_document(&mut self) -> TrustedNodeAddress { fn get_document(&mut self) -> TrustedNodeAddress {
let doc = self.document.root(); let doc = self.document.root();
let node: JSRef<Node> = NodeCast::from_ref(*doc); let node: JSRef<Node> = NodeCast::from_ref(doc.r());
node.to_trusted_node_address() node.to_trusted_node_address()
} }
@ -66,7 +66,7 @@ impl<'a> TreeSink<TrustedNodeAddress> for servohtmlparser::Sink {
fn elem_name(&self, target: TrustedNodeAddress) -> QualName { fn elem_name(&self, target: TrustedNodeAddress) -> QualName {
let node: Root<Node> = unsafe { JS::from_trusted_node_address(target).root() }; let node: Root<Node> = unsafe { JS::from_trusted_node_address(target).root() };
let elem: JSRef<Element> = ElementCast::to_ref(*node) let elem: JSRef<Element> = ElementCast::to_ref(node.r())
.expect("tried to get name of non-Element in HTML parsing"); .expect("tried to get name of non-Element in HTML parsing");
QualName { QualName {
ns: elem.namespace().clone(), ns: elem.namespace().clone(),
@ -77,22 +77,22 @@ impl<'a> TreeSink<TrustedNodeAddress> for servohtmlparser::Sink {
fn create_element(&mut self, name: QualName, attrs: Vec<Attribute>) fn create_element(&mut self, name: QualName, attrs: Vec<Attribute>)
-> TrustedNodeAddress { -> TrustedNodeAddress {
let doc = self.document.root(); let doc = self.document.root();
let elem = Element::create(name, None, *doc, let elem = Element::create(name, None, doc.r(),
ElementCreator::ParserCreated).root(); ElementCreator::ParserCreated).root();
for attr in attrs.into_iter() { for attr in attrs.into_iter() {
elem.set_attribute_from_parser(attr.name, attr.value, None); elem.r().set_attribute_from_parser(attr.name, attr.value, None);
} }
let node: JSRef<Node> = NodeCast::from_ref(*elem); let node: JSRef<Node> = NodeCast::from_ref(elem.r());
node.to_trusted_node_address() node.to_trusted_node_address()
} }
fn create_comment(&mut self, text: String) -> TrustedNodeAddress { fn create_comment(&mut self, text: String) -> TrustedNodeAddress {
let doc = self.document.root(); let doc = self.document.root();
let comment = Comment::new(text, *doc); let comment = Comment::new(text, doc.r());
let node: Root<Node> = NodeCast::from_temporary(comment).root(); let node: Root<Node> = NodeCast::from_temporary(comment).root();
node.to_trusted_node_address() node.r().to_trusted_node_address()
} }
fn append_before_sibling(&mut self, fn append_before_sibling(&mut self,
@ -100,13 +100,13 @@ impl<'a> TreeSink<TrustedNodeAddress> for servohtmlparser::Sink {
new_node: NodeOrText<TrustedNodeAddress>) -> Result<(), NodeOrText<TrustedNodeAddress>> { new_node: NodeOrText<TrustedNodeAddress>) -> Result<(), NodeOrText<TrustedNodeAddress>> {
// If there is no parent, return the node to the parser. // If there is no parent, return the node to the parser.
let sibling: Root<Node> = unsafe { JS::from_trusted_node_address(sibling).root() }; let sibling: Root<Node> = unsafe { JS::from_trusted_node_address(sibling).root() };
let parent = match sibling.parent_node() { let parent = match sibling.r().parent_node() {
Some(p) => p.root(), Some(p) => p.root(),
None => return Err(new_node), None => return Err(new_node),
}; };
let child = self.get_or_create(new_node).root(); let child = self.get_or_create(new_node).root();
assert!(parent.InsertBefore(*child, Some(*sibling)).is_ok()); assert!(parent.r().InsertBefore(child.r(), Some(sibling.r())).is_ok());
Ok(()) Ok(())
} }
@ -116,7 +116,7 @@ impl<'a> TreeSink<TrustedNodeAddress> for servohtmlparser::Sink {
fn set_quirks_mode(&mut self, mode: QuirksMode) { fn set_quirks_mode(&mut self, mode: QuirksMode) {
let doc = self.document.root(); let doc = self.document.root();
doc.set_quirks_mode(mode); doc.r().set_quirks_mode(mode);
} }
fn append(&mut self, parent: TrustedNodeAddress, child: NodeOrText<TrustedNodeAddress>) { fn append(&mut self, parent: TrustedNodeAddress, child: NodeOrText<TrustedNodeAddress>) {
@ -124,21 +124,21 @@ impl<'a> TreeSink<TrustedNodeAddress> for servohtmlparser::Sink {
let child = self.get_or_create(child).root(); let child = self.get_or_create(child).root();
// FIXME(#3701): Use a simpler algorithm and merge adjacent text nodes // FIXME(#3701): Use a simpler algorithm and merge adjacent text nodes
assert!(parent.AppendChild(*child).is_ok()); assert!(parent.r().AppendChild(child.r()).is_ok());
} }
fn append_doctype_to_document(&mut self, name: String, public_id: String, system_id: String) { fn append_doctype_to_document(&mut self, name: String, public_id: String, system_id: String) {
let doc = self.document.root(); let doc = self.document.root();
let doc_node: JSRef<Node> = NodeCast::from_ref(*doc); let doc_node: JSRef<Node> = NodeCast::from_ref(doc.r());
let doctype = DocumentType::new(name, Some(public_id), Some(system_id), *doc); let doctype = DocumentType::new(name, Some(public_id), Some(system_id), doc.r());
let node: Root<Node> = NodeCast::from_temporary(doctype).root(); let node: Root<Node> = NodeCast::from_temporary(doctype).root();
assert!(doc_node.AppendChild(*node).is_ok()); assert!(doc_node.AppendChild(node.r()).is_ok());
} }
fn add_attrs_if_missing(&mut self, target: TrustedNodeAddress, attrs: Vec<Attribute>) { fn add_attrs_if_missing(&mut self, target: TrustedNodeAddress, attrs: Vec<Attribute>) {
let node: Root<Node> = unsafe { JS::from_trusted_node_address(target).root() }; let node: Root<Node> = unsafe { JS::from_trusted_node_address(target).root() };
let elem: JSRef<Element> = ElementCast::to_ref(*node) let elem: JSRef<Element> = ElementCast::to_ref(node.r())
.expect("tried to set attrs on non-Element in HTML parsing"); .expect("tried to set attrs on non-Element in HTML parsing");
for attr in attrs.into_iter() { for attr in attrs.into_iter() {
elem.set_attribute_from_parser(attr.name, attr.value, None); elem.set_attribute_from_parser(attr.name, attr.value, None);
@ -151,13 +151,13 @@ impl<'a> TreeSink<TrustedNodeAddress> for servohtmlparser::Sink {
fn mark_script_already_started(&mut self, node: TrustedNodeAddress) { fn mark_script_already_started(&mut self, node: TrustedNodeAddress) {
let node: Root<Node> = unsafe { JS::from_trusted_node_address(node).root() }; let node: Root<Node> = unsafe { JS::from_trusted_node_address(node).root() };
let script: Option<JSRef<HTMLScriptElement>> = HTMLScriptElementCast::to_ref(*node); let script: Option<JSRef<HTMLScriptElement>> = HTMLScriptElementCast::to_ref(node.r());
script.map(|script| script.mark_already_started()); script.map(|script| script.mark_already_started());
} }
fn complete_script(&mut self, node: TrustedNodeAddress) { fn complete_script(&mut self, node: TrustedNodeAddress) {
let node: Root<Node> = unsafe { JS::from_trusted_node_address(node).root() }; let node: Root<Node> = unsafe { JS::from_trusted_node_address(node).root() };
let script: Option<JSRef<HTMLScriptElement>> = HTMLScriptElementCast::to_ref(*node); let script: Option<JSRef<HTMLScriptElement>> = HTMLScriptElementCast::to_ref(node.r());
script.map(|script| script.prepare()); script.map(|script| script.prepare());
} }
} }
@ -166,7 +166,7 @@ pub fn parse_html(document: JSRef<Document>,
input: HTMLInput, input: HTMLInput,
url: &Url) { url: &Url) {
let parser = ServoHTMLParser::new(Some(url.clone()), document).root(); let parser = ServoHTMLParser::new(Some(url.clone()), document).root();
let parser: JSRef<ServoHTMLParser> = *parser; let parser: JSRef<ServoHTMLParser> = parser.r();
let nested_parse = task_state::get().contains(task_state::IN_HTML_PARSER); let nested_parse = task_state::get().contains(task_state::IN_HTML_PARSER);
if !nested_parse { if !nested_parse {

View file

@ -654,7 +654,7 @@ impl ScriptTask {
pipeline ID not associated with this script task. This is a bug."); pipeline ID not associated with this script task. This is a bug.");
let frame = page.frame(); let frame = page.frame();
let window = frame.as_ref().unwrap().window.root(); let window = frame.as_ref().unwrap().window.root();
window.handle_fire_timer(timer_id); window.r().handle_fire_timer(timer_id);
} }
/// Handles a notification that reflow completed. /// Handles a notification that reflow completed.
@ -787,11 +787,11 @@ impl ScriptTask {
} else { } else {
url.clone() url.clone()
}; };
let document = Document::new(*window, Some(doc_url.clone()), let document = Document::new(window.r(), Some(doc_url.clone()),
IsHTMLDocument::HTMLDocument, None, IsHTMLDocument::HTMLDocument, None,
DocumentSource::FromParser).root(); DocumentSource::FromParser).root();
window.init_browser_context(*document); window.r().init_browser_context(document.r());
self.compositor.borrow_mut().set_ready_state(pipeline_id, Loading); self.compositor.borrow_mut().set_ready_state(pipeline_id, Loading);
@ -799,8 +799,8 @@ impl ScriptTask {
// Create the root frame. // Create the root frame.
let mut frame = page.mut_frame(); let mut frame = page.mut_frame();
*frame = Some(Frame { *frame = Some(Frame {
document: JS::from_rooted(*document), document: JS::from_rooted(document.r()),
window: JS::from_rooted(*window), window: JS::from_rooted(window.r()),
}); });
} }
@ -820,7 +820,7 @@ impl ScriptTask {
load_response.metadata.headers.as_ref().map(|headers| { load_response.metadata.headers.as_ref().map(|headers| {
headers.get().map(|&LastModified(ref tm)| { headers.get().map(|&LastModified(ref tm)| {
document.set_last_modified(dom_last_modified(tm)); document.r().set_last_modified(dom_last_modified(tm));
}); });
}); });
@ -836,22 +836,22 @@ impl ScriptTask {
(HTMLInput::InputUrl(load_response), final_url) (HTMLInput::InputUrl(load_response), final_url)
} else { } else {
let evalstr = load_data.url.non_relative_scheme_data().unwrap(); let evalstr = load_data.url.non_relative_scheme_data().unwrap();
let jsval = window.evaluate_js_with_result(evalstr); let jsval = window.r().evaluate_js_with_result(evalstr);
let strval = FromJSValConvertible::from_jsval(self.get_cx(), jsval, let strval = FromJSValConvertible::from_jsval(self.get_cx(), jsval,
StringificationBehavior::Empty); StringificationBehavior::Empty);
(HTMLInput::InputString(strval.unwrap_or("".into_string())), doc_url) (HTMLInput::InputString(strval.unwrap_or("".into_string())), doc_url)
}; };
parse_html(*document, parser_input, &final_url); parse_html(document.r(), parser_input, &final_url);
document.set_ready_state(DocumentReadyState::Interactive); document.r().set_ready_state(DocumentReadyState::Interactive);
self.compositor.borrow_mut().set_ready_state(pipeline_id, PerformingLayout); self.compositor.borrow_mut().set_ready_state(pipeline_id, PerformingLayout);
// Kick off the initial reflow of the page. // Kick off the initial reflow of the page.
debug!("kicking off initial reflow of {}", final_url); debug!("kicking off initial reflow of {}", final_url);
document.content_changed(NodeCast::from_ref(*document), document.r().content_changed(NodeCast::from_ref(document.r()),
NodeDamage::OtherNodeDamage); NodeDamage::OtherNodeDamage);
window.flush_layout(ReflowGoal::ForDisplay, ReflowQueryType::NoQuery); window.r().flush_layout(ReflowGoal::ForDisplay, ReflowQueryType::NoQuery);
{ {
// No more reflow required // No more reflow required
@ -860,24 +860,24 @@ impl ScriptTask {
} }
// https://html.spec.whatwg.org/multipage/#the-end step 4 // https://html.spec.whatwg.org/multipage/#the-end step 4
let event = Event::new(GlobalRef::Window(*window), "DOMContentLoaded".into_string(), let event = Event::new(GlobalRef::Window(window.r()), "DOMContentLoaded".into_string(),
EventBubbles::DoesNotBubble, EventBubbles::DoesNotBubble,
EventCancelable::NotCancelable).root(); EventCancelable::NotCancelable).root();
let doctarget: JSRef<EventTarget> = EventTargetCast::from_ref(*document); let doctarget: JSRef<EventTarget> = EventTargetCast::from_ref(document.r());
let _ = doctarget.DispatchEvent(*event); let _ = doctarget.DispatchEvent(event.r());
// We have no concept of a document loader right now, so just dispatch the // We have no concept of a document loader right now, so just dispatch the
// "load" event as soon as we've finished executing all scripts parsed during // "load" event as soon as we've finished executing all scripts parsed during
// the initial load. // the initial load.
// https://html.spec.whatwg.org/multipage/#the-end step 7 // https://html.spec.whatwg.org/multipage/#the-end step 7
document.set_ready_state(DocumentReadyState::Complete); document.r().set_ready_state(DocumentReadyState::Complete);
let event = Event::new(GlobalRef::Window(*window), "load".into_string(), let event = Event::new(GlobalRef::Window(window.r()), "load".into_string(),
EventBubbles::DoesNotBubble, EventBubbles::DoesNotBubble,
EventCancelable::NotCancelable).root(); EventCancelable::NotCancelable).root();
let wintarget: JSRef<EventTarget> = EventTargetCast::from_ref(*window); let wintarget: JSRef<EventTarget> = EventTargetCast::from_ref(window.r());
let _ = wintarget.dispatch_event_with_target(doctarget, *event); let _ = wintarget.dispatch_event_with_target(doctarget, event.r());
*page.fragment_name.borrow_mut() = final_url.fragment.clone(); *page.fragment_name.borrow_mut() = final_url.fragment.clone();
@ -889,7 +889,7 @@ impl ScriptTask {
None => {} None => {}
Some(ref chan) => { Some(ref chan) => {
let page_info = DevtoolsPageInfo { let page_info = DevtoolsPageInfo {
title: document.Title(), title: document.r().Title(),
url: final_url url: final_url
}; };
chan.send(NewGlobal(pipeline_id, self.devtools_sender.clone(), chan.send(NewGlobal(pipeline_id, self.devtools_sender.clone(),
@ -945,7 +945,8 @@ impl ScriptTask {
let page = get_page(&*self.page.borrow(), pipeline_id); let page = get_page(&*self.page.borrow(), pipeline_id);
let frame = page.frame(); let frame = page.frame();
let document = frame.as_ref().unwrap().document.root(); let document = frame.as_ref().unwrap().document.root();
document.content_changed(*node_to_dirty, NodeDamage::OtherNodeDamage); document.r().content_changed(node_to_dirty.r(),
NodeDamage::OtherNodeDamage);
} }
self.handle_reflow_event(pipeline_id); self.handle_reflow_event(pipeline_id);
@ -975,14 +976,14 @@ impl ScriptTask {
let page = get_page(&*self.page.borrow(), pipeline_id); let page = get_page(&*self.page.borrow(), pipeline_id);
let frame = page.frame(); let frame = page.frame();
let window = frame.as_ref().unwrap().window.root(); let window = frame.as_ref().unwrap().window.root();
let doc = window.Document().root(); let doc = window.r().Document().root();
let focused = doc.get_focused_element().root(); let focused = doc.r().get_focused_element().root();
let body = doc.GetBody().root(); let body = doc.r().GetBody().root();
let target: JSRef<EventTarget> = match (&focused, &body) { let target: JSRef<EventTarget> = match (&focused, &body) {
(&Some(ref focused), _) => EventTargetCast::from_ref(**focused), (&Some(ref focused), _) => EventTargetCast::from_ref(focused.r()),
(&None, &Some(ref body)) => EventTargetCast::from_ref(**body), (&None, &Some(ref body)) => EventTargetCast::from_ref(body.r()),
(&None, &None) => EventTargetCast::from_ref(*window), (&None, &None) => EventTargetCast::from_ref(window.r()),
}; };
let ctrl = modifiers.contains(CONTROL); let ctrl = modifiers.contains(CONTROL);
@ -999,26 +1000,28 @@ impl ScriptTask {
let props = KeyboardEvent::key_properties(key, modifiers); let props = KeyboardEvent::key_properties(key, modifiers);
let keyevent = KeyboardEvent::new(*window, ev_type, true, true, Some(*window), 0, let keyevent = KeyboardEvent::new(window.r(), ev_type, true, true,
Some(window.r()), 0,
props.key.into_string(), props.code.into_string(), props.key.into_string(), props.code.into_string(),
props.location, is_repeating, is_composing, props.location, is_repeating, is_composing,
ctrl, alt, shift, meta, ctrl, alt, shift, meta,
None, props.key_code).root(); None, props.key_code).root();
let event = EventCast::from_ref(*keyevent); let event = EventCast::from_ref(keyevent.r());
let _ = target.DispatchEvent(event); let _ = target.DispatchEvent(event);
let mut prevented = event.DefaultPrevented(); let mut prevented = event.DefaultPrevented();
// https://dvcs.w3.org/hg/dom3events/raw-file/tip/html/DOM3-Events.html#keys-cancelable-keys // https://dvcs.w3.org/hg/dom3events/raw-file/tip/html/DOM3-Events.html#keys-cancelable-keys
if state != KeyState::Released && props.is_printable() && !prevented { if state != KeyState::Released && props.is_printable() && !prevented {
// https://dvcs.w3.org/hg/dom3events/raw-file/tip/html/DOM3-Events.html#keypress-event-order // https://dvcs.w3.org/hg/dom3events/raw-file/tip/html/DOM3-Events.html#keypress-event-order
let event = KeyboardEvent::new(*window, "keypress".into_string(), true, true, Some(*window), let event = KeyboardEvent::new(window.r(), "keypress".into_string(),
true, true, Some(window.r()),
0, props.key.into_string(), props.code.into_string(), 0, props.key.into_string(), props.code.into_string(),
props.location, is_repeating, is_composing, props.location, is_repeating, is_composing,
ctrl, alt, shift, meta, ctrl, alt, shift, meta,
props.char_code, 0).root(); props.char_code, 0).root();
let _ = target.DispatchEvent(EventCast::from_ref(*event)); let _ = target.DispatchEvent(EventCast::from_ref(event.r()));
let ev = EventCast::from_ref(*event); let ev = EventCast::from_ref(event.r());
prevented = ev.DefaultPrevented(); prevented = ev.DefaultPrevented();
// TODO: if keypress event is canceled, prevent firing input events // TODO: if keypress event is canceled, prevent firing input events
} }
@ -1044,7 +1047,7 @@ impl ScriptTask {
_ => () _ => ()
} }
window.flush_layout(ReflowGoal::ForDisplay, ReflowQueryType::NoQuery); window.r().flush_layout(ReflowGoal::ForDisplay, ReflowQueryType::NoQuery);
} }
/// The entry point for content to notify that a new load has been requested /// The entry point for content to notify that a new load has been requested
@ -1060,7 +1063,7 @@ impl ScriptTask {
let page = get_page(&*self.page.borrow(), pipeline_id); let page = get_page(&*self.page.borrow(), pipeline_id);
match page.find_fragment_node(url.fragment.unwrap()).root() { match page.find_fragment_node(url.fragment.unwrap()).root() {
Some(node) => { Some(node) => {
self.scroll_fragment_point(pipeline_id, *node); self.scroll_fragment_point(pipeline_id, node.r());
} }
None => {} None => {}
} }
@ -1084,7 +1087,7 @@ impl ScriptTask {
.and_then(|name| page.find_fragment_node(name)) .and_then(|name| page.find_fragment_node(name))
.root(); .root();
match fragment_node { match fragment_node {
Some(node) => self.scroll_fragment_point(pipeline_id, *node), Some(node) => self.scroll_fragment_point(pipeline_id, node.r()),
None => {} None => {}
} }
@ -1095,13 +1098,13 @@ impl ScriptTask {
Some(window) => { Some(window) => {
// http://dev.w3.org/csswg/cssom-view/#resizing-viewports // http://dev.w3.org/csswg/cssom-view/#resizing-viewports
// https://dvcs.w3.org/hg/dom3events/raw-file/tip/html/DOM3-Events.html#event-type-resize // https://dvcs.w3.org/hg/dom3events/raw-file/tip/html/DOM3-Events.html#event-type-resize
let uievent = UIEvent::new(window.clone(), let uievent = UIEvent::new(window.r(),
"resize".into_string(), false, "resize".into_string(), false,
false, Some(window.clone()), false, Some(window.r()),
0i32).root(); 0i32).root();
let event: JSRef<Event> = EventCast::from_ref(*uievent); let event: JSRef<Event> = EventCast::from_ref(uievent.r());
let wintarget: JSRef<EventTarget> = EventTargetCast::from_ref(*window); let wintarget: JSRef<EventTarget> = EventTargetCast::from_ref(window.r());
wintarget.dispatch_event(event); wintarget.dispatch_event(event);
} }
None => () None => ()
@ -1128,9 +1131,9 @@ impl ScriptTask {
node::from_untrusted_node_address( node::from_untrusted_node_address(
self.js_runtime.ptr, node_address).root(); self.js_runtime.ptr, node_address).root();
let maybe_node = match ElementCast::to_ref(*temp_node) { let maybe_node = match ElementCast::to_ref(temp_node.r()) {
Some(element) => Some(element), Some(element) => Some(element),
None => temp_node.ancestors().filter_map(ElementCast::to_ref).next(), None => temp_node.r().ancestors().filter_map(ElementCast::to_ref).next(),
}; };
match maybe_node { match maybe_node {
@ -1142,21 +1145,21 @@ impl ScriptTask {
match *page.frame() { match *page.frame() {
Some(ref frame) => { Some(ref frame) => {
let window = frame.window.root(); let window = frame.window.root();
let doc = window.Document().root(); let doc = window.r().Document().root();
doc.begin_focus_transaction(); doc.r().begin_focus_transaction();
let event = let event =
Event::new(GlobalRef::Window(*window), Event::new(GlobalRef::Window(window.r()),
"click".into_string(), "click".into_string(),
EventBubbles::Bubbles, EventBubbles::Bubbles,
EventCancelable::Cancelable).root(); EventCancelable::Cancelable).root();
// https://dvcs.w3.org/hg/dom3events/raw-file/tip/html/DOM3-Events.html#trusted-events // https://dvcs.w3.org/hg/dom3events/raw-file/tip/html/DOM3-Events.html#trusted-events
event.set_trusted(true); event.r().set_trusted(true);
// https://html.spec.whatwg.org/multipage/interaction.html#run-authentic-click-activation-steps // https://html.spec.whatwg.org/multipage/interaction.html#run-authentic-click-activation-steps
el.authentic_click_activation(*event); el.authentic_click_activation(event.r());
doc.commit_focus_transaction(); doc.r().commit_focus_transaction();
window.flush_layout(ReflowGoal::ForDisplay, ReflowQueryType::NoQuery); window.r().flush_layout(ReflowGoal::ForDisplay, ReflowQueryType::NoQuery);
} }
None => {} None => {}
} }
@ -1182,7 +1185,7 @@ impl ScriptTask {
Some(ref mut mouse_over_targets) => { Some(ref mut mouse_over_targets) => {
for node in mouse_over_targets.iter_mut() { for node in mouse_over_targets.iter_mut() {
let node = node.root(); let node = node.root();
node.set_hover_state(false); node.r().set_hover_state(false);
} }
} }
None => {} None => {}
@ -1198,19 +1201,19 @@ impl ScriptTask {
let x = point.x.to_i32().unwrap_or(0); let x = point.x.to_i32().unwrap_or(0);
let y = point.y.to_i32().unwrap_or(0); let y = point.y.to_i32().unwrap_or(0);
let mouse_event = MouseEvent::new(*window, let mouse_event = MouseEvent::new(window.r(),
"mousemove".into_string(), "mousemove".into_string(),
true, true,
true, true,
Some(*window), Some(window.r()),
0i32, 0i32,
x, y, x, y, x, y, x, y,
false, false, false, false, false, false, false, false,
0i16, 0i16,
None).root(); None).root();
let event: JSRef<Event> = EventCast::from_ref(*mouse_event); let event: JSRef<Event> = EventCast::from_ref(mouse_event.r());
let target: JSRef<EventTarget> = EventTargetCast::from_ref(*top_most_node); let target: JSRef<EventTarget> = EventTargetCast::from_ref(top_most_node.r());
target.dispatch_event(event); target.dispatch_event(event);
} }
} }