Generate bindings for Node, CharacterData, Text, Element, and HTMLElement. Hook up text nodes to use the new bindings.

This commit is contained in:
Josh Matthews 2013-07-28 11:43:24 -04:00
parent c9bc2046f6
commit fd4efad70c
20 changed files with 1069 additions and 62 deletions

View file

@ -114,6 +114,12 @@ DOMInterfaces = {
} }
}], }],
'CharacterData': {
'nativeType': 'AbstractNode<ScriptView>',
'concreteType': 'CharacterData',
'pointerType': ''
},
'ClientRect': [ 'ClientRect': [
{ {
'nativeType': 'ClientRect', 'nativeType': 'ClientRect',
@ -161,6 +167,11 @@ DOMInterfaces = {
} }
}], }],
'Element': {
'nativeType': 'AbstractNode<ScriptView>',
'pointerType': ''
},
'Event': { 'Event': {
}, },
@ -218,6 +229,11 @@ DOMInterfaces = {
'pointerType': '', 'pointerType': '',
}, },
'HTMLElement': {
'nativeType': 'AbstractNode<ScriptView>',
'pointerType': ''
},
'HTMLOptionsCollection': [ 'HTMLOptionsCollection': [
{ {
'nativeType': 'nsHTMLOptionCollection', 'nativeType': 'nsHTMLOptionCollection',
@ -266,6 +282,12 @@ DOMInterfaces = {
'MouseEvent': { 'MouseEvent': {
}, },
'Node': {
'nativeType': 'AbstractNode<ScriptView>',
'concreteType': 'Node<ScriptView>',
'pointerType': ''
},
'NodeList': [ 'NodeList': [
{ {
'nativeType': 'nsINodeList', 'nativeType': 'nsINodeList',
@ -343,6 +365,12 @@ DOMInterfaces = {
'resultNotAddRefed': [ 'getItem' ] 'resultNotAddRefed': [ 'getItem' ]
}], }],
'Text': {
'nativeType': 'AbstractNode<ScriptView>',
'concreteType': 'Text',
'pointerType': ''
},
'UIEvent': { 'UIEvent': {
}, },
@ -533,13 +561,13 @@ addExternalIface('CSSRule')
addExternalIface('CSSValue') addExternalIface('CSSValue')
addExternalIface('DOMStringList', nativeType='nsDOMStringList', addExternalIface('DOMStringList', nativeType='nsDOMStringList',
headerFile='nsDOMLists.h') headerFile='nsDOMLists.h')
addExternalIface('Element', nativeType='AbstractNode<ScriptView>', pointerType='') #addExternalIface('Element', nativeType='AbstractNode<ScriptView>', pointerType='')
addExternalIface('File') addExternalIface('File')
addExternalIface('HitRegionOptions', nativeType='nsISupports') addExternalIface('HitRegionOptions', nativeType='nsISupports')
addExternalIface('HTMLElement', nativeType='AbstractNode<ScriptView>', pointerType='') #addExternalIface('HTMLElement', nativeType='AbstractNode<ScriptView>', pointerType='')
addExternalIface('HTMLHeadElement', nativeType='AbstractNode<ScriptView>', pointerType='') addExternalIface('HTMLHeadElement', nativeType='AbstractNode<ScriptView>', pointerType='')
addExternalIface('ImageData', nativeType='mozilla::dom::ImageData') addExternalIface('ImageData', nativeType='mozilla::dom::ImageData')
addExternalIface('Node', nativeType='AbstractNode<ScriptView>', pointerType='') #addExternalIface('Node', nativeType='AbstractNode<ScriptView>', pointerType='')
addExternalIface('PaintRequest') addExternalIface('PaintRequest')
addExternalIface('SVGLength') addExternalIface('SVGLength')
addExternalIface('SVGMatrix') addExternalIface('SVGMatrix')

View file

@ -0,0 +1,28 @@
/* -*- Mode: IDL; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this file,
* You can obtain one at http://mozilla.org/MPL/2.0/.
*
* The origin of this IDL file is
* http://dom.spec.whatwg.org/#characterdata
*
* Copyright © 2012 W3C® (MIT, ERCIM, Keio), All Rights Reserved. W3C
* liability, trademark and document use rules apply.
*/
interface CharacterData : Node {
[TreatNullAs=EmptyString,SetterThrows] attribute DOMString data;
readonly attribute unsigned long length;
[Throws]
DOMString substringData(unsigned long offset, unsigned long count);
[Throws]
void appendData(DOMString data);
[Throws]
void insertData(unsigned long offset, DOMString data);
[Throws]
void deleteData(unsigned long offset, unsigned long count);
[Throws]
void replaceData(unsigned long offset, unsigned long count, DOMString data);
};
//CharacterData implements ChildNode;

View file

@ -1453,7 +1453,7 @@ def getWrapTemplateForType(type, descriptorProvider, result, successCode,
if not haveSuccessCode: if not haveSuccessCode:
return wrapCall + ";\n" + "return if (*vp).v != 0 { 1 } else { 0 };" return wrapCall + ";\n" + "return if (*vp).v != 0 { 1 } else { 0 };"
failureCode = "return 0;" failureCode = "return 0;"
str = ("if !%s {\n" + str = ("if !(%s as bool) {\n" +
CGIndenter(CGGeneric(failureCode)).define() + "\n" + CGIndenter(CGGeneric(failureCode)).define() + "\n" +
"}\n" + "}\n" +
successCode) % (wrapCall) successCode) % (wrapCall)
@ -1522,12 +1522,10 @@ for (uint32_t i = 0; i < length; ++i) {
if not isCreator: if not isCreator:
raise MethodNotCreatorError(descriptor.interface.identifier.name) raise MethodNotCreatorError(descriptor.interface.identifier.name)
wrapMethod = "WrapNewBindingNonWrapperCachedObject" wrapMethod = "WrapNewBindingNonWrapperCachedObject"
properResult = result
if descriptor.pointerType == '': if descriptor.pointerType == '':
properResult = result + ".as_cacheable_wrapper()" wrap = "%s.wrap(cx, ${obj}, ${jsvalPtr} as *mut JSVal)" % result
else: else:
properResult += " as @mut CacheableWrapper" wrap = "%s(cx, ${obj}, %s as @mut CacheableWrapper, ${jsvalPtr} as *mut JSVal)" % (wrapMethod, result)
wrap = "%s(cx, ${obj}, %s, ${jsvalPtr} as *mut JSVal)" % (wrapMethod, properResult)
# We don't support prefable stuff in workers. # We don't support prefable stuff in workers.
assert(not descriptor.prefable or not descriptor.workers) assert(not descriptor.prefable or not descriptor.workers)
if not descriptor.prefable: if not descriptor.prefable:
@ -2476,7 +2474,7 @@ class CGWrapWithCacheMethod(CGAbstractMethod):
def __init__(self, descriptor): def __init__(self, descriptor):
assert descriptor.interface.hasInterfacePrototypeObject() assert descriptor.interface.hasInterfacePrototypeObject()
args = [Argument('*JSContext', 'aCx'), Argument('*JSObject', 'aScope'), args = [Argument('*JSContext', 'aCx'), Argument('*JSObject', 'aScope'),
Argument('@mut ' + descriptor.name, 'aObject'), Argument('@mut ' + descriptor.concreteType, 'aObject'),
Argument('*mut bool', 'aTriedToWrap')] Argument('*mut bool', 'aTriedToWrap')]
CGAbstractMethod.__init__(self, descriptor, 'Wrap_', '*JSObject', args) CGAbstractMethod.__init__(self, descriptor, 'Wrap_', '*JSObject', args)
@ -2513,7 +2511,8 @@ class CGWrapMethod(CGAbstractMethod):
# XXX can we wrap if we don't have an interface prototype object? # XXX can we wrap if we don't have an interface prototype object?
assert descriptor.interface.hasInterfacePrototypeObject() assert descriptor.interface.hasInterfacePrototypeObject()
args = [Argument('*JSContext', 'aCx'), Argument('*JSObject', 'aScope'), args = [Argument('*JSContext', 'aCx'), Argument('*JSObject', 'aScope'),
Argument('@mut ' + descriptor.name, 'aObject'), Argument('*mut bool', 'aTriedToWrap')] Argument('@mut ' + descriptor.concreteType, 'aObject'),
Argument('*mut bool', 'aTriedToWrap')]
CGAbstractMethod.__init__(self, descriptor, 'Wrap', '*JSObject', args, inline=True, pub=True) CGAbstractMethod.__init__(self, descriptor, 'Wrap', '*JSObject', args, inline=True, pub=True)
def definition_body(self): def definition_body(self):
@ -3161,7 +3160,7 @@ class CGAbstractBindingMethod(CGAbstractExternMethod):
" return false as JSBool;\n" " return false as JSBool;\n"
"}\n" "}\n"
"\n" "\n"
"let this: *rust_box<%s>;" % self.descriptor.name)) "let this: *rust_box<%s>;" % self.descriptor.concreteType))
def generate_code(self): def generate_code(self):
assert(False) # Override me assert(False) # Override me
@ -3201,7 +3200,7 @@ class CGSpecializedMethod(CGAbstractExternMethod):
self.method = method self.method = method
name = method.identifier.name name = method.identifier.name
args = [Argument('*JSContext', 'cx'), Argument('JSHandleObject', 'obj'), args = [Argument('*JSContext', 'cx'), Argument('JSHandleObject', 'obj'),
Argument('*mut %s' % descriptor.name, 'this'), Argument('*mut %s' % descriptor.concreteType, 'this'),
Argument('libc::c_uint', 'argc'), Argument('*mut JSVal', 'vp')] Argument('libc::c_uint', 'argc'), Argument('*mut JSVal', 'vp')]
CGAbstractExternMethod.__init__(self, descriptor, name, 'JSBool', args) CGAbstractExternMethod.__init__(self, descriptor, name, 'JSBool', args)
@ -3246,7 +3245,7 @@ class CGSpecializedGetter(CGAbstractExternMethod):
name = 'get_' + attr.identifier.name name = 'get_' + attr.identifier.name
args = [ Argument('*JSContext', 'cx'), args = [ Argument('*JSContext', 'cx'),
Argument('JSHandleObject', 'obj'), Argument('JSHandleObject', 'obj'),
Argument('*%s' % descriptor.name, 'this'), Argument('*%s' % descriptor.concreteType, 'this'),
Argument('*mut JSVal', 'vp') ] Argument('*mut JSVal', 'vp') ]
CGAbstractExternMethod.__init__(self, descriptor, name, "JSBool", args) CGAbstractExternMethod.__init__(self, descriptor, name, "JSBool", args)
@ -3305,7 +3304,7 @@ class CGSpecializedSetter(CGAbstractExternMethod):
name = 'set_' + attr.identifier.name name = 'set_' + attr.identifier.name
args = [ Argument('*JSContext', 'cx'), args = [ Argument('*JSContext', 'cx'),
Argument('JSHandleObject', 'obj'), Argument('JSHandleObject', 'obj'),
Argument('*mut %s' % descriptor.name, 'this'), Argument('*mut %s' % descriptor.concreteType, 'this'),
Argument('*mut JSVal', 'argv')] Argument('*mut JSVal', 'argv')]
CGAbstractExternMethod.__init__(self, descriptor, name, "JSBool", args) CGAbstractExternMethod.__init__(self, descriptor, name, "JSBool", args)
@ -3968,7 +3967,7 @@ def finalizeHook(descriptor, hookName, context):
assert descriptor.nativeIsISupports assert descriptor.nativeIsISupports
release = """let val = JS_GetReservedSlot(obj, 0); release = """let val = JS_GetReservedSlot(obj, 0);
let _: @mut %s = cast::transmute(RUST_JSVAL_TO_PRIVATE(val)); let _: @mut %s = cast::transmute(RUST_JSVAL_TO_PRIVATE(val));
""" % descriptor.name """ % descriptor.concreteType
#return clearWrapper + release #return clearWrapper + release
return release return release
@ -4603,8 +4602,11 @@ class CGBindingRoot(CGThing):
'js::jsapi::*', 'js::jsapi::*',
'js::jsfriendapi::bindgen::*', 'js::jsfriendapi::bindgen::*',
'js::glue::*', 'js::glue::*',
'dom::node::AbstractNode', #XXXjdm 'dom::characterdata::CharacterData', #XXXjdm
'dom::node::{AbstractNode, Node, Text}', #XXXjdm
'dom::document::{Document, AbstractDocument}', #XXXjdm 'dom::document::{Document, AbstractDocument}', #XXXjdm
'dom::element::Element', #XXXjdm
'dom::htmlelement::HTMLElement', #XXXjdm
'dom::htmldocument::HTMLDocument', #XXXjdm 'dom::htmldocument::HTMLDocument', #XXXjdm
'dom::bindings::utils::*', 'dom::bindings::utils::*',
'dom::bindings::conversions::*', 'dom::bindings::conversions::*',

View file

@ -0,0 +1,189 @@
/* -*- Mode: IDL; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this file,
* You can obtain one at http://mozilla.org/MPL/2.0/.
*
* The origin of this IDL file is
* http://dom.spec.whatwg.org/#element and
* http://domparsing.spec.whatwg.org/ and
* http://dev.w3.org/csswg/cssom-view/ and
* http://www.w3.org/TR/selectors-api/
*
* Copyright © 2012 W3C® (MIT, ERCIM, Keio), All Rights Reserved. W3C
* liability, trademark and document use rules apply.
*/
interface Element : Node {
/*
We haven't moved these from Node to Element like the spec wants.
[Throws]
readonly attribute DOMString? namespaceURI;
readonly attribute DOMString? prefix;
readonly attribute DOMString localName;
*/
// Not [Constant] because it depends on which document we're in
[Pure]
readonly attribute DOMString tagName;
[Pure]
attribute DOMString id;
/*
FIXME Bug 810677 Move className from HTMLElement to Element
attribute DOMString className;
*/
/*[Constant]
readonly attribute DOMTokenList? classList;*/
/*[Constant]
readonly attribute MozNamedAttrMap attributes;*/
DOMString? getAttribute(DOMString name);
DOMString? getAttributeNS(DOMString? namespace, DOMString localName);
[Throws]
void setAttribute(DOMString name, DOMString value);
[Throws]
void setAttributeNS(DOMString? namespace, DOMString name, DOMString value);
[Throws]
void removeAttribute(DOMString name);
[Throws]
void removeAttributeNS(DOMString? namespace, DOMString localName);
boolean hasAttribute(DOMString name);
boolean hasAttributeNS(DOMString? namespace, DOMString localName);
HTMLCollection getElementsByTagName(DOMString localName);
[Throws]
HTMLCollection getElementsByTagNameNS(DOMString? namespace, DOMString localName);
HTMLCollection getElementsByClassName(DOMString classNames);
/**
* The ratio of font-size-inflated text font size to computed font
* size for this element. This will query the element for its primary frame,
* and then use this to get font size inflation information about the frame.
* This will be 1.0 if font size inflation is not enabled, and -1.0 if an
* error occurred during the retrieval of the font size inflation.
*
* @note The font size inflation ratio that is returned is actually the
* font size inflation data for the element's _primary frame_, not the
* element itself, but for most purposes, this should be sufficient.
*/
/*[ChromeOnly]
readonly attribute float fontSizeInflation;*/
// Mozilla specific stuff
/*[SetterThrows,LenientThis]
attribute EventHandler onmouseenter;
[SetterThrows,LenientThis]
attribute EventHandler onmouseleave;
[SetterThrows]
attribute EventHandler onwheel;*/
// Selectors API
/**
* Returns whether this element would be selected by the given selector
* string.
*
* See <http://dev.w3.org/2006/webapi/selectors-api2/#matchesselector>
*/
[Throws]
boolean mozMatchesSelector(DOMString selector);
// Proprietary extensions
/**
* Set this during a mousedown event to grab and retarget all mouse events
* to this element until the mouse button is released or releaseCapture is
* called. If retargetToElement is true, then all events are targetted at
* this element. If false, events can also fire at descendants of this
* element.
*
*/
void setCapture(optional boolean retargetToElement = false);
/**
* If this element has captured the mouse, release the capture. If another
* element has captured the mouse, this method has no effect.
*/
void releaseCapture();
// Mozilla extensions
/**
* Requests that this element be made the full-screen element, as per the DOM
* full-screen api.
*
* @see <https://wiki.mozilla.org/index.php?title=Gecko:FullScreenAPI>
*/
void mozRequestFullScreen();
/**
* Requests that this element be made the pointer-locked element, as per the DOM
* pointer lock api.
*
* @see <http://dvcs.w3.org/hg/pointerlock/raw-file/default/index.html>
*/
void mozRequestPointerLock();
// Obsolete methods.
/*Attr? getAttributeNode(DOMString name);
[Throws]
Attr? setAttributeNode(Attr newAttr);
[Throws]
Attr? removeAttributeNode(Attr oldAttr);
Attr? getAttributeNodeNS(DOMString? namespaceURI, DOMString localName);
[Throws]
Attr? setAttributeNodeNS(Attr newAttr);*/
};
// http://dev.w3.org/csswg/cssom-view/#extensions-to-the-element-interface
partial interface Element {
ClientRectList getClientRects();
ClientRect getBoundingClientRect();
// scrolling
void scrollIntoView(optional boolean top = true);
// None of the CSSOM attributes are [Pure], because they flush
attribute long scrollTop; // scroll on setting
attribute long scrollLeft; // scroll on setting
readonly attribute long scrollWidth;
readonly attribute long scrollHeight;
readonly attribute long clientTop;
readonly attribute long clientLeft;
readonly attribute long clientWidth;
readonly attribute long clientHeight;
// Mozilla specific stuff
/* The maximum offset that the element can be scrolled to
(i.e., the value that scrollLeft/scrollTop would be clamped to if they were
set to arbitrarily large values. */
/*readonly attribute long scrollTopMax;
readonly attribute long scrollLeftMax;*/
};
// http://dvcs.w3.org/hg/undomanager/raw-file/tip/undomanager.html
/*partial interface Element {
[Pref="dom.undo_manager.enabled"]
readonly attribute UndoManager? undoManager;
[SetterThrows,Pref="dom.undo_manager.enabled"]
attribute boolean undoScope;
};*/
// http://domparsing.spec.whatwg.org/#extensions-to-the-element-interface
partial interface Element {
[Throws,TreatNullAs=EmptyString]
attribute DOMString innerHTML;
[Throws,TreatNullAs=EmptyString]
attribute DOMString outerHTML;
[Throws]
void insertAdjacentHTML(DOMString position, DOMString text);
};
// http://www.w3.org/TR/selectors-api/#interface-definitions
partial interface Element {
[Throws]
Element? querySelector(DOMString selectors);
/*[Throws]
NodeList querySelectorAll(DOMString selectors);*/
};
/*Element implements ChildNode;
Element implements ParentNode;*/

View file

@ -5,7 +5,6 @@
*/ */
interface Selection; interface Selection;
interface HTMLElement;
interface HTMLHeadElement; interface HTMLHeadElement;
[OverrideBuiltins] [OverrideBuiltins]

View file

@ -0,0 +1,118 @@
/* -*- Mode: IDL; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this file,
* You can obtain one at http://mozilla.org/MPL/2.0/.
*
* The origin of this IDL file is
* http://www.whatwg.org/specs/web-apps/current-work/ and
* http://dev.w3.org/csswg/cssom-view/
*
* © Copyright 2004-2011 Apple Computer, Inc., Mozilla Foundation, and
* Opera Software ASA. You are granted a license to use, reproduce
* and create derivative works of this document.
*/
interface HTMLElement : Element {
// metadata attributes
attribute DOMString title;
attribute DOMString lang;
// attribute boolean translate;
[SetterThrows, Pure]
attribute DOMString dir;
/*[Constant]
readonly attribute DOMStringMap dataset;*/
// microdata
/*[SetterThrows, Pure]
attribute boolean itemScope;
[PutForwards=value,Constant] readonly attribute DOMSettableTokenList itemType;
[SetterThrows, Pure]
attribute DOMString itemId;
[PutForwards=value,Constant] readonly attribute DOMSettableTokenList itemRef;
[PutForwards=value,Constant] readonly attribute DOMSettableTokenList itemProp;*/
/*[Constant]
readonly attribute HTMLPropertiesCollection properties;*/
[Throws]
attribute any itemValue;
// user interaction
[SetterThrows, Pure]
attribute boolean hidden;
void click();
[SetterThrows, Pure]
attribute long tabIndex;
[Throws]
void focus();
[Throws]
void blur();
[SetterThrows, Pure]
attribute DOMString accessKey;
[Pure]
readonly attribute DOMString accessKeyLabel;
[SetterThrows, Pure]
attribute boolean draggable;
//[PutForwards=value] readonly attribute DOMSettableTokenList dropzone;
[SetterThrows, Pure]
attribute DOMString contentEditable;
[Pure]
readonly attribute boolean isContentEditable;
/*[Pure]
readonly attribute HTMLMenuElement? contextMenu;*/
//[SetterThrows]
// attribute HTMLMenuElement? contextMenu;
[SetterThrows, Pure]
attribute boolean spellcheck;
// command API
//readonly attribute DOMString? commandType;
//readonly attribute DOMString? commandLabel;
//readonly attribute DOMString? commandIcon;
//readonly attribute boolean? commandHidden;
//readonly attribute boolean? commandDisabled;
//readonly attribute boolean? commandChecked;
// styling
/*[PutForwards=cssText, Constant]
readonly attribute CSSStyleDeclaration style;*/
// Mozilla specific stuff
// FIXME Bug 810677 Move className from HTMLElement to Element
attribute DOMString className;
/*[SetterThrows]
attribute EventHandler oncopy;
[SetterThrows]
attribute EventHandler oncut;
[SetterThrows]
attribute EventHandler onpaste;*/
};
// http://dev.w3.org/csswg/cssom-view/#extensions-to-the-htmlelement-interface
partial interface HTMLElement {
// CSSOM things are not [Pure] because they can flush
readonly attribute Element? offsetParent;
readonly attribute long offsetTop;
readonly attribute long offsetLeft;
readonly attribute long offsetWidth;
readonly attribute long offsetHeight;
};
/*[NoInterfaceObject]
interface TouchEventHandlers {
[SetterThrows,Func="nsGenericHTMLElement::TouchEventsEnabled"]
attribute EventHandler ontouchstart;
[SetterThrows,Func="nsGenericHTMLElement::TouchEventsEnabled"]
attribute EventHandler ontouchend;
[SetterThrows,Func="nsGenericHTMLElement::TouchEventsEnabled"]
attribute EventHandler ontouchmove;
[SetterThrows,Func="nsGenericHTMLElement::TouchEventsEnabled"]
attribute EventHandler ontouchenter;
[SetterThrows,Func="nsGenericHTMLElement::TouchEventsEnabled"]
attribute EventHandler ontouchleave;
[SetterThrows,Func="nsGenericHTMLElement::TouchEventsEnabled"]
attribute EventHandler ontouchcancel;
};*/
/*HTMLElement implements GlobalEventHandlers;
HTMLElement implements NodeEventHandlers;
HTMLElement implements TouchEventHandlers;*/

View file

@ -0,0 +1,107 @@
/* -*- Mode: IDL; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this file,
* You can obtain one at http://mozilla.org/MPL/2.0/.
*
* The origin of this IDL file is
* http://www.w3.org/TR/2012/WD-dom-20120105/
*
* Copyright © 2012 W3C® (MIT, ERCIM, Keio), All Rights Reserved. W3C
* liability, trademark and document use rules apply.
*/
/*interface Principal;
interface URI;
interface UserDataHandler;*/
interface Node /*: EventTarget*/ {
const unsigned short ELEMENT_NODE = 1;
const unsigned short ATTRIBUTE_NODE = 2; // historical
const unsigned short TEXT_NODE = 3;
const unsigned short CDATA_SECTION_NODE = 4; // historical
const unsigned short ENTITY_REFERENCE_NODE = 5; // historical
const unsigned short ENTITY_NODE = 6; // historical
const unsigned short PROCESSING_INSTRUCTION_NODE = 7;
const unsigned short COMMENT_NODE = 8;
const unsigned short DOCUMENT_NODE = 9;
const unsigned short DOCUMENT_TYPE_NODE = 10;
const unsigned short DOCUMENT_FRAGMENT_NODE = 11;
const unsigned short NOTATION_NODE = 12; // historical
[Constant]
readonly attribute unsigned short nodeType;
[Pure]
readonly attribute DOMString nodeName;
[Pure]
readonly attribute DOMString? baseURI;
[Pure]
readonly attribute Document? ownerDocument;
[Pure]
readonly attribute Node? parentNode;
[Pure]
readonly attribute Element? parentElement;
boolean hasChildNodes();
/*[Constant]
readonly attribute NodeList childNodes;*/
[Pure]
readonly attribute Node? firstChild;
[Pure]
readonly attribute Node? lastChild;
[Pure]
readonly attribute Node? previousSibling;
[Pure]
readonly attribute Node? nextSibling;
[SetterThrows, Pure]
attribute DOMString? nodeValue;
[SetterThrows, Pure]
attribute DOMString? textContent;
/*[Throws]
Node insertBefore(Node node, Node? child);*/ //XXXjdm we don't deal well with Node? parameters
[Throws]
Node appendChild(Node node);
[Throws]
Node replaceChild(Node node, Node child);
[Throws]
Node removeChild(Node child);
void normalize();
[Throws]
Node cloneNode(optional boolean deep = true);
// boolean isEqualNode(Node? node); //XXXjdm we don't deal well with Node? parameters
const unsigned short DOCUMENT_POSITION_DISCONNECTED = 0x01;
const unsigned short DOCUMENT_POSITION_PRECEDING = 0x02;
const unsigned short DOCUMENT_POSITION_FOLLOWING = 0x04;
const unsigned short DOCUMENT_POSITION_CONTAINS = 0x08;
const unsigned short DOCUMENT_POSITION_CONTAINED_BY = 0x10;
const unsigned short DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC = 0x20; // historical
unsigned short compareDocumentPosition(Node other);
//boolean contains(Node? other); //XXXjdm we don't deal well with Node? parameters
DOMString? lookupPrefix(DOMString? namespace);
DOMString? lookupNamespaceURI(DOMString? prefix);
boolean isDefaultNamespace(DOMString? namespace);
// Mozilla-specific stuff
// These have been moved to Element in the spec.
// If we move namespaceURI, prefix and localName to Element they should return
// a non-nullable type.
[Constant]
readonly attribute DOMString? namespaceURI;
[Constant]
readonly attribute DOMString? prefix;
[Constant]
readonly attribute DOMString? localName;
boolean hasAttributes();
/*[Throws, Func="nsINode::IsChromeOrXBL"]
any setUserData(DOMString key, any data, UserDataHandler? handler);
[Throws, Func="nsINode::IsChromeOrXBL"]
any getUserData(DOMString key);*/
/*[ChromeOnly]
readonly attribute Principal nodePrincipal;
[ChromeOnly]
readonly attribute URI? baseURIObject;*/
};

View file

@ -0,0 +1,19 @@
/* -*- Mode: IDL; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this file,
* You can obtain one at http://mozilla.org/MPL/2.0/.
*
* The origin of this IDL file is
* http://www.w3.org/TR/2012/WD-dom-20120105/
*
* Copyright © 2012 W3C® (MIT, ERCIM, Keio), All Rights Reserved. W3C
* liability, trademark and document use rules apply.
*/
[Constructor(optional DOMString data = "")]
interface Text : CharacterData {
[Throws]
Text splitText(unsigned long offset);
[Throws]
readonly attribute DOMString wholeText;
};

View file

@ -10,8 +10,6 @@
* liability, trademark and document use rules apply. * liability, trademark and document use rules apply.
*/ */
interface Node;
[Constructor(DOMString type, optional UIEventInit eventInitDict)] [Constructor(DOMString type, optional UIEventInit eventInitDict)]
interface UIEvent : Event interface UIEvent : Event
{ {

View file

@ -37,7 +37,7 @@ extern fn finalize(_fop: *JSFreeOp, obj: *JSObject) {
unsafe { unsafe {
let node: AbstractNode<ScriptView> = unwrap(obj); let node: AbstractNode<ScriptView> = unwrap(obj);
//XXXjdm We need separate finalizers for each specialty element type like headings //XXXjdm We need separate finalizers for each specialty element type like headings
let _elem: ~Element = cast::transmute(node.raw_object()); let _elem: @Element = cast::transmute(node.raw_object());
} }
} }

View file

@ -2,12 +2,13 @@
* License, v. 2.0. If a copy of the MPL was not distributed with this * License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use dom::bindings::codegen::TextBinding;
use dom::bindings::element; use dom::bindings::element;
use dom::bindings::text; use dom::bindings::text;
use dom::bindings::utils; use dom::bindings::utils;
use dom::bindings::utils::{CacheableWrapper, WrapperCache, DerivedWrapper}; use dom::bindings::utils::{CacheableWrapper, WrapperCache, DerivedWrapper};
use dom::node::{AbstractNode, Node, ElementNodeTypeId, TextNodeTypeId, CommentNodeTypeId}; use dom::node::{AbstractNode, Node, ElementNodeTypeId, TextNodeTypeId, CommentNodeTypeId};
use dom::node::{DoctypeNodeTypeId, ScriptView}; use dom::node::{DoctypeNodeTypeId, ScriptView, Text};
use std::cast; use std::cast;
use std::libc::c_uint; use std::libc::c_uint;
@ -17,7 +18,7 @@ use js::jsapi::*;
use js::jsapi::{JSContext, JSVal, JSObject, JSBool, JSPropertySpec}; use js::jsapi::{JSContext, JSVal, JSObject, JSBool, JSPropertySpec};
use js::jsapi::{JSPropertyOpWrapper, JSStrictPropertyOpWrapper}; use js::jsapi::{JSPropertyOpWrapper, JSStrictPropertyOpWrapper};
use js::jsval::{INT_TO_JSVAL}; use js::jsval::{INT_TO_JSVAL};
use js::rust::{Compartment, jsobj}; use js::rust::{Compartment};
use js::{JSPROP_ENUMERATE, JSPROP_SHARED, JSVAL_NULL}; use js::{JSPROP_ENUMERATE, JSPROP_SHARED, JSVAL_NULL};
use js::{JS_THIS_OBJECT, JSPROP_NATIVE_ACCESSORS}; use js::{JS_THIS_OBJECT, JSPROP_NATIVE_ACCESSORS};
use servo_util::tree::TreeNodeRef; use servo_util::tree::TreeNodeRef;
@ -62,12 +63,16 @@ pub fn init(compartment: @mut Compartment) {
} }
#[allow(non_implicitly_copyable_typarams)] #[allow(non_implicitly_copyable_typarams)]
pub fn create(cx: *JSContext, node: &mut AbstractNode<ScriptView>) -> jsobj { pub fn create(cx: *JSContext, node: &mut AbstractNode<ScriptView>) -> *JSObject {
match node.type_id() { match node.type_id() {
ElementNodeTypeId(_) => element::create(cx, node), ElementNodeTypeId(_) => element::create(cx, node).ptr,
TextNodeTypeId |
CommentNodeTypeId | CommentNodeTypeId |
DoctypeNodeTypeId => text::create(cx, node), DoctypeNodeTypeId => text::create(cx, node).ptr,
TextNodeTypeId => {
let mut unused = false;
let node: @mut Text = unsafe { cast::transmute(node.raw_object()) };
TextBinding::Wrap(cx, ptr::null(), node, &mut unused)
}
} }
} }

View file

@ -616,7 +616,7 @@ pub extern fn ThrowingConstructor(_cx: *JSContext, _argc: uint, _vp: *JSVal) ->
} }
pub fn initialize_global(global: *JSObject) { pub fn initialize_global(global: *JSObject) {
let protoArray = @mut ([0 as *JSObject, ..25]); //XXXjdm PrototyepList::id::_ID_Count let protoArray = @mut ([0 as *JSObject, ..30]); //XXXjdm PrototyepList::id::_ID_Count
unsafe { unsafe {
//XXXjdm we should be storing the box pointer instead of the inner //XXXjdm we should be storing the box pointer instead of the inner
let box = squirrel_away(protoArray); let box = squirrel_away(protoArray);
@ -835,7 +835,7 @@ impl DerivedWrapper for AbstractNode<ScriptView> {
unsafe { *vp = RUST_OBJECT_TO_JSVAL(wrapper) }; unsafe { *vp = RUST_OBJECT_TO_JSVAL(wrapper) };
return 1; return 1;
} }
unsafe { *vp = RUST_OBJECT_TO_JSVAL(node::create(cx, self).ptr) }; unsafe { *vp = RUST_OBJECT_TO_JSVAL(node::create(cx, self)) };
return 1; return 1;
} }

View file

@ -4,8 +4,10 @@
//! DOM bindings for `CharacterData`. //! DOM bindings for `CharacterData`.
use dom::bindings::utils::{DOMString, null_string, str}; use dom::bindings::utils::{DOMString, null_string, str, ErrorResult};
use dom::bindings::utils::{BindingObject, CacheableWrapper, WrapperCache};
use dom::node::{Node, NodeTypeId, ScriptView}; use dom::node::{Node, NodeTypeId, ScriptView};
use js::jsapi::{JSObject, JSContext};
pub struct CharacterData { pub struct CharacterData {
parent: Node<ScriptView>, parent: Node<ScriptView>,
@ -20,12 +22,12 @@ impl CharacterData {
} }
} }
pub fn GetData(&self) -> DOMString { pub fn Data(&self) -> DOMString {
copy self.data copy self.data
} }
pub fn SetData(&mut self, arg: DOMString) { pub fn SetData(&mut self, arg: &DOMString, _rv: &mut ErrorResult) {
self.data = arg; self.data = (*arg).clone();
} }
pub fn Length(&self) -> u32 { pub fn Length(&self) -> u32 {
@ -35,28 +37,43 @@ impl CharacterData {
} }
} }
pub fn SubstringData(&self, offset: u32, count: u32) -> DOMString { pub fn SubstringData(&self, offset: u32, count: u32, _rv: &mut ErrorResult) -> DOMString {
match self.data { match self.data {
str(ref s) => str(s.slice(offset as uint, count as uint).to_str()), str(ref s) => str(s.slice(offset as uint, count as uint).to_str()),
null_string => null_string null_string => null_string
} }
} }
pub fn AppendData(&mut self, arg: DOMString) { pub fn AppendData(&mut self, arg: &DOMString, _rv: &mut ErrorResult) {
let s = self.data.to_str(); let s = self.data.to_str();
self.data = str(s.append(arg.to_str())); self.data = str(s.append(arg.to_str()));
} }
pub fn InsertData(&mut self, _offset: u32, _arg: DOMString) { pub fn InsertData(&mut self, _offset: u32, _arg: &DOMString, _rv: &mut ErrorResult) {
fail!("CharacterData::InsertData() is unimplemented") fail!("CharacterData::InsertData() is unimplemented")
} }
pub fn DeleteData(&mut self, _offset: u32, _count: u32) { pub fn DeleteData(&mut self, _offset: u32, _count: u32, _rv: &mut ErrorResult) {
fail!("CharacterData::DeleteData() is unimplemented") fail!("CharacterData::DeleteData() is unimplemented")
} }
pub fn ReplaceData(&mut self, _offset: u32, _count: u32, _arg: DOMString) { pub fn ReplaceData(&mut self, _offset: u32, _count: u32, _arg: &DOMString, _rv: &mut ErrorResult) {
fail!("CharacterData::ReplaceData() is unimplemented") fail!("CharacterData::ReplaceData() is unimplemented")
} }
} }
impl CacheableWrapper for CharacterData {
fn get_wrappercache(&mut self) -> &mut WrapperCache {
self.parent.get_wrappercache()
}
fn wrap_object_shared(@mut self, _cx: *JSContext, _scope: *JSObject) -> *JSObject {
fail!(~"need to implement wrapping");
}
}
impl BindingObject for CharacterData {
fn GetParentObject(&self, cx: *JSContext) -> Option<@mut CacheableWrapper> {
self.parent.GetParentObject(cx)
}
}

View file

@ -37,18 +37,6 @@ impl AbstractDocument {
} }
} }
pub unsafe fn as_cacheable_wrapper(&self) -> @mut CacheableWrapper {
match self.with_base(|doc| doc.doctype) {
HTML => {
let doc: @mut HTMLDocument = cast::transmute(self.document);
doc as @mut CacheableWrapper
}
SVG | XML => {
fail!("no SVG or XML documents yet")
}
}
}
unsafe fn transmute<T, R>(&self, f: &fn(&T) -> R) -> R { unsafe fn transmute<T, R>(&self, f: &fn(&T) -> R) -> R {
let box: *rust_box<T> = cast::transmute(self.document); let box: *rust_box<T> = cast::transmute(self.document);
f(&(*box).payload) f(&(*box).payload)
@ -113,7 +101,7 @@ impl Document {
} }
pub fn Constructor(owner: @mut Window, _rv: &mut ErrorResult) -> AbstractDocument { pub fn Constructor(owner: @mut Window, _rv: &mut ErrorResult) -> AbstractDocument {
let root = ~HTMLHtmlElement { let root = @HTMLHtmlElement {
parent: Element::new(HTMLHtmlElementTypeId, ~"html") parent: Element::new(HTMLHtmlElementTypeId, ~"html")
}; };

View file

@ -41,7 +41,7 @@ impl DOMParser {
_rv: &mut ErrorResult) _rv: &mut ErrorResult)
-> AbstractDocument { -> AbstractDocument {
unsafe { unsafe {
let root = ~HTMLHtmlElement { let root = @HTMLHtmlElement {
parent: Element::new(HTMLHtmlElementTypeId, ~"html") parent: Element::new(HTMLHtmlElementTypeId, ~"html")
}; };

View file

@ -4,13 +4,17 @@
//! Element nodes. //! Element nodes.
use dom::bindings::utils::{DOMString, CacheableWrapper}; use dom::bindings::utils::{DOMString, null_string, ErrorResult};
use dom::bindings::utils::{CacheableWrapper, BindingObject, WrapperCache};
use dom::clientrect::ClientRect; use dom::clientrect::ClientRect;
use dom::clientrectlist::ClientRectList; use dom::clientrectlist::ClientRectList;
use dom::node::{ElementNodeTypeId, Node, ScriptView}; use dom::htmlcollection::HTMLCollection;
use dom::node::{ElementNodeTypeId, Node, ScriptView, AbstractNode};
use layout_interface::{ContentBoxQuery, ContentBoxResponse, ContentBoxesQuery}; use layout_interface::{ContentBoxQuery, ContentBoxResponse, ContentBoxesQuery};
use layout_interface::{ContentBoxesResponse}; use layout_interface::{ContentBoxesResponse};
use js::jsapi::{JSContext, JSObject};
use std::cell::Cell; use std::cell::Cell;
use std::comm::ChanOne; use std::comm::ChanOne;
use std::comm; use std::comm;
@ -257,6 +261,160 @@ impl<'self> Element {
} }
} }
} }
fn get_scope_and_cx(&self) -> (*JSObject, *JSContext) {
let doc = self.parent.owner_doc.get();
let win = doc.with_base(|doc| doc.window.get());
let cx = unsafe {(*win.page).js_info.get_ref().js_compartment.cx.ptr};
let cache = win.get_wrappercache();
let scope = cache.get_wrapper();
(scope, cx)
}
}
impl Element {
pub fn TagName(&self) -> DOMString {
null_string
}
pub fn Id(&self) -> DOMString {
null_string
}
pub fn SetId(&self, _id: &DOMString) {
}
pub fn GetAttribute(&self, _name: &DOMString) -> DOMString {
null_string
}
pub fn GetAttributeNS(&self, _namespace: &DOMString, _localname: &DOMString) -> DOMString {
null_string
}
pub fn SetAttribute(&self, _name: &DOMString, _value: &DOMString, _rv: &mut ErrorResult) {
}
pub fn SetAttributeNS(&self, _namespace: &DOMString, _localname: &DOMString, _value: &DOMString, _rv: &mut ErrorResult) {
}
pub fn RemoveAttribute(&self, _name: &DOMString, _rv: &mut ErrorResult) -> bool {
false
}
pub fn RemoveAttributeNS(&self, _namespace: &DOMString, _localname: &DOMString, _rv: &mut ErrorResult) -> bool {
false
}
pub fn HasAttribute(&self, _name: &DOMString) -> bool {
false
}
pub fn HasAttributeNS(&self, _nameapce: &DOMString, _localname: &DOMString) -> bool {
false
}
pub fn GetElementsByTagName(&self, _localname: &DOMString) -> @mut HTMLCollection {
let (scope, cx) = self.get_scope_and_cx();
HTMLCollection::new(~[], cx, scope)
}
pub fn GetElementsByTagNameNS(&self, _namespace: &DOMString, _localname: &DOMString, _rv: &mut ErrorResult) -> @mut HTMLCollection {
let (scope, cx) = self.get_scope_and_cx();
HTMLCollection::new(~[], cx, scope)
}
pub fn GetElementsByClassName(&self, _names: &DOMString) -> @mut HTMLCollection {
let (scope, cx) = self.get_scope_and_cx();
HTMLCollection::new(~[], cx, scope)
}
pub fn MozMatchesSelector(&self, _selector: &DOMString, _rv: &mut ErrorResult) -> bool {
false
}
pub fn SetCapture(&self, _retargetToElement: bool) {
}
pub fn ReleaseCapture(&self) {
}
pub fn MozRequestFullScreen(&self) {
}
pub fn MozRequestPointerLock(&self) {
}
pub fn GetClientRects(&self) -> @mut ClientRectList {
let (scope, cx) = self.get_scope_and_cx();
ClientRectList::new(~[], cx, scope)
}
pub fn GetBoundingClientRect(&self) -> @mut ClientRect {
fail!("stub")
}
pub fn ScrollIntoView(&self, _top: bool) {
}
pub fn ScrollTop(&self) -> i32 {
0
}
pub fn SetScrollTop(&mut self, _scroll_top: i32) {
}
pub fn ScrollLeft(&self) -> i32 {
0
}
pub fn SetScrollLeft(&mut self, _scroll_left: i32) {
}
pub fn ScrollWidth(&self) -> i32 {
0
}
pub fn ScrollHeight(&self) -> i32 {
0
}
pub fn ClientTop(&self) -> i32 {
0
}
pub fn ClientLeft(&self) -> i32 {
0
}
pub fn ClientWidth(&self) -> i32 {
0
}
pub fn ClientHeight(&self) -> i32 {
0
}
pub fn GetInnerHTML(&self, _rv: &mut ErrorResult) -> DOMString {
null_string
}
pub fn SetInnerHTML(&mut self, _value: &DOMString, _rv: &mut ErrorResult) {
}
pub fn GetOuterHTML(&self, _rv: &mut ErrorResult) -> DOMString {
null_string
}
pub fn SetOuterHTML(&mut self, _value: &DOMString, _rv: &mut ErrorResult) {
}
pub fn InsertAdjacentHTML(&mut self, _position: &DOMString, _text: &DOMString, _rv: &mut ErrorResult) {
}
pub fn QuerySelector(&self, _selectors: &DOMString, _rv: &mut ErrorResult) -> Option<AbstractNode<ScriptView>> {
None
}
} }
pub struct Attr { pub struct Attr {
@ -282,3 +440,18 @@ pub enum HeadingLevel {
Heading6, Heading6,
} }
impl CacheableWrapper for Element {
fn get_wrappercache(&mut self) -> &mut WrapperCache {
self.parent.get_wrappercache()
}
fn wrap_object_shared(@mut self, _cx: *JSContext, _scope: *JSObject) -> *JSObject {
fail!(~"need to implement wrapping");
}
}
impl BindingObject for Element {
fn GetParentObject(&self, cx: *JSContext) -> Option<@mut CacheableWrapper> {
self.parent.GetParentObject(cx)
}
}

View file

@ -0,0 +1,146 @@
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use dom::bindings::utils::{DOMString, null_string, ErrorResult};
use dom::bindings::utils::{CacheableWrapper, BindingObject, WrapperCache};
use dom::element::Element;
use dom::node::{AbstractNode, ScriptView};
use js::jsapi::{JSObject, JSContext, JSVal};
use js::JSVAL_NULL;
pub struct HTMLElement {
parent: Element
}
impl HTMLElement {
pub fn Title(&self) -> DOMString {
null_string
}
pub fn SetTitle(&mut self, _title: &DOMString) {
}
pub fn Lang(&self) -> DOMString {
null_string
}
pub fn SetLang(&mut self, _lang: &DOMString) {
}
pub fn Dir(&self) -> DOMString {
null_string
}
pub fn SetDir(&mut self, _dir: &DOMString, _rv: &mut ErrorResult) {
}
pub fn GetItemValue(&self, _cx: *JSContext, _rv: &mut ErrorResult) -> JSVal {
JSVAL_NULL
}
pub fn SetItemValue(&mut self, _cx: *JSContext, _val: JSVal, _rv: &mut ErrorResult) {
}
pub fn Hidden(&self) -> bool {
false
}
pub fn SetHidden(&mut self, _hidden: bool, _rv: &mut ErrorResult) {
}
pub fn Click(&self) {
}
pub fn TabIndex(&self) -> i32 {
0
}
pub fn SetTabIndex(&mut self, _index: i32, _rv: &mut ErrorResult) {
}
pub fn Focus(&self, _rv: &mut ErrorResult) {
}
pub fn Blur(&self, _rv: &mut ErrorResult) {
}
pub fn AccessKey(&self) -> DOMString {
null_string
}
pub fn SetAccessKey(&self, _key: &DOMString, _rv: &mut ErrorResult) {
}
pub fn AccessKeyLabel(&self) -> DOMString {
null_string
}
pub fn Draggable(&self) -> bool {
false
}
pub fn SetDraggable(&mut self, _draggable: bool, _rv: &mut ErrorResult) {
}
pub fn ContentEditable(&self) -> DOMString {
null_string
}
pub fn SetContentEditable(&mut self, _val: &DOMString, _rv: &mut ErrorResult) {
}
pub fn IsContentEditable(&self) -> bool {
false
}
pub fn Spellcheck(&self) -> bool {
false
}
pub fn SetSpellcheck(&self, _val: bool, _rv: &mut ErrorResult) {
}
pub fn ClassName(&self) -> DOMString {
null_string
}
pub fn SetClassName(&self, _class: &DOMString) {
}
pub fn GetOffsetParent(&self) -> Option<AbstractNode<ScriptView>> {
None
}
pub fn OffsetTop(&self) -> i32 {
0
}
pub fn OffsetLeft(&self) -> i32 {
0
}
pub fn OffsetWidth(&self) -> i32 {
0
}
pub fn OffsetHeight(&self) -> i32 {
0
}
}
impl CacheableWrapper for HTMLElement {
fn get_wrappercache(&mut self) -> &mut WrapperCache {
self.parent.get_wrappercache()
}
fn wrap_object_shared(@mut self, _cx: *JSContext, _scope: *JSObject) -> *JSObject {
fail!(~"need to implement wrapping");
}
}
impl BindingObject for HTMLElement {
fn GetParentObject(&self, cx: *JSContext) -> Option<@mut CacheableWrapper> {
self.parent.GetParentObject(cx)
}
}

View file

@ -5,19 +5,21 @@
//! The core DOM types. Defines the basic DOM hierarchy as well as all the HTML elements. //! The core DOM types. Defines the basic DOM hierarchy as well as all the HTML elements.
use dom::bindings::node; use dom::bindings::node;
use dom::bindings::utils::WrapperCache; use dom::bindings::utils::{WrapperCache, DOMString, null_string, ErrorResult};
use dom::bindings::utils::{BindingObject, CacheableWrapper};
use dom::bindings; use dom::bindings;
use dom::characterdata::CharacterData; use dom::characterdata::CharacterData;
use dom::document::AbstractDocument; use dom::document::AbstractDocument;
use dom::element::{Element, ElementTypeId, HTMLImageElement, HTMLImageElementTypeId, HTMLIframeElementTypeId, HTMLIframeElement}; use dom::element::{Element, ElementTypeId, HTMLImageElement, HTMLImageElementTypeId, HTMLIframeElementTypeId, HTMLIframeElement};
use dom::element::{HTMLStyleElementTypeId}; use dom::element::{HTMLStyleElementTypeId};
use dom::window::Window;
use std::cast; use std::cast;
use std::cast::transmute; use std::cast::transmute;
use std::libc::c_void; use std::libc::c_void;
use std::uint; use std::uint;
use js::jsapi::{JSObject, JSContext};
use js::rust::Compartment; use js::rust::Compartment;
use js::jsapi::{JSContext};
use netsurfcss::util::VoidPtrLike; use netsurfcss::util::VoidPtrLike;
use servo_util::tree::{TreeNode, TreeNodeRef, TreeUtils}; use servo_util::tree::{TreeNode, TreeNodeRef, TreeUtils};
@ -151,6 +153,19 @@ impl Text {
parent: CharacterData::new(TextNodeTypeId, text) parent: CharacterData::new(TextNodeTypeId, text)
} }
} }
pub fn Constructor(owner: @mut Window, text: &DOMString, _rv: &mut ErrorResult) -> AbstractNode<ScriptView> {
let cx = unsafe {(*owner.page).js_info.get_ref().js_compartment.cx.ptr};
unsafe { Node::as_abstract_node(cx, @Text::new(text.to_str())) }
}
pub fn SplitText(&self, _offset: u32, _rv: &mut ErrorResult) -> AbstractNode<ScriptView> {
fail!("unimplemented")
}
pub fn GetWholeText(&self, _rv: &mut ErrorResult) -> DOMString {
null_string
}
} }
impl<View> Clone for AbstractNode<View> { impl<View> Clone for AbstractNode<View> {
@ -207,6 +222,18 @@ impl<View> TreeNodeRef<Node<View>> for AbstractNode<View> {
impl<'self, View> AbstractNode<View> { impl<'self, View> AbstractNode<View> {
// Unsafe accessors // Unsafe accessors
pub unsafe fn as_cacheable_wrapper(&self) -> @mut CacheableWrapper {
match self.type_id() {
TextNodeTypeId => {
let node: @mut Text = cast::transmute(self.obj);
node as @mut CacheableWrapper
}
_ => {
fail!("unsupported node type")
}
}
}
/// Returns the layout data, unsafely cast to whatever type layout wishes. Only layout is /// Returns the layout data, unsafely cast to whatever type layout wishes. Only layout is
/// allowed to call this. This is wildly unsafe and is therefore marked as such. /// allowed to call this. This is wildly unsafe and is therefore marked as such.
pub unsafe fn unsafe_layout_data<T>(self) -> @mut T { pub unsafe fn unsafe_layout_data<T>(self) -> @mut T {
@ -426,7 +453,7 @@ impl<View> Iterator<AbstractNode<View>> for AbstractNodeChildrenIterator<View> {
} }
impl Node<ScriptView> { impl Node<ScriptView> {
pub unsafe fn as_abstract_node<N>(cx: *JSContext, node: ~N) -> AbstractNode<ScriptView> { pub unsafe fn as_abstract_node<N>(cx: *JSContext, node: @N) -> AbstractNode<ScriptView> {
// This surrenders memory management of the node! // This surrenders memory management of the node!
let mut node = AbstractNode { let mut node = AbstractNode {
obj: transmute(node), obj: transmute(node),
@ -495,6 +522,128 @@ impl Node<ScriptView> {
} }
} }
impl Node<ScriptView> {
pub fn NodeType(&self) -> u16 {
0
}
pub fn NodeName(&self) -> DOMString {
null_string
}
pub fn GetBaseURI(&self) -> DOMString {
null_string
}
pub fn GetOwnerDocument(&self) -> Option<AbstractDocument> {
None
}
pub fn GetParentNode(&self) -> Option<AbstractNode<ScriptView>> {
None
}
pub fn GetParentElement(&self) -> Option<AbstractNode<ScriptView>> {
None
}
pub fn HasChildNodes(&self) -> bool {
false
}
pub fn GetFirstChild(&self) -> Option<AbstractNode<ScriptView>> {
None
}
pub fn GetLastChild(&self) -> Option<AbstractNode<ScriptView>> {
None
}
pub fn GetPreviousSibling(&self) -> Option<AbstractNode<ScriptView>> {
None
}
pub fn GetNextSibling(&self) -> Option<AbstractNode<ScriptView>> {
None
}
pub fn GetNodeValue(&self) -> DOMString {
null_string
}
pub fn SetNodeValue(&mut self, _val: &DOMString, _rv: &mut ErrorResult) {
}
pub fn GetTextContent(&self) -> DOMString {
null_string
}
pub fn SetTextContent(&mut self, _val: &DOMString, _rv: &mut ErrorResult) {
}
pub fn InsertBefore(&mut self, _node: AbstractNode<ScriptView>, _child: Option<AbstractNode<ScriptView>>, _rv: &mut ErrorResult) -> AbstractNode<ScriptView> {
fail!("stub")
}
pub fn AppendChild(&mut self, _node: AbstractNode<ScriptView>, _rv: &mut ErrorResult) -> AbstractNode<ScriptView> {
fail!("stub")
}
pub fn ReplaceChild(&mut self, _node: AbstractNode<ScriptView>, _child: AbstractNode<ScriptView>, _rv: &mut ErrorResult) -> AbstractNode<ScriptView> {
fail!("stub")
}
pub fn RemoveChild(&mut self, _node: AbstractNode<ScriptView>, _rv: &mut ErrorResult) -> AbstractNode<ScriptView> {
fail!("stub")
}
pub fn Normalize(&mut self) {
}
pub fn CloneNode(&self, _deep: bool, _rv: &mut ErrorResult) -> AbstractNode<ScriptView> {
fail!("stub")
}
pub fn IsEqualNode(&self, _node: Option<AbstractNode<ScriptView>>) -> bool {
false
}
pub fn CompareDocumentPosition(&self, _other: AbstractNode<ScriptView>) -> u16 {
0
}
pub fn Contains(&self, _other: Option<AbstractNode<ScriptView>>) -> bool {
false
}
pub fn LookupPrefix(&self, _prefix: &DOMString) -> DOMString {
null_string
}
pub fn LookupNamespaceURI(&self, _namespace: &DOMString) -> DOMString {
null_string
}
pub fn IsDefaultNamespace(&self, _namespace: &DOMString) -> bool {
false
}
pub fn GetNamespaceURI(&self) -> DOMString {
null_string
}
pub fn GetPrefix(&self) -> DOMString {
null_string
}
pub fn GetLocalName(&self) -> DOMString {
null_string
}
pub fn HasAttributes(&self) -> bool {
false
}
}
/// The CSS library requires that DOM nodes be convertible to `*c_void` via the `VoidPtrLike` /// The CSS library requires that DOM nodes be convertible to `*c_void` via the `VoidPtrLike`
/// trait. /// trait.
@ -520,3 +669,38 @@ pub fn define_bindings(compartment: @mut Compartment) {
bindings::utils::initialize_global(compartment.global_obj.ptr); bindings::utils::initialize_global(compartment.global_obj.ptr);
bindings::codegen::RegisterBindings::Register(compartment); bindings::codegen::RegisterBindings::Register(compartment);
} }
impl CacheableWrapper for Node<ScriptView> {
fn get_wrappercache(&mut self) -> &mut WrapperCache {
unsafe { cast::transmute(&mut self.wrapper) }
}
fn wrap_object_shared(@mut self, _cx: *JSContext, _scope: *JSObject) -> *JSObject {
fail!(~"need to implement wrapping");
}
}
impl BindingObject for Node<ScriptView> {
fn GetParentObject(&self, _cx: *JSContext) -> Option<@mut CacheableWrapper> {
match self.parent_node {
Some(node) => Some(unsafe {node.as_cacheable_wrapper()}),
None => None
}
}
}
impl CacheableWrapper for Text {
fn get_wrappercache(&mut self) -> &mut WrapperCache {
self.parent.get_wrappercache()
}
fn wrap_object_shared(@mut self, _cx: *JSContext, _scope: *JSObject) -> *JSObject {
fail!(~"need to implement wrapping");
}
}
impl BindingObject for Text {
fn GetParentObject(&self, cx: *JSContext) -> Option<@mut CacheableWrapper> {
self.parent.GetParentObject(cx)
}
}

View file

@ -56,7 +56,7 @@ use geom::size::Size2D;
macro_rules! handle_element( macro_rules! handle_element(
($cx: expr, $tag:expr, $string:expr, $type_id:expr, $ctor:ident, [ $(($field:ident : $field_init:expr)),* ]) => ( ($cx: expr, $tag:expr, $string:expr, $type_id:expr, $ctor:ident, [ $(($field:ident : $field_init:expr)),* ]) => (
if eq_slice($tag, $string) { if eq_slice($tag, $string) {
let _element = ~$ctor { let _element = @$ctor {
parent: Element::new($type_id, ($tag).to_str()), parent: Element::new($type_id, ($tag).to_str()),
$( $(
$field: $field_init, $field: $field_init,
@ -233,7 +233,7 @@ fn build_element_from_tag(cx: *JSContext, tag: &str) -> AbstractNode<ScriptView>
handle_element!(cx, tag, "h6", HTMLHeadingElementTypeId, HTMLHeadingElement, [(level: Heading6)]); handle_element!(cx, tag, "h6", HTMLHeadingElementTypeId, HTMLHeadingElement, [(level: Heading6)]);
unsafe { unsafe {
Node::as_abstract_node(cx, ~Element::new(UnknownElementTypeId, tag.to_str())) Node::as_abstract_node(cx, @Element::new(UnknownElementTypeId, tag.to_str()))
} }
} }
@ -272,7 +272,7 @@ pub fn parse_html(cx: *JSContext,
let url3 = url.clone(); let url3 = url.clone();
// Build the root node. // Build the root node.
let root = ~HTMLHtmlElement { parent: Element::new(HTMLHtmlElementTypeId, ~"html") }; let root = @HTMLHtmlElement { parent: Element::new(HTMLHtmlElementTypeId, ~"html") };
let root = unsafe { Node::as_abstract_node(cx, root) }; let root = unsafe { Node::as_abstract_node(cx, root) };
debug!("created new node"); debug!("created new node");
let mut parser = hubbub::Parser("UTF-8", false); let mut parser = hubbub::Parser("UTF-8", false);
@ -289,7 +289,7 @@ pub fn parse_html(cx: *JSContext,
create_comment: |data: ~str| { create_comment: |data: ~str| {
debug!("create comment"); debug!("create comment");
unsafe { unsafe {
Node::as_abstract_node(cx, ~Comment::new(data)).to_hubbub_node() Node::as_abstract_node(cx, @Comment::new(data)).to_hubbub_node()
} }
}, },
create_doctype: |doctype: ~hubbub::Doctype| { create_doctype: |doctype: ~hubbub::Doctype| {
@ -298,7 +298,7 @@ pub fn parse_html(cx: *JSContext,
public_id: public_id, public_id: public_id,
system_id: system_id, system_id: system_id,
force_quirks: force_quirks } = doctype; force_quirks: force_quirks } = doctype;
let node = ~Doctype::new(name, let node = @Doctype::new(name,
public_id, public_id,
system_id, system_id,
force_quirks); force_quirks);
@ -383,7 +383,7 @@ pub fn parse_html(cx: *JSContext,
create_text: |data: ~str| { create_text: |data: ~str| {
debug!("create text"); debug!("create text");
unsafe { unsafe {
Node::as_abstract_node(cx, ~Text::new(data)).to_hubbub_node() Node::as_abstract_node(cx, @Text::new(data)).to_hubbub_node()
} }
}, },
ref_node: |_| {}, ref_node: |_| {},

View file

@ -33,18 +33,23 @@ pub mod dom {
pub mod domparser; pub mod domparser;
pub mod codegen { pub mod codegen {
pub mod BlobBinding; pub mod BlobBinding;
pub mod CharacterDataBinding;
pub mod ClientRectBinding; pub mod ClientRectBinding;
pub mod ClientRectListBinding; pub mod ClientRectListBinding;
pub mod DocumentBinding; pub mod DocumentBinding;
pub mod DOMParserBinding; pub mod DOMParserBinding;
pub mod ElementBinding;
pub mod EventBinding; pub mod EventBinding;
pub mod EventTargetBinding; pub mod EventTargetBinding;
pub mod FormDataBinding; pub mod FormDataBinding;
pub mod HTMLCollectionBinding; pub mod HTMLCollectionBinding;
pub mod HTMLDocumentBinding; pub mod HTMLDocumentBinding;
pub mod HTMLElementBinding;
pub mod MouseEventBinding; pub mod MouseEventBinding;
pub mod NodeBinding;
pub mod PrototypeList; pub mod PrototypeList;
pub mod RegisterBindings; pub mod RegisterBindings;
pub mod TextBinding;
pub mod UIEventBinding; pub mod UIEventBinding;
pub mod WindowBinding; pub mod WindowBinding;
pub mod WindowProxyBinding; pub mod WindowProxyBinding;
@ -62,6 +67,7 @@ pub mod dom {
pub mod formdata; pub mod formdata;
pub mod htmlcollection; pub mod htmlcollection;
pub mod htmldocument; pub mod htmldocument;
pub mod htmlelement;
pub mod mouseevent; pub mod mouseevent;
pub mod node; pub mod node;
pub mod uievent; pub mod uievent;