Clean up the cast calls

This commit is contained in:
Anthony Ramine 2015-10-07 14:55:02 +02:00
parent 13ea3ac413
commit 68014af78e
66 changed files with 412 additions and 718 deletions

View file

@ -44,12 +44,12 @@ use script::dom::bindings::codegen::InheritTypes::{CharacterDataTypeId, ElementT
use script::dom::bindings::codegen::InheritTypes::{HTMLElementTypeId, NodeTypeId}; use script::dom::bindings::codegen::InheritTypes::{HTMLElementTypeId, NodeTypeId};
use script::dom::bindings::conversions::Castable; use script::dom::bindings::conversions::Castable;
use script::dom::bindings::js::LayoutJS; use script::dom::bindings::js::LayoutJS;
use script::dom::characterdata::{CharacterData, LayoutCharacterDataHelpers}; use script::dom::characterdata::LayoutCharacterDataHelpers;
use script::dom::element; use script::dom::element;
use script::dom::element::{Element, LayoutElementHelpers, RawLayoutElementHelpers}; use script::dom::element::{Element, LayoutElementHelpers, RawLayoutElementHelpers};
use script::dom::htmlcanvaselement::{HTMLCanvasElement, LayoutHTMLCanvasElementHelpers}; use script::dom::htmlcanvaselement::LayoutHTMLCanvasElementHelpers;
use script::dom::htmliframeelement::HTMLIFrameElement; use script::dom::htmliframeelement::HTMLIFrameElement;
use script::dom::htmlimageelement::{HTMLImageElement, LayoutHTMLImageElementHelpers}; use script::dom::htmlimageelement::LayoutHTMLImageElementHelpers;
use script::dom::htmlinputelement::{HTMLInputElement, LayoutHTMLInputElementHelpers}; use script::dom::htmlinputelement::{HTMLInputElement, LayoutHTMLInputElementHelpers};
use script::dom::htmltextareaelement::{HTMLTextAreaElement, LayoutHTMLTextAreaElementHelpers}; use script::dom::htmltextareaelement::{HTMLTextAreaElement, LayoutHTMLTextAreaElementHelpers};
use script::dom::node::{HAS_CHANGED, HAS_DIRTY_DESCENDANTS, HAS_DIRTY_SIBLINGS, IS_DIRTY}; use script::dom::node::{HAS_CHANGED, HAS_DIRTY_DESCENDANTS, HAS_DIRTY_SIBLINGS, IS_DIRTY};
@ -358,7 +358,7 @@ impl<'le> LayoutElement<'le> {
pub fn as_node(&self) -> LayoutNode<'le> { pub fn as_node(&self) -> LayoutNode<'le> {
LayoutNode { LayoutNode {
node: self.element.upcast::<Node>(), node: self.element.upcast(),
chain: PhantomData, chain: PhantomData,
} }
} }
@ -377,7 +377,7 @@ fn as_element<'le>(node: LayoutJS<Node>) -> Option<LayoutElement<'le>> {
impl<'le> ::selectors::Element for LayoutElement<'le> { impl<'le> ::selectors::Element for LayoutElement<'le> {
fn parent_element(&self) -> Option<LayoutElement<'le>> { fn parent_element(&self) -> Option<LayoutElement<'le>> {
unsafe { unsafe {
self.element.upcast::<Node>().parent_node_ref().and_then(as_element) self.element.upcast().parent_node_ref().and_then(as_element)
} }
} }
@ -422,7 +422,7 @@ impl<'le> ::selectors::Element for LayoutElement<'le> {
self.as_node().children().all(|node| match node.type_id() { self.as_node().children().all(|node| match node.type_id() {
NodeTypeId::Element(..) => false, NodeTypeId::Element(..) => false,
NodeTypeId::CharacterData(CharacterDataTypeId::Text) => unsafe { NodeTypeId::CharacterData(CharacterDataTypeId::Text) => unsafe {
node.node.downcast::<CharacterData>().unwrap().data_for_layout().is_empty() node.node.downcast().unwrap().data_for_layout().is_empty()
}, },
_ => true _ => true
}) })
@ -695,7 +695,7 @@ impl<'ln> ThreadSafeLayoutNode<'ln> {
#[inline] #[inline]
pub fn as_element(&self) -> ThreadSafeLayoutElement<'ln> { pub fn as_element(&self) -> ThreadSafeLayoutElement<'ln> {
unsafe { unsafe {
let element = match self.get_jsmanaged().downcast::<Element>() { let element = match self.get_jsmanaged().downcast() {
Some(e) => e.unsafe_get(), Some(e) => e.unsafe_get(),
None => panic!("not an element") None => panic!("not an element")
}; };
@ -786,12 +786,12 @@ impl<'ln> ThreadSafeLayoutNode<'ln> {
pub fn is_ignorable_whitespace(&self) -> bool { pub fn is_ignorable_whitespace(&self) -> bool {
unsafe { unsafe {
let text: LayoutJS<Text> = match self.get_jsmanaged().downcast::<Text>() { let text: LayoutJS<Text> = match self.get_jsmanaged().downcast() {
Some(text) => text, Some(text) => text,
None => return false None => return false
}; };
if !is_whitespace(text.upcast::<CharacterData>().data_for_layout()) { if !is_whitespace(text.upcast().data_for_layout()) {
return false return false
} }
@ -814,8 +814,7 @@ impl<'ln> ThreadSafeLayoutNode<'ln> {
pub fn get_unsigned_integer_attribute(self, attribute: UnsignedIntegerAttribute) pub fn get_unsigned_integer_attribute(self, attribute: UnsignedIntegerAttribute)
-> Option<u32> { -> Option<u32> {
unsafe { unsafe {
let elem: Option<LayoutJS<Element>> = self.get_jsmanaged().downcast::<Element>(); match self.get_jsmanaged().downcast::<Element>() {
match elem {
Some(element) => { Some(element) => {
element.get_unsigned_integer_attribute_for_layout(attribute) element.get_unsigned_integer_attribute_for_layout(attribute)
} }
@ -900,20 +899,17 @@ impl<'ln> ThreadSafeLayoutNode<'ln> {
} }
let this = unsafe { self.get_jsmanaged() }; let this = unsafe { self.get_jsmanaged() };
let text = this.downcast::<Text>(); if let Some(text) = this.downcast::<Text>() {
if let Some(text) = text {
let data = unsafe { let data = unsafe {
text.upcast::<CharacterData>().data_for_layout().to_owned() text.upcast().data_for_layout().to_owned()
}; };
return TextContent::Text(data); return TextContent::Text(data);
} }
let input = this.downcast::<HTMLInputElement>(); if let Some(input) = this.downcast::<HTMLInputElement>() {
if let Some(input) = input {
let data = unsafe { input.get_value_for_layout() }; let data = unsafe { input.get_value_for_layout() };
return TextContent::Text(data); return TextContent::Text(data);
} }
let area = this.downcast::<HTMLTextAreaElement>(); if let Some(area) = this.downcast::<HTMLTextAreaElement>() {
if let Some(area) = area {
let data = unsafe { area.get_value_for_layout() }; let data = unsafe { area.get_value_for_layout() };
return TextContent::Text(data); return TextContent::Text(data);
} }
@ -926,7 +922,7 @@ impl<'ln> ThreadSafeLayoutNode<'ln> {
let this = unsafe { let this = unsafe {
self.get_jsmanaged() self.get_jsmanaged()
}; };
let input = this.downcast::<HTMLInputElement>(); let input = this.downcast();
if let Some(input) = input { if let Some(input) = input {
let insertion_point = unsafe { let insertion_point = unsafe {
input.get_insertion_point_for_layout() input.get_insertion_point_for_layout()
@ -954,7 +950,7 @@ impl<'ln> ThreadSafeLayoutNode<'ln> {
/// FIXME(pcwalton): Don't copy URLs. /// FIXME(pcwalton): Don't copy URLs.
pub fn image_url(&self) -> Option<Url> { pub fn image_url(&self) -> Option<Url> {
unsafe { unsafe {
self.get_jsmanaged().downcast::<HTMLImageElement>() self.get_jsmanaged().downcast()
.expect("not an image!") .expect("not an image!")
.image_url() .image_url()
} }
@ -962,28 +958,28 @@ impl<'ln> ThreadSafeLayoutNode<'ln> {
pub fn canvas_renderer_id(&self) -> Option<usize> { pub fn canvas_renderer_id(&self) -> Option<usize> {
unsafe { unsafe {
let canvas_element = self.get_jsmanaged().downcast::<HTMLCanvasElement>(); let canvas_element = self.get_jsmanaged().downcast();
canvas_element.and_then(|elem| elem.get_renderer_id()) canvas_element.and_then(|elem| elem.get_renderer_id())
} }
} }
pub fn canvas_ipc_renderer(&self) -> Option<IpcSender<CanvasMsg>> { pub fn canvas_ipc_renderer(&self) -> Option<IpcSender<CanvasMsg>> {
unsafe { unsafe {
let canvas_element = self.get_jsmanaged().downcast::<HTMLCanvasElement>(); let canvas_element = self.get_jsmanaged().downcast();
canvas_element.and_then(|elem| elem.get_ipc_renderer()) canvas_element.and_then(|elem| elem.get_ipc_renderer())
} }
} }
pub fn canvas_width(&self) -> u32 { pub fn canvas_width(&self) -> u32 {
unsafe { unsafe {
let canvas_element = self.get_jsmanaged().downcast::<HTMLCanvasElement>(); let canvas_element = self.get_jsmanaged().downcast();
canvas_element.unwrap().get_canvas_width() canvas_element.unwrap().get_canvas_width()
} }
} }
pub fn canvas_height(&self) -> u32 { pub fn canvas_height(&self) -> u32 {
unsafe { unsafe {
let canvas_element = self.get_jsmanaged().downcast::<HTMLCanvasElement>(); let canvas_element = self.get_jsmanaged().downcast();
canvas_element.unwrap().get_canvas_height() canvas_element.unwrap().get_canvas_height()
} }
} }

View file

@ -45,7 +45,7 @@ pub trait Activatable {
// Step 4 // Step 4
// https://html.spec.whatwg.org/multipage/#fire-a-synthetic-mouse-event // https://html.spec.whatwg.org/multipage/#fire-a-synthetic-mouse-event
let win = window_from_node(element); let win = window_from_node(element);
let target = element.upcast::<EventTarget>(); let target = element.upcast();
let mouse = MouseEvent::new(win.r(), "click".to_owned(), let mouse = MouseEvent::new(win.r(), "click".to_owned(),
EventBubbles::DoesNotBubble, EventCancelable::NotCancelable, Some(win.r()), 1, EventBubbles::DoesNotBubble, EventCancelable::NotCancelable, Some(win.r()), 1,
0, 0, 0, 0, ctrlKey, shiftKey, altKey, metaKey, 0, 0, 0, 0, ctrlKey, shiftKey, altKey, metaKey,

View file

@ -12,7 +12,6 @@ use dom::bindings::js::{JS, MutNullableHeap};
use dom::bindings::js::{LayoutJS, Root, RootedReference}; use dom::bindings::js::{LayoutJS, Root, RootedReference};
use dom::bindings::utils::{Reflector, reflect_dom_object}; use dom::bindings::utils::{Reflector, reflect_dom_object};
use dom::element::{AttributeMutation, Element}; use dom::element::{AttributeMutation, Element};
use dom::node::Node;
use dom::values::UNSIGNED_LONG_MAX; use dom::values::UNSIGNED_LONG_MAX;
use dom::virtualmethods::vtable_for; use dom::virtualmethods::vtable_for;
use dom::window::Window; use dom::window::Window;
@ -288,7 +287,7 @@ impl Attr {
assert!(Some(owner) == self.owner().r()); assert!(Some(owner) == self.owner().r());
mem::swap(&mut *self.value.borrow_mut(), &mut value); mem::swap(&mut *self.value.borrow_mut(), &mut value);
if self.namespace == ns!("") { if self.namespace == ns!("") {
vtable_for(owner.upcast::<Node>()).attribute_mutated( vtable_for(owner.upcast()).attribute_mutated(
self, AttributeMutation::Set(Some(&value))); self, AttributeMutation::Set(Some(&value)));
} }
} }

View file

@ -147,9 +147,7 @@ impl CanvasRenderingContext2D {
} }
fn mark_as_dirty(&self) { fn mark_as_dirty(&self) {
let canvas = self.canvas.root(); self.canvas.root().upcast::<Node>().dirty(NodeDamage::OtherNodeDamage);
let node = canvas.upcast::<Node>();
node.dirty(NodeDamage::OtherNodeDamage);
} }
fn update_transform(&self) { fn update_transform(&self) {

View file

@ -134,14 +134,12 @@ impl CharacterDataMethods for CharacterData {
// https://dom.spec.whatwg.org/#dom-nondocumenttypechildnode-previouselementsibling // https://dom.spec.whatwg.org/#dom-nondocumenttypechildnode-previouselementsibling
fn GetPreviousElementSibling(&self) -> Option<Root<Element>> { fn GetPreviousElementSibling(&self) -> Option<Root<Element>> {
self.upcast::<Node>().preceding_siblings() self.upcast::<Node>().preceding_siblings().filter_map(Root::downcast).next()
.filter_map(Root::downcast::<Element>).next()
} }
// https://dom.spec.whatwg.org/#dom-nondocumenttypechildnode-nextelementsibling // https://dom.spec.whatwg.org/#dom-nondocumenttypechildnode-nextelementsibling
fn GetNextElementSibling(&self) -> Option<Root<Element>> { fn GetNextElementSibling(&self) -> Option<Root<Element>> {
self.upcast::<Node>().following_siblings() self.upcast::<Node>().following_siblings().filter_map(Root::downcast).next()
.filter_map(Root::downcast::<Element>).next()
} }
} }

View file

@ -89,11 +89,11 @@ pub fn create_element(name: QualName, prefix: Option<Atom>,
macro_rules! make( macro_rules! make(
($ctor:ident) => ({ ($ctor:ident) => ({
let obj = $ctor::new((*name.local).to_owned(), prefix, document); let obj = $ctor::new((*name.local).to_owned(), prefix, document);
Root::upcast::<Element>(obj) Root::upcast(obj)
}); });
($ctor:ident, $($arg:expr),+) => ({ ($ctor:ident, $($arg:expr),+) => ({
let obj = $ctor::new((*name.local).to_owned(), prefix, document, $($arg),+); let obj = $ctor::new((*name.local).to_owned(), prefix, document, $($arg),+);
Root::upcast::<Element>(obj) Root::upcast(obj)
}) })
); );

View file

@ -242,7 +242,7 @@ impl CSSStyleDeclarationMethods for CSSStyleDeclaration {
} }
let document = document_from_node(element); let document = document_from_node(element);
let node = element.upcast::<Node>(); let node = element.upcast();
document.r().content_changed(node, NodeDamage::NodeStyleDamaged); document.r().content_changed(node, NodeDamage::NodeStyleDamaged);
Ok(()) Ok(())
} }
@ -276,7 +276,7 @@ impl CSSStyleDeclarationMethods for CSSStyleDeclaration {
} }
let document = document_from_node(element); let document = document_from_node(element);
let node = element.upcast::<Node>(); let node = element.upcast();
document.r().content_changed(node, NodeDamage::NodeStyleDamaged); document.r().content_changed(node, NodeDamage::NodeStyleDamaged);
Ok(()) Ok(())
} }

View file

@ -15,7 +15,6 @@ use dom::bindings::js::{Root, RootCollection};
use dom::bindings::refcounted::LiveDOMReferences; use dom::bindings::refcounted::LiveDOMReferences;
use dom::bindings::structuredclone::StructuredCloneData; use dom::bindings::structuredclone::StructuredCloneData;
use dom::bindings::utils::Reflectable; use dom::bindings::utils::Reflectable;
use dom::eventtarget::EventTarget;
use dom::messageevent::MessageEvent; use dom::messageevent::MessageEvent;
use dom::worker::{SimpleWorkerErrorHandler, TrustedWorkerAddress, WorkerMessageHandler}; use dom::worker::{SimpleWorkerErrorHandler, TrustedWorkerAddress, WorkerMessageHandler};
use dom::workerglobalscope::WorkerGlobalScope; use dom::workerglobalscope::WorkerGlobalScope;
@ -289,7 +288,7 @@ impl DedicatedWorkerGlobalScope {
match msg { match msg {
WorkerScriptMsg::DOMMessage(data) => { WorkerScriptMsg::DOMMessage(data) => {
let scope = self.upcast::<WorkerGlobalScope>(); let scope = self.upcast::<WorkerGlobalScope>();
let target = self.upcast::<EventTarget>(); let target = self.upcast();
let _ar = JSAutoRequest::new(scope.get_cx()); let _ar = JSAutoRequest::new(scope.get_cx());
let _ac = JSAutoCompartment::new(scope.get_cx(), scope.reflector().get_jsobject().get()); let _ac = JSAutoCompartment::new(scope.get_cx(), scope.reflector().get_jsobject().get());
let mut message = RootedValue::new(scope.get_cx(), UndefinedValue()); let mut message = RootedValue::new(scope.get_cx(), UndefinedValue());
@ -323,7 +322,7 @@ impl DedicatedWorkerGlobalScope {
fn handle_event(&self, event: MixedMessage) { fn handle_event(&self, event: MixedMessage) {
match event { match event {
MixedMessage::FromDevtools(msg) => { MixedMessage::FromDevtools(msg) => {
let global_ref = GlobalRef::Worker(self.upcast::<WorkerGlobalScope>()); let global_ref = GlobalRef::Worker(self.upcast());
match msg { match msg {
DevtoolScriptControlMsg::EvaluateJS(_pipe_id, string, sender) => DevtoolScriptControlMsg::EvaluateJS(_pipe_id, string, sender) =>
devtools::handle_evaluate_js(&global_ref, string, sender), devtools::handle_evaluate_js(&global_ref, string, sender),

View file

@ -290,8 +290,7 @@ impl Document {
let base = self.upcast::<Node>() let base = self.upcast::<Node>()
.traverse_preorder() .traverse_preorder()
.filter_map(Root::downcast::<HTMLBaseElement>) .filter_map(Root::downcast::<HTMLBaseElement>)
.filter(|element| element.upcast::<Element>().has_attribute(&atom!("href"))) .find(|element| element.upcast::<Element>().has_attribute(&atom!("href")));
.next();
self.base_element.set(base.r()); self.base_element.set(base.r());
} }
@ -379,10 +378,7 @@ impl Document {
element: &Element, element: &Element,
id: Atom) { id: Atom) {
debug!("Adding named element to document {:p}: {:p} id={}", self, element, id); debug!("Adding named element to document {:p}: {:p} id={}", self, element, id);
assert!({ assert!(element.upcast::<Node>().is_in_doc());
let node = element.upcast::<Node>();
node.is_in_doc()
});
assert!(!id.is_empty()); assert!(!id.is_empty());
let mut idmap = self.idmap.borrow_mut(); let mut idmap = self.idmap.borrow_mut();
@ -401,7 +397,7 @@ impl Document {
let mut head: usize = 0; let mut head: usize = 0;
let root = root.upcast::<Node>(); let root = root.upcast::<Node>();
for node in root.traverse_preorder() { for node in root.traverse_preorder() {
if let Some(elem) = node.downcast::<Element>() { if let Some(elem) = node.downcast() {
if (*elements)[head].root().r() == elem { if (*elements)[head].root().r() == elem {
head += 1; head += 1;
} }
@ -420,7 +416,7 @@ impl Document {
/// https://html.spec.whatwg.org/multipage/#the-indicated-part-of-the-document /// https://html.spec.whatwg.org/multipage/#the-indicated-part-of-the-document
pub fn find_fragment_node(&self, fragid: &str) -> Option<Root<Element>> { pub fn find_fragment_node(&self, fragid: &str) -> Option<Root<Element>> {
self.GetElementById(fragid.to_owned()).or_else(|| { self.GetElementById(fragid.to_owned()).or_else(|| {
let check_anchor = |&node: &&HTMLAnchorElement| { let check_anchor = |node: &HTMLAnchorElement| {
let elem = node.upcast::<Element>(); let elem = node.upcast::<Element>();
elem.get_attribute(&ns!(""), &atom!("name")).map_or(false, |attr| { elem.get_attribute(&ns!(""), &atom!("name")).map_or(false, |attr| {
&**attr.r().value() == fragid &**attr.r().value() == fragid
@ -428,9 +424,9 @@ impl Document {
}; };
let doc_node = self.upcast::<Node>(); let doc_node = self.upcast::<Node>();
doc_node.traverse_preorder() doc_node.traverse_preorder()
.filter_map(Root::downcast::<HTMLAnchorElement>) .filter_map(Root::downcast)
.find(|node| check_anchor(&node.r())) .find(|node| check_anchor(&node))
.map(Root::upcast::<Element>) .map(Root::upcast)
}) })
} }
@ -606,7 +602,7 @@ impl Document {
match mouse_event_type { match mouse_event_type {
MouseEventType::Click => el.authentic_click_activation(event), MouseEventType::Click => el.authentic_click_activation(event),
_ => { _ => {
let target = node.upcast::<EventTarget>(); let target = node.upcast();
event.fire(target); event.fire(target);
}, },
} }
@ -664,7 +660,7 @@ impl Document {
if target_ref.get_hover_state() { if target_ref.get_hover_state() {
target_ref.set_hover_state(false); target_ref.set_hover_state(false);
let target = target_ref.upcast::<EventTarget>(); let target = target_ref.upcast();
self.fire_mouse_event(point, &target, "mouseout".to_owned()); self.fire_mouse_event(point, &target, "mouseout".to_owned());
} }
@ -678,7 +674,7 @@ impl Document {
if !target.get_hover_state() { if !target.get_hover_state() {
target.set_hover_state(true); target.set_hover_state(true);
let target = target.upcast::<EventTarget>(); let target = target.upcast();
self.fire_mouse_event(point, target, "mouseover".to_owned()); self.fire_mouse_event(point, target, "mouseover".to_owned());
@ -690,7 +686,7 @@ impl Document {
let top_most_node = let top_most_node =
node::from_untrusted_node_address(js_runtime, mouse_over_addresses[0]); node::from_untrusted_node_address(js_runtime, mouse_over_addresses[0]);
let target = top_most_node.upcast::<EventTarget>(); let target = top_most_node.upcast();
self.fire_mouse_event(point, target, "mousemove".to_owned()); self.fire_mouse_event(point, target, "mousemove".to_owned());
} }
@ -713,9 +709,9 @@ impl Document {
let body = self.GetBody(); let body = self.GetBody();
let target = match (&focused, &body) { let target = match (&focused, &body) {
(&Some(ref focused), _) => focused.upcast::<EventTarget>(), (&Some(ref focused), _) => focused.upcast(),
(&None, &Some(ref body)) => body.upcast::<EventTarget>(), (&None, &Some(ref body)) => body.upcast(),
(&None, &None) => self.window.upcast::<EventTarget>(), (&None, &None) => self.window.upcast(),
}; };
let ctrl = modifiers.contains(CONTROL); let ctrl = modifiers.contains(CONTROL);
@ -768,7 +764,7 @@ impl Document {
// https://www.w3.org/Bugs/Public/show_bug.cgi?id=27337 // https://www.w3.org/Bugs/Public/show_bug.cgi?id=27337
match key { match key {
Key::Space if !prevented && state == KeyState::Released => { Key::Space if !prevented && state == KeyState::Released => {
let maybe_elem: Option<&Element> = target.downcast::<Element>(); let maybe_elem = target.downcast::<Element>();
if let Some(el) = maybe_elem { if let Some(el) = maybe_elem {
if let Some(a) = el.as_maybe_activatable() { if let Some(a) = el.as_maybe_activatable() {
a.synthetic_click_activation(ctrl, alt, shift, meta); a.synthetic_click_activation(ctrl, alt, shift, meta);
@ -776,7 +772,7 @@ impl Document {
} }
} }
Key::Enter if !prevented && state == KeyState::Released => { Key::Enter if !prevented && state == KeyState::Released => {
let maybe_elem: Option<&Element> = target.downcast::<Element>(); let maybe_elem = target.downcast::<Element>();
if let Some(el) = maybe_elem { if let Some(el) = maybe_elem {
if let Some(a) = el.as_maybe_activatable() { if let Some(a) = el.as_maybe_activatable() {
a.implicit_submission(ctrl, alt, shift, meta); a.implicit_submission(ctrl, alt, shift, meta);
@ -797,7 +793,7 @@ impl Document {
match nodes.into_iter().next().unwrap() { match nodes.into_iter().next().unwrap() {
NodeOrString::eNode(node) => Ok(node), NodeOrString::eNode(node) => Ok(node),
NodeOrString::eString(string) => { NodeOrString::eString(string) => {
Ok(Root::upcast::<Node>(self.CreateTextNode(string))) Ok(Root::upcast(self.CreateTextNode(string)))
}, },
} }
} else { } else {
@ -940,7 +936,8 @@ impl Document {
/// Find an iframe element in the document. /// Find an iframe element in the document.
pub fn find_iframe(&self, subpage_id: SubpageId) -> Option<Root<HTMLIFrameElement>> { pub fn find_iframe(&self, subpage_id: SubpageId) -> Option<Root<HTMLIFrameElement>> {
self.upcast::<Node>().traverse_preorder() self.upcast::<Node>()
.traverse_preorder()
.filter_map(Root::downcast::<HTMLIFrameElement>) .filter_map(Root::downcast::<HTMLIFrameElement>)
.find(|node| node.r().subpage_id() == Some(subpage_id)) .find(|node| node.r().subpage_id() == Some(subpage_id))
} }
@ -1073,10 +1070,7 @@ impl Document {
} }
fn get_html_element(&self) -> Option<Root<HTMLHtmlElement>> { fn get_html_element(&self) -> Option<Root<HTMLHtmlElement>> {
self.GetDocumentElement() self.GetDocumentElement().and_then(Root::downcast)
.r()
.and_then(Castable::downcast::<HTMLHtmlElement>)
.map(Root::from_ref)
} }
/// https://html.spec.whatwg.org/multipage/#appropriate-template-contents-owner-document /// https://html.spec.whatwg.org/multipage/#appropriate-template-contents-owner-document
@ -1131,7 +1125,7 @@ impl DocumentMethods for Document {
match self.get_focused_element() { match self.get_focused_element() {
Some(element) => Some(element), // Step 3. and 4. Some(element) => Some(element), // Step 3. and 4.
None => match self.GetBody() { // Step 5. None => match self.GetBody() { // Step 5.
Some(body) => Some(Root::upcast::<Element>(body)), Some(body) => Some(Root::upcast(body)),
None => self.GetDocumentElement(), None => self.GetDocumentElement(),
} }
} }
@ -1186,32 +1180,28 @@ impl DocumentMethods for Document {
// https://dom.spec.whatwg.org/#dom-document-doctype // https://dom.spec.whatwg.org/#dom-document-doctype
fn GetDoctype(&self) -> Option<Root<DocumentType>> { fn GetDoctype(&self) -> Option<Root<DocumentType>> {
let node = self.upcast::<Node>(); self.upcast::<Node>().children().filter_map(Root::downcast).next()
node.children()
.filter_map(|c| c.downcast::<DocumentType>().map(Root::from_ref))
.next()
} }
// https://dom.spec.whatwg.org/#dom-document-documentelement // https://dom.spec.whatwg.org/#dom-document-documentelement
fn GetDocumentElement(&self) -> Option<Root<Element>> { fn GetDocumentElement(&self) -> Option<Root<Element>> {
let node = self.upcast::<Node>(); self.upcast::<Node>().child_elements().next()
node.child_elements().next()
} }
// https://dom.spec.whatwg.org/#dom-document-getelementsbytagname // https://dom.spec.whatwg.org/#dom-document-getelementsbytagname
fn GetElementsByTagName(&self, tag_name: DOMString) -> Root<HTMLCollection> { fn GetElementsByTagName(&self, tag_name: DOMString) -> Root<HTMLCollection> {
HTMLCollection::by_tag_name(&self.window, self.upcast::<Node>(), tag_name) HTMLCollection::by_tag_name(&self.window, self.upcast(), tag_name)
} }
// https://dom.spec.whatwg.org/#dom-document-getelementsbytagnamens // https://dom.spec.whatwg.org/#dom-document-getelementsbytagnamens
fn GetElementsByTagNameNS(&self, maybe_ns: Option<DOMString>, tag_name: DOMString) fn GetElementsByTagNameNS(&self, maybe_ns: Option<DOMString>, tag_name: DOMString)
-> Root<HTMLCollection> { -> Root<HTMLCollection> {
HTMLCollection::by_tag_name_ns(&self.window, self.upcast::<Node>(), tag_name, maybe_ns) HTMLCollection::by_tag_name_ns(&self.window, self.upcast(), tag_name, maybe_ns)
} }
// https://dom.spec.whatwg.org/#dom-document-getelementsbyclassname // https://dom.spec.whatwg.org/#dom-document-getelementsbyclassname
fn GetElementsByClassName(&self, classes: DOMString) -> Root<HTMLCollection> { fn GetElementsByClassName(&self, classes: DOMString) -> Root<HTMLCollection> {
HTMLCollection::by_class_name(&self.window, self.upcast::<Node>(), classes) HTMLCollection::by_class_name(&self.window, self.upcast(), classes)
} }
// https://dom.spec.whatwg.org/#dom-nonelementparentnode-getelementbyid // https://dom.spec.whatwg.org/#dom-nonelementparentnode-getelementbyid
@ -1335,19 +1325,20 @@ impl DocumentMethods for Document {
fn CreateEvent(&self, mut interface: DOMString) -> Fallible<Root<Event>> { fn CreateEvent(&self, mut interface: DOMString) -> Fallible<Root<Event>> {
interface.make_ascii_lowercase(); interface.make_ascii_lowercase();
match &*interface { match &*interface {
"uievents" | "uievent" => Ok(Root::upcast::<Event>( "uievents" | "uievent" =>
UIEvent::new_uninitialized(&self.window))), Ok(Root::upcast(UIEvent::new_uninitialized(&self.window))),
"mouseevents" | "mouseevent" => Ok(Root::upcast::<Event>( "mouseevents" | "mouseevent" =>
MouseEvent::new_uninitialized(&self.window))), Ok(Root::upcast(MouseEvent::new_uninitialized(&self.window))),
"customevent" => Ok(Root::upcast::<Event>( "customevent" =>
CustomEvent::new_uninitialized(GlobalRef::Window(&self.window)))), Ok(Root::upcast(CustomEvent::new_uninitialized(GlobalRef::Window(&self.window)))),
"htmlevents" | "events" | "event" => Ok(Event::new_uninitialized( "htmlevents" | "events" | "event" =>
GlobalRef::Window(&self.window))), Ok(Event::new_uninitialized(GlobalRef::Window(&self.window))),
"keyboardevent" | "keyevents" => Ok(Root::upcast::<Event>( "keyboardevent" | "keyevents" =>
KeyboardEvent::new_uninitialized(&self.window))), Ok(Root::upcast(KeyboardEvent::new_uninitialized(&self.window))),
"messageevent" => Ok(Root::upcast::<Event>( "messageevent" =>
MessageEvent::new_uninitialized(GlobalRef::Window(&self.window)))), Ok(Root::upcast(MessageEvent::new_uninitialized(GlobalRef::Window(&self.window)))),
_ => Err(Error::NotSupported) _ =>
Err(Error::NotSupported),
} }
} }
@ -1389,7 +1380,7 @@ impl DocumentMethods for Document {
// Step 2. // Step 2.
root.upcast::<Node>() root.upcast::<Node>()
.traverse_preorder() .traverse_preorder()
.find(|node| node.r().is::<HTMLTitleElement>()) .find(|node| node.is::<HTMLTitleElement>())
} }
}); });
@ -1423,7 +1414,7 @@ impl DocumentMethods for Document {
let elem = Element::create(name, None, self, let elem = Element::create(name, None, self,
ElementCreator::ScriptCreated); ElementCreator::ScriptCreated);
root.upcast::<Node>() root.upcast::<Node>()
.AppendChild(elem.upcast::<Node>()) .AppendChild(elem.upcast())
.unwrap() .unwrap()
} }
} }
@ -1440,7 +1431,7 @@ impl DocumentMethods for Document {
let elem = Element::create(name, None, self, let elem = Element::create(name, None, self,
ElementCreator::ScriptCreated); ElementCreator::ScriptCreated);
head.upcast::<Node>() head.upcast::<Node>()
.AppendChild(elem.upcast::<Node>()) .AppendChild(elem.upcast())
.unwrap() .unwrap()
}, },
None => return, None => return,
@ -1457,10 +1448,7 @@ impl DocumentMethods for Document {
// https://html.spec.whatwg.org/multipage/#dom-document-head // https://html.spec.whatwg.org/multipage/#dom-document-head
fn GetHead(&self) -> Option<Root<HTMLHeadElement>> { fn GetHead(&self) -> Option<Root<HTMLHeadElement>> {
self.get_html_element().and_then(|root| { self.get_html_element().and_then(|root| {
let node = root.upcast::<Node>(); root.upcast::<Node>().children().filter_map(Root::downcast).next()
node.children()
.filter_map(|c| c.downcast::<HTMLHeadElement>().map(Root::from_ref))
.next()
}) })
} }
@ -1479,9 +1467,7 @@ impl DocumentMethods for Document {
NodeTypeId::Element(ElementTypeId::HTMLElement(HTMLElementTypeId::HTMLFrameSetElement)) => true, NodeTypeId::Element(ElementTypeId::HTMLElement(HTMLElementTypeId::HTMLFrameSetElement)) => true,
_ => false _ => false
} }
}).map(|node| { }).map(|node| Root::downcast(node).unwrap())
Root::from_ref(node.downcast::<HTMLElement>().unwrap())
})
}) })
} }
@ -1510,9 +1496,7 @@ impl DocumentMethods for Document {
// Step 3. // Step 3.
(Some(ref root), &Some(ref child)) => { (Some(ref root), &Some(ref child)) => {
let root = root.upcast::<Node>(); let root = root.upcast::<Node>();
let child = child.upcast::<Node>(); root.ReplaceChild(new_body.upcast(), child.upcast()).unwrap();
let new_body = new_body.upcast::<Node>();
assert!(root.ReplaceChild(new_body, child).is_ok())
}, },
// Step 4. // Step 4.
@ -1521,8 +1505,7 @@ impl DocumentMethods for Document {
// Step 5. // Step 5.
(Some(ref root), &None) => { (Some(ref root), &None) => {
let root = root.upcast::<Node>(); let root = root.upcast::<Node>();
let new_body = new_body.upcast::<Node>(); root.AppendChild(new_body.upcast()).unwrap();
assert!(root.AppendChild(new_body).is_ok());
} }
} }
Ok(()) Ok(())
@ -1547,18 +1530,16 @@ impl DocumentMethods for Document {
// https://html.spec.whatwg.org/multipage/#dom-document-images // https://html.spec.whatwg.org/multipage/#dom-document-images
fn Images(&self) -> Root<HTMLCollection> { fn Images(&self) -> Root<HTMLCollection> {
self.images.or_init(|| { self.images.or_init(|| {
let root = self.upcast::<Node>();
let filter = box ImagesFilter; let filter = box ImagesFilter;
HTMLCollection::create(&self.window, root, filter) HTMLCollection::create(&self.window, self.upcast(), filter)
}) })
} }
// https://html.spec.whatwg.org/multipage/#dom-document-embeds // https://html.spec.whatwg.org/multipage/#dom-document-embeds
fn Embeds(&self) -> Root<HTMLCollection> { fn Embeds(&self) -> Root<HTMLCollection> {
self.embeds.or_init(|| { self.embeds.or_init(|| {
let root = self.upcast::<Node>();
let filter = box EmbedsFilter; let filter = box EmbedsFilter;
HTMLCollection::create(&self.window, root, filter) HTMLCollection::create(&self.window, self.upcast(), filter)
}) })
} }
@ -1570,36 +1551,32 @@ impl DocumentMethods for Document {
// https://html.spec.whatwg.org/multipage/#dom-document-links // https://html.spec.whatwg.org/multipage/#dom-document-links
fn Links(&self) -> Root<HTMLCollection> { fn Links(&self) -> Root<HTMLCollection> {
self.links.or_init(|| { self.links.or_init(|| {
let root = self.upcast::<Node>();
let filter = box LinksFilter; let filter = box LinksFilter;
HTMLCollection::create(&self.window, root, filter) HTMLCollection::create(&self.window, self.upcast(), filter)
}) })
} }
// https://html.spec.whatwg.org/multipage/#dom-document-forms // https://html.spec.whatwg.org/multipage/#dom-document-forms
fn Forms(&self) -> Root<HTMLCollection> { fn Forms(&self) -> Root<HTMLCollection> {
self.forms.or_init(|| { self.forms.or_init(|| {
let root = self.upcast::<Node>();
let filter = box FormsFilter; let filter = box FormsFilter;
HTMLCollection::create(&self.window, root, filter) HTMLCollection::create(&self.window, self.upcast(), filter)
}) })
} }
// https://html.spec.whatwg.org/multipage/#dom-document-scripts // https://html.spec.whatwg.org/multipage/#dom-document-scripts
fn Scripts(&self) -> Root<HTMLCollection> { fn Scripts(&self) -> Root<HTMLCollection> {
self.scripts.or_init(|| { self.scripts.or_init(|| {
let root = self.upcast::<Node>();
let filter = box ScriptsFilter; let filter = box ScriptsFilter;
HTMLCollection::create(&self.window, root, filter) HTMLCollection::create(&self.window, self.upcast(), filter)
}) })
} }
// https://html.spec.whatwg.org/multipage/#dom-document-anchors // https://html.spec.whatwg.org/multipage/#dom-document-anchors
fn Anchors(&self) -> Root<HTMLCollection> { fn Anchors(&self) -> Root<HTMLCollection> {
self.anchors.or_init(|| { self.anchors.or_init(|| {
let root = self.upcast::<Node>();
let filter = box AnchorsFilter; let filter = box AnchorsFilter;
HTMLCollection::create(&self.window, root, filter) HTMLCollection::create(&self.window, self.upcast(), filter)
}) })
} }
@ -1607,9 +1584,8 @@ impl DocumentMethods for Document {
fn Applets(&self) -> Root<HTMLCollection> { fn Applets(&self) -> Root<HTMLCollection> {
// FIXME: This should be return OBJECT elements containing applets. // FIXME: This should be return OBJECT elements containing applets.
self.applets.or_init(|| { self.applets.or_init(|| {
let root = self.upcast::<Node>();
let filter = box AppletsFilter; let filter = box AppletsFilter;
HTMLCollection::create(&self.window, root, filter) HTMLCollection::create(&self.window, self.upcast(), filter)
}) })
} }
@ -1620,7 +1596,7 @@ impl DocumentMethods for Document {
// https://dom.spec.whatwg.org/#dom-parentnode-children // https://dom.spec.whatwg.org/#dom-parentnode-children
fn Children(&self) -> Root<HTMLCollection> { fn Children(&self) -> Root<HTMLCollection> {
HTMLCollection::children(&self.window, self.upcast::<Node>()) HTMLCollection::children(&self.window, self.upcast())
} }
// https://dom.spec.whatwg.org/#dom-parentnode-firstelementchild // https://dom.spec.whatwg.org/#dom-parentnode-firstelementchild
@ -1630,7 +1606,7 @@ impl DocumentMethods for Document {
// https://dom.spec.whatwg.org/#dom-parentnode-lastelementchild // https://dom.spec.whatwg.org/#dom-parentnode-lastelementchild
fn GetLastElementChild(&self) -> Option<Root<Element>> { fn GetLastElementChild(&self) -> Option<Root<Element>> {
self.upcast::<Node>().rev_children().filter_map(Root::downcast::<Element>).next() self.upcast::<Node>().rev_children().filter_map(Root::downcast).next()
} }
// https://dom.spec.whatwg.org/#dom-parentnode-childelementcount // https://dom.spec.whatwg.org/#dom-parentnode-childelementcount
@ -1713,7 +1689,7 @@ impl DocumentMethods for Document {
} }
impl CollectionFilter for NamedElementFilter { impl CollectionFilter for NamedElementFilter {
fn filter(&self, elem: &Element, _root: &Node) -> bool { fn filter(&self, elem: &Element, _root: &Node) -> bool {
filter_by_name(&self.name, elem.upcast::<Node>()) filter_by_name(&self.name, elem.upcast())
} }
} }
// https://html.spec.whatwg.org/multipage/#dom-document-nameditem-filter // https://html.spec.whatwg.org/multipage/#dom-document-nameditem-filter
@ -1866,9 +1842,8 @@ impl DocumentProgressHandler {
EventBubbles::DoesNotBubble, EventBubbles::DoesNotBubble,
EventCancelable::NotCancelable); EventCancelable::NotCancelable);
let wintarget = window.upcast::<EventTarget>(); let wintarget = window.upcast::<EventTarget>();
let doctarget = document.upcast::<EventTarget>();
event.r().set_trusted(true); event.r().set_trusted(true);
let _ = wintarget.dispatch_event_with_target(doctarget, event.r()); let _ = wintarget.dispatch_event_with_target(document.upcast(), &event);
let browsing_context = window.browsing_context(); let browsing_context = window.browsing_context();
let browsing_context = browsing_context.as_ref().unwrap(); let browsing_context = browsing_context.as_ref().unwrap();
@ -1878,8 +1853,7 @@ impl DocumentProgressHandler {
let event = Event::new(GlobalRef::Window(frame_window.r()), "load".to_owned(), let event = Event::new(GlobalRef::Window(frame_window.r()), "load".to_owned(),
EventBubbles::DoesNotBubble, EventBubbles::DoesNotBubble,
EventCancelable::NotCancelable); EventCancelable::NotCancelable);
let target = frame_element.upcast::<EventTarget>(); event.fire(frame_element.upcast());
event.r().fire(target);
}; };
document.r().notify_constellation_load(); document.r().notify_constellation_load();

View file

@ -48,7 +48,7 @@ impl DocumentFragmentMethods for DocumentFragment {
// https://dom.spec.whatwg.org/#dom-parentnode-children // https://dom.spec.whatwg.org/#dom-parentnode-children
fn Children(&self) -> Root<HTMLCollection> { fn Children(&self) -> Root<HTMLCollection> {
let window = window_from_node(self); let window = window_from_node(self);
HTMLCollection::children(window.r(), self.upcast::<Node>()) HTMLCollection::children(&window, self.upcast())
} }
// https://dom.spec.whatwg.org/#dom-nonelementparentnode-getelementbyid // https://dom.spec.whatwg.org/#dom-nonelementparentnode-getelementbyid
@ -90,13 +90,11 @@ impl DocumentFragmentMethods for DocumentFragment {
// https://dom.spec.whatwg.org/#dom-parentnode-queryselector // https://dom.spec.whatwg.org/#dom-parentnode-queryselector
fn QuerySelector(&self, selectors: DOMString) -> Fallible<Option<Root<Element>>> { fn QuerySelector(&self, selectors: DOMString) -> Fallible<Option<Root<Element>>> {
let root = self.upcast::<Node>(); self.upcast::<Node>().query_selector(selectors)
root.query_selector(selectors)
} }
// https://dom.spec.whatwg.org/#dom-parentnode-queryselectorall // https://dom.spec.whatwg.org/#dom-parentnode-queryselectorall
fn QuerySelectorAll(&self, selectors: DOMString) -> Fallible<Root<NodeList>> { fn QuerySelectorAll(&self, selectors: DOMString) -> Fallible<Root<NodeList>> {
let root = self.upcast::<Node>(); self.upcast::<Node>().query_selector_all(selectors)
root.query_selector_all(selectors)
} }
} }

View file

@ -98,7 +98,6 @@ impl DocumentTypeMethods for DocumentType {
// https://dom.spec.whatwg.org/#dom-childnode-remove // https://dom.spec.whatwg.org/#dom-childnode-remove
fn Remove(&self) { fn Remove(&self) {
let node = self.upcast::<Node>(); self.upcast::<Node>().remove_self();
node.remove_self();
} }
} }

View file

@ -80,20 +80,13 @@ impl DOMImplementationMethods for DOMImplementation {
let doc_node = doc.upcast::<Node>(); let doc_node = doc.upcast::<Node>();
// Step 4. // Step 4.
match maybe_doctype { if let Some(doc_type) = maybe_doctype {
None => (), doc_node.AppendChild(doc_type.upcast()).unwrap();
Some(ref doctype) => {
let doc_type = doctype.upcast::<Node>();
assert!(doc_node.AppendChild(doc_type).is_ok())
}
} }
// Step 5. // Step 5.
match maybe_elem { if let Some(ref elem) = maybe_elem {
None => (), doc_node.AppendChild(elem.upcast()).unwrap();
Some(ref elem) => {
assert!(doc_node.AppendChild(elem.upcast::<Node>()).is_ok())
}
} }
} }
@ -117,7 +110,7 @@ impl DOMImplementationMethods for DOMImplementation {
// Step 3. // Step 3.
let doc_node = doc.upcast::<Node>(); let doc_node = doc.upcast::<Node>();
let doc_type = DocumentType::new("html".to_owned(), None, None, doc.r()); let doc_type = DocumentType::new("html".to_owned(), None, None, doc.r());
assert!(doc_node.AppendChild(doc_type.upcast::<Node>()).is_ok()); doc_node.AppendChild(doc_type.upcast()).unwrap();
} }
{ {
@ -125,13 +118,13 @@ impl DOMImplementationMethods for DOMImplementation {
let doc_node = doc.upcast::<Node>(); let doc_node = doc.upcast::<Node>();
let doc_html = Root::upcast::<Node>( let doc_html = Root::upcast::<Node>(
HTMLHtmlElement::new("html".to_owned(), None, doc.r())); HTMLHtmlElement::new("html".to_owned(), None, doc.r()));
assert!(doc_node.AppendChild(doc_html.r()).is_ok()); doc_node.AppendChild(&doc_html).expect("Appending failed");
{ {
// Step 5. // Step 5.
let doc_head = Root::upcast::<Node>( let doc_head = Root::upcast::<Node>(
HTMLHeadElement::new("head".to_owned(), None, doc.r())); HTMLHeadElement::new("head".to_owned(), None, doc.r()));
assert!(doc_html.r().AppendChild(doc_head.r()).is_ok()); doc_html.AppendChild(&doc_head).unwrap();
// Step 6. // Step 6.
match title { match title {
@ -140,18 +133,18 @@ impl DOMImplementationMethods for DOMImplementation {
// Step 6.1. // Step 6.1.
let doc_title = Root::upcast::<Node>( let doc_title = Root::upcast::<Node>(
HTMLTitleElement::new("title".to_owned(), None, doc.r())); HTMLTitleElement::new("title".to_owned(), None, doc.r()));
assert!(doc_head.r().AppendChild(doc_title.r()).is_ok()); doc_head.AppendChild(&doc_title).unwrap();
// Step 6.2. // Step 6.2.
let title_text = Text::new(title_str, doc.r()); let title_text = Text::new(title_str, doc.r());
assert!(doc_title.r().AppendChild(title_text.upcast::<Node>()).is_ok()); doc_title.AppendChild(title_text.upcast()).unwrap();
} }
} }
} }
// Step 7. // Step 7.
let doc_body = HTMLBodyElement::new("body".to_owned(), None, doc.r()); let doc_body = HTMLBodyElement::new("body".to_owned(), None, doc.r());
assert!(doc_html.r().AppendChild(doc_body.upcast::<Node>()).is_ok()); doc_html.AppendChild(doc_body.upcast()).unwrap();
} }
// Step 8. // Step 8.

View file

@ -35,7 +35,6 @@ use dom::domrect::DOMRect;
use dom::domrectlist::DOMRectList; use dom::domrectlist::DOMRectList;
use dom::domtokenlist::DOMTokenList; use dom::domtokenlist::DOMTokenList;
use dom::event::Event; use dom::event::Event;
use dom::eventtarget::EventTarget;
use dom::htmlanchorelement::HTMLAnchorElement; use dom::htmlanchorelement::HTMLAnchorElement;
use dom::htmlbodyelement::HTMLBodyElement; use dom::htmlbodyelement::HTMLBodyElement;
use dom::htmlcollection::HTMLCollection; use dom::htmlcollection::HTMLCollection;
@ -544,8 +543,7 @@ impl LayoutElementHelpers for LayoutJS<Element> {
if (*self.unsafe_get()).namespace != ns!(HTML) { if (*self.unsafe_get()).namespace != ns!(HTML) {
return false return false
} }
let node = self.upcast::<Node>(); self.upcast::<Node>().owner_doc_for_layout().is_html_document_for_layout()
node.owner_doc_for_layout().is_html_document_for_layout()
} }
#[allow(unsafe_code)] #[allow(unsafe_code)]
@ -623,8 +621,7 @@ pub enum StylePriority {
impl Element { impl Element {
pub fn html_element_in_html_document(&self) -> bool { pub fn html_element_in_html_document(&self) -> bool {
let node = self.upcast::<Node>(); self.namespace == ns!(HTML) && self.upcast::<Node>().is_in_html_doc()
self.namespace == ns!(HTML) && node.is_in_html_doc()
} }
pub fn local_name(&self) -> &Atom { pub fn local_name(&self) -> &Atom {
@ -784,9 +781,8 @@ impl Element {
} }
pub fn serialize(&self, traversal_scope: TraversalScope) -> Fallible<DOMString> { pub fn serialize(&self, traversal_scope: TraversalScope) -> Fallible<DOMString> {
let node = self.upcast::<Node>();
let mut writer = vec![]; let mut writer = vec![];
match serialize(&mut writer, &node, match serialize(&mut writer, &self.upcast::<Node>(),
SerializeOpts { SerializeOpts {
traversal_scope: traversal_scope, traversal_scope: traversal_scope,
.. Default::default() .. Default::default()
@ -798,10 +794,7 @@ impl Element {
// https://html.spec.whatwg.org/multipage/#root-element // https://html.spec.whatwg.org/multipage/#root-element
pub fn get_root_element(&self) -> Root<Element> { pub fn get_root_element(&self) -> Root<Element> {
let node = self.upcast::<Node>(); self.upcast::<Node>().inclusive_ancestors().filter_map(Root::downcast).last()
node.inclusive_ancestors()
.filter_map(Root::downcast::<Element>)
.last()
.expect("We know inclusive_ancestors will return `self` which is an element") .expect("We know inclusive_ancestors will return `self` which is an element")
} }
@ -889,8 +882,7 @@ impl Element {
let attr = Attr::new(&window, local_name, value, name, namespace, prefix, Some(self)); let attr = Attr::new(&window, local_name, value, name, namespace, prefix, Some(self));
self.attrs.borrow_mut().push(JS::from_rooted(&attr)); self.attrs.borrow_mut().push(JS::from_rooted(&attr));
if in_empty_ns { if in_empty_ns {
vtable_for(self.upcast::<Node>()).attribute_mutated( vtable_for(self.upcast()).attribute_mutated(&attr, AttributeMutation::Set(None));
&attr, AttributeMutation::Set(None));
} }
} }
@ -974,8 +966,7 @@ impl Element {
pub fn parse_attribute(&self, namespace: &Namespace, local_name: &Atom, pub fn parse_attribute(&self, namespace: &Namespace, local_name: &Atom,
value: DOMString) -> AttrValue { value: DOMString) -> AttrValue {
if *namespace == ns!("") { if *namespace == ns!("") {
vtable_for(&self.upcast::<Node>()) vtable_for(self.upcast()).parse_plain_attribute(local_name, value)
.parse_plain_attribute(local_name, value)
} else { } else {
AttrValue::String(value) AttrValue::String(value)
} }
@ -1001,20 +992,15 @@ impl Element {
let attr = (*self.attrs.borrow())[idx].root(); let attr = (*self.attrs.borrow())[idx].root();
self.attrs.borrow_mut().remove(idx); self.attrs.borrow_mut().remove(idx);
attr.set_owner(None); attr.set_owner(None);
let node = self.upcast::<Node>();
if attr.namespace() == &ns!("") { if attr.namespace() == &ns!("") {
vtable_for(node).attribute_mutated(&attr, AttributeMutation::Removed); vtable_for(self.upcast()).attribute_mutated(&attr, AttributeMutation::Removed);
} }
attr attr
}) })
} }
pub fn has_class(&self, name: &Atom) -> bool { pub fn has_class(&self, name: &Atom) -> bool {
let quirks_mode = { let quirks_mode = document_from_node(self).quirks_mode();
let node = self.upcast::<Node>();
let owner_doc = node.owner_doc();
owner_doc.r().quirks_mode()
};
let is_equal = |lhs: &Atom, rhs: &Atom| match quirks_mode { let is_equal = |lhs: &Atom, rhs: &Atom| match quirks_mode {
NoQuirks | LimitedQuirks => lhs == rhs, NoQuirks | LimitedQuirks => lhs == rhs,
Quirks => lhs.eq_ignore_ascii_case(&rhs) Quirks => lhs.eq_ignore_ascii_case(&rhs)
@ -1175,14 +1161,7 @@ impl ElementMethods for Element {
// https://dom.spec.whatwg.org/#dom-element-attributes // https://dom.spec.whatwg.org/#dom-element-attributes
fn Attributes(&self) -> Root<NamedNodeMap> { fn Attributes(&self) -> Root<NamedNodeMap> {
self.attr_list.or_init(|| { self.attr_list.or_init(|| NamedNodeMap::new(&window_from_node(self), self))
let doc = {
let node = self.upcast::<Node>();
node.owner_doc()
};
let window = doc.r().window();
NamedNodeMap::new(window, self)
})
} }
// https://dom.spec.whatwg.org/#dom-element-getattribute // https://dom.spec.whatwg.org/#dom-element-getattribute
@ -1277,27 +1256,26 @@ impl ElementMethods for Element {
// https://dom.spec.whatwg.org/#dom-element-getelementsbytagname // https://dom.spec.whatwg.org/#dom-element-getelementsbytagname
fn GetElementsByTagName(&self, localname: DOMString) -> Root<HTMLCollection> { fn GetElementsByTagName(&self, localname: DOMString) -> Root<HTMLCollection> {
let window = window_from_node(self); let window = window_from_node(self);
HTMLCollection::by_tag_name(window.r(), self.upcast::<Node>(), localname) HTMLCollection::by_tag_name(window.r(), self.upcast(), localname)
} }
// https://dom.spec.whatwg.org/#dom-element-getelementsbytagnamens // https://dom.spec.whatwg.org/#dom-element-getelementsbytagnamens
fn GetElementsByTagNameNS(&self, maybe_ns: Option<DOMString>, fn GetElementsByTagNameNS(&self, maybe_ns: Option<DOMString>,
localname: DOMString) -> Root<HTMLCollection> { localname: DOMString) -> Root<HTMLCollection> {
let window = window_from_node(self); let window = window_from_node(self);
HTMLCollection::by_tag_name_ns(window.r(), self.upcast::<Node>(), localname, maybe_ns) HTMLCollection::by_tag_name_ns(window.r(), self.upcast(), localname, maybe_ns)
} }
// https://dom.spec.whatwg.org/#dom-element-getelementsbyclassname // https://dom.spec.whatwg.org/#dom-element-getelementsbyclassname
fn GetElementsByClassName(&self, classes: DOMString) -> Root<HTMLCollection> { fn GetElementsByClassName(&self, classes: DOMString) -> Root<HTMLCollection> {
let window = window_from_node(self); let window = window_from_node(self);
HTMLCollection::by_class_name(window.r(), self.upcast::<Node>(), classes) HTMLCollection::by_class_name(window.r(), self.upcast(), classes)
} }
// https://drafts.csswg.org/cssom-view/#dom-element-getclientrects // https://drafts.csswg.org/cssom-view/#dom-element-getclientrects
fn GetClientRects(&self) -> Root<DOMRectList> { fn GetClientRects(&self) -> Root<DOMRectList> {
let win = window_from_node(self); let win = window_from_node(self);
let node = self.upcast::<Node>(); let raw_rects = self.upcast::<Node>().get_content_boxes();
let raw_rects = node.get_content_boxes();
let rects = raw_rects.iter().map(|rect| { let rects = raw_rects.iter().map(|rect| {
DOMRect::new(GlobalRef::Window(win.r()), DOMRect::new(GlobalRef::Window(win.r()),
rect.origin.x.to_f64_px(), rect.origin.x.to_f64_px(),
@ -1311,8 +1289,7 @@ impl ElementMethods for Element {
// https://drafts.csswg.org/cssom-view/#dom-element-getboundingclientrect // https://drafts.csswg.org/cssom-view/#dom-element-getboundingclientrect
fn GetBoundingClientRect(&self) -> Root<DOMRect> { fn GetBoundingClientRect(&self) -> Root<DOMRect> {
let win = window_from_node(self); let win = window_from_node(self);
let node = self.upcast::<Node>(); let rect = self.upcast::<Node>().get_bounding_content_box();
let rect = node.get_bounding_content_box();
DOMRect::new(GlobalRef::Window(win.r()), DOMRect::new(GlobalRef::Window(win.r()),
rect.origin.x.to_f64_px(), rect.origin.x.to_f64_px(),
rect.origin.y.to_f64_px(), rect.origin.y.to_f64_px(),
@ -1322,26 +1299,22 @@ impl ElementMethods for Element {
// https://drafts.csswg.org/cssom-view/#dom-element-clienttop // https://drafts.csswg.org/cssom-view/#dom-element-clienttop
fn ClientTop(&self) -> i32 { fn ClientTop(&self) -> i32 {
let node = self.upcast::<Node>(); self.upcast::<Node>().get_client_rect().origin.y
node.get_client_rect().origin.y
} }
// https://drafts.csswg.org/cssom-view/#dom-element-clientleft // https://drafts.csswg.org/cssom-view/#dom-element-clientleft
fn ClientLeft(&self) -> i32 { fn ClientLeft(&self) -> i32 {
let node = self.upcast::<Node>(); self.upcast::<Node>().get_client_rect().origin.x
node.get_client_rect().origin.x
} }
// https://drafts.csswg.org/cssom-view/#dom-element-clientwidth // https://drafts.csswg.org/cssom-view/#dom-element-clientwidth
fn ClientWidth(&self) -> i32 { fn ClientWidth(&self) -> i32 {
let node = self.upcast::<Node>(); self.upcast::<Node>().get_client_rect().size.width
node.get_client_rect().size.width
} }
// https://drafts.csswg.org/cssom-view/#dom-element-clientheight // https://drafts.csswg.org/cssom-view/#dom-element-clientheight
fn ClientHeight(&self) -> i32 { fn ClientHeight(&self) -> i32 {
let node = self.upcast::<Node>(); self.upcast::<Node>().get_client_rect().size.height
node.get_client_rect().size.height
} }
/// https://w3c.github.io/DOM-Parsing/#widl-Element-innerHTML /// https://w3c.github.io/DOM-Parsing/#widl-Element-innerHTML
@ -1358,11 +1331,11 @@ impl ElementMethods for Element {
// Step 2. // Step 2.
// https://github.com/w3c/DOM-Parsing/issues/1 // https://github.com/w3c/DOM-Parsing/issues/1
let target = if let Some(template) = self.downcast::<HTMLTemplateElement>() { let target = if let Some(template) = self.downcast::<HTMLTemplateElement>() {
Root::upcast::<Node>(template.Content()) Root::upcast(template.Content())
} else { } else {
Root::from_ref(context_node) Root::from_ref(context_node)
}; };
Node::replace_all(Some(frag.upcast::<Node>()), &target); Node::replace_all(Some(frag.upcast()), &target);
Ok(()) Ok(())
} }
@ -1393,7 +1366,7 @@ impl ElementMethods for Element {
let body_elem = Element::create(QualName::new(ns!(HTML), atom!(body)), let body_elem = Element::create(QualName::new(ns!(HTML), atom!(body)),
None, context_document.r(), None, context_document.r(),
ElementCreator::ScriptCreated); ElementCreator::ScriptCreated);
Root::upcast::<Node>(body_elem) Root::upcast(body_elem)
}, },
_ => context_node.GetParentNode().unwrap() _ => context_node.GetParentNode().unwrap()
}; };
@ -1401,27 +1374,24 @@ impl ElementMethods for Element {
// Step 5. // Step 5.
let frag = try!(parent.r().parse_fragment(value)); let frag = try!(parent.r().parse_fragment(value));
// Step 6. // Step 6.
try!(context_parent.r().ReplaceChild(frag.upcast::<Node>(), try!(context_parent.ReplaceChild(frag.upcast(), context_node));
context_node));
Ok(()) Ok(())
} }
// https://dom.spec.whatwg.org/#dom-nondocumenttypechildnode-previouselementsibling // https://dom.spec.whatwg.org/#dom-nondocumenttypechildnode-previouselementsibling
fn GetPreviousElementSibling(&self) -> Option<Root<Element>> { fn GetPreviousElementSibling(&self) -> Option<Root<Element>> {
self.upcast::<Node>().preceding_siblings() self.upcast::<Node>().preceding_siblings().filter_map(Root::downcast).next()
.filter_map(Root::downcast::<Element>).next()
} }
// https://dom.spec.whatwg.org/#dom-nondocumenttypechildnode-nextelementsibling // https://dom.spec.whatwg.org/#dom-nondocumenttypechildnode-nextelementsibling
fn GetNextElementSibling(&self) -> Option<Root<Element>> { fn GetNextElementSibling(&self) -> Option<Root<Element>> {
self.upcast::<Node>().following_siblings() self.upcast::<Node>().following_siblings().filter_map(Root::downcast).next()
.filter_map(Root::downcast::<Element>).next()
} }
// https://dom.spec.whatwg.org/#dom-parentnode-children // https://dom.spec.whatwg.org/#dom-parentnode-children
fn Children(&self) -> Root<HTMLCollection> { fn Children(&self) -> Root<HTMLCollection> {
let window = window_from_node(self); let window = window_from_node(self);
HTMLCollection::children(window.r(), self.upcast::<Node>()) HTMLCollection::children(window.r(), self.upcast())
} }
// https://dom.spec.whatwg.org/#dom-parentnode-firstelementchild // https://dom.spec.whatwg.org/#dom-parentnode-firstelementchild
@ -1478,8 +1448,7 @@ impl ElementMethods for Element {
// https://dom.spec.whatwg.org/#dom-childnode-remove // https://dom.spec.whatwg.org/#dom-childnode-remove
fn Remove(&self) { fn Remove(&self) {
let node = self.upcast::<Node>(); self.upcast::<Node>().remove_self();
node.remove_self();
} }
// https://dom.spec.whatwg.org/#dom-element-matches // https://dom.spec.whatwg.org/#dom-element-matches
@ -1513,8 +1482,7 @@ impl ElementMethods for Element {
impl VirtualMethods for Element { impl VirtualMethods for Element {
fn super_type(&self) -> Option<&VirtualMethods> { fn super_type(&self) -> Option<&VirtualMethods> {
let node: &Node = self.upcast::<Node>(); Some(self.upcast::<Node>() as &VirtualMethods)
Some(node as &VirtualMethods)
} }
fn attribute_mutated(&self, attr: &Attr, mutation: AttributeMutation) { fn attribute_mutated(&self, attr: &Attr, mutation: AttributeMutation) {
@ -1620,15 +1588,15 @@ impl<'a> ::selectors::Element for Root<Element> {
} }
fn last_child_element(&self) -> Option<Root<Element>> { fn last_child_element(&self) -> Option<Root<Element>> {
self.node.rev_children().filter_map(Root::downcast::<Element>).next() self.node.rev_children().filter_map(Root::downcast).next()
} }
fn prev_sibling_element(&self) -> Option<Root<Element>> { fn prev_sibling_element(&self) -> Option<Root<Element>> {
self.node.preceding_siblings().filter_map(Root::downcast::<Element>).next() self.node.preceding_siblings().filter_map(Root::downcast).next()
} }
fn next_sibling_element(&self) -> Option<Root<Element>> { fn next_sibling_element(&self) -> Option<Root<Element>> {
self.node.following_siblings().filter_map(Root::downcast::<Element>).next() self.node.following_siblings().filter_map(Root::downcast).next()
} }
fn is_root(&self) -> bool { fn is_root(&self) -> bool {
@ -1701,15 +1669,13 @@ impl<'a> ::selectors::Element for Root<Element> {
Element::get_enabled_state(self) Element::get_enabled_state(self)
} }
fn get_checked_state(&self) -> bool { fn get_checked_state(&self) -> bool {
let input_element: Option<&HTMLInputElement> = self.downcast::<HTMLInputElement>(); match self.downcast::<HTMLInputElement>() {
match input_element {
Some(input) => input.Checked(), Some(input) => input.Checked(),
None => false, None => false,
} }
} }
fn get_indeterminate_state(&self) -> bool { fn get_indeterminate_state(&self) -> bool {
let input_element: Option<&HTMLInputElement> = self.downcast::<HTMLInputElement>(); match self.downcast::<HTMLInputElement>() {
match input_element {
Some(input) => input.get_indeterminate_state(), Some(input) => input.get_indeterminate_state(),
None => false, None => false,
} }
@ -1729,8 +1695,7 @@ impl<'a> ::selectors::Element for Root<Element> {
} }
} }
fn has_servo_nonzero_border(&self) -> bool { fn has_servo_nonzero_border(&self) -> bool {
let table_element: Option<&HTMLTableElement> = self.downcast::<HTMLTableElement>(); match self.downcast::<HTMLTableElement>() {
match table_element {
None => false, None => false,
Some(this) => { Some(this) => {
match this.get_border() { match this.get_border() {
@ -1774,8 +1739,7 @@ impl<'a> ::selectors::Element for Root<Element> {
impl Element { impl Element {
pub fn as_maybe_activatable(&self) -> Option<&Activatable> { pub fn as_maybe_activatable(&self) -> Option<&Activatable> {
let node = self.upcast::<Node>(); let element = match self.upcast::<Node>().type_id() {
let element = match node.type_id() {
NodeTypeId::Element(ElementTypeId::HTMLElement(HTMLElementTypeId::HTMLInputElement)) => { NodeTypeId::Element(ElementTypeId::HTMLElement(HTMLElementTypeId::HTMLInputElement)) => {
let element = self.downcast::<HTMLInputElement>().unwrap(); let element = self.downcast::<HTMLInputElement>().unwrap();
Some(element as &Activatable) Some(element as &Activatable)
@ -1798,13 +1762,11 @@ impl Element {
} }
pub fn click_in_progress(&self) -> bool { pub fn click_in_progress(&self) -> bool {
let node = self.upcast::<Node>(); self.upcast::<Node>().get_flag(CLICK_IN_PROGRESS)
node.get_flag(CLICK_IN_PROGRESS)
} }
pub fn set_click_in_progress(&self, click: bool) { pub fn set_click_in_progress(&self, click: bool) {
let node = self.upcast::<Node>(); self.upcast::<Node>().set_flag(CLICK_IN_PROGRESS, click)
node.set_flag(CLICK_IN_PROGRESS, click)
} }
// https://html.spec.whatwg.org/multipage/#nearest-activatable-element // https://html.spec.whatwg.org/multipage/#nearest-activatable-element
@ -1838,7 +1800,7 @@ impl Element {
// the script can generate more click events from the handler) // the script can generate more click events from the handler)
assert!(!self.click_in_progress()); assert!(!self.click_in_progress());
let target = self.upcast::<EventTarget>(); let target = self.upcast();
// Step 2 (requires canvas support) // Step 2 (requires canvas support)
// Step 3 // Step 3
self.set_click_in_progress(true); self.set_click_in_progress(true);

View file

@ -150,8 +150,7 @@ pub fn dispatch_event(target: &EventTarget, pseudo_target: Option<&EventTarget>,
let mut chain: RootedVec<JS<EventTarget>> = RootedVec::new(); let mut chain: RootedVec<JS<EventTarget>> = RootedVec::new();
if let Some(target_node) = target.downcast::<Node>() { if let Some(target_node) = target.downcast::<Node>() {
for ancestor in target_node.ancestors() { for ancestor in target_node.ancestors() {
let ancestor_target = ancestor.upcast::<EventTarget>(); chain.push(JS::from_ref(ancestor.upcast()));
chain.push(JS::from_ref(ancestor_target))
} }
} }
@ -161,13 +160,9 @@ pub fn dispatch_event(target: &EventTarget, pseudo_target: Option<&EventTarget>,
let target = event.GetTarget(); let target = event.GetTarget();
match target { match target {
Some(ref target) => { Some(ref target) => {
let node: Option<&Node> = target.downcast::<Node>(); if let Some(node) = target.downcast::<Node>() {
match node { let vtable = vtable_for(&node);
Some(node) => { vtable.handle_event(event);
let vtable = vtable_for(&node);
vtable.handle_event(event);
}
None => {}
} }
} }
None => {} None => {}

View file

@ -324,10 +324,7 @@ impl FileReader {
let progressevent = ProgressEvent::new(global.r(), let progressevent = ProgressEvent::new(global.r(),
type_, EventBubbles::DoesNotBubble, EventCancelable::NotCancelable, type_, EventBubbles::DoesNotBubble, EventCancelable::NotCancelable,
total.is_some(), loaded, total.unwrap_or(0)); total.is_some(), loaded, total.unwrap_or(0));
progressevent.upcast::<Event>().fire(self.upcast());
let target = self.upcast::<EventTarget>();
let event = progressevent.upcast::<Event>();
event.fire(target);
} }
fn terminate_ongoing_reading(&self) { fn terminate_ongoing_reading(&self) {

View file

@ -116,7 +116,7 @@ impl FormDataMethods for FormData {
impl FormData { impl FormData {
fn get_file_from_blob(&self, value: &Blob, filename: Option<DOMString>) -> Root<File> { fn get_file_from_blob(&self, value: &Blob, filename: Option<DOMString>) -> Root<File> {
let global = self.global.root(); let global = self.global.root();
let f: Option<&File> = value.downcast::<File>(); let f = value.downcast::<File>();
let name = filename.unwrap_or(f.map(|inner| inner.name().clone()).unwrap_or("blob".to_owned())); let name = filename.unwrap_or(f.map(|inner| inner.name().clone()).unwrap_or("blob".to_owned()));
File::new(global.r(), value, name) File::new(global.r(), value, name)
} }

View file

@ -56,8 +56,7 @@ impl HTMLAnchorElement {
impl VirtualMethods for HTMLAnchorElement { impl VirtualMethods for HTMLAnchorElement {
fn super_type(&self) -> Option<&VirtualMethods> { fn super_type(&self) -> Option<&VirtualMethods> {
let htmlelement: &HTMLElement = self.upcast::<HTMLElement>(); Some(self.upcast::<HTMLElement>() as &VirtualMethods)
Some(htmlelement as &VirtualMethods)
} }
fn parse_plain_attribute(&self, name: &Atom, value: DOMString) -> AttrValue { fn parse_plain_attribute(&self, name: &Atom, value: DOMString) -> AttrValue {
@ -71,20 +70,18 @@ impl VirtualMethods for HTMLAnchorElement {
impl HTMLAnchorElementMethods for HTMLAnchorElement { impl HTMLAnchorElementMethods for HTMLAnchorElement {
// https://html.spec.whatwg.org/multipage/#dom-a-text // https://html.spec.whatwg.org/multipage/#dom-a-text
fn Text(&self) -> DOMString { fn Text(&self) -> DOMString {
let node = self.upcast::<Node>(); self.upcast::<Node>().GetTextContent().unwrap()
node.GetTextContent().unwrap()
} }
// https://html.spec.whatwg.org/multipage/#dom-a-text // https://html.spec.whatwg.org/multipage/#dom-a-text
fn SetText(&self, value: DOMString) { fn SetText(&self, value: DOMString) {
let node = self.upcast::<Node>(); self.upcast::<Node>().SetTextContent(Some(value))
node.SetTextContent(Some(value))
} }
// https://html.spec.whatwg.org/multipage/#dom-a-rellist // https://html.spec.whatwg.org/multipage/#dom-a-rellist
fn RelList(&self) -> Root<DOMTokenList> { fn RelList(&self) -> Root<DOMTokenList> {
self.rel_list.or_init(|| { self.rel_list.or_init(|| {
DOMTokenList::new(self.upcast::<Element>(), &atom!("rel")) DOMTokenList::new(self.upcast(), &atom!("rel"))
}) })
} }

View file

@ -10,7 +10,6 @@ use dom::bindings::js::{JS, MutNullableHeap, Root};
use dom::bindings::utils::Reflectable; use dom::bindings::utils::Reflectable;
use dom::document::Document; use dom::document::Document;
use dom::domtokenlist::DOMTokenList; use dom::domtokenlist::DOMTokenList;
use dom::element::Element;
use dom::htmlelement::HTMLElement; use dom::htmlelement::HTMLElement;
use dom::node::Node; use dom::node::Node;
use dom::virtualmethods::VirtualMethods; use dom::virtualmethods::VirtualMethods;
@ -43,8 +42,7 @@ impl HTMLAreaElement {
impl VirtualMethods for HTMLAreaElement { impl VirtualMethods for HTMLAreaElement {
fn super_type(&self) -> Option<&VirtualMethods> { fn super_type(&self) -> Option<&VirtualMethods> {
let htmlelement: &HTMLElement = self.upcast::<HTMLElement>(); Some(self.upcast::<HTMLElement>() as &VirtualMethods)
Some(htmlelement as &VirtualMethods)
} }
fn parse_plain_attribute(&self, name: &Atom, value: DOMString) -> AttrValue { fn parse_plain_attribute(&self, name: &Atom, value: DOMString) -> AttrValue {
@ -59,7 +57,7 @@ impl HTMLAreaElementMethods for HTMLAreaElement {
// https://html.spec.whatwg.org/multipage/#dom-area-rellist // https://html.spec.whatwg.org/multipage/#dom-area-rellist
fn RelList(&self) -> Root<DOMTokenList> { fn RelList(&self) -> Root<DOMTokenList> {
self.rel_list.or_init(|| { self.rel_list.or_init(|| {
DOMTokenList::new(self.upcast::<Element>(), &atom!("rel")) DOMTokenList::new(self.upcast(), &atom!("rel"))
}) })
} }
} }

View file

@ -124,8 +124,7 @@ impl HTMLBodyElement {
impl VirtualMethods for HTMLBodyElement { impl VirtualMethods for HTMLBodyElement {
fn super_type(&self) -> Option<&VirtualMethods> { fn super_type(&self) -> Option<&VirtualMethods> {
let element: &HTMLElement = self.upcast::<HTMLElement>(); Some(self.upcast::<HTMLElement>() as &VirtualMethods)
Some(element as &VirtualMethods)
} }
fn bind_to_tree(&self, tree_in_doc: bool) { fn bind_to_tree(&self, tree_in_doc: bool) {

View file

@ -82,8 +82,7 @@ impl HTMLButtonElementMethods for HTMLButtonElement {
// https://html.spec.whatwg.org/multipage/#dom-button-type // https://html.spec.whatwg.org/multipage/#dom-button-type
fn Type(&self) -> DOMString { fn Type(&self) -> DOMString {
let elem = self.upcast::<Element>(); let mut ty = self.upcast::<Element>().get_string_attribute(&atom!("type"));
let mut ty = elem.get_string_attribute(&atom!("type"));
ty.make_ascii_lowercase(); ty.make_ascii_lowercase();
// https://html.spec.whatwg.org/multipage/#attr-button-type // https://html.spec.whatwg.org/multipage/#attr-button-type
match &*ty { match &*ty {
@ -135,8 +134,7 @@ impl HTMLButtonElementMethods for HTMLButtonElement {
impl VirtualMethods for HTMLButtonElement { impl VirtualMethods for HTMLButtonElement {
fn super_type(&self) -> Option<&VirtualMethods> { fn super_type(&self) -> Option<&VirtualMethods> {
let htmlelement: &HTMLElement = self.upcast::<HTMLElement>(); Some(self.upcast::<HTMLElement>() as &VirtualMethods)
Some(htmlelement as &VirtualMethods)
} }
fn attribute_mutated(&self, attr: &Attr, mutation: AttributeMutation) { fn attribute_mutated(&self, attr: &Attr, mutation: AttributeMutation) {
@ -166,8 +164,7 @@ impl VirtualMethods for HTMLButtonElement {
s.bind_to_tree(tree_in_doc); s.bind_to_tree(tree_in_doc);
} }
let el = self.upcast::<Element>(); self.upcast::<Element>().check_ancestors_disabled_state_for_form_control();
el.check_ancestors_disabled_state_for_form_control();
} }
fn unbind_from_tree(&self, tree_in_doc: bool) { fn unbind_from_tree(&self, tree_in_doc: bool) {
@ -189,13 +186,12 @@ impl FormControl for HTMLButtonElement {}
impl<'a> Activatable for &'a HTMLButtonElement { impl<'a> Activatable for &'a HTMLButtonElement {
fn as_element(&self) -> &Element { fn as_element(&self) -> &Element {
self.upcast::<Element>() self.upcast()
} }
fn is_instance_activatable(&self) -> bool { fn is_instance_activatable(&self) -> bool {
//https://html.spec.whatwg.org/multipage/#the-button-element //https://html.spec.whatwg.org/multipage/#the-button-element
let el = self.upcast::<Element>(); !self.upcast::<Element>().get_disabled_state()
!(el.get_disabled_state())
} }
// https://html.spec.whatwg.org/multipage/#run-pre-click-activation-steps // https://html.spec.whatwg.org/multipage/#run-pre-click-activation-steps
@ -228,8 +224,7 @@ impl<'a> Activatable for &'a HTMLButtonElement {
let doc = document_from_node(*self); let doc = document_from_node(*self);
let node = doc.upcast::<Node>(); let node = doc.upcast::<Node>();
let owner = self.form_owner(); let owner = self.form_owner();
let elem = self.upcast::<Element>(); if owner.is_none() || self.upcast::<Element>().click_in_progress() {
if owner.is_none() || elem.click_in_progress() {
return; return;
} }
node.query_selector_iter("button[type=submit]".to_owned()).unwrap() node.query_selector_iter("button[type=submit]".to_owned()).unwrap()

View file

@ -225,8 +225,7 @@ impl HTMLCanvasElementMethods for HTMLCanvasElement {
// https://html.spec.whatwg.org/multipage/#dom-canvas-width // https://html.spec.whatwg.org/multipage/#dom-canvas-width
fn SetWidth(&self, width: u32) { fn SetWidth(&self, width: u32) {
let elem = self.upcast::<Element>(); self.upcast::<Element>().set_uint_attribute(&atom!("width"), width)
elem.set_uint_attribute(&atom!("width"), width)
} }
// https://html.spec.whatwg.org/multipage/#dom-canvas-height // https://html.spec.whatwg.org/multipage/#dom-canvas-height
@ -236,8 +235,7 @@ impl HTMLCanvasElementMethods for HTMLCanvasElement {
// https://html.spec.whatwg.org/multipage/#dom-canvas-height // https://html.spec.whatwg.org/multipage/#dom-canvas-height
fn SetHeight(&self, height: u32) { fn SetHeight(&self, height: u32) {
let elem = self.upcast::<Element>(); self.upcast::<Element>().set_uint_attribute(&atom!("height"), height)
elem.set_uint_attribute(&atom!("height"), height)
} }
// https://html.spec.whatwg.org/multipage/#dom-canvas-getcontext // https://html.spec.whatwg.org/multipage/#dom-canvas-getcontext
@ -264,8 +262,7 @@ impl HTMLCanvasElementMethods for HTMLCanvasElement {
impl VirtualMethods for HTMLCanvasElement { impl VirtualMethods for HTMLCanvasElement {
fn super_type(&self) -> Option<&VirtualMethods> { fn super_type(&self) -> Option<&VirtualMethods> {
let element: &HTMLElement = self.upcast::<HTMLElement>(); Some(self.upcast::<HTMLElement>() as &VirtualMethods)
Some(element as &VirtualMethods)
} }
fn attribute_mutated(&self, attr: &Attr, mutation: AttributeMutation) { fn attribute_mutated(&self, attr: &Attr, mutation: AttributeMutation) {

View file

@ -154,7 +154,7 @@ impl HTMLCollection {
struct ElementChildFilter; struct ElementChildFilter;
impl CollectionFilter for ElementChildFilter { impl CollectionFilter for ElementChildFilter {
fn filter(&self, elem: &Element, root: &Node) -> bool { fn filter(&self, elem: &Element, root: &Node) -> bool {
root.is_parent_of(elem.upcast::<Node>()) root.is_parent_of(elem.upcast())
} }
} }
HTMLCollection::create(window, root, box ElementChildFilter) HTMLCollection::create(window, root, box ElementChildFilter)
@ -186,8 +186,8 @@ impl<'a> Iterator for HTMLCollectionElementsIter<'a> {
let filter = self.filter; let filter = self.filter;
let root = self.root.r(); let root = self.root.r();
self.node_iter.by_ref() self.node_iter.by_ref()
.filter_map(Root::downcast::<Element>) .filter_map(Root::downcast)
.filter(|element| filter.filter(element.r(), root)) .filter(|element| filter.filter(&element, root))
.next() .next()
} }
} }

View file

@ -48,9 +48,8 @@ impl HTMLDataListElementMethods for HTMLDataListElement {
elem.is::<HTMLOptionElement>() elem.is::<HTMLOptionElement>()
} }
} }
let node = self.upcast::<Node>();
let filter = box HTMLDataListOptionsFilter; let filter = box HTMLDataListOptionsFilter;
let window = window_from_node(node); let window = window_from_node(self);
HTMLCollection::create(window.r(), node, filter) HTMLCollection::create(window.r(), self.upcast(), filter)
} }
} }

View file

@ -162,41 +162,37 @@ impl HTMLElementMethods for HTMLElement {
let win = window_from_node(self); let win = window_from_node(self);
win.r().SetOnload(listener) win.r().SetOnload(listener)
} else { } else {
let target = self.upcast::<EventTarget>(); self.upcast::<EventTarget>().set_event_handler_common("load", listener)
target.set_event_handler_common("load", listener)
} }
} }
// https://html.spec.whatwg.org/multipage/#dom-click // https://html.spec.whatwg.org/multipage/#dom-click
fn Click(&self) { fn Click(&self) {
let maybe_input: Option<&HTMLInputElement> = self.downcast::<HTMLInputElement>(); if let Some(i) = self.downcast::<HTMLInputElement>() {
if let Some(i) = maybe_input {
if i.Disabled() { if i.Disabled() {
return; return;
} }
} }
let element = self.upcast::<Element>();
// https://www.w3.org/Bugs/Public/show_bug.cgi?id=27430 ? // https://www.w3.org/Bugs/Public/show_bug.cgi?id=27430 ?
element.as_maybe_activatable().map(|a| a.synthetic_click_activation(false, false, false, false)); self.upcast::<Element>()
.as_maybe_activatable()
.map(|a| a.synthetic_click_activation(false, false, false, false));
} }
// https://html.spec.whatwg.org/multipage/#dom-focus // https://html.spec.whatwg.org/multipage/#dom-focus
fn Focus(&self) { fn Focus(&self) {
// TODO: Mark the element as locked for focus and run the focusing steps. // TODO: Mark the element as locked for focus and run the focusing steps.
// https://html.spec.whatwg.org/multipage/#focusing-steps // https://html.spec.whatwg.org/multipage/#focusing-steps
let element = self.upcast::<Element>();
let document = document_from_node(self); let document = document_from_node(self);
let document = document.r();
document.begin_focus_transaction(); document.begin_focus_transaction();
document.request_focus(element); document.request_focus(self.upcast());
document.commit_focus_transaction(FocusType::Element); document.commit_focus_transaction(FocusType::Element);
} }
// https://html.spec.whatwg.org/multipage/#dom-blur // https://html.spec.whatwg.org/multipage/#dom-blur
fn Blur(&self) { fn Blur(&self) {
// TODO: Run the unfocusing steps. // TODO: Run the unfocusing steps.
let el = self.upcast::<Element>(); if !self.upcast::<Element>().get_focus_state() {
if !el.get_focus_state() {
return; return;
} }
// https://html.spec.whatwg.org/multipage/#unfocusing-steps // https://html.spec.whatwg.org/multipage/#unfocusing-steps
@ -286,29 +282,25 @@ impl HTMLElement {
.nth(1).map_or(false, |ch| ch >= 'a' && ch <= 'z') { .nth(1).map_or(false, |ch| ch >= 'a' && ch <= 'z') {
return Err(Error::Syntax); return Err(Error::Syntax);
} }
let element = self.upcast::<Element>(); self.upcast::<Element>().set_custom_attribute(to_snake_case(name), value)
element.set_custom_attribute(to_snake_case(name), value)
} }
pub fn get_custom_attr(&self, local_name: DOMString) -> Option<DOMString> { pub fn get_custom_attr(&self, local_name: DOMString) -> Option<DOMString> {
let element = self.upcast::<Element>();
let local_name = Atom::from_slice(&to_snake_case(local_name)); let local_name = Atom::from_slice(&to_snake_case(local_name));
element.get_attribute(&ns!(""), &local_name).map(|attr| { self.upcast::<Element>().get_attribute(&ns!(""), &local_name).map(|attr| {
(**attr.r().value()).to_owned() (**attr.r().value()).to_owned()
}) })
} }
pub fn delete_custom_attr(&self, local_name: DOMString) { pub fn delete_custom_attr(&self, local_name: DOMString) {
let element = self.upcast::<Element>();
let local_name = Atom::from_slice(&to_snake_case(local_name)); let local_name = Atom::from_slice(&to_snake_case(local_name));
element.remove_attribute(&ns!(""), &local_name); self.upcast::<Element>().remove_attribute(&ns!(""), &local_name);
} }
} }
impl VirtualMethods for HTMLElement { impl VirtualMethods for HTMLElement {
fn super_type(&self) -> Option<&VirtualMethods> { fn super_type(&self) -> Option<&VirtualMethods> {
let element: &Element = self.upcast::<Element>(); Some(self.upcast::<Element>() as &VirtualMethods)
Some(element as &VirtualMethods)
} }
fn attribute_mutated(&self, attr: &Attr, mutation: AttributeMutation) { fn attribute_mutated(&self, attr: &Attr, mutation: AttributeMutation) {

View file

@ -56,10 +56,9 @@ impl HTMLFieldSetElementMethods for HTMLFieldSetElement {
TAG_NAMES.iter().any(|&tag_name| tag_name == &**elem.local_name()) TAG_NAMES.iter().any(|&tag_name| tag_name == &**elem.local_name())
} }
} }
let node = self.upcast::<Node>();
let filter = box ElementsFilter; let filter = box ElementsFilter;
let window = window_from_node(node); let window = window_from_node(self);
HTMLCollection::create(window.r(), node, filter) HTMLCollection::create(window.r(), self.upcast(), filter)
} }
// https://html.spec.whatwg.org/multipage/#dom-cva-validity // https://html.spec.whatwg.org/multipage/#dom-cva-validity
@ -82,8 +81,7 @@ impl HTMLFieldSetElementMethods for HTMLFieldSetElement {
impl VirtualMethods for HTMLFieldSetElement { impl VirtualMethods for HTMLFieldSetElement {
fn super_type(&self) -> Option<&VirtualMethods> { fn super_type(&self) -> Option<&VirtualMethods> {
let htmlelement: &HTMLElement = self.upcast::<HTMLElement>(); Some(self.upcast::<HTMLElement>() as &VirtualMethods)
Some(htmlelement as &VirtualMethods)
} }
fn attribute_mutated(&self, attr: &Attr, mutation: AttributeMutation) { fn attribute_mutated(&self, attr: &Attr, mutation: AttributeMutation) {

View file

@ -71,8 +71,7 @@ impl HTMLFontElementMethods for HTMLFontElement {
impl VirtualMethods for HTMLFontElement { impl VirtualMethods for HTMLFontElement {
fn super_type(&self) -> Option<&VirtualMethods> { fn super_type(&self) -> Option<&VirtualMethods> {
let htmlelement = self.upcast::<HTMLElement>(); Some(self.upcast::<HTMLElement>() as &VirtualMethods)
Some(htmlelement as &VirtualMethods)
} }
fn attribute_mutated(&self, attr: &Attr, mutation: AttributeMutation) { fn attribute_mutated(&self, attr: &Attr, mutation: AttributeMutation) {

View file

@ -17,7 +17,6 @@ use dom::bindings::utils::Reflectable;
use dom::document::Document; use dom::document::Document;
use dom::element::Element; use dom::element::Element;
use dom::event::{Event, EventBubbles, EventCancelable}; use dom::event::{Event, EventBubbles, EventCancelable};
use dom::eventtarget::EventTarget;
use dom::htmlbuttonelement::{HTMLButtonElement}; use dom::htmlbuttonelement::{HTMLButtonElement};
use dom::htmldatalistelement::HTMLDataListElement; use dom::htmldatalistelement::HTMLDataListElement;
use dom::htmlelement::HTMLElement; use dom::htmlelement::HTMLElement;
@ -163,8 +162,7 @@ impl HTMLFormElement {
"submit".to_owned(), "submit".to_owned(),
EventBubbles::Bubbles, EventBubbles::Bubbles,
EventCancelable::Cancelable); EventCancelable::Cancelable);
let target = self.upcast::<EventTarget>(); event.fire(self.upcast());
event.r().fire(target);
if event.r().DefaultPrevented() { if event.r().DefaultPrevented() {
return; return;
} }
@ -316,21 +314,17 @@ impl HTMLFormElement {
"reset".to_owned(), "reset".to_owned(),
EventBubbles::Bubbles, EventBubbles::Bubbles,
EventCancelable::Cancelable); EventCancelable::Cancelable);
let target = self.upcast::<EventTarget>(); event.fire(self.upcast());
event.r().fire(target);
if event.r().DefaultPrevented() { if event.r().DefaultPrevented() {
return; return;
} }
let node = self.upcast::<Node>();
// TODO: This is an incorrect way of getting controls owned // TODO: This is an incorrect way of getting controls owned
// by the form, but good enough until html5ever lands // by the form, but good enough until html5ever lands
for child in node.traverse_preorder() { for child in self.upcast::<Node>().traverse_preorder() {
match child.r().type_id() { match child.r().type_id() {
NodeTypeId::Element(ElementTypeId::HTMLElement(HTMLElementTypeId::HTMLInputElement)) => { NodeTypeId::Element(ElementTypeId::HTMLElement(HTMLElementTypeId::HTMLInputElement)) => {
let input = child.downcast::<HTMLInputElement>().unwrap(); child.downcast::<HTMLInputElement>().unwrap().reset();
input.reset()
} }
// TODO HTMLKeygenElement unimplemented // TODO HTMLKeygenElement unimplemented
//NodeTypeId::Element(ElementTypeId::HTMLElement(HTMLElementTypeId::HTMLKeygenElement)) => { //NodeTypeId::Element(ElementTypeId::HTMLElement(HTMLElementTypeId::HTMLKeygenElement)) => {
@ -342,8 +336,7 @@ impl HTMLFormElement {
{} {}
} }
NodeTypeId::Element(ElementTypeId::HTMLElement(HTMLElementTypeId::HTMLTextAreaElement)) => { NodeTypeId::Element(ElementTypeId::HTMLElement(HTMLElementTypeId::HTMLTextAreaElement)) => {
let textarea = child.downcast::<HTMLTextAreaElement>().unwrap(); child.downcast::<HTMLTextAreaElement>().unwrap().reset();
textarea.reset()
} }
NodeTypeId::Element(ElementTypeId::HTMLElement(HTMLElementTypeId::HTMLOutputElement)) => { NodeTypeId::Element(ElementTypeId::HTMLElement(HTMLElementTypeId::HTMLOutputElement)) => {
// Unimplemented // Unimplemented
@ -484,13 +477,7 @@ pub trait FormControl: DerivedFrom<Element> + Reflectable {
_ => () _ => ()
} }
} }
let node = elem.upcast::<Node>(); elem.upcast::<Node>().ancestors().filter_map(Root::downcast).next()
for ancestor in node.ancestors() {
if let Some(ancestor) = ancestor.downcast::<HTMLFormElement>() {
return Some(Root::from_ref(ancestor))
}
}
None
} }
fn get_form_attribute<InputFn, OwnerFn>(&self, fn get_form_attribute<InputFn, OwnerFn>(&self,
@ -509,7 +496,7 @@ pub trait FormControl: DerivedFrom<Element> + Reflectable {
} }
fn to_element(&self) -> &Element { fn to_element(&self) -> &Element {
self.upcast::<Element>() self.upcast()
} }
} }

View file

@ -37,8 +37,7 @@ impl HTMLHeadElement {
impl VirtualMethods for HTMLHeadElement { impl VirtualMethods for HTMLHeadElement {
fn super_type(&self) -> Option<&VirtualMethods> { fn super_type(&self) -> Option<&VirtualMethods> {
let htmlelement: &HTMLElement = self.upcast::<HTMLElement>(); Some(self.upcast::<HTMLElement>() as &VirtualMethods)
Some(htmlelement as &VirtualMethods)
} }
fn bind_to_tree(&self, _tree_in_doc: bool) { fn bind_to_tree(&self, _tree_in_doc: bool) {
load_script(self); load_script(self);

View file

@ -15,7 +15,6 @@ use dom::customevent::CustomEvent;
use dom::document::Document; use dom::document::Document;
use dom::element::{self, AttributeMutation, Element}; use dom::element::{self, AttributeMutation, Element};
use dom::event::Event; use dom::event::Event;
use dom::eventtarget::EventTarget;
use dom::htmlelement::HTMLElement; use dom::htmlelement::HTMLElement;
use dom::node::{Node, window_from_node}; use dom::node::{Node, window_from_node};
use dom::urlhelper::UrlHelper; use dom::urlhelper::UrlHelper;
@ -148,9 +147,7 @@ impl HTMLIFrameElement {
true, true,
true, true,
detail.handle()); detail.handle());
let target = self.upcast::<EventTarget>(); custom_event.upcast::<Event>().fire(self.upcast());
let event = custom_event.upcast::<Event>();
event.fire(target);
} }
} }
@ -161,7 +158,7 @@ impl HTMLIFrameElement {
#[allow(unsafe_code)] #[allow(unsafe_code)]
pub fn get_width(&self) -> LengthOrPercentageOrAuto { pub fn get_width(&self) -> LengthOrPercentageOrAuto {
unsafe { unsafe {
element::get_attr_for_layout(self.upcast::<Element>(), element::get_attr_for_layout(self.upcast(),
&ns!(""), &ns!(""),
&atom!("width")).map(|attribute| { &atom!("width")).map(|attribute| {
str::parse_length(&**attribute.value_for_layout()) str::parse_length(&**attribute.value_for_layout())
@ -172,7 +169,7 @@ impl HTMLIFrameElement {
#[allow(unsafe_code)] #[allow(unsafe_code)]
pub fn get_height(&self) -> LengthOrPercentageOrAuto { pub fn get_height(&self) -> LengthOrPercentageOrAuto {
unsafe { unsafe {
element::get_attr_for_layout(self.upcast::<Element>(), element::get_attr_for_layout(self.upcast(),
&ns!(""), &ns!(""),
&atom!("height")).map(|attribute| { &atom!("height")).map(|attribute| {
str::parse_length(&**attribute.value_for_layout()) str::parse_length(&**attribute.value_for_layout())
@ -227,8 +224,7 @@ impl HTMLIFrameElementLayoutMethods for LayoutJS<HTMLIFrameElement> {
pub fn Navigate(iframe: &HTMLIFrameElement, direction: NavigationDirection) -> Fallible<()> { pub fn Navigate(iframe: &HTMLIFrameElement, direction: NavigationDirection) -> Fallible<()> {
if iframe.Mozbrowser() { if iframe.Mozbrowser() {
let node = iframe.upcast::<Node>(); if iframe.upcast::<Node>().is_in_doc() {
if node.is_in_doc() {
let window = window_from_node(iframe); let window = window_from_node(iframe);
let window = window.r(); let window = window.r();
@ -249,26 +245,22 @@ pub fn Navigate(iframe: &HTMLIFrameElement, direction: NavigationDirection) -> F
impl HTMLIFrameElementMethods for HTMLIFrameElement { impl HTMLIFrameElementMethods for HTMLIFrameElement {
// https://html.spec.whatwg.org/multipage/#dom-iframe-src // https://html.spec.whatwg.org/multipage/#dom-iframe-src
fn Src(&self) -> DOMString { fn Src(&self) -> DOMString {
let element = self.upcast::<Element>(); self.upcast::<Element>().get_string_attribute(&atom!("src"))
element.get_string_attribute(&atom!("src"))
} }
// https://html.spec.whatwg.org/multipage/#dom-iframe-src // https://html.spec.whatwg.org/multipage/#dom-iframe-src
fn SetSrc(&self, src: DOMString) { fn SetSrc(&self, src: DOMString) {
let element = self.upcast::<Element>(); self.upcast::<Element>().set_url_attribute(&atom!("src"), src)
element.set_url_attribute(&atom!("src"), src)
} }
// https://html.spec.whatwg.org/multipage/#dom-iframe-sandbox // https://html.spec.whatwg.org/multipage/#dom-iframe-sandbox
fn Sandbox(&self) -> DOMString { fn Sandbox(&self) -> DOMString {
let element = self.upcast::<Element>(); self.upcast::<Element>().get_string_attribute(&atom!("sandbox"))
element.get_string_attribute(&atom!("sandbox"))
} }
// https://html.spec.whatwg.org/multipage/#dom-iframe-sandbox // https://html.spec.whatwg.org/multipage/#dom-iframe-sandbox
fn SetSandbox(&self, sandbox: DOMString) { fn SetSandbox(&self, sandbox: DOMString) {
let element = self.upcast::<Element>(); self.upcast::<Element>().set_tokenlist_attribute(&atom!("sandbox"), sandbox);
element.set_tokenlist_attribute(&atom!("sandbox"), sandbox);
} }
// https://html.spec.whatwg.org/multipage/#dom-iframe-contentwindow // https://html.spec.whatwg.org/multipage/#dom-iframe-contentwindow
@ -360,8 +352,7 @@ impl HTMLIFrameElementMethods for HTMLIFrameElement {
impl VirtualMethods for HTMLIFrameElement { impl VirtualMethods for HTMLIFrameElement {
fn super_type(&self) -> Option<&VirtualMethods> { fn super_type(&self) -> Option<&VirtualMethods> {
let htmlelement: &HTMLElement = self.upcast::<HTMLElement>(); Some(self.upcast::<HTMLElement>() as &VirtualMethods)
Some(htmlelement as &VirtualMethods)
} }
fn attribute_mutated(&self, attr: &Attr, mutation: AttributeMutation) { fn attribute_mutated(&self, attr: &Attr, mutation: AttributeMutation) {

View file

@ -16,7 +16,6 @@ use dom::bindings::refcounted::Trusted;
use dom::document::Document; use dom::document::Document;
use dom::element::{AttributeMutation, Element}; use dom::element::{AttributeMutation, Element};
use dom::event::{Event, EventBubbles, EventCancelable}; use dom::event::{Event, EventBubbles, EventCancelable};
use dom::eventtarget::EventTarget;
use dom::htmlelement::HTMLElement; use dom::htmlelement::HTMLElement;
use dom::node::{Node, NodeDamage, document_from_node, window_from_node}; use dom::node::{Node, NodeDamage, document_from_node, window_from_node};
use dom::virtualmethods::VirtualMethods; use dom::virtualmethods::VirtualMethods;
@ -74,9 +73,8 @@ impl Runnable for ImageResponseHandlerRunnable {
}; };
// Mark the node dirty // Mark the node dirty
let node = element.upcast::<Node>(); let document = document_from_node(&*element);
let document = document_from_node(node); document.content_changed(element.upcast(), NodeDamage::OtherNodeDamage);
document.r().content_changed(node, NodeDamage::OtherNodeDamage);
// Fire image.onload // Fire image.onload
let window = window_from_node(document.r()); let window = window_from_node(document.r());
@ -84,9 +82,7 @@ impl Runnable for ImageResponseHandlerRunnable {
"load".to_owned(), "load".to_owned(),
EventBubbles::DoesNotBubble, EventBubbles::DoesNotBubble,
EventCancelable::NotCancelable); EventCancelable::NotCancelable);
let event = event.r(); event.fire(element.upcast());
let target = node.upcast::<EventTarget>();
event.fire(target);
// Trigger reflow // Trigger reflow
window.r().add_pending_reflow(); window.r().add_pending_reflow();
@ -97,8 +93,7 @@ impl HTMLImageElement {
/// Makes the local `image` member match the status of the `src` attribute and starts /// Makes the local `image` member match the status of the `src` attribute and starts
/// prefetching the image. This method must be called after `src` is changed. /// prefetching the image. This method must be called after `src` is changed.
fn update_image(&self, value: Option<(DOMString, Url)>) { fn update_image(&self, value: Option<(DOMString, Url)>) {
let node = self.upcast::<Node>(); let document = document_from_node(self);
let document = node.owner_doc();
let window = document.r().window(); let window = document.r().window();
let image_cache = window.image_cache_task(); let image_cache = window.image_cache_task();
match value { match value {
@ -204,8 +199,7 @@ impl HTMLImageElementMethods for HTMLImageElement {
// https://html.spec.whatwg.org/multipage/#dom-img-ismap // https://html.spec.whatwg.org/multipage/#dom-img-ismap
fn SetIsMap(&self, is_map: bool) { fn SetIsMap(&self, is_map: bool) {
let element = self.upcast::<Element>(); self.upcast::<Element>().set_string_attribute(&atom!("ismap"), is_map.to_string())
element.set_string_attribute(&atom!("ismap"), is_map.to_string())
} }
// https://html.spec.whatwg.org/multipage/#dom-img-width // https://html.spec.whatwg.org/multipage/#dom-img-width
@ -217,8 +211,7 @@ impl HTMLImageElementMethods for HTMLImageElement {
// https://html.spec.whatwg.org/multipage/#dom-img-width // https://html.spec.whatwg.org/multipage/#dom-img-width
fn SetWidth(&self, width: u32) { fn SetWidth(&self, width: u32) {
let elem = self.upcast::<Element>(); self.upcast::<Element>().set_uint_attribute(&atom!("width"), width)
elem.set_uint_attribute(&atom!("width"), width)
} }
// https://html.spec.whatwg.org/multipage/#dom-img-height // https://html.spec.whatwg.org/multipage/#dom-img-height
@ -230,8 +223,7 @@ impl HTMLImageElementMethods for HTMLImageElement {
// https://html.spec.whatwg.org/multipage/#dom-img-height // https://html.spec.whatwg.org/multipage/#dom-img-height
fn SetHeight(&self, height: u32) { fn SetHeight(&self, height: u32) {
let elem = self.upcast::<Element>(); self.upcast::<Element>().set_uint_attribute(&atom!("height"), height)
elem.set_uint_attribute(&atom!("height"), height)
} }
// https://html.spec.whatwg.org/multipage/#dom-img-naturalwidth // https://html.spec.whatwg.org/multipage/#dom-img-naturalwidth
@ -299,8 +291,7 @@ impl HTMLImageElementMethods for HTMLImageElement {
impl VirtualMethods for HTMLImageElement { impl VirtualMethods for HTMLImageElement {
fn super_type(&self) -> Option<&VirtualMethods> { fn super_type(&self) -> Option<&VirtualMethods> {
let htmlelement: &HTMLElement = self.upcast::<HTMLElement>(); Some(self.upcast::<HTMLElement>() as &VirtualMethods)
Some(htmlelement as &VirtualMethods)
} }
fn attribute_mutated(&self, attr: &Attr, mutation: AttributeMutation) { fn attribute_mutated(&self, attr: &Attr, mutation: AttributeMutation) {

View file

@ -353,7 +353,6 @@ fn broadcast_radio_checked(broadcaster: &HTMLInputElement, group: Option<&Atom>)
//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(); let owner = broadcaster.form_owner();
let doc = document_from_node(broadcaster); let doc = document_from_node(broadcaster);
let doc_node = doc.upcast::<Node>();
// This function is a workaround for lifetime constraint difficulties. // This function is a workaround for lifetime constraint difficulties.
fn do_broadcast(doc_node: &Node, broadcaster: &HTMLInputElement, fn do_broadcast(doc_node: &Node, broadcaster: &HTMLInputElement,
@ -368,7 +367,7 @@ fn broadcast_radio_checked(broadcaster: &HTMLInputElement, group: Option<&Atom>)
} }
} }
do_broadcast(doc_node, broadcaster, owner.r(), group) do_broadcast(doc.upcast(), broadcaster, owner.r(), group)
} }
// https://html.spec.whatwg.org/multipage/#radio-button-group // https://html.spec.whatwg.org/multipage/#radio-button-group
@ -388,8 +387,7 @@ fn in_same_group(other: &HTMLInputElement, owner: Option<&HTMLFormElement>,
impl HTMLInputElement { impl HTMLInputElement {
fn force_relayout(&self) { fn force_relayout(&self) {
let doc = document_from_node(self); let doc = document_from_node(self);
let node = self.upcast::<Node>(); doc.content_changed(self.upcast(), NodeDamage::OtherNodeDamage)
doc.r().content_changed(node, NodeDamage::OtherNodeDamage)
} }
fn radio_group_updated(&self, group: Option<&Atom>) { fn radio_group_updated(&self, group: Option<&Atom>) {
@ -439,8 +437,8 @@ impl HTMLInputElement {
// https://html.spec.whatwg.org/multipage/#radio-button-group // https://html.spec.whatwg.org/multipage/#radio-button-group
fn get_radio_group_name(&self) -> Option<Atom> { fn get_radio_group_name(&self) -> Option<Atom> {
//TODO: determine form owner //TODO: determine form owner
let elem = self.upcast::<Element>(); self.upcast::<Element>()
elem.get_attribute(&ns!(""), &atom!("name")) .get_attribute(&ns!(""), &atom!("name"))
.map(|name| name.value().as_atom().clone()) .map(|name| name.value().as_atom().clone())
} }
@ -468,8 +466,7 @@ impl HTMLInputElement {
fn mutable(&self) -> bool { fn mutable(&self) -> bool {
// https://html.spec.whatwg.org/multipage/#the-input-element:concept-fe-mutable // https://html.spec.whatwg.org/multipage/#the-input-element:concept-fe-mutable
// https://html.spec.whatwg.org/multipage/#the-readonly-attribute:concept-fe-mutable // https://html.spec.whatwg.org/multipage/#the-readonly-attribute:concept-fe-mutable
let el = self.upcast::<Element>(); !(self.upcast::<Element>().get_disabled_state() || self.ReadOnly())
!(el.get_disabled_state() || self.ReadOnly())
} }
// https://html.spec.whatwg.org/multipage/#the-input-element:concept-form-reset-control // https://html.spec.whatwg.org/multipage/#the-input-element:concept-form-reset-control
@ -491,8 +488,7 @@ impl HTMLInputElement {
impl VirtualMethods for HTMLInputElement { impl VirtualMethods for HTMLInputElement {
fn super_type(&self) -> Option<&VirtualMethods> { fn super_type(&self) -> Option<&VirtualMethods> {
let htmlelement: &HTMLElement = self.upcast::<HTMLElement>(); Some(self.upcast::<HTMLElement>() as &VirtualMethods)
Some(htmlelement as &VirtualMethods)
} }
fn attribute_mutated(&self, attr: &Attr, mutation: AttributeMutation) { fn attribute_mutated(&self, attr: &Attr, mutation: AttributeMutation) {
@ -592,8 +588,7 @@ impl VirtualMethods for HTMLInputElement {
s.bind_to_tree(tree_in_doc); s.bind_to_tree(tree_in_doc);
} }
let el = self.upcast::<Element>(); self.upcast::<Element>().check_ancestors_disabled_state_for_form_control();
el.check_ancestors_disabled_state_for_form_control();
} }
fn unbind_from_tree(&self, tree_in_doc: bool) { fn unbind_from_tree(&self, tree_in_doc: bool) {
@ -626,13 +621,11 @@ impl VirtualMethods for HTMLInputElement {
//TODO: set the editing position for text inputs //TODO: set the editing position for text inputs
let doc = document_from_node(self); document_from_node(self).request_focus(self.upcast());
doc.r().request_focus(self.upcast::<Element>());
} else if &*event.Type() == "keydown" && !event.DefaultPrevented() && } else if &*event.Type() == "keydown" && !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) {
let keyevent: Option<&KeyboardEvent> = event.downcast::<KeyboardEvent>(); if let Some(keyevent) = event.downcast::<KeyboardEvent>() {
keyevent.map(|keyevent| {
// This can't be inlined, as holding on to textinput.borrow_mut() // This can't be inlined, as holding on to textinput.borrow_mut()
// during self.implicit_submission will cause a panic. // during self.implicit_submission will cause a panic.
let action = self.textinput.borrow_mut().handle_keydown(keyevent); let action = self.textinput.borrow_mut().handle_keydown(keyevent);
@ -653,7 +646,7 @@ impl VirtualMethods for HTMLInputElement {
} }
Nothing => (), Nothing => (),
} }
}); }
} }
} }
} }
@ -662,7 +655,7 @@ impl FormControl for HTMLInputElement {}
impl Activatable for HTMLInputElement { impl Activatable for HTMLInputElement {
fn as_element(&self) -> &Element { fn as_element(&self) -> &Element {
self.upcast::<Element>() self.upcast()
} }
fn is_instance_activatable(&self) -> bool { fn is_instance_activatable(&self) -> bool {
@ -809,19 +802,19 @@ impl Activatable for HTMLInputElement {
// https://html.spec.whatwg.org/multipage/#radio-button-state-(type=radio):activation-behavior // https://html.spec.whatwg.org/multipage/#radio-button-state-(type=radio):activation-behavior
if self.mutable() { if self.mutable() {
let win = window_from_node(self); let win = window_from_node(self);
let target = self.upcast();
let event = Event::new(GlobalRef::Window(win.r()), let event = Event::new(GlobalRef::Window(win.r()),
"input".to_owned(), "input".to_owned(),
EventBubbles::Bubbles, EventBubbles::Bubbles,
EventCancelable::NotCancelable); EventCancelable::NotCancelable);
let target = self.upcast::<EventTarget>(); event.fire(target);
event.r().fire(target);
let event = Event::new(GlobalRef::Window(win.r()), let event = Event::new(GlobalRef::Window(win.r()),
"change".to_owned(), "change".to_owned(),
EventBubbles::Bubbles, EventBubbles::Bubbles,
EventCancelable::NotCancelable); EventCancelable::NotCancelable);
let target = self.upcast::<EventTarget>(); event.fire(target);
event.r().fire(target);
} }
}, },
_ => () _ => ()
@ -839,8 +832,7 @@ impl Activatable for HTMLInputElement {
Some(ref f) => f Some(ref f) => f
}; };
let elem = self.upcast::<Element>(); if self.upcast::<Element>().click_in_progress() {
if elem.click_in_progress() {
return; return;
} }
let submit_button; let submit_button;

View file

@ -89,8 +89,7 @@ fn is_favicon(value: &Option<String>) -> bool {
impl VirtualMethods for HTMLLinkElement { impl VirtualMethods for HTMLLinkElement {
fn super_type(&self) -> Option<&VirtualMethods> { fn super_type(&self) -> Option<&VirtualMethods> {
let htmlelement: &HTMLElement = self.upcast::<HTMLElement>(); Some(self.upcast::<HTMLElement>() as &VirtualMethods)
Some(htmlelement as &VirtualMethods)
} }
fn attribute_mutated(&self, attr: &Attr, mutation: AttributeMutation) { fn attribute_mutated(&self, attr: &Attr, mutation: AttributeMutation) {
@ -98,7 +97,7 @@ impl VirtualMethods for HTMLLinkElement {
if !self.upcast::<Node>().is_in_doc() || mutation == AttributeMutation::Removed { if !self.upcast::<Node>().is_in_doc() || mutation == AttributeMutation::Removed {
return; return;
} }
let rel = get_attr(self.upcast::<Element>(), &atom!(rel)); let rel = get_attr(self.upcast(), &atom!(rel));
match attr.local_name() { match attr.local_name() {
&atom!(href) => { &atom!(href) => {
if is_stylesheet(&rel) { if is_stylesheet(&rel) {
@ -129,7 +128,7 @@ impl VirtualMethods for HTMLLinkElement {
} }
if tree_in_doc { if tree_in_doc {
let element = self.upcast::<Element>(); let element = self.upcast();
let rel = get_attr(element, &atom!("rel")); let rel = get_attr(element, &atom!("rel"));
let href = get_attr(element, &atom!("href")); let href = get_attr(element, &atom!("href"));
@ -224,9 +223,7 @@ impl HTMLLinkElementMethods for HTMLLinkElement {
// https://html.spec.whatwg.org/multipage/#dom-link-rellist // https://html.spec.whatwg.org/multipage/#dom-link-rellist
fn RelList(&self) -> Root<DOMTokenList> { fn RelList(&self) -> Root<DOMTokenList> {
self.rel_list.or_init(|| { self.rel_list.or_init(|| DOMTokenList::new(self.upcast(), &atom!("rel")))
DOMTokenList::new(self.upcast::<Element>(), &atom!("rel"))
})
} }
// https://html.spec.whatwg.org/multipage/#dom-link-charset // https://html.spec.whatwg.org/multipage/#dom-link-charset
@ -267,7 +264,6 @@ impl StylesheetLoadResponder for StylesheetLoadDispatcher {
let event = Event::new(GlobalRef::Window(window.r()), "load".to_owned(), let event = Event::new(GlobalRef::Window(window.r()), "load".to_owned(),
EventBubbles::DoesNotBubble, EventBubbles::DoesNotBubble,
EventCancelable::NotCancelable); EventCancelable::NotCancelable);
let target = elem.upcast::<EventTarget>(); event.fire(elem.upcast::<EventTarget>());
event.r().fire(target);
} }
} }

View file

@ -57,8 +57,7 @@ impl HTMLMetaElement {
let content = content.value(); let content = content.value();
if !content.is_empty() { if !content.is_empty() {
if let Some(translated_rule) = ViewportRule::from_meta(&**content) { if let Some(translated_rule) = ViewportRule::from_meta(&**content) {
let node = self.upcast::<Node>(); let win = window_from_node(self);
let win = window_from_node(node);
let LayoutChan(ref layout_chan) = win.r().layout_chan(); let LayoutChan(ref layout_chan) = win.r().layout_chan();
layout_chan.send(Msg::AddMetaViewport(translated_rule)).unwrap(); layout_chan.send(Msg::AddMetaViewport(translated_rule)).unwrap();
@ -84,8 +83,7 @@ impl HTMLMetaElementMethods for HTMLMetaElement {
impl VirtualMethods for HTMLMetaElement { impl VirtualMethods for HTMLMetaElement {
fn super_type(&self) -> Option<&VirtualMethods> { fn super_type(&self) -> Option<&VirtualMethods> {
let htmlelement: &HTMLElement = self.upcast::<HTMLElement>(); Some(self.upcast::<HTMLElement>() as &VirtualMethods)
Some(htmlelement as &VirtualMethods)
} }
fn bind_to_tree(&self, tree_in_doc: bool) { fn bind_to_tree(&self, tree_in_doc: bool) {

View file

@ -92,8 +92,7 @@ impl HTMLObjectElementMethods for HTMLObjectElement {
impl VirtualMethods for HTMLObjectElement { impl VirtualMethods for HTMLObjectElement {
fn super_type(&self) -> Option<&VirtualMethods> { fn super_type(&self) -> Option<&VirtualMethods> {
let htmlelement: &HTMLElement = self.upcast::<HTMLElement>(); Some(self.upcast::<HTMLElement>() as &VirtualMethods)
Some(htmlelement as &VirtualMethods)
} }
fn attribute_mutated(&self, attr: &Attr, mutation: AttributeMutation) { fn attribute_mutated(&self, attr: &Attr, mutation: AttributeMutation) {

View file

@ -50,8 +50,7 @@ impl HTMLOptGroupElementMethods for HTMLOptGroupElement {
impl VirtualMethods for HTMLOptGroupElement { impl VirtualMethods for HTMLOptGroupElement {
fn super_type(&self) -> Option<&VirtualMethods> { fn super_type(&self) -> Option<&VirtualMethods> {
let htmlelement: &HTMLElement = self.upcast::<HTMLElement>(); Some(self.upcast::<HTMLElement>() as &VirtualMethods)
Some(htmlelement as &VirtualMethods)
} }
fn attribute_mutated(&self, attr: &Attr, mutation: AttributeMutation) { fn attribute_mutated(&self, attr: &Attr, mutation: AttributeMutation) {

View file

@ -64,7 +64,7 @@ fn collect_text(element: &Element, value: &mut DOMString) {
if child.is::<Text>() { if child.is::<Text>() {
let characterdata = child.downcast::<CharacterData>().unwrap(); let characterdata = child.downcast::<CharacterData>().unwrap();
value.push_str(&characterdata.Data()); value.push_str(&characterdata.Data());
} else if let Some(element_child) = child.downcast::<Element>() { } else if let Some(element_child) = child.downcast() {
collect_text(element_child, value); collect_text(element_child, value);
} }
} }
@ -76,22 +76,19 @@ impl HTMLOptionElementMethods for HTMLOptionElement {
// https://html.spec.whatwg.org/multipage/#dom-option-disabled // https://html.spec.whatwg.org/multipage/#dom-option-disabled
fn SetDisabled(&self, disabled: bool) { fn SetDisabled(&self, disabled: bool) {
let elem = self.upcast::<Element>(); self.upcast::<Element>().set_bool_attribute(&atom!("disabled"), disabled)
elem.set_bool_attribute(&atom!("disabled"), disabled)
} }
// https://html.spec.whatwg.org/multipage/#dom-option-text // https://html.spec.whatwg.org/multipage/#dom-option-text
fn Text(&self) -> DOMString { fn Text(&self) -> DOMString {
let element = self.upcast::<Element>();
let mut content = String::new(); let mut content = String::new();
collect_text(element, &mut content); collect_text(self.upcast(), &mut content);
str_join(split_html_space_chars(&content), " ") str_join(split_html_space_chars(&content), " ")
} }
// https://html.spec.whatwg.org/multipage/#dom-option-text // https://html.spec.whatwg.org/multipage/#dom-option-text
fn SetText(&self, value: DOMString) { fn SetText(&self, value: DOMString) {
let node = self.upcast::<Node>(); self.upcast::<Node>().SetTextContent(Some(value))
node.SetTextContent(Some(value))
} }
// https://html.spec.whatwg.org/multipage/#attr-option-value // https://html.spec.whatwg.org/multipage/#attr-option-value
@ -144,8 +141,7 @@ impl HTMLOptionElementMethods for HTMLOptionElement {
impl VirtualMethods for HTMLOptionElement { impl VirtualMethods for HTMLOptionElement {
fn super_type(&self) -> Option<&VirtualMethods> { fn super_type(&self) -> Option<&VirtualMethods> {
let htmlelement: &HTMLElement = self.upcast::<HTMLElement>(); Some(self.upcast::<HTMLElement>() as &VirtualMethods)
Some(htmlelement as &VirtualMethods)
} }
fn attribute_mutated(&self, attr: &Attr, mutation: AttributeMutation) { fn attribute_mutated(&self, attr: &Attr, mutation: AttributeMutation) {
@ -190,8 +186,7 @@ impl VirtualMethods for HTMLOptionElement {
s.bind_to_tree(tree_in_doc); s.bind_to_tree(tree_in_doc);
} }
let el = self.upcast::<Element>(); self.upcast::<Element>().check_parent_disabled_state_for_option();
el.check_parent_disabled_state_for_option();
} }
fn unbind_from_tree(&self, tree_in_doc: bool) { fn unbind_from_tree(&self, tree_in_doc: bool) {

View file

@ -19,7 +19,6 @@ use dom::bindings::trace::JSTraceable;
use dom::document::Document; use dom::document::Document;
use dom::element::{AttributeMutation, Element, ElementCreator}; use dom::element::{AttributeMutation, Element, ElementCreator};
use dom::event::{Event, EventBubbles, EventCancelable}; use dom::event::{Event, EventBubbles, EventCancelable};
use dom::eventtarget::EventTarget;
use dom::htmlelement::HTMLElement; use dom::htmlelement::HTMLElement;
use dom::node::{ChildrenMutation, CloneChildrenFlag, Node}; use dom::node::{ChildrenMutation, CloneChildrenFlag, Node};
use dom::node::{document_from_node, window_from_node}; use dom::node::{document_from_node, window_from_node};
@ -190,8 +189,7 @@ impl HTMLScriptElement {
return NextParserState::Continue; return NextParserState::Continue;
} }
// Step 5. // Step 5.
let node = self.upcast::<Node>(); if !self.upcast::<Node>().is_in_doc() {
if !node.is_in_doc() {
return NextParserState::Continue; return NextParserState::Continue;
} }
// Step 6, 7. // Step 6, 7.
@ -507,16 +505,13 @@ impl HTMLScriptElement {
type_, type_,
bubbles, bubbles,
cancelable); cancelable);
let event = event.r(); event.fire(self.upcast())
let target = self.upcast::<EventTarget>();
event.fire(target)
} }
} }
impl VirtualMethods for HTMLScriptElement { impl VirtualMethods for HTMLScriptElement {
fn super_type(&self) -> Option<&VirtualMethods> { fn super_type(&self) -> Option<&VirtualMethods> {
let htmlelement: &HTMLElement = self.upcast::<HTMLElement>(); Some(self.upcast::<HTMLElement>() as &VirtualMethods)
Some(htmlelement as &VirtualMethods)
} }
fn attribute_mutated(&self, attr: &Attr, mutation: AttributeMutation) { fn attribute_mutated(&self, attr: &Attr, mutation: AttributeMutation) {
@ -537,8 +532,7 @@ impl VirtualMethods for HTMLScriptElement {
if let Some(ref s) = self.super_type() { if let Some(ref s) = self.super_type() {
s.children_changed(mutation); s.children_changed(mutation);
} }
let node = self.upcast::<Node>(); if !self.parser_inserted.get() && self.upcast::<Node>().is_in_doc() {
if !self.parser_inserted.get() && node.is_in_doc() {
self.prepare(); self.prepare();
} }
} }
@ -561,8 +555,7 @@ impl VirtualMethods for HTMLScriptElement {
// https://html.spec.whatwg.org/multipage/#already-started // https://html.spec.whatwg.org/multipage/#already-started
if self.already_started.get() { if self.already_started.get() {
let copy_elem = copy.downcast::<HTMLScriptElement>().unwrap(); copy.downcast::<HTMLScriptElement>().unwrap().mark_already_started();
copy_elem.mark_already_started();
} }
} }
} }
@ -580,8 +573,7 @@ impl HTMLScriptElementMethods for HTMLScriptElement {
// https://html.spec.whatwg.org/multipage/#dom-script-text // https://html.spec.whatwg.org/multipage/#dom-script-text
fn SetText(&self, value: DOMString) { fn SetText(&self, value: DOMString) {
let node = self.upcast::<Node>(); self.upcast::<Node>().SetTextContent(Some(value))
node.SetTextContent(Some(value))
} }
} }

View file

@ -101,8 +101,7 @@ impl HTMLSelectElementMethods for HTMLSelectElement {
impl VirtualMethods for HTMLSelectElement { impl VirtualMethods for HTMLSelectElement {
fn super_type(&self) -> Option<&VirtualMethods> { fn super_type(&self) -> Option<&VirtualMethods> {
let htmlelement: &HTMLElement = self.upcast::<HTMLElement>(); Some(self.upcast::<HTMLElement>() as &VirtualMethods)
Some(htmlelement as &VirtualMethods)
} }
fn attribute_mutated(&self, attr: &Attr, mutation: AttributeMutation) { fn attribute_mutated(&self, attr: &Attr, mutation: AttributeMutation) {
@ -128,8 +127,7 @@ impl VirtualMethods for HTMLSelectElement {
s.bind_to_tree(tree_in_doc); s.bind_to_tree(tree_in_doc);
} }
let el = self.upcast::<Element>(); self.upcast::<Element>().check_ancestors_disabled_state_for_form_control();
el.check_ancestors_disabled_state_for_form_control();
} }
fn unbind_from_tree(&self, tree_in_doc: bool) { fn unbind_from_tree(&self, tree_in_doc: bool) {

View file

@ -65,16 +65,14 @@ impl HTMLStyleElement {
impl VirtualMethods for HTMLStyleElement { impl VirtualMethods for HTMLStyleElement {
fn super_type(&self) -> Option<&VirtualMethods> { fn super_type(&self) -> Option<&VirtualMethods> {
let htmlelement: &HTMLElement = self.upcast::<HTMLElement>(); Some(self.upcast::<HTMLElement>() as &VirtualMethods)
Some(htmlelement as &VirtualMethods)
} }
fn children_changed(&self, mutation: &ChildrenMutation) { fn children_changed(&self, mutation: &ChildrenMutation) {
if let Some(ref s) = self.super_type() { if let Some(ref s) = self.super_type() {
s.children_changed(mutation); s.children_changed(mutation);
} }
let node = self.upcast::<Node>(); if self.upcast::<Node>().is_in_doc() {
if node.is_in_doc() {
self.parse_own_css(); self.parse_own_css();
} }
} }

View file

@ -102,8 +102,7 @@ impl HTMLTableCellElementLayoutHelpers for LayoutJS<HTMLTableCellElement> {
impl VirtualMethods for HTMLTableCellElement { impl VirtualMethods for HTMLTableCellElement {
fn super_type(&self) -> Option<&VirtualMethods> { fn super_type(&self) -> Option<&VirtualMethods> {
let htmlelement: &HTMLElement = self.upcast::<HTMLElement>(); Some(self.upcast::<HTMLElement>() as &VirtualMethods)
Some(htmlelement as &VirtualMethods)
} }
fn attribute_mutated(&self, attr: &Attr, mutation: AttributeMutation) { fn attribute_mutated(&self, attr: &Attr, mutation: AttributeMutation) {

View file

@ -52,25 +52,19 @@ impl HTMLTableElement {
impl HTMLTableElementMethods for HTMLTableElement { impl HTMLTableElementMethods for HTMLTableElement {
// https://html.spec.whatwg.org/multipage/#dom-table-caption // https://html.spec.whatwg.org/multipage/#dom-table-caption
fn GetCaption(&self) -> Option<Root<HTMLTableCaptionElement>> { fn GetCaption(&self) -> Option<Root<HTMLTableCaptionElement>> {
let node = self.upcast::<Node>(); self.upcast::<Node>().children().filter_map(Root::downcast).next()
node.children()
.filter_map(|c| {
c.downcast::<HTMLTableCaptionElement>().map(Root::from_ref)
})
.next()
} }
// https://html.spec.whatwg.org/multipage/#dom-table-caption // https://html.spec.whatwg.org/multipage/#dom-table-caption
fn SetCaption(&self, new_caption: Option<&HTMLTableCaptionElement>) { fn SetCaption(&self, new_caption: Option<&HTMLTableCaptionElement>) {
let node = self.upcast::<Node>();
if let Some(ref caption) = self.GetCaption() { if let Some(ref caption) = self.GetCaption() {
caption.upcast::<Node>().remove_self(); caption.upcast::<Node>().remove_self();
} }
if let Some(caption) = new_caption { if let Some(caption) = new_caption {
assert!(node.InsertBefore(caption.upcast::<Node>(), let node = self.upcast::<Node>();
node.GetFirstChild().as_ref().map(|n| n.r())).is_ok()); node.InsertBefore(caption.upcast(), node.GetFirstChild().r())
.expect("Insertion failed");
} }
} }
@ -86,7 +80,7 @@ impl HTMLTableElementMethods for HTMLTableElement {
caption caption
} }
}; };
Root::upcast::<HTMLElement>(caption) Root::upcast(caption)
} }
// https://html.spec.whatwg.org/multipage/#dom-table-deletecaption // https://html.spec.whatwg.org/multipage/#dom-table-deletecaption
@ -107,10 +101,10 @@ impl HTMLTableElementMethods for HTMLTableElement {
.filter_map(Root::downcast::<Element>) .filter_map(Root::downcast::<Element>)
.find(|n| n.is::<HTMLTableSectionElement>() && n.local_name() == &atom!("tbody")); .find(|n| n.is::<HTMLTableSectionElement>() && n.local_name() == &atom!("tbody"));
let reference_element = let reference_element =
last_tbody.and_then(|t| Root::upcast::<Node>(t).GetNextSibling()); last_tbody.and_then(|t| t.upcast::<Node>().GetNextSibling());
assert!(node.InsertBefore(tbody.upcast::<Node>(), node.InsertBefore(tbody.upcast(), reference_element.r())
reference_element.r()).is_ok()); .expect("Insertion failed");
tbody tbody
} }
@ -142,8 +136,7 @@ impl HTMLTableElement {
impl VirtualMethods for HTMLTableElement { impl VirtualMethods for HTMLTableElement {
fn super_type(&self) -> Option<&VirtualMethods> { fn super_type(&self) -> Option<&VirtualMethods> {
let htmlelement: &HTMLElement = self.upcast::<HTMLElement>(); Some(self.upcast::<HTMLElement>() as &VirtualMethods)
Some(htmlelement as &VirtualMethods)
} }
fn attribute_mutated(&self, attr: &Attr, mutation: AttributeMutation) { fn attribute_mutated(&self, attr: &Attr, mutation: AttributeMutation) {

View file

@ -72,7 +72,7 @@ impl HTMLTableRowElementMethods for HTMLTableRowElement {
self.cells.or_init(|| { self.cells.or_init(|| {
let window = window_from_node(self); let window = window_from_node(self);
let filter = box CellsFilter; let filter = box CellsFilter;
HTMLCollection::create(window.r(), self.upcast::<Node>(), filter) HTMLCollection::create(window.r(), self.upcast(), filter)
}) })
} }
@ -97,8 +97,7 @@ impl HTMLTableRowElementMethods for HTMLTableRowElement {
impl VirtualMethods for HTMLTableRowElement { impl VirtualMethods for HTMLTableRowElement {
fn super_type(&self) -> Option<&VirtualMethods> { fn super_type(&self) -> Option<&VirtualMethods> {
let htmlelement: &HTMLElement = self.upcast::<HTMLElement>(); Some(self.upcast::<HTMLElement>() as &VirtualMethods)
Some(htmlelement as &VirtualMethods)
} }
fn attribute_mutated(&self, attr: &Attr, mutation: AttributeMutation) { fn attribute_mutated(&self, attr: &Attr, mutation: AttributeMutation) {

View file

@ -58,7 +58,7 @@ impl CollectionFilter for RowsFilter {
impl HTMLTableSectionElementMethods for HTMLTableSectionElement { impl HTMLTableSectionElementMethods for HTMLTableSectionElement {
// https://html.spec.whatwg.org/multipage/#dom-tbody-rows // https://html.spec.whatwg.org/multipage/#dom-tbody-rows
fn Rows(&self) -> Root<HTMLCollection> { fn Rows(&self) -> Root<HTMLCollection> {
HTMLCollection::create(&window_from_node(self), self.upcast::<Node>(), box RowsFilter) HTMLCollection::create(&window_from_node(self), self.upcast(), box RowsFilter)
} }
// https://html.spec.whatwg.org/multipage/#dom-tbody-insertrow // https://html.spec.whatwg.org/multipage/#dom-tbody-insertrow
@ -82,8 +82,7 @@ impl HTMLTableSectionElementMethods for HTMLTableSectionElement {
impl VirtualMethods for HTMLTableSectionElement { impl VirtualMethods for HTMLTableSectionElement {
fn super_type(&self) -> Option<&VirtualMethods> { fn super_type(&self) -> Option<&VirtualMethods> {
let htmlelement: &HTMLElement = self.upcast::<HTMLElement>(); Some(self.upcast::<HTMLElement>() as &VirtualMethods)
Some(htmlelement as &VirtualMethods)
} }
fn attribute_mutated(&self, attr: &Attr, mutation: AttributeMutation) { fn attribute_mutated(&self, attr: &Attr, mutation: AttributeMutation) {

View file

@ -64,7 +64,7 @@ impl VirtualMethods for HTMLTemplateElement {
// Step 1. // Step 1.
let doc = document_from_node(self).appropriate_template_contents_owner_document(); let doc = document_from_node(self).appropriate_template_contents_owner_document();
// Step 2. // Step 2.
Node::adopt(self.Content().upcast::<Node>(), &doc); Node::adopt(self.Content().upcast(), &doc);
} }
/// https://html.spec.whatwg.org/multipage/#the-template-element:concept-node-clone-ext /// https://html.spec.whatwg.org/multipage/#the-template-element:concept-node-clone-ext
@ -79,7 +79,7 @@ impl VirtualMethods for HTMLTemplateElement {
// Steps 2-3. // Steps 2-3.
let copy_contents = Root::upcast::<Node>(copy.Content()); let copy_contents = Root::upcast::<Node>(copy.Content());
let copy_contents_doc = copy_contents.owner_doc(); let copy_contents_doc = copy_contents.owner_doc();
for child in Root::upcast::<Node>(self.Content()).children() { for child in self.Content().upcast::<Node>().children() {
let copy_child = Node::clone( let copy_child = Node::clone(
&child, Some(&copy_contents_doc), CloneChildrenFlag::CloneChildren); &child, Some(&copy_contents_doc), CloneChildrenFlag::CloneChildren);
copy_contents.AppendChild(&copy_child).unwrap(); copy_contents.AppendChild(&copy_child).unwrap();

View file

@ -169,14 +169,12 @@ impl HTMLTextAreaElementMethods for HTMLTextAreaElement {
// https://html.spec.whatwg.org/multipage/#dom-textarea-defaultvalue // https://html.spec.whatwg.org/multipage/#dom-textarea-defaultvalue
fn DefaultValue(&self) -> DOMString { fn DefaultValue(&self) -> DOMString {
let node = self.upcast::<Node>(); self.upcast::<Node>().GetTextContent().unwrap()
node.GetTextContent().unwrap()
} }
// https://html.spec.whatwg.org/multipage/#dom-textarea-defaultvalue // https://html.spec.whatwg.org/multipage/#dom-textarea-defaultvalue
fn SetDefaultValue(&self, value: DOMString) { fn SetDefaultValue(&self, value: DOMString) {
let node = self.upcast::<Node>(); self.upcast::<Node>().SetTextContent(Some(value));
node.SetTextContent(Some(value));
// if the element's dirty value flag is false, then the element's // if the element's dirty value flag is false, then the element's
// raw value must be set to the value of the element's textContent IDL attribute // raw value must be set to the value of the element's textContent IDL attribute
@ -218,8 +216,7 @@ impl HTMLTextAreaElement {
impl HTMLTextAreaElement { impl HTMLTextAreaElement {
fn force_relayout(&self) { fn force_relayout(&self) {
let doc = document_from_node(self); let doc = document_from_node(self);
let node = self.upcast::<Node>(); doc.content_changed(self.upcast(), NodeDamage::OtherNodeDamage)
doc.r().content_changed(node, NodeDamage::OtherNodeDamage)
} }
fn dispatch_change_event(&self) { fn dispatch_change_event(&self) {
@ -230,15 +227,13 @@ impl HTMLTextAreaElement {
EventBubbles::DoesNotBubble, EventBubbles::DoesNotBubble,
EventCancelable::NotCancelable); EventCancelable::NotCancelable);
let target = self.upcast::<EventTarget>(); self.upcast::<EventTarget>().dispatch_event(&event);
target.dispatch_event(event.r());
} }
} }
impl VirtualMethods for HTMLTextAreaElement { impl VirtualMethods for HTMLTextAreaElement {
fn super_type(&self) -> Option<&VirtualMethods> { fn super_type(&self) -> Option<&VirtualMethods> {
let htmlelement: &HTMLElement = self.upcast::<HTMLElement>(); Some(self.upcast::<HTMLElement>() as &VirtualMethods)
Some(htmlelement as &VirtualMethods)
} }
fn attribute_mutated(&self, attr: &Attr, mutation: AttributeMutation) { fn attribute_mutated(&self, attr: &Attr, mutation: AttributeMutation) {
@ -279,8 +274,7 @@ impl VirtualMethods for HTMLTextAreaElement {
s.bind_to_tree(tree_in_doc); s.bind_to_tree(tree_in_doc);
} }
let el = self.upcast::<Element>(); self.upcast::<Element>().check_ancestors_disabled_state_for_form_control();
el.check_ancestors_disabled_state_for_form_control();
} }
fn parse_plain_attribute(&self, name: &Atom, value: DOMString) -> AttrValue { fn parse_plain_attribute(&self, name: &Atom, value: DOMString) -> AttrValue {
@ -298,7 +292,7 @@ impl VirtualMethods for HTMLTextAreaElement {
let node = self.upcast::<Node>(); let node = self.upcast::<Node>();
let el = self.upcast::<Element>(); let el = self.upcast::<Element>();
if node.ancestors().any(|ancestor| ancestor.r().is::<HTMLFieldSetElement>()) { if node.ancestors().any(|ancestor| ancestor.is::<HTMLFieldSetElement>()) {
el.check_ancestors_disabled_state_for_form_control(); el.check_ancestors_disabled_state_for_form_control();
} else { } else {
el.check_disabled_attribute(); el.check_disabled_attribute();
@ -323,11 +317,9 @@ impl VirtualMethods for HTMLTextAreaElement {
if &*event.Type() == "click" && !event.DefaultPrevented() { if &*event.Type() == "click" && !event.DefaultPrevented() {
//TODO: set the editing position for text inputs //TODO: set the editing position for text inputs
let doc = document_from_node(self); document_from_node(self).request_focus(self.upcast());
doc.r().request_focus(self.upcast::<Element>());
} else if &*event.Type() == "keydown" && !event.DefaultPrevented() { } else if &*event.Type() == "keydown" && !event.DefaultPrevented() {
let keyevent: Option<&KeyboardEvent> = event.downcast::<KeyboardEvent>(); if let Some(kevent) = event.downcast::<KeyboardEvent>() {
keyevent.map(|kevent| {
match self.textinput.borrow_mut().handle_keydown(kevent) { match self.textinput.borrow_mut().handle_keydown(kevent) {
KeyReaction::TriggerDefaultAction => (), KeyReaction::TriggerDefaultAction => (),
KeyReaction::DispatchInput => { KeyReaction::DispatchInput => {
@ -351,7 +343,7 @@ impl VirtualMethods for HTMLTextAreaElement {
} }
KeyReaction::Nothing => (), KeyReaction::Nothing => (),
} }
}); }
} }
} }
} }

View file

@ -39,13 +39,10 @@ impl HTMLTitleElement {
impl HTMLTitleElementMethods for HTMLTitleElement { impl HTMLTitleElementMethods for HTMLTitleElement {
// https://html.spec.whatwg.org/multipage/#dom-title-text // https://html.spec.whatwg.org/multipage/#dom-title-text
fn Text(&self) -> DOMString { fn Text(&self) -> DOMString {
let node = self.upcast::<Node>();
let mut content = String::new(); let mut content = String::new();
for child in node.children() { for child in self.upcast::<Node>().children() {
let text: Option<&Text> = child.downcast::<Text>(); if let Some(text) = child.downcast::<Text>() {
match text { content.push_str(&text.upcast::<CharacterData>().data());
Some(text) => content.push_str(&text.upcast::<CharacterData>().data()),
None => (),
} }
} }
content content
@ -53,15 +50,13 @@ impl HTMLTitleElementMethods for HTMLTitleElement {
// https://html.spec.whatwg.org/multipage/#dom-title-text // https://html.spec.whatwg.org/multipage/#dom-title-text
fn SetText(&self, value: DOMString) { fn SetText(&self, value: DOMString) {
let node = self.upcast::<Node>(); self.upcast::<Node>().SetTextContent(Some(value))
node.SetTextContent(Some(value))
} }
} }
impl VirtualMethods for HTMLTitleElement { impl VirtualMethods for HTMLTitleElement {
fn super_type(&self) -> Option<&VirtualMethods> { fn super_type(&self) -> Option<&VirtualMethods> {
let htmlelement: &HTMLElement = self.upcast::<HTMLElement>(); Some(self.upcast::<HTMLElement>() as &VirtualMethods)
Some(htmlelement as &VirtualMethods)
} }
fn children_changed(&self, mutation: &ChildrenMutation) { fn children_changed(&self, mutation: &ChildrenMutation) {

View file

@ -762,13 +762,12 @@ impl KeyboardEventMethods for KeyboardEvent {
_modifiersListArg: DOMString, _modifiersListArg: DOMString,
repeat: bool, repeat: bool,
_locale: DOMString) { _locale: DOMString) {
let event = self.upcast::<Event>(); if self.upcast::<Event>().dispatching() {
if event.dispatching() {
return; return;
} }
let uievent = self.upcast::<UIEvent>(); self.upcast::<UIEvent>()
uievent.InitUIEvent(typeArg, canBubbleArg, cancelableArg, viewArg, 0); .InitUIEvent(typeArg, canBubbleArg, cancelableArg, viewArg, 0);
*self.key_string.borrow_mut() = keyArg; *self.key_string.borrow_mut() = keyArg;
self.location.set(locationArg); self.location.set(locationArg);
self.repeat.set(repeat); self.repeat.set(repeat);

View file

@ -78,8 +78,7 @@ impl MessageEvent {
let messageevent = MessageEvent::new( let messageevent = MessageEvent::new(
scope, "message".to_owned(), false, false, message, scope, "message".to_owned(), false, false, message,
"".to_owned(), "".to_owned()); "".to_owned(), "".to_owned());
let event = messageevent.upcast::<Event>(); messageevent.upcast::<Event>().fire(target);
event.fire(target);
} }
} }

View file

@ -151,8 +151,8 @@
//! # use script::dom::node::Node; //! # use script::dom::node::Node;
//! # use script::dom::htmlelement::HTMLElement; //! # use script::dom::htmlelement::HTMLElement;
//! fn f(element: &Element) { //! fn f(element: &Element) {
//! let base: &Node = element.upcast::<Node>(); //! let base = element.upcast::<Node>();
//! let derived: Option<&HTMLElement> = element.downcast::<HTMLElement>(); //! let derived = element.downcast::<HTMLElement>();
//! } //! }
//! ``` //! ```
//! //!

View file

@ -189,13 +189,12 @@ impl MouseEventMethods for MouseEvent {
metaKeyArg: bool, metaKeyArg: bool,
buttonArg: i16, buttonArg: i16,
relatedTargetArg: Option<&EventTarget>) { relatedTargetArg: Option<&EventTarget>) {
let event: &Event = self.upcast::<Event>(); if self.upcast::<Event>().dispatching() {
if event.dispatching() {
return; return;
} }
let uievent: &UIEvent = self.upcast::<UIEvent>(); self.upcast::<UIEvent>()
uievent.InitUIEvent(typeArg, canBubbleArg, cancelableArg, viewArg, detailArg); .InitUIEvent(typeArg, canBubbleArg, cancelableArg, viewArg, detailArg);
self.screen_x.set(screenXArg); self.screen_x.set(screenXArg);
self.screen_y.set(screenYArg); self.screen_y.set(screenYArg);
self.client_x.set(clientXArg); self.client_x.set(clientXArg);

View file

@ -355,9 +355,9 @@ impl<'a> Iterator for QuerySelectorIterator {
// TODO(cgaebel): Is it worth it to build a bloom filter here // TODO(cgaebel): Is it worth it to build a bloom filter here
// (instead of passing `None`)? Probably. // (instead of passing `None`)? Probably.
self.iterator.by_ref().filter_map(|node| { self.iterator.by_ref().filter_map(|node| {
if let Some(element) = Root::downcast::<Element>(node) { if let Some(element) = Root::downcast(node) {
if matches(selectors, &element, None) { if matches(selectors, &element, None) {
return Some(Root::upcast::<Node>(element)) return Some(Root::upcast(element));
} }
} }
None None
@ -718,7 +718,7 @@ impl Node {
Err(()) => Err(Error::Syntax), Err(()) => Err(Error::Syntax),
// Step 3. // Step 3.
Ok(ref selectors) => { Ok(ref selectors) => {
Ok(self.traverse_preorder().filter_map(Root::downcast::<Element>).find(|element| { Ok(self.traverse_preorder().filter_map(Root::downcast).find(|element| {
matches(selectors, element, None) matches(selectors, element, None)
})) }))
} }
@ -787,12 +787,7 @@ impl Node {
} }
pub fn child_elements(&self) -> ChildElementIterator { pub fn child_elements(&self) -> ChildElementIterator {
fn to_temporary(node: Root<Node>) -> Option<Root<Element>> { self.children().filter_map(Root::downcast as fn(_) -> _).peekable()
Root::downcast::<Element>(node)
}
self.children()
.filter_map(to_temporary as fn(_) -> _)
.peekable()
} }
pub fn remove_self(&self) { pub fn remove_self(&self) {
@ -823,18 +818,10 @@ impl Node {
name: "".to_owned(), name: "".to_owned(),
publicId: "".to_owned(), publicId: "".to_owned(),
systemId: "".to_owned(), systemId: "".to_owned(),
attrs: self.downcast().map(Element::summarize).unwrap_or(vec![]),
attrs: {
let e: Option<&Element> = self.downcast::<Element>();
match e {
Some(element) => element.summarize(),
None => vec!(),
}
},
isDocumentElement: isDocumentElement:
self.owner_doc() self.owner_doc()
.r()
.GetDocumentElement() .GetDocumentElement()
.map(|elem| elem.upcast::<Node>() == self) .map(|elem| elem.upcast::<Node>() == self)
.unwrap_or(false), .unwrap_or(false),
@ -846,12 +833,10 @@ impl Node {
// https://dvcs.w3.org/hg/innerhtml/raw-file/tip/index.html#dfn-concept-parse-fragment // https://dvcs.w3.org/hg/innerhtml/raw-file/tip/index.html#dfn-concept-parse-fragment
pub fn parse_fragment(&self, markup: DOMString) -> Fallible<Root<DocumentFragment>> { pub fn parse_fragment(&self, markup: DOMString) -> Fallible<Root<DocumentFragment>> {
let context_node: &Node = self.upcast::<Node>();
let context_document = document_from_node(self); let context_document = document_from_node(self);
let fragment = DocumentFragment::new(context_document.r()); let fragment = DocumentFragment::new(context_document.r());
if context_document.r().is_html_document() { if context_document.r().is_html_document() {
let fragment_node = fragment.upcast::<Node>(); parse_html_fragment(self.upcast(), markup, fragment.upcast());
parse_html_fragment(context_node, markup, fragment_node);
} else { } else {
// FIXME: XML case // FIXME: XML case
unimplemented!(); unimplemented!();
@ -1619,7 +1604,7 @@ impl Node {
// XXXabinader: clone() for each node as trait? // XXXabinader: clone() for each node as trait?
let copy: Root<Node> = match node.type_id() { let copy: Root<Node> = match node.type_id() {
NodeTypeId::DocumentType => { NodeTypeId::DocumentType => {
let doctype: &DocumentType = node.downcast::<DocumentType>().unwrap(); let doctype = node.downcast::<DocumentType>().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.r()); Some(doctype.system_id().clone()), document.r());
@ -1720,8 +1705,7 @@ impl Node {
pub fn collect_text_contents<T: Iterator<Item=Root<Node>>>(iterator: T) -> String { pub fn collect_text_contents<T: Iterator<Item=Root<Node>>>(iterator: T) -> String {
let mut content = String::new(); let mut content = String::new();
for node in iterator { for node in iterator {
let text = node.downcast::<Text>(); match node.downcast::<Text>() {
match text {
Some(text) => content.push_str(&text.upcast::<CharacterData>().Data()), Some(text) => content.push_str(&text.upcast::<CharacterData>().Data()),
None => (), None => (),
} }
@ -1778,7 +1762,7 @@ impl Node {
// Step 3. // Step 3.
None => ns!(""), None => ns!(""),
// Step 4. // Step 4.
Some(parent) => Node::locate_namespace(parent.upcast::<Node>(), prefix) Some(parent) => Node::locate_namespace(parent.upcast(), prefix)
} }
}, },
NodeTypeId::Document => { NodeTypeId::Document => {
@ -1787,7 +1771,7 @@ impl Node {
None => ns!(""), None => ns!(""),
// Step 2. // Step 2.
Some(document_element) => { Some(document_element) => {
Node::locate_namespace(document_element.upcast::<Node>(), prefix) Node::locate_namespace(document_element.upcast(), prefix)
} }
} }
}, },
@ -1797,7 +1781,7 @@ impl Node {
// Step 1. // Step 1.
None => ns!(""), None => ns!(""),
// Step 2. // Step 2.
Some(parent) => Node::locate_namespace(parent.upcast::<Node>(), prefix) Some(parent) => Node::locate_namespace(parent.upcast(), prefix)
} }
} }
} }
@ -1828,19 +1812,15 @@ impl NodeMethods for Node {
fn NodeName(&self) -> DOMString { fn NodeName(&self) -> DOMString {
match self.type_id() { match self.type_id() {
NodeTypeId::Element(..) => { NodeTypeId::Element(..) => {
let elem: &Element = self.downcast::<Element>().unwrap(); self.downcast::<Element>().unwrap().TagName()
elem.TagName()
} }
NodeTypeId::CharacterData(CharacterDataTypeId::Text) => "#text".to_owned(), NodeTypeId::CharacterData(CharacterDataTypeId::Text) => "#text".to_owned(),
NodeTypeId::CharacterData(CharacterDataTypeId::ProcessingInstruction) => { NodeTypeId::CharacterData(CharacterDataTypeId::ProcessingInstruction) => {
let processing_instruction: &ProcessingInstruction = self.downcast::<ProcessingInstruction>().unwrap().Target()
self.downcast::<ProcessingInstruction>().unwrap();
processing_instruction.Target()
} }
NodeTypeId::CharacterData(CharacterDataTypeId::Comment) => "#comment".to_owned(), NodeTypeId::CharacterData(CharacterDataTypeId::Comment) => "#comment".to_owned(),
NodeTypeId::DocumentType => { NodeTypeId::DocumentType => {
let doctype: &DocumentType = self.downcast::<DocumentType>().unwrap(); self.downcast::<DocumentType>().unwrap().name().clone()
doctype.name().clone()
}, },
NodeTypeId::DocumentFragment => "#document-fragment".to_owned(), NodeTypeId::DocumentFragment => "#document-fragment".to_owned(),
NodeTypeId::Document => "#document".to_owned() NodeTypeId::Document => "#document".to_owned()
@ -1870,7 +1850,7 @@ impl NodeMethods for Node {
// https://dom.spec.whatwg.org/#dom-node-parentelement // https://dom.spec.whatwg.org/#dom-node-parentelement
fn GetParentElement(&self) -> Option<Root<Element>> { fn GetParentElement(&self) -> Option<Root<Element>> {
self.GetParentNode().and_then(Root::downcast::<Element>) self.GetParentNode().and_then(Root::downcast)
} }
// https://dom.spec.whatwg.org/#dom-node-haschildnodes // https://dom.spec.whatwg.org/#dom-node-haschildnodes
@ -1911,7 +1891,7 @@ impl NodeMethods for Node {
fn GetNodeValue(&self) -> Option<DOMString> { fn GetNodeValue(&self) -> Option<DOMString> {
match self.type_id() { match self.type_id() {
NodeTypeId::CharacterData(..) => { NodeTypeId::CharacterData(..) => {
let chardata: &CharacterData = self.downcast::<CharacterData>().unwrap(); let chardata = self.downcast::<CharacterData>().unwrap();
Some(chardata.Data()) Some(chardata.Data())
} }
_ => { _ => {
@ -1939,7 +1919,7 @@ impl NodeMethods for Node {
Some(content) Some(content)
} }
NodeTypeId::CharacterData(..) => { NodeTypeId::CharacterData(..) => {
let characterdata: &CharacterData = self.downcast::<CharacterData>().unwrap(); let characterdata = self.downcast::<CharacterData>().unwrap();
Some(characterdata.Data()) Some(characterdata.Data())
} }
NodeTypeId::DocumentType | NodeTypeId::DocumentType |
@ -1959,15 +1939,14 @@ impl NodeMethods for Node {
let node = if value.is_empty() { let node = if value.is_empty() {
None None
} else { } else {
let document = self.owner_doc(); Some(Root::upcast(self.owner_doc().CreateTextNode(value)))
Some(Root::upcast::<Node>(document.r().CreateTextNode(value)))
}; };
// Step 3. // Step 3.
Node::replace_all(node.r(), self); Node::replace_all(node.r(), self);
} }
NodeTypeId::CharacterData(..) => { NodeTypeId::CharacterData(..) => {
let characterdata: &CharacterData = self.downcast::<CharacterData>().unwrap(); let characterdata = self.downcast::<CharacterData>().unwrap();
characterdata.SetData(value); characterdata.SetData(value);
// Notify the document that the content of this node is different // Notify the document that the content of this node is different
@ -2034,8 +2013,7 @@ impl NodeMethods for Node {
0 => (), 0 => (),
// Step 6.1.2 // Step 6.1.2
1 => { 1 => {
if self.child_elements() if self.child_elements().any(|c| c.upcast::<Node>() != child) {
.any(|c| c.upcast::<Node>() != child) {
return Err(Error::HierarchyRequest); return Err(Error::HierarchyRequest);
} }
if child.following_siblings() if child.following_siblings()
@ -2137,14 +2115,13 @@ impl NodeMethods for Node {
for child in self.children() { for child in self.children() {
match child.downcast::<Text>() { match child.downcast::<Text>() {
Some(text) => { Some(text) => {
let characterdata: &CharacterData = text.upcast::<CharacterData>(); let characterdata = text.upcast::<CharacterData>();
if characterdata.Length() == 0 { if characterdata.Length() == 0 {
Node::remove(&*child, self, SuppressObserver::Unsuppressed); Node::remove(&*child, self, SuppressObserver::Unsuppressed);
} else { } else {
match prev_text { match prev_text {
Some(ref text_node) => { Some(ref text_node) => {
let prev_characterdata = let prev_characterdata = text_node.upcast::<CharacterData>();
text_node.upcast::<CharacterData>();
prev_characterdata.append_data(&**characterdata.data()); prev_characterdata.append_data(&**characterdata.data());
Node::remove(&*child, self, SuppressObserver::Unsuppressed); Node::remove(&*child, self, SuppressObserver::Unsuppressed);
}, },
@ -2172,34 +2149,34 @@ impl NodeMethods for Node {
// https://dom.spec.whatwg.org/#dom-node-isequalnode // https://dom.spec.whatwg.org/#dom-node-isequalnode
fn IsEqualNode(&self, maybe_node: Option<&Node>) -> bool { fn IsEqualNode(&self, maybe_node: Option<&Node>) -> bool {
fn is_equal_doctype(node: &Node, other: &Node) -> bool { fn is_equal_doctype(node: &Node, other: &Node) -> bool {
let doctype: &DocumentType = node.downcast::<DocumentType>().unwrap(); let doctype = node.downcast::<DocumentType>().unwrap();
let other_doctype: &DocumentType = other.downcast::<DocumentType>().unwrap(); let other_doctype = other.downcast::<DocumentType>().unwrap();
(*doctype.name() == *other_doctype.name()) && (*doctype.name() == *other_doctype.name()) &&
(*doctype.public_id() == *other_doctype.public_id()) && (*doctype.public_id() == *other_doctype.public_id()) &&
(*doctype.system_id() == *other_doctype.system_id()) (*doctype.system_id() == *other_doctype.system_id())
} }
fn is_equal_element(node: &Node, other: &Node) -> bool { fn is_equal_element(node: &Node, other: &Node) -> bool {
let element: &Element = node.downcast::<Element>().unwrap(); let element = node.downcast::<Element>().unwrap();
let other_element: &Element = other.downcast::<Element>().unwrap(); let other_element = other.downcast::<Element>().unwrap();
(*element.namespace() == *other_element.namespace()) && (*element.namespace() == *other_element.namespace()) &&
(*element.prefix() == *other_element.prefix()) && (*element.prefix() == *other_element.prefix()) &&
(*element.local_name() == *other_element.local_name()) && (*element.local_name() == *other_element.local_name()) &&
(element.attrs().len() == other_element.attrs().len()) (element.attrs().len() == other_element.attrs().len())
} }
fn is_equal_processinginstruction(node: &Node, other: &Node) -> bool { fn is_equal_processinginstruction(node: &Node, other: &Node) -> bool {
let pi: &ProcessingInstruction = node.downcast::<ProcessingInstruction>().unwrap(); let pi = node.downcast::<ProcessingInstruction>().unwrap();
let other_pi: &ProcessingInstruction = other.downcast::<ProcessingInstruction>().unwrap(); let other_pi = other.downcast::<ProcessingInstruction>().unwrap();
(*pi.target() == *other_pi.target()) && (*pi.target() == *other_pi.target()) &&
(*pi.upcast::<CharacterData>().data() == *other_pi.upcast::<CharacterData>().data()) (*pi.upcast::<CharacterData>().data() == *other_pi.upcast::<CharacterData>().data())
} }
fn is_equal_characterdata(node: &Node, other: &Node) -> bool { fn is_equal_characterdata(node: &Node, other: &Node) -> bool {
let characterdata: &CharacterData = node.downcast::<CharacterData>().unwrap(); let characterdata = node.downcast::<CharacterData>().unwrap();
let other_characterdata: &CharacterData = other.downcast::<CharacterData>().unwrap(); let other_characterdata = other.downcast::<CharacterData>().unwrap();
*characterdata.data() == *other_characterdata.data() *characterdata.data() == *other_characterdata.data()
} }
fn is_equal_element_attrs(node: &Node, other: &Node) -> bool { fn is_equal_element_attrs(node: &Node, other: &Node) -> bool {
let element: &Element = node.downcast::<Element>().unwrap(); let element = node.downcast::<Element>().unwrap();
let other_element: &Element = other.downcast::<Element>().unwrap(); let other_element = other.downcast::<Element>().unwrap();
assert!(element.attrs().len() == other_element.attrs().len()); assert!(element.attrs().len() == other_element.attrs().len());
// FIXME(https://github.com/rust-lang/rust/issues/23338) // FIXME(https://github.com/rust-lang/rust/issues/23338)
let attrs = element.attrs(); let attrs = element.attrs();
@ -2327,7 +2304,9 @@ impl NodeMethods for Node {
// Step 2. // Step 2.
match self.type_id() { match self.type_id() {
NodeTypeId::Element(..) => self.downcast::<Element>().unwrap().lookup_prefix(namespace), NodeTypeId::Element(..) => {
self.downcast::<Element>().unwrap().lookup_prefix(namespace)
},
NodeTypeId::Document => { NodeTypeId::Document => {
self.downcast::<Document>().unwrap().GetDocumentElement().and_then(|element| { self.downcast::<Document>().unwrap().GetDocumentElement().and_then(|element| {
element.r().lookup_prefix(namespace) element.r().lookup_prefix(namespace)
@ -2376,8 +2355,7 @@ pub struct TrustedNodeAddress(pub *const c_void);
unsafe impl Send for TrustedNodeAddress {} unsafe impl Send for TrustedNodeAddress {}
pub fn document_from_node<T: DerivedFrom<Node> + Reflectable>(derived: &T) -> Root<Document> { pub fn document_from_node<T: DerivedFrom<Node> + Reflectable>(derived: &T) -> Root<Document> {
let node: &Node = derived.upcast::<Node>(); derived.upcast().owner_doc()
node.owner_doc()
} }
pub fn window_from_node<T: DerivedFrom<Node> + Reflectable>(derived: &T) -> Root<Window> { pub fn window_from_node<T: DerivedFrom<Node> + Reflectable>(derived: &T) -> Root<Window> {
@ -2387,8 +2365,7 @@ pub fn window_from_node<T: DerivedFrom<Node> + Reflectable>(derived: &T) -> Root
impl VirtualMethods for Node { impl VirtualMethods for Node {
fn super_type(&self) -> Option<&VirtualMethods> { fn super_type(&self) -> Option<&VirtualMethods> {
let eventtarget: &EventTarget = self.upcast::<EventTarget>(); Some(self.upcast::<EventTarget>() as &VirtualMethods)
Some(eventtarget as &VirtualMethods)
} }
fn children_changed(&self, mutation: &ChildrenMutation) { fn children_changed(&self, mutation: &ChildrenMutation) {

View file

@ -43,7 +43,7 @@ impl Range {
} }
pub fn new_with_doc(document: &Document) -> Root<Range> { pub fn new_with_doc(document: &Document) -> Root<Range> {
let root = document.upcast::<Node>(); let root = document.upcast();
Range::new(document, root, 0, root, 0) Range::new(document, root, 0, root, 0)
} }
@ -369,7 +369,7 @@ impl RangeMethods for Range {
let text = text.SubstringData(start_offset, end_offset - start_offset); let text = text.SubstringData(start_offset, end_offset - start_offset);
clone.downcast::<CharacterData>().unwrap().SetData(text.unwrap()); clone.downcast::<CharacterData>().unwrap().SetData(text.unwrap());
// Step 4.3. // Step 4.3.
try!(fragment.upcast::<Node>().AppendChild(clone.r())); try!(fragment.upcast::<Node>().AppendChild(&clone));
// Step 4.4 // Step 4.4
return Ok(fragment); return Ok(fragment);
} }
@ -389,12 +389,12 @@ impl RangeMethods for Range {
let text = text.SubstringData(start_offset, start_node.len() - start_offset); let text = text.SubstringData(start_offset, start_node.len() - start_offset);
clone.downcast::<CharacterData>().unwrap().SetData(text.unwrap()); clone.downcast::<CharacterData>().unwrap().SetData(text.unwrap());
// Step 13.3. // Step 13.3.
try!(fragment.upcast::<Node>().AppendChild(clone.r())); try!(fragment.upcast::<Node>().AppendChild(&clone));
} else { } else {
// Step 14.1. // Step 14.1.
let clone = child.CloneNode(false); let clone = child.CloneNode(false);
// Step 14.2. // Step 14.2.
try!(fragment.upcast::<Node>().AppendChild(clone.r())); try!(fragment.upcast::<Node>().AppendChild(&clone));
// Step 14.3. // Step 14.3.
let subrange = Range::new(clone.owner_doc().r(), let subrange = Range::new(clone.owner_doc().r(),
start_node.r(), start_node.r(),
@ -404,7 +404,7 @@ impl RangeMethods for Range {
// Step 14.4. // Step 14.4.
let subfragment = try!(subrange.CloneContents()); let subfragment = try!(subrange.CloneContents());
// Step 14.5. // Step 14.5.
try!(clone.AppendChild(subfragment.upcast::<Node>())); try!(clone.AppendChild(subfragment.upcast()));
} }
} }
@ -413,7 +413,7 @@ impl RangeMethods for Range {
// Step 15.1. // Step 15.1.
let clone = child.CloneNode(true); let clone = child.CloneNode(true);
// Step 15.2. // Step 15.2.
try!(fragment.upcast::<Node>().AppendChild(clone.r())); try!(fragment.upcast::<Node>().AppendChild(&clone));
} }
if let Some(child) = last_contained_child { if let Some(child) = last_contained_child {
@ -426,12 +426,12 @@ impl RangeMethods for Range {
let text = text.SubstringData(0, end_offset); let text = text.SubstringData(0, end_offset);
clone.downcast::<CharacterData>().unwrap().SetData(text.unwrap()); clone.downcast::<CharacterData>().unwrap().SetData(text.unwrap());
// Step 16.3. // Step 16.3.
try!(fragment.upcast::<Node>().AppendChild(clone.r())); try!(fragment.upcast::<Node>().AppendChild(&clone));
} else { } else {
// Step 17.1. // Step 17.1.
let clone = child.CloneNode(false); let clone = child.CloneNode(false);
// Step 17.2. // Step 17.2.
try!(fragment.upcast::<Node>().AppendChild(clone.r())); try!(fragment.upcast::<Node>().AppendChild(&clone));
// Step 17.3. // Step 17.3.
let subrange = Range::new(clone.owner_doc().r(), let subrange = Range::new(clone.owner_doc().r(),
child.r(), child.r(),
@ -441,7 +441,7 @@ impl RangeMethods for Range {
// Step 17.4. // Step 17.4.
let subfragment = try!(subrange.CloneContents()); let subfragment = try!(subrange.CloneContents());
// Step 17.5. // Step 17.5.
try!(clone.AppendChild(subfragment.upcast::<Node>())); try!(clone.AppendChild(subfragment.upcast()));
} }
} }
@ -477,7 +477,7 @@ impl RangeMethods for Range {
let text = end_data.SubstringData(start_offset, end_offset - start_offset); let text = end_data.SubstringData(start_offset, end_offset - start_offset);
clone.downcast::<CharacterData>().unwrap().SetData(text.unwrap()); clone.downcast::<CharacterData>().unwrap().SetData(text.unwrap());
// Step 4.3. // Step 4.3.
try!(fragment.upcast::<Node>().AppendChild(clone.r())); try!(fragment.upcast::<Node>().AppendChild(&clone));
// Step 4.4. // Step 4.4.
try!(end_data.ReplaceData(start_offset, try!(end_data.ReplaceData(start_offset,
end_offset - start_offset, end_offset - start_offset,
@ -513,7 +513,7 @@ impl RangeMethods for Range {
start_node.len() - start_offset); start_node.len() - start_offset);
clone.downcast::<CharacterData>().unwrap().SetData(text.unwrap()); clone.downcast::<CharacterData>().unwrap().SetData(text.unwrap());
// Step 15.3. // Step 15.3.
try!(fragment.upcast::<Node>().AppendChild(clone.r())); try!(fragment.upcast::<Node>().AppendChild(&clone));
// Step 15.4. // Step 15.4.
try!(start_data.ReplaceData(start_offset, try!(start_data.ReplaceData(start_offset,
start_node.len() - start_offset, start_node.len() - start_offset,
@ -522,7 +522,7 @@ impl RangeMethods for Range {
// Step 16.1. // Step 16.1.
let clone = child.CloneNode(false); let clone = child.CloneNode(false);
// Step 16.2. // Step 16.2.
try!(fragment.upcast::<Node>().AppendChild(clone.r())); try!(fragment.upcast::<Node>().AppendChild(&clone));
// Step 16.3. // Step 16.3.
let subrange = Range::new(clone.owner_doc().r(), let subrange = Range::new(clone.owner_doc().r(),
start_node.r(), start_node.r(),
@ -532,13 +532,13 @@ impl RangeMethods for Range {
// Step 16.4. // Step 16.4.
let subfragment = try!(subrange.ExtractContents()); let subfragment = try!(subrange.ExtractContents());
// Step 16.5. // Step 16.5.
try!(clone.AppendChild(subfragment.upcast::<Node>())); try!(clone.AppendChild(subfragment.upcast()));
} }
} }
// Step 17. // Step 17.
for child in contained_children { for child in contained_children {
try!(fragment.upcast::<Node>().AppendChild(child.r())); try!(fragment.upcast::<Node>().AppendChild(&child));
} }
if let Some(child) = last_contained_child { if let Some(child) = last_contained_child {
@ -550,14 +550,14 @@ impl RangeMethods for Range {
let text = end_data.SubstringData(0, end_offset); let text = end_data.SubstringData(0, end_offset);
clone.downcast::<CharacterData>().unwrap().SetData(text.unwrap()); clone.downcast::<CharacterData>().unwrap().SetData(text.unwrap());
// Step 18.3. // Step 18.3.
try!(fragment.upcast::<Node>().AppendChild(clone.r())); try!(fragment.upcast::<Node>().AppendChild(&clone));
// Step 18.4. // Step 18.4.
try!(end_data.ReplaceData(0, end_offset, "".to_owned())); try!(end_data.ReplaceData(0, end_offset, "".to_owned()));
} else { } else {
// Step 19.1. // Step 19.1.
let clone = child.CloneNode(false); let clone = child.CloneNode(false);
// Step 19.2. // Step 19.2.
try!(fragment.upcast::<Node>().AppendChild(clone.r())); try!(fragment.upcast::<Node>().AppendChild(&clone));
// Step 19.3. // Step 19.3.
let subrange = Range::new(clone.owner_doc().r(), let subrange = Range::new(clone.owner_doc().r(),
child.r(), child.r(),
@ -567,7 +567,7 @@ impl RangeMethods for Range {
// Step 19.4. // Step 19.4.
let subfragment = try!(subrange.ExtractContents()); let subfragment = try!(subrange.ExtractContents());
// Step 19.5. // Step 19.5.
try!(clone.AppendChild(subfragment.upcast::<Node>())); try!(clone.AppendChild(subfragment.upcast()));
} }
} }
@ -697,7 +697,7 @@ impl RangeMethods for Range {
try!(self.InsertNode(new_parent)); try!(self.InsertNode(new_parent));
// Step 6. // Step 6.
let _ = try!(new_parent.AppendChild(fragment.upcast::<Node>())); try!(new_parent.AppendChild(fragment.upcast()));
// Step 7. // Step 7.
self.SelectNode(new_parent) self.SelectNode(new_parent)

View file

@ -48,7 +48,7 @@ impl Sink {
NodeOrText::AppendNode(n) => n.root(), NodeOrText::AppendNode(n) => n.root(),
NodeOrText::AppendText(t) => { NodeOrText::AppendText(t) => {
let text = Text::new(t.into(), &self.document); let text = Text::new(t.into(), &self.document);
Root::upcast::<Node>(text) Root::upcast(text)
} }
} }
} }

View file

@ -11,7 +11,6 @@ use dom::bindings::js::{Root, RootedReference};
use dom::bindings::refcounted::Trusted; use dom::bindings::refcounted::Trusted;
use dom::bindings::utils::{Reflector, reflect_dom_object}; use dom::bindings::utils::{Reflector, reflect_dom_object};
use dom::event::{Event, EventBubbles, EventCancelable}; use dom::event::{Event, EventBubbles, EventCancelable};
use dom::eventtarget::EventTarget;
use dom::storageevent::StorageEvent; use dom::storageevent::StorageEvent;
use dom::urlhelper::UrlHelper; use dom::urlhelper::UrlHelper;
use ipc_channel::ipc; use ipc_channel::ipc;
@ -193,7 +192,6 @@ impl MainThreadRunnable for StorageEventRunnable {
ev_url.to_string(), ev_url.to_string(),
Some(storage) Some(storage)
); );
let event = storage_event.upcast::<Event>();
let root_page = script_task.root_page(); let root_page = script_task.root_page();
for it_page in root_page.iter() { for it_page in root_page.iter() {
@ -203,8 +201,7 @@ impl MainThreadRunnable for StorageEventRunnable {
// TODO: Such a Document object is not necessarily fully active, but events fired on such // TODO: Such a Document object is not necessarily fully active, but events fired on such
// objects are ignored by the event loop until the Document becomes fully active again. // objects are ignored by the event loop until the Document becomes fully active again.
if ev_window.pipeline() != it_window.pipeline() { if ev_window.pipeline() != it_window.pipeline() {
let target = it_window.upcast::<EventTarget>(); storage_event.upcast::<Event>().fire(it_window.upcast());
event.fire(target);
} }
} }
} }

View file

@ -63,9 +63,7 @@ impl TextMethods for Text {
let parent = node.GetParentNode(); let parent = node.GetParentNode();
if let Some(ref parent) = parent { if let Some(ref parent) = parent {
// Step 7. // Step 7.
parent.r().InsertBefore(new_node.upcast::<Node>(), parent.InsertBefore(new_node.upcast(), node.GetNextSibling().r()).unwrap();
node.GetNextSibling().r())
.unwrap();
// TODO: Ranges. // TODO: Ranges.
} }
// Step 8. // Step 8.

View file

@ -86,7 +86,7 @@ impl UIEventMethods for UIEvent {
cancelable: bool, cancelable: bool,
view: Option<&Window>, view: Option<&Window>,
detail: i32) { detail: i32) {
let event: &Event = self.upcast::<Event>(); let event = self.upcast::<Event>();
if event.dispatching() { if event.dispatching() {
return; return;
} }

View file

@ -44,8 +44,7 @@ pub fn load_script(head: &HTMLHeadElement) {
let new_script = doc.CreateElement("script".to_owned()).unwrap(); let new_script = doc.CreateElement("script".to_owned()).unwrap();
let new_script = new_script.r(); let new_script = new_script.r();
new_script.set_string_attribute(&atom!("src"), name); new_script.set_string_attribute(&atom!("src"), name);
let new_script_node = new_script.upcast::<Node>(); node.InsertBefore(new_script.upcast(), first_child.r()).unwrap();
node.InsertBefore(new_script_node, first_child.r()).unwrap();
} }
} }
} }

View file

@ -123,131 +123,97 @@ pub trait VirtualMethods {
pub fn vtable_for(node: &Node) -> &VirtualMethods { pub fn vtable_for(node: &Node) -> &VirtualMethods {
match node.type_id() { match node.type_id() {
NodeTypeId::Element(ElementTypeId::HTMLElement(HTMLElementTypeId::HTMLAnchorElement)) => { NodeTypeId::Element(ElementTypeId::HTMLElement(HTMLElementTypeId::HTMLAnchorElement)) => {
let element = node.downcast::<HTMLAnchorElement>().unwrap(); node.downcast::<HTMLAnchorElement>().unwrap() as &VirtualMethods
element as &VirtualMethods
} }
NodeTypeId::Element(ElementTypeId::HTMLElement(HTMLElementTypeId::HTMLAppletElement)) => { NodeTypeId::Element(ElementTypeId::HTMLElement(HTMLElementTypeId::HTMLAppletElement)) => {
node.downcast::<HTMLAppletElement>().unwrap() as &VirtualMethods node.downcast::<HTMLAppletElement>().unwrap() as &VirtualMethods
} }
NodeTypeId::Element(ElementTypeId::HTMLElement(HTMLElementTypeId::HTMLAreaElement)) => { NodeTypeId::Element(ElementTypeId::HTMLElement(HTMLElementTypeId::HTMLAreaElement)) => {
let element = node.downcast::<HTMLAreaElement>().unwrap(); node.downcast::<HTMLAreaElement>().unwrap() as &VirtualMethods
element as &VirtualMethods
} }
NodeTypeId::Element(ElementTypeId::HTMLElement(HTMLElementTypeId::HTMLBaseElement)) => { NodeTypeId::Element(ElementTypeId::HTMLElement(HTMLElementTypeId::HTMLBaseElement)) => {
let element = node.downcast::<HTMLBaseElement>().unwrap(); node.downcast::<HTMLBaseElement>().unwrap() as &VirtualMethods
element as &VirtualMethods
} }
NodeTypeId::Element(ElementTypeId::HTMLElement(HTMLElementTypeId::HTMLBodyElement)) => { NodeTypeId::Element(ElementTypeId::HTMLElement(HTMLElementTypeId::HTMLBodyElement)) => {
let element = node.downcast::<HTMLBodyElement>().unwrap(); node.downcast::<HTMLBodyElement>().unwrap() as &VirtualMethods
element as &VirtualMethods
} }
NodeTypeId::Element(ElementTypeId::HTMLElement(HTMLElementTypeId::HTMLButtonElement)) => { NodeTypeId::Element(ElementTypeId::HTMLElement(HTMLElementTypeId::HTMLButtonElement)) => {
let element = node.downcast::<HTMLButtonElement>().unwrap(); node.downcast::<HTMLButtonElement>().unwrap() as &VirtualMethods
element as &VirtualMethods
} }
NodeTypeId::Element(ElementTypeId::HTMLElement(HTMLElementTypeId::HTMLCanvasElement)) => { NodeTypeId::Element(ElementTypeId::HTMLElement(HTMLElementTypeId::HTMLCanvasElement)) => {
let element = node.downcast::<HTMLCanvasElement>().unwrap(); node.downcast::<HTMLCanvasElement>().unwrap() as &VirtualMethods
element as &VirtualMethods
} }
NodeTypeId::Element(ElementTypeId::HTMLElement(HTMLElementTypeId::HTMLFieldSetElement)) => { NodeTypeId::Element(ElementTypeId::HTMLElement(HTMLElementTypeId::HTMLFieldSetElement)) => {
let element = node.downcast::<HTMLFieldSetElement>().unwrap(); node.downcast::<HTMLFieldSetElement>().unwrap() as &VirtualMethods
element as &VirtualMethods
} }
NodeTypeId::Element(ElementTypeId::HTMLElement(HTMLElementTypeId::HTMLFontElement)) => { NodeTypeId::Element(ElementTypeId::HTMLElement(HTMLElementTypeId::HTMLFontElement)) => {
let element = node.downcast::<HTMLFontElement>().unwrap(); node.downcast::<HTMLFontElement>().unwrap() as &VirtualMethods
element as &VirtualMethods
} }
NodeTypeId::Element(ElementTypeId::HTMLElement(HTMLElementTypeId::HTMLFormElement)) => { NodeTypeId::Element(ElementTypeId::HTMLElement(HTMLElementTypeId::HTMLFormElement)) => {
let element = node.downcast::<HTMLFormElement>().unwrap(); node.downcast::<HTMLFormElement>().unwrap() as &VirtualMethods
element as &VirtualMethods
} }
NodeTypeId::Element(ElementTypeId::HTMLElement(HTMLElementTypeId::HTMLHeadElement)) => { NodeTypeId::Element(ElementTypeId::HTMLElement(HTMLElementTypeId::HTMLHeadElement)) => {
let element = node.downcast::<HTMLHeadElement>().unwrap(); node.downcast::<HTMLHeadElement>().unwrap() as &VirtualMethods
element as &VirtualMethods
} }
NodeTypeId::Element(ElementTypeId::HTMLElement(HTMLElementTypeId::HTMLImageElement)) => { NodeTypeId::Element(ElementTypeId::HTMLElement(HTMLElementTypeId::HTMLImageElement)) => {
let element = node.downcast::<HTMLImageElement>().unwrap(); node.downcast::<HTMLImageElement>().unwrap() as &VirtualMethods
element as &VirtualMethods
} }
NodeTypeId::Element(ElementTypeId::HTMLElement(HTMLElementTypeId::HTMLIFrameElement)) => { NodeTypeId::Element(ElementTypeId::HTMLElement(HTMLElementTypeId::HTMLIFrameElement)) => {
let element = node.downcast::<HTMLIFrameElement>().unwrap(); node.downcast::<HTMLIFrameElement>().unwrap() as &VirtualMethods
element as &VirtualMethods
} }
NodeTypeId::Element(ElementTypeId::HTMLElement(HTMLElementTypeId::HTMLInputElement)) => { NodeTypeId::Element(ElementTypeId::HTMLElement(HTMLElementTypeId::HTMLInputElement)) => {
let element = node.downcast::<HTMLInputElement>().unwrap(); node.downcast::<HTMLInputElement>().unwrap() as &VirtualMethods
element as &VirtualMethods
} }
NodeTypeId::Element(ElementTypeId::HTMLElement(HTMLElementTypeId::HTMLLinkElement)) => { NodeTypeId::Element(ElementTypeId::HTMLElement(HTMLElementTypeId::HTMLLinkElement)) => {
let element = node.downcast::<HTMLLinkElement>().unwrap(); node.downcast::<HTMLLinkElement>().unwrap() as &VirtualMethods
element as &VirtualMethods
} }
NodeTypeId::Element(ElementTypeId::HTMLElement(HTMLElementTypeId::HTMLMetaElement)) => { NodeTypeId::Element(ElementTypeId::HTMLElement(HTMLElementTypeId::HTMLMetaElement)) => {
let element = node.downcast::<HTMLMetaElement>().unwrap(); node.downcast::<HTMLMetaElement>().unwrap() as &VirtualMethods
element as &VirtualMethods
} }
NodeTypeId::Element(ElementTypeId::HTMLElement(HTMLElementTypeId::HTMLObjectElement)) => { NodeTypeId::Element(ElementTypeId::HTMLElement(HTMLElementTypeId::HTMLObjectElement)) => {
let element = node.downcast::<HTMLObjectElement>().unwrap(); node.downcast::<HTMLObjectElement>().unwrap() as &VirtualMethods
element as &VirtualMethods
} }
NodeTypeId::Element(ElementTypeId::HTMLElement(HTMLElementTypeId::HTMLOptGroupElement)) => { NodeTypeId::Element(ElementTypeId::HTMLElement(HTMLElementTypeId::HTMLOptGroupElement)) => {
let element = node.downcast::<HTMLOptGroupElement>().unwrap(); node.downcast::<HTMLOptGroupElement>().unwrap() as &VirtualMethods
element as &VirtualMethods
} }
NodeTypeId::Element(ElementTypeId::HTMLElement(HTMLElementTypeId::HTMLOptionElement)) => { NodeTypeId::Element(ElementTypeId::HTMLElement(HTMLElementTypeId::HTMLOptionElement)) => {
let element = node.downcast::<HTMLOptionElement>().unwrap(); node.downcast::<HTMLOptionElement>().unwrap() as &VirtualMethods
element as &VirtualMethods
} }
NodeTypeId::Element(ElementTypeId::HTMLElement(HTMLElementTypeId::HTMLScriptElement)) => { NodeTypeId::Element(ElementTypeId::HTMLElement(HTMLElementTypeId::HTMLScriptElement)) => {
let element = node.downcast::<HTMLScriptElement>().unwrap(); node.downcast::<HTMLScriptElement>().unwrap() as &VirtualMethods
element as &VirtualMethods
} }
NodeTypeId::Element(ElementTypeId::HTMLElement(HTMLElementTypeId::HTMLSelectElement)) => { NodeTypeId::Element(ElementTypeId::HTMLElement(HTMLElementTypeId::HTMLSelectElement)) => {
let element = node.downcast::<HTMLSelectElement>().unwrap(); node.downcast::<HTMLSelectElement>().unwrap() as &VirtualMethods
element as &VirtualMethods
} }
NodeTypeId::Element(ElementTypeId::HTMLElement(HTMLElementTypeId::HTMLStyleElement)) => { NodeTypeId::Element(ElementTypeId::HTMLElement(HTMLElementTypeId::HTMLStyleElement)) => {
let element = node.downcast::<HTMLStyleElement>().unwrap(); node.downcast::<HTMLStyleElement>().unwrap() as &VirtualMethods
element as &VirtualMethods
} }
NodeTypeId::Element(ElementTypeId::HTMLElement(HTMLElementTypeId::HTMLTableElement)) => { NodeTypeId::Element(ElementTypeId::HTMLElement(HTMLElementTypeId::HTMLTableElement)) => {
let element = node.downcast::<HTMLTableElement>().unwrap() as &VirtualMethods
node.downcast::<HTMLTableElement>().unwrap();
element as &VirtualMethods
} }
NodeTypeId::Element(ElementTypeId::HTMLElement(HTMLElementTypeId::HTMLTableCellElement(_))) => { NodeTypeId::Element(ElementTypeId::HTMLElement(HTMLElementTypeId::HTMLTableCellElement(_))) => {
let element = node.downcast::<HTMLTableCellElement>().unwrap() as &VirtualMethods
node.downcast::<HTMLTableCellElement>().unwrap();
element as &VirtualMethods
} }
NodeTypeId::Element(ElementTypeId::HTMLElement(HTMLElementTypeId::HTMLTableRowElement)) => { NodeTypeId::Element(ElementTypeId::HTMLElement(HTMLElementTypeId::HTMLTableRowElement)) => {
let element = node.downcast::<HTMLTableRowElement>().unwrap() as &VirtualMethods
node.downcast::<HTMLTableRowElement>().unwrap();
element as &VirtualMethods
} }
NodeTypeId::Element(ElementTypeId::HTMLElement(HTMLElementTypeId::HTMLTableSectionElement)) => { NodeTypeId::Element(ElementTypeId::HTMLElement(HTMLElementTypeId::HTMLTableSectionElement)) => {
let element = node.downcast::<HTMLTableSectionElement>().unwrap() as &VirtualMethods
node.downcast::<HTMLTableSectionElement>().unwrap();
element as &VirtualMethods
} }
NodeTypeId::Element(ElementTypeId::HTMLElement(HTMLElementTypeId::HTMLTemplateElement)) => { NodeTypeId::Element(ElementTypeId::HTMLElement(HTMLElementTypeId::HTMLTemplateElement)) => {
node.downcast::<HTMLTemplateElement>().unwrap() as &VirtualMethods node.downcast::<HTMLTemplateElement>().unwrap() as &VirtualMethods
} }
NodeTypeId::Element(ElementTypeId::HTMLElement(HTMLElementTypeId::HTMLTextAreaElement)) => { NodeTypeId::Element(ElementTypeId::HTMLElement(HTMLElementTypeId::HTMLTextAreaElement)) => {
let element = node.downcast::<HTMLTextAreaElement>().unwrap(); node.downcast::<HTMLTextAreaElement>().unwrap() as &VirtualMethods
element as &VirtualMethods
} }
NodeTypeId::Element(ElementTypeId::HTMLElement(HTMLElementTypeId::HTMLTitleElement)) => { NodeTypeId::Element(ElementTypeId::HTMLElement(HTMLElementTypeId::HTMLTitleElement)) => {
let element = node.downcast::<HTMLTitleElement>().unwrap() as &VirtualMethods
node.downcast::<HTMLTitleElement>().unwrap();
element as &VirtualMethods
} }
NodeTypeId::Element(ElementTypeId::Element) => { NodeTypeId::Element(ElementTypeId::Element) => {
let element = node.downcast::<Element>().unwrap(); node.downcast::<Element>().unwrap() as &VirtualMethods
element as &VirtualMethods
} }
NodeTypeId::Element(_) => { NodeTypeId::Element(_) => {
let element = node.downcast::<HTMLElement>().unwrap(); node.downcast::<HTMLElement>().unwrap() as &VirtualMethods
element as &VirtualMethods
} }
_ => { _ => {
node as &VirtualMethods node as &VirtualMethods

View file

@ -14,7 +14,6 @@ use dom::bindings::global::{GlobalField, GlobalRef};
use dom::bindings::js::{JS, LayoutJS, MutNullableHeap, Root}; use dom::bindings::js::{JS, LayoutJS, MutNullableHeap, Root};
use dom::bindings::utils::{Reflector, reflect_dom_object}; use dom::bindings::utils::{Reflector, reflect_dom_object};
use dom::event::{Event, EventBubbles, EventCancelable}; use dom::event::{Event, EventBubbles, EventCancelable};
use dom::eventtarget::EventTarget;
use dom::htmlcanvaselement::HTMLCanvasElement; use dom::htmlcanvaselement::HTMLCanvasElement;
use dom::htmlcanvaselement::utils as canvas_utils; use dom::htmlcanvaselement::utils as canvas_utils;
use dom::node::{Node, NodeDamage, window_from_node}; use dom::node::{Node, NodeDamage, window_from_node};
@ -121,7 +120,7 @@ impl WebGLRenderingContext {
EventBubbles::DoesNotBubble, EventBubbles::DoesNotBubble,
EventCancelable::Cancelable, EventCancelable::Cancelable,
msg); msg);
event.upcast::<Event>().fire(canvas.upcast::<EventTarget>()); event.upcast::<Event>().fire(canvas.upcast());
None None
} }
} }
@ -153,9 +152,7 @@ impl WebGLRenderingContext {
} }
fn mark_as_dirty(&self) { fn mark_as_dirty(&self) {
let canvas = self.canvas.root(); self.canvas.root().upcast::<Node>().dirty(NodeDamage::OtherNodeDamage);
let node = canvas.upcast::<Node>();
node.dirty(NodeDamage::OtherNodeDamage);
} }
} }

View file

@ -454,7 +454,7 @@ impl Runnable for ConnectionEstablishedTask {
let event = Event::new(global.r(), "open".to_owned(), let event = Event::new(global.r(), "open".to_owned(),
EventBubbles::DoesNotBubble, EventBubbles::DoesNotBubble,
EventCancelable::NotCancelable); EventCancelable::NotCancelable);
event.fire(ws.upcast::<EventTarget>()); event.fire(ws.upcast());
} }
} }
@ -496,8 +496,7 @@ impl Runnable for CloseTask {
"error".to_owned(), "error".to_owned(),
EventBubbles::DoesNotBubble, EventBubbles::DoesNotBubble,
EventCancelable::Cancelable); EventCancelable::Cancelable);
let target = ws.upcast::<EventTarget>(); event.fire(ws.upcast());
event.r().fire(target);
} }
let rsn = ws.reason.borrow(); let rsn = ws.reason.borrow();
let rsn_clone = rsn.clone(); let rsn_clone = rsn.clone();
@ -511,9 +510,7 @@ impl Runnable for CloseTask {
ws.clean_close.get(), ws.clean_close.get(),
ws.code.get(), ws.code.get(),
rsn_clone); rsn_clone);
let target = ws.upcast::<EventTarget>(); close_event.upcast::<Event>().fire(ws.upcast());
let event = close_event.upcast::<Event>();
event.fire(target);
} }
} }
@ -562,7 +559,6 @@ impl Runnable for MessageReceivedTask {
}, },
} }
let target = ws.upcast::<EventTarget>(); MessageEvent::dispatch_jsval(ws.upcast(), global.r(), message.handle());
MessageEvent::dispatch_jsval(target, global.r(), message.handle());
} }
} }

View file

@ -793,8 +793,7 @@ impl<'a, T: Reflectable> ScriptHelpers for &'a T {
impl Window { impl Window {
pub fn clear_js_runtime(&self) { pub fn clear_js_runtime(&self) {
let document = self.Document(); self.Document().upcast::<Node>().teardown();
document.upcast::<Node>().teardown();
// The above code may not catch all DOM objects // The above code may not catch all DOM objects
// (e.g. DOM objects removed from the tree that haven't // (e.g. DOM objects removed from the tree that haven't
@ -835,9 +834,7 @@ impl Window {
let body = self.Document().GetBody(); let body = self.Document().GetBody();
let (x, y) = match body { let (x, y) = match body {
Some(e) => { Some(e) => {
let node = e.upcast::<Node>(); let content_size = e.upcast::<Node>().get_bounding_content_box();
let content_size = node.get_bounding_content_box();
let content_height = content_size.size.height.to_f64_px(); let content_height = content_size.size.height.to_f64_px();
let content_width = content_size.size.width.to_f64_px(); let content_width = content_size.size.width.to_f64_px();
(xfinite.max(0.0f64).min(content_width - width), (xfinite.max(0.0f64).min(content_width - width),
@ -1055,7 +1052,7 @@ impl Window {
let js_runtime = js_runtime.as_ref().unwrap(); let js_runtime = js_runtime.as_ref().unwrap();
let element = response.node_address.and_then(|parent_node_address| { let element = response.node_address.and_then(|parent_node_address| {
let node = from_untrusted_node_address(js_runtime.rt(), parent_node_address); let node = from_untrusted_node_address(js_runtime.rt(), parent_node_address);
Root::downcast::<Element>(node) Root::downcast(node)
}); });
(element, response.rect) (element, response.rect)
} }

View file

@ -115,7 +115,7 @@ impl Worker {
let worker = address.root(); let worker = address.root();
let global = worker.r().global.root(); let global = worker.r().global.root();
let target = worker.upcast::<EventTarget>(); let target = worker.upcast();
let _ar = JSAutoRequest::new(global.r().get_cx()); let _ar = JSAutoRequest::new(global.r().get_cx());
let _ac = JSAutoCompartment::new(global.r().get_cx(), target.reflector().get_jsobject().get()); let _ac = JSAutoCompartment::new(global.r().get_cx(), target.reflector().get_jsobject().get());
let mut message = RootedValue::new(global.r().get_cx(), UndefinedValue()); let mut message = RootedValue::new(global.r().get_cx(), UndefinedValue());
@ -126,13 +126,11 @@ impl Worker {
pub fn dispatch_simple_error(address: TrustedWorkerAddress) { pub fn dispatch_simple_error(address: TrustedWorkerAddress) {
let worker = address.root(); let worker = address.root();
let global = worker.r().global.root(); let global = worker.r().global.root();
let target = worker.upcast::<EventTarget>();
let event = Event::new(global.r(), let event = Event::new(global.r(),
"error".to_owned(), "error".to_owned(),
EventBubbles::DoesNotBubble, EventBubbles::DoesNotBubble,
EventCancelable::NotCancelable); EventCancelable::NotCancelable);
event.r().fire(target); event.fire(worker.upcast());
} }
pub fn handle_error_message(address: TrustedWorkerAddress, message: DOMString, pub fn handle_error_message(address: TrustedWorkerAddress, message: DOMString,
@ -140,12 +138,10 @@ impl Worker {
let worker = address.root(); let worker = address.root();
let global = worker.r().global.root(); let global = worker.r().global.root();
let error = RootedValue::new(global.r().get_cx(), UndefinedValue()); let error = RootedValue::new(global.r().get_cx(), UndefinedValue());
let target = worker.upcast::<EventTarget>();
let errorevent = ErrorEvent::new(global.r(), "error".to_owned(), let errorevent = ErrorEvent::new(global.r(), "error".to_owned(),
EventBubbles::Bubbles, EventCancelable::Cancelable, EventBubbles::Bubbles, EventCancelable::Cancelable,
message, filename, lineno, colno, error.handle()); message, filename, lineno, colno, error.handle());
let event = errorevent.upcast::<Event>(); errorevent.upcast::<Event>().fire(worker.upcast());
event.fire(target);
} }
} }

View file

@ -737,8 +737,7 @@ impl XMLHttpRequest {
"readystatechange".to_owned(), "readystatechange".to_owned(),
EventBubbles::DoesNotBubble, EventBubbles::DoesNotBubble,
EventCancelable::Cancelable); EventCancelable::Cancelable);
let target = self.upcast::<EventTarget>(); event.fire(self.upcast());
event.r().fire(target);
} }
fn process_headers_available(&self, cors_request: Option<CORSRequest>, fn process_headers_available(&self, cors_request: Option<CORSRequest>,
@ -921,12 +920,11 @@ impl XMLHttpRequest {
total.is_some(), loaded, total.is_some(), loaded,
total.unwrap_or(0)); total.unwrap_or(0));
let target = if upload { let target = if upload {
self.upload.upcast::<EventTarget>() self.upload.upcast()
} else { } else {
self.upcast::<EventTarget>() self.upcast()
}; };
let event = progressevent.upcast::<Event>(); progressevent.upcast::<Event>().fire(target);
event.fire(target);
} }
fn dispatch_upload_progress_event(&self, type_: DOMString, partial_load: Option<u64>) { fn dispatch_upload_progress_event(&self, type_: DOMString, partial_load: Option<u64>) {

View file

@ -45,16 +45,14 @@ impl<'a> TreeSink for servohtmlparser::Sink {
type Handle = JS<Node>; type Handle = JS<Node>;
fn get_document(&mut self) -> JS<Node> { fn get_document(&mut self) -> JS<Node> {
let doc = self.document.root(); JS::from_ref(self.document.root().upcast())
let node = doc.upcast::<Node>();
JS::from_ref(node)
} }
fn get_template_contents(&self, target: JS<Node>) -> JS<Node> { fn get_template_contents(&self, target: JS<Node>) -> JS<Node> {
let target = target.root(); let target = target.root();
let template = target.downcast::<HTMLTemplateElement>() let template = target.downcast::<HTMLTemplateElement>()
.expect("tried to get template contents of non-HTMLTemplateElement in HTML parsing"); .expect("tried to get template contents of non-HTMLTemplateElement in HTML parsing");
JS::from_ref(template.Content().upcast::<Node>()) JS::from_ref(template.Content().upcast())
} }
fn same_node(&self, x: JS<Node>, y: JS<Node>) -> bool { fn same_node(&self, x: JS<Node>, y: JS<Node>) -> bool {
@ -81,15 +79,13 @@ impl<'a> TreeSink for servohtmlparser::Sink {
elem.r().set_attribute_from_parser(attr.name, attr.value.into(), None); elem.r().set_attribute_from_parser(attr.name, attr.value.into(), None);
} }
let node = elem.upcast::<Node>(); JS::from_ref(elem.upcast())
JS::from_ref(node)
} }
fn create_comment(&mut self, text: StrTendril) -> JS<Node> { fn create_comment(&mut self, text: StrTendril) -> JS<Node> {
let doc = self.document.root(); let doc = self.document.root();
let comment = Comment::new(text.into(), doc.r()); let comment = Comment::new(text.into(), doc.r());
let node = Root::upcast::<Node>(comment); JS::from_ref(comment.upcast())
JS::from_rooted(&node)
} }
fn append_before_sibling(&mut self, fn append_before_sibling(&mut self,
@ -127,12 +123,9 @@ impl<'a> TreeSink for servohtmlparser::Sink {
fn append_doctype_to_document(&mut self, name: StrTendril, public_id: StrTendril, fn append_doctype_to_document(&mut self, name: StrTendril, public_id: StrTendril,
system_id: StrTendril) { system_id: StrTendril) {
let doc = self.document.root(); let doc = self.document.root();
let doc_node = doc.upcast::<Node>();
let doctype = DocumentType::new( let doctype = DocumentType::new(
name.into(), Some(public_id.into()), Some(system_id.into()), doc.r()); name.into(), Some(public_id.into()), Some(system_id.into()), doc.r());
let node: Root<Node> = Root::upcast::<Node>(doctype); doc.upcast::<Node>().AppendChild(doctype.upcast()).expect("Appending failed");
assert!(doc_node.AppendChild(node.r()).is_ok());
} }
fn add_attrs_if_missing(&mut self, target: JS<Node>, attrs: Vec<Attribute>) { fn add_attrs_if_missing(&mut self, target: JS<Node>, attrs: Vec<Attribute>) {
@ -153,13 +146,13 @@ impl<'a> TreeSink for servohtmlparser::Sink {
fn mark_script_already_started(&mut self, node: JS<Node>) { fn mark_script_already_started(&mut self, node: JS<Node>) {
let node: Root<Node> = node.root(); let node: Root<Node> = node.root();
let script: Option<&HTMLScriptElement> = node.downcast::<HTMLScriptElement>(); let script = node.downcast::<HTMLScriptElement>();
script.map(|script| script.mark_already_started()); script.map(|script| script.mark_already_started());
} }
fn complete_script(&mut self, node: JS<Node>) -> NextParserState { fn complete_script(&mut self, node: JS<Node>) -> NextParserState {
let node: Root<Node> = node.root(); let node: Root<Node> = node.root();
let script: Option<&HTMLScriptElement> = node.downcast::<HTMLScriptElement>(); let script = node.downcast::<HTMLScriptElement>();
if let Some(script) = script { if let Some(script) = script {
return script.prepare(); return script.prepare();
} }
@ -305,8 +298,7 @@ pub fn parse_html_fragment(context_node: &Node,
// Step 14. // Step 14.
let root_element = document.r().GetDocumentElement().expect("no document element"); let root_element = document.r().GetDocumentElement().expect("no document element");
let root_node = root_element.upcast::<Node>(); for child in root_element.upcast::<Node>().children() {
for child in root_node.children() {
output.AppendChild(child.r()).unwrap(); output.AppendChild(child.r()).unwrap();
} }
} }

View file

@ -34,7 +34,6 @@ use dom::document::{Document, DocumentProgressHandler, IsHTMLDocument};
use dom::document::{DocumentProgressTask, DocumentSource, MouseEventType}; use dom::document::{DocumentProgressTask, DocumentSource, MouseEventType};
use dom::element::Element; use dom::element::Element;
use dom::event::{Event, EventBubbles, EventCancelable}; use dom::event::{Event, EventBubbles, EventCancelable};
use dom::eventtarget::EventTarget;
use dom::node::{Node, NodeDamage, window_from_node}; use dom::node::{Node, NodeDamage, window_from_node};
use dom::servohtmlparser::{ParserContext, ServoHTMLParser}; use dom::servohtmlparser::{ParserContext, ServoHTMLParser};
use dom::uievent::UIEvent; use dom::uievent::UIEvent;
@ -1256,12 +1255,10 @@ impl ScriptTask {
urls.push(current_url.clone()); urls.push(current_url.clone());
for child in it_page.document().upcast::<Node>().traverse_preorder() { for child in it_page.document().upcast::<Node>().traverse_preorder() {
let target = child.upcast::<EventTarget>(); dom_tree_size += heap_size_of_self_and_children(&*child);
dom_tree_size += heap_size_of_self_and_children(target);
} }
let window = it_page.window(); let window = it_page.window();
let target = window.upcast::<EventTarget>(); dom_tree_size += heap_size_of_self_and_children(&*window);
dom_tree_size += heap_size_of_self_and_children(target);
reports.push(Report { reports.push(Report {
path: path![format!("url({})", current_url), "dom-tree"], path: path![format!("url({})", current_url), "dom-tree"],
@ -1323,9 +1320,8 @@ impl ScriptTask {
let frame_element = doc.find_iframe(subpage_id); let frame_element = doc.find_iframe(subpage_id);
if let Some(ref frame_element) = frame_element { if let Some(ref frame_element) = frame_element {
let element = frame_element.upcast::<Element>();
doc.r().begin_focus_transaction(); doc.r().begin_focus_transaction();
doc.r().request_focus(element); doc.r().request_focus(frame_element.upcast());
doc.r().commit_focus_transaction(FocusType::Parent); doc.r().commit_focus_transaction(FocusType::Parent);
} }
} }
@ -1625,7 +1621,7 @@ impl ScriptTask {
DocumentSource::FromParser, DocumentSource::FromParser,
loader); loader);
let frame_element = frame_element.r().map(Castable::upcast::<Element>); let frame_element = frame_element.r().map(Castable::upcast);
window.r().init_browsing_context(document.r(), frame_element); window.r().init_browsing_context(document.r(), frame_element);
// Create the root frame // Create the root frame
@ -1671,9 +1667,8 @@ impl ScriptTask {
} }
} }
fn scroll_fragment_point(&self, pipeline_id: PipelineId, node: &Element) { fn scroll_fragment_point(&self, pipeline_id: PipelineId, element: &Element) {
let node = node.upcast::<Node>(); let rect = element.upcast::<Node>().get_bounding_content_box();
let rect = node.get_bounding_content_box();
let point = Point2D::new(rect.origin.x.to_f32_px(), rect.origin.y.to_f32_px()); let point = Point2D::new(rect.origin.x.to_f32_px(), rect.origin.y.to_f32_px());
// FIXME(#2003, pcwalton): This is pretty bogus when multiple layers are involved. // FIXME(#2003, pcwalton): This is pretty bogus when multiple layers are involved.
// Really what needs to happen is that this needs to go through layout to ask which // Really what needs to happen is that this needs to go through layout to ask which
@ -1844,10 +1839,7 @@ impl ScriptTask {
"resize".to_owned(), EventBubbles::DoesNotBubble, "resize".to_owned(), EventBubbles::DoesNotBubble,
EventCancelable::NotCancelable, Some(window.r()), EventCancelable::NotCancelable, Some(window.r()),
0i32); 0i32);
let event = uievent.upcast::<Event>(); uievent.upcast::<Event>().fire(window.upcast());
let wintarget = window.upcast::<EventTarget>();
event.fire(wintarget);
} }
/// Initiate a non-blocking fetch for a specified resource. Stores the InProgressLoad /// Initiate a non-blocking fetch for a specified resource. Stores the InProgressLoad
@ -1905,7 +1897,7 @@ impl ScriptTask {
// 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.r().disarm_reflow_timeout(); document.r().disarm_reflow_timeout();
document.r().content_changed(document.upcast::<Node>(), document.r().content_changed(document.upcast(),
NodeDamage::OtherNodeDamage); NodeDamage::OtherNodeDamage);
let window = window_from_node(document.r()); let window = window_from_node(document.r());
window.r().reflow(ReflowGoal::ForDisplay, ReflowQueryType::NoQuery, ReflowReason::FirstLoad); window.r().reflow(ReflowGoal::ForDisplay, ReflowQueryType::NoQuery, ReflowReason::FirstLoad);

View file

@ -116,8 +116,7 @@ pub fn handle_find_element_css(page: &Rc<Page>, _pipeline: PipelineId, selector:
reply: IpcSender<Result<Option<String>, ()>>) { reply: IpcSender<Result<Option<String>, ()>>) {
reply.send(match page.document().r().QuerySelector(selector.clone()) { reply.send(match page.document().r().QuerySelector(selector.clone()) {
Ok(node) => { Ok(node) => {
let result = node.map(|x| x.upcast::<Node>().get_unique_id()); Ok(node.map(|x| x.upcast::<Node>().get_unique_id()))
Ok(result)
} }
Err(_) => Err(()) Err(_) => Err(())
}).unwrap(); }).unwrap();
@ -172,8 +171,7 @@ pub fn handle_get_name(page: &Rc<Page>,
reply: IpcSender<Result<String, ()>>) { reply: IpcSender<Result<String, ()>>) {
reply.send(match find_node_by_unique_id(&*page, pipeline, node_id) { reply.send(match find_node_by_unique_id(&*page, pipeline, node_id) {
Some(node) => { Some(node) => {
let element = node.downcast::<Element>().unwrap(); Ok(node.downcast::<Element>().unwrap().TagName())
Ok(element.TagName())
}, },
None => Err(()) None => Err(())
}).unwrap(); }).unwrap();