auto merge of #674 : jdm/servo/nodegen, r=kmcallister

The first commit sets up a bunch of the infrastructure required and gets Text nodes onto the generated bindings. The remaining commits generate bindings for and convert selected element types to use them. The last one (HTMLAnchorElement) should be representative of the kind of work required for remaining elements, I've worked out and minimized the repetitive goop that's required.
This commit is contained in:
bors-servo 2013-08-06 16:03:40 -07:00
commit 956646a73d
26 changed files with 1395 additions and 110 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': {
}, },
@ -266,6 +277,12 @@ DOMInterfaces = {
'MouseEvent': { 'MouseEvent': {
}, },
'Node': {
'nativeType': 'AbstractNode<ScriptView>',
'concreteType': 'Node<ScriptView>',
'pointerType': ''
},
'NodeList': [ 'NodeList': [
{ {
'nativeType': 'nsINodeList', 'nativeType': 'nsINodeList',
@ -343,6 +360,12 @@ DOMInterfaces = {
'resultNotAddRefed': [ 'getItem' ] 'resultNotAddRefed': [ 'getItem' ]
}], }],
'Text': {
'nativeType': 'AbstractNode<ScriptView>',
'concreteType': 'Text',
'pointerType': ''
},
'UIEvent': { 'UIEvent': {
}, },
@ -515,6 +538,17 @@ def addExternalIface(iface, nativeType=None, headerFile=None, pointerType=None):
domInterface['pointerType'] = pointerType domInterface['pointerType'] = pointerType
DOMInterfaces[iface] = domInterface DOMInterfaces[iface] = domInterface
def addHTMLElement(element):
DOMInterfaces[element] = {
'nativeType': 'AbstractNode<ScriptView>',
'pointerType': ''
}
addHTMLElement('HTMLAnchorElement')
addHTMLElement('HTMLElement')
addHTMLElement('HTMLHeadElement')
addHTMLElement('HTMLHtmlElement')
# If you add one of these, you need to make sure nsDOMQS.h has the relevant # If you add one of these, you need to make sure nsDOMQS.h has the relevant
# macros added for it # macros added for it
def addExternalHTMLElement(element): def addExternalHTMLElement(element):
@ -533,13 +567,9 @@ 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('File') addExternalIface('File')
addExternalIface('HitRegionOptions', nativeType='nsISupports') addExternalIface('HitRegionOptions', nativeType='nsISupports')
addExternalIface('HTMLElement', 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('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
@ -4238,7 +4237,7 @@ class CGNamespacedEnum(CGThing):
entries.append(entry) entries.append(entry)
# Append a Count. # Append a Count.
entries.append('_' + enumName + '_Count') entries.append('_' + enumName + '_Count = ' + str(len(entries)))
# Indent. # Indent.
entries = [' ' + e for e in entries] entries = [' ' + e for e in entries]
@ -4603,8 +4602,12 @@ 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, HTMLHeadElement, HTMLHtmlElement}', #XXXjdm
'dom::htmlanchorelement::HTMLAnchorElement', #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

@ -0,0 +1,54 @@
/* -*- 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/#the-a-element
* http://www.whatwg.org/specs/web-apps/current-work/#other-elements,-attributes-and-apis
* © 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.
*/
// http://www.whatwg.org/specs/web-apps/current-work/#the-a-element
interface HTMLAnchorElement : HTMLElement {
// No support for stringifier attributes yet
//[SetterThrows]
//stringifier attribute DOMString href;
//stringifier;
[SetterThrows]
attribute DOMString href;
[SetterThrows]
attribute DOMString target;
[SetterThrows]
attribute DOMString download;
[SetterThrows]
attribute DOMString ping;
[SetterThrows]
attribute DOMString rel;
// relList not supported yet
//readonly attribute DOMTokenList relList;
[SetterThrows]
attribute DOMString hreflang;
[SetterThrows]
attribute DOMString type;
[SetterThrows]
attribute DOMString text;
};
//HTMLAnchorElement implements URLUtils;
// http://www.whatwg.org/specs/web-apps/current-work/#other-elements,-attributes-and-apis
partial interface HTMLAnchorElement {
[SetterThrows]
attribute DOMString coords;
[SetterThrows]
attribute DOMString charset;
[SetterThrows]
attribute DOMString name;
[SetterThrows]
attribute DOMString rev;
[SetterThrows]
attribute DOMString shape;
};

View file

@ -5,8 +5,6 @@
*/ */
interface Selection; interface Selection;
interface HTMLElement;
interface HTMLHeadElement;
[OverrideBuiltins] [OverrideBuiltins]
interface HTMLDocument : Document { interface HTMLDocument : Document {

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,15 @@
/* -*- 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/#the-head-element
*
* © 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.
*/
// http://www.whatwg.org/specs/web-apps/current-work/#the-head-element
interface HTMLHeadElement : HTMLElement {};

View file

@ -0,0 +1,22 @@
/* -*- 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/#the-html-element
* http://www.whatwg.org/specs/web-apps/current-work/#other-elements,-attributes-and-apis
*
* © 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.
*/
// http://www.whatwg.org/specs/web-apps/current-work/#the-html-element
interface HTMLHtmlElement : HTMLElement {};
// http://www.whatwg.org/specs/web-apps/current-work/#other-elements,-attributes-and-apis
partial interface HTMLHtmlElement {
[SetterThrows, Pure]
attribute DOMString version;
};

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

@ -6,8 +6,11 @@ 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::element::{HTMLHeadElementTypeId, HTMLHtmlElementTypeId, HTMLAnchorElementTypeId};
use dom::element::{HTMLHeadElement, HTMLHtmlElement};
use dom::htmlanchorelement::HTMLAnchorElement;
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 +20,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;
@ -61,13 +64,26 @@ pub fn init(compartment: @mut Compartment) {
} }
} }
macro_rules! generate_element(
($name: ident) => ({
let node: @mut $name = unsafe { cast::transmute(node.raw_object()) };
node.wrap_object_shared(cx, ptr::null())
})
)
#[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(HTMLAnchorElementTypeId) => generate_element!(HTMLAnchorElement),
TextNodeTypeId | ElementNodeTypeId(HTMLHeadElementTypeId) => generate_element!(HTMLHeadElement),
ElementNodeTypeId(HTMLHtmlElementTypeId) => generate_element!(HTMLHtmlElement),
ElementNodeTypeId(_) => element::create(cx, node).ptr,
CommentNodeTypeId | CommentNodeTypeId |
DoctypeNodeTypeId => text::create(cx, node), DoctypeNodeTypeId => text::create(cx, node).ptr,
TextNodeTypeId => {
let node: @mut Text = unsafe { cast::transmute(node.raw_object()) };
node.wrap_object_shared(cx, ptr::null())
}
} }
} }

View file

@ -3,6 +3,7 @@
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use dom::bindings::codegen::PrototypeList; use dom::bindings::codegen::PrototypeList;
use dom::bindings::codegen::PrototypeList::MAX_PROTO_CHAIN_LENGTH;
use dom::bindings::node; use dom::bindings::node;
use dom::node::{AbstractNode, ScriptView}; use dom::node::{AbstractNode, ScriptView};
use script_task::page_from_context; use script_task::page_from_context;
@ -401,7 +402,7 @@ pub struct ConstantSpec {
pub struct DOMClass { pub struct DOMClass {
// A list of interfaces that this object implements, in order of decreasing // A list of interfaces that this object implements, in order of decreasing
// derivedness. // derivedness.
interface_chain: [PrototypeList::id::ID, ..3 /*max prototype chain length*/], interface_chain: [PrototypeList::id::ID, ..MAX_PROTO_CHAIN_LENGTH],
unused: bool, // DOMObjectIsISupports (always false) unused: bool, // DOMObjectIsISupports (always false)
native_hooks: *NativePropertyHooks native_hooks: *NativePropertyHooks
@ -616,7 +617,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, ..33]); //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 +836,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

@ -5,10 +5,11 @@
use dom::bindings::codegen::DocumentBinding; use dom::bindings::codegen::DocumentBinding;
use dom::bindings::utils::{DOMString, WrapperCache, ErrorResult, null_string, str}; use dom::bindings::utils::{DOMString, WrapperCache, ErrorResult, null_string, str};
use dom::bindings::utils::{BindingObject, CacheableWrapper, rust_box, DerivedWrapper}; use dom::bindings::utils::{BindingObject, CacheableWrapper, rust_box, DerivedWrapper};
use dom::element::{HTMLHtmlElement, HTMLHtmlElementTypeId, Element}; use dom::element::{HTMLHtmlElement, HTMLHtmlElementTypeId};
use dom::event::Event; use dom::event::Event;
use dom::htmlcollection::HTMLCollection; use dom::htmlcollection::HTMLCollection;
use dom::htmldocument::HTMLDocument; use dom::htmldocument::HTMLDocument;
use dom::htmlelement::HTMLElement;
use dom::node::{AbstractNode, ScriptView, Node}; use dom::node::{AbstractNode, ScriptView, Node};
use dom::window::Window; use dom::window::Window;
use dom::windowproxy::WindowProxy; use dom::windowproxy::WindowProxy;
@ -37,18 +38,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,8 +102,8 @@ 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: HTMLElement::new(HTMLHtmlElementTypeId, ~"html")
}; };
let cx = unsafe {(*owner.page).js_info.get_ref().js_compartment.cx.ptr}; let cx = unsafe {(*owner.page).js_info.get_ref().js_compartment.cx.ptr};

View file

@ -6,8 +6,9 @@ use dom::bindings::codegen::DOMParserBinding;
use dom::bindings::codegen::DOMParserBinding::SupportedTypeValues::{Text_html, Text_xml}; use dom::bindings::codegen::DOMParserBinding::SupportedTypeValues::{Text_html, Text_xml};
use dom::bindings::utils::{DOMString, ErrorResult, WrapperCache, CacheableWrapper}; use dom::bindings::utils::{DOMString, ErrorResult, WrapperCache, CacheableWrapper};
use dom::document::{AbstractDocument, Document, XML}; use dom::document::{AbstractDocument, Document, XML};
use dom::element::{Element, HTMLHtmlElement, HTMLHtmlElementTypeId}; use dom::element::{HTMLHtmlElement, HTMLHtmlElementTypeId};
use dom::htmldocument::HTMLDocument; use dom::htmldocument::HTMLDocument;
use dom::htmlelement::HTMLElement;
use dom::node::Node; use dom::node::Node;
use dom::window::Window; use dom::window::Window;
@ -41,8 +42,8 @@ impl DOMParser {
_rv: &mut ErrorResult) _rv: &mut ErrorResult)
-> AbstractDocument { -> AbstractDocument {
unsafe { unsafe {
let root = ~HTMLHtmlElement { let root = @HTMLHtmlElement {
parent: Element::new(HTMLHtmlElementTypeId, ~"html") parent: HTMLElement::new(HTMLHtmlElementTypeId, ~"html")
}; };
let root = Node::as_abstract_node((*self.owner.page).js_info.get_ref().js_compartment.cx.ptr, root); let root = Node::as_abstract_node((*self.owner.page).js_info.get_ref().js_compartment.cx.ptr, root);

View file

@ -4,13 +4,21 @@
//! Element nodes. //! Element nodes.
use dom::bindings::utils::{DOMString, CacheableWrapper}; use dom::bindings::codegen::{HTMLHeadElementBinding, HTMLHtmlElementBinding};
use dom::bindings::codegen::{HTMLAnchorElementBinding};
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::htmlanchorelement::HTMLAnchorElement;
use dom::htmlcollection::HTMLCollection;
use dom::htmlelement::HTMLElement;
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;
@ -26,6 +34,22 @@ pub struct Element {
attrs: ~[Attr], attrs: ~[Attr],
} }
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!("no wrapping")
}
}
impl BindingObject for Element {
fn GetParentObject(&self, cx: *JSContext) -> Option<@mut CacheableWrapper> {
self.parent.GetParentObject(cx)
}
}
#[deriving(Eq)] #[deriving(Eq)]
pub enum ElementTypeId { pub enum ElementTypeId {
HTMLAnchorElementTypeId, HTMLAnchorElementTypeId,
@ -69,57 +93,97 @@ pub enum ElementTypeId {
// Regular old elements // Regular old elements
// //
pub struct HTMLAnchorElement { parent: Element } pub struct HTMLAsideElement { parent: HTMLElement }
pub struct HTMLAsideElement { parent: Element } pub struct HTMLBRElement { parent: HTMLElement }
pub struct HTMLBRElement { parent: Element } pub struct HTMLBodyElement { parent: HTMLElement }
pub struct HTMLBodyElement { parent: Element } pub struct HTMLBoldElement { parent: HTMLElement }
pub struct HTMLBoldElement { parent: Element } pub struct HTMLDivElement { parent: HTMLElement }
pub struct HTMLDivElement { parent: Element } pub struct HTMLFontElement { parent: HTMLElement }
pub struct HTMLFontElement { parent: Element } pub struct HTMLFormElement { parent: HTMLElement }
pub struct HTMLFormElement { parent: Element } pub struct HTMLHRElement { parent: HTMLElement }
pub struct HTMLHRElement { parent: Element } pub struct HTMLHeadElement { parent: HTMLElement }
pub struct HTMLHeadElement { parent: Element } pub struct HTMLHtmlElement { parent: HTMLElement }
pub struct HTMLHtmlElement { parent: Element } pub struct HTMLInputElement { parent: HTMLElement }
pub struct HTMLInputElement { parent: Element } pub struct HTMLItalicElement { parent: HTMLElement }
pub struct HTMLItalicElement { parent: Element } pub struct HTMLLinkElement { parent: HTMLElement }
pub struct HTMLLinkElement { parent: Element } pub struct HTMLListItemElement { parent: HTMLElement }
pub struct HTMLListItemElement { parent: Element } pub struct HTMLMetaElement { parent: HTMLElement }
pub struct HTMLMetaElement { parent: Element } pub struct HTMLOListElement { parent: HTMLElement }
pub struct HTMLOListElement { parent: Element } pub struct HTMLOptionElement { parent: HTMLElement }
pub struct HTMLOptionElement { parent: Element } pub struct HTMLParagraphElement { parent: HTMLElement }
pub struct HTMLParagraphElement { parent: Element } pub struct HTMLScriptElement { parent: HTMLElement }
pub struct HTMLScriptElement { parent: Element } pub struct HTMLSectionElement { parent: HTMLElement }
pub struct HTMLSectionElement { parent: Element } pub struct HTMLSelectElement { parent: HTMLElement }
pub struct HTMLSelectElement { parent: Element } pub struct HTMLSmallElement { parent: HTMLElement }
pub struct HTMLSmallElement { parent: Element } pub struct HTMLSpanElement { parent: HTMLElement }
pub struct HTMLSpanElement { parent: Element } pub struct HTMLStyleElement { parent: HTMLElement }
pub struct HTMLStyleElement { parent: Element } pub struct HTMLTableBodyElement { parent: HTMLElement }
pub struct HTMLTableBodyElement { parent: Element } pub struct HTMLTableCellElement { parent: HTMLElement }
pub struct HTMLTableCellElement { parent: Element } pub struct HTMLTableElement { parent: HTMLElement }
pub struct HTMLTableElement { parent: Element } pub struct HTMLTableRowElement { parent: HTMLElement }
pub struct HTMLTableRowElement { parent: Element } pub struct HTMLTitleElement { parent: HTMLElement }
pub struct HTMLTitleElement { parent: Element } pub struct HTMLUListElement { parent: HTMLElement }
pub struct HTMLUListElement { parent: Element } pub struct UnknownElement { parent: HTMLElement }
pub struct UnknownElement { parent: Element }
impl HTMLHtmlElement {
pub fn Version(&self) -> DOMString {
null_string
}
pub fn SetVersion(&mut self, _version: &DOMString, _rv: &mut ErrorResult) {
}
}
pub macro_rules! generate_cacheable_wrapper(
($name: ident, $wrap: path) => (
impl CacheableWrapper for $name {
fn get_wrappercache(&mut self) -> &mut WrapperCache {
self.parent.get_wrappercache()
}
fn wrap_object_shared(@mut self, cx: *JSContext, scope: *JSObject) -> *JSObject {
let mut unused = false;
$wrap(cx, scope, self, &mut unused)
}
}
)
)
pub macro_rules! generate_binding_object(
($name: ident) => (
impl BindingObject for $name {
fn GetParentObject(&self, cx: *JSContext) -> Option<@mut CacheableWrapper> {
self.parent.GetParentObject(cx)
}
}
)
)
generate_cacheable_wrapper!(HTMLHeadElement, HTMLHeadElementBinding::Wrap)
generate_binding_object!(HTMLHeadElement)
generate_cacheable_wrapper!(HTMLHtmlElement, HTMLHtmlElementBinding::Wrap)
generate_binding_object!(HTMLHtmlElement)
generate_cacheable_wrapper!(HTMLAnchorElement, HTMLAnchorElementBinding::Wrap)
generate_binding_object!(HTMLAnchorElement)
// //
// Fancier elements // Fancier elements
// //
pub struct HTMLHeadingElement { pub struct HTMLHeadingElement {
parent: Element, parent: HTMLElement,
level: HeadingLevel, level: HeadingLevel,
} }
pub struct HTMLIframeElement { pub struct HTMLIframeElement {
parent: Element, parent: HTMLElement,
frame: Option<Url>, frame: Option<Url>,
subpage_id: Option<SubpageId>, subpage_id: Option<SubpageId>,
size_future_chan: Option<ChanOne<Size2D<uint>>>, size_future_chan: Option<ChanOne<Size2D<uint>>>,
} }
pub struct HTMLImageElement { pub struct HTMLImageElement {
parent: Element, parent: HTMLElement,
image: Option<Url>, image: Option<Url>,
} }
@ -257,6 +321,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 {
@ -281,4 +499,3 @@ pub enum HeadingLevel {
Heading5, Heading5,
Heading6, Heading6,
} }

View file

@ -0,0 +1,103 @@
/* 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::htmlelement::HTMLElement;
use dom::bindings::utils::{DOMString, null_string, ErrorResult};
pub struct HTMLAnchorElement {
parent: HTMLElement
}
impl HTMLAnchorElement {
pub fn Href(&self) -> DOMString {
null_string
}
pub fn SetHref(&mut self, _href: &DOMString, _rv: &mut ErrorResult) {
}
pub fn Target(&self) -> DOMString {
null_string
}
pub fn SetTarget(&self, _target: &DOMString, _rv: &mut ErrorResult) {
}
pub fn Download(&self) -> DOMString {
null_string
}
pub fn SetDownload(&self, _download: &DOMString, _rv: &mut ErrorResult) {
}
pub fn Ping(&self) -> DOMString {
null_string
}
pub fn SetPing(&self, _ping: &DOMString, _rv: &mut ErrorResult) {
}
pub fn Rel(&self) -> DOMString {
null_string
}
pub fn SetRel(&self, _rel: &DOMString, _rv: &mut ErrorResult) {
}
pub fn Hreflang(&self) -> DOMString {
null_string
}
pub fn SetHreflang(&self, _href_lang: &DOMString, _rv: &mut ErrorResult) {
}
pub fn Type(&self) -> DOMString {
null_string
}
pub fn SetType(&mut self, _type: &DOMString, _rv: &mut ErrorResult) {
}
pub fn Text(&self) -> DOMString {
null_string
}
pub fn SetText(&mut self, _text: &DOMString, _rv: &mut ErrorResult) {
}
pub fn Coords(&self) -> DOMString {
null_string
}
pub fn SetCoords(&mut self, _coords: &DOMString, _rv: &mut ErrorResult) {
}
pub fn Charset(&self) -> DOMString {
null_string
}
pub fn SetCharset(&mut self, _charset: &DOMString, _rv: &mut ErrorResult) {
}
pub fn Name(&self) -> DOMString {
null_string
}
pub fn SetName(&mut self, _name: &DOMString, _rv: &mut ErrorResult) {
}
pub fn Rev(&self) -> DOMString {
null_string
}
pub fn SetRev(&mut self, _rev: &DOMString, _rv: &mut ErrorResult) {
}
pub fn Shape(&self) -> DOMString {
null_string
}
pub fn SetShape(&mut self, _shape: &DOMString, _rv: &mut ErrorResult) {
}
}

View file

@ -0,0 +1,156 @@
/* 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::codegen::HTMLElementBinding;
use dom::bindings::utils::{DOMString, null_string, ErrorResult};
use dom::bindings::utils::{CacheableWrapper, BindingObject, WrapperCache};
use dom::element::{Element, ElementTypeId};
use dom::node::{AbstractNode, ScriptView};
use js::jsapi::{JSObject, JSContext, JSVal};
use js::JSVAL_NULL;
pub struct HTMLElement {
parent: Element
}
impl HTMLElement {
pub fn new(type_id: ElementTypeId, tag_name: ~str) -> HTMLElement {
HTMLElement {
parent: Element::new(type_id, tag_name)
}
}
}
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 {
let mut unused = false;
HTMLElementBinding::Wrap(cx, scope, self, &mut unused)
}
}
impl BindingObject for HTMLElement {
fn GetParentObject(&self, cx: *JSContext) -> Option<@mut CacheableWrapper> {
self.parent.GetParentObject(cx)
}
}

View file

@ -4,20 +4,23 @@
//! 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::codegen::TextBinding;
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 +154,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 +223,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 +454,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 +523,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 +670,39 @@ 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 {
let mut unused = false;
TextBinding::Wrap(cx, scope, self, &mut unused)
}
}
impl BindingObject for Text {
fn GetParentObject(&self, cx: *JSContext) -> Option<@mut CacheableWrapper> {
self.parent.GetParentObject(cx)
}
}

View file

@ -15,7 +15,7 @@ use dom::element::{HTMLAnchorElementTypeId, HTMLAsideElementTypeId, HTMLBRElemen
HTMLTableCellElementTypeId, HTMLTableElementTypeId, HTMLTableCellElementTypeId, HTMLTableElementTypeId,
HTMLTableRowElementTypeId, HTMLTitleElementTypeId, HTMLUListElementTypeId, HTMLTableRowElementTypeId, HTMLTitleElementTypeId, HTMLUListElementTypeId,
UnknownElementTypeId}; UnknownElementTypeId};
use dom::element::{HTMLAnchorElement, HTMLAsideElement, HTMLBRElement, HTMLBodyElement, use dom::element::{HTMLAsideElement, HTMLBRElement, HTMLBodyElement,
HTMLBoldElement, HTMLDivElement, HTMLFontElement, HTMLFormElement, HTMLBoldElement, HTMLDivElement, HTMLFontElement, HTMLFormElement,
HTMLHRElement, HTMLHeadElement, HTMLHeadingElement, HTMLHtmlElement, HTMLHRElement, HTMLHeadElement, HTMLHeadingElement, HTMLHtmlElement,
HTMLInputElement, HTMLImageElement, HTMLIframeElement, HTMLInputElement, HTMLImageElement, HTMLIframeElement,
@ -27,7 +27,9 @@ use dom::element::{HTMLAnchorElement, HTMLAsideElement, HTMLBRElement, HTMLBodyE
HTMLTitleElement, HTMLUListElement}; HTMLTitleElement, HTMLUListElement};
use dom::element::{HTMLHeadingElementTypeId, Heading1, Heading2, Heading3, Heading4, Heading5, use dom::element::{HTMLHeadingElementTypeId, Heading1, Heading2, Heading3, Heading4, Heading5,
Heading6}; Heading6};
use dom::htmlanchorelement::HTMLAnchorElement;
use dom::element::{Element, Attr}; use dom::element::{Element, Attr};
use dom::htmlelement::HTMLElement;
use dom::node::{AbstractNode, Comment, Doctype, ElementNodeTypeId, Node, ScriptView}; use dom::node::{AbstractNode, Comment, Doctype, ElementNodeTypeId, Node, ScriptView};
use dom::node::{Text}; use dom::node::{Text};
use html::cssparse::{InlineProvenance, StylesheetProvenance, UrlProvenance, spawn_css_parser}; use html::cssparse::{InlineProvenance, StylesheetProvenance, UrlProvenance, spawn_css_parser};
@ -56,8 +58,8 @@ 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: HTMLElement::new($type_id, ($tag).to_str()),
$( $(
$field: $field_init, $field: $field_init,
)* )*
@ -233,7 +235,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 +274,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: HTMLElement::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 +291,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 +300,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);
@ -337,7 +339,8 @@ pub fn parse_html(cx: *JSContext,
ElementNodeTypeId(HTMLIframeElementTypeId) => { ElementNodeTypeId(HTMLIframeElementTypeId) => {
do node.with_mut_iframe_element |iframe_element| { do node.with_mut_iframe_element |iframe_element| {
let src_opt = iframe_element.parent.get_attr("src").map(|x| x.to_str()); let elem = &mut iframe_element.parent.parent;
let src_opt = elem.get_attr("src").map(|x| x.to_str());
for src_opt.iter().advance |src| { for src_opt.iter().advance |src| {
let iframe_url = make_url(src.clone(), Some(url2.clone())); let iframe_url = make_url(src.clone(), Some(url2.clone()));
iframe_element.frame = Some(iframe_url.clone()); iframe_element.frame = Some(iframe_url.clone());
@ -359,7 +362,8 @@ pub fn parse_html(cx: *JSContext,
ElementNodeTypeId(HTMLImageElementTypeId) => { ElementNodeTypeId(HTMLImageElementTypeId) => {
do node.with_mut_image_element |image_element| { do node.with_mut_image_element |image_element| {
let src_opt = image_element.parent.get_attr("src").map(|x| x.to_str()); let elem = &mut image_element.parent.parent;
let src_opt = elem.get_attr("src").map(|x| x.to_str());
match src_opt { match src_opt {
None => {} None => {}
Some(src) => { Some(src) => {
@ -383,7 +387,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,26 @@ 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 HTMLAnchorElementBinding;
pub mod HTMLCollectionBinding; pub mod HTMLCollectionBinding;
pub mod HTMLDocumentBinding; pub mod HTMLDocumentBinding;
pub mod HTMLElementBinding;
pub mod HTMLHeadElementBinding;
pub mod HTMLHtmlElementBinding;
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;
@ -60,8 +68,10 @@ pub mod dom {
pub mod event; pub mod event;
pub mod eventtarget; pub mod eventtarget;
pub mod formdata; pub mod formdata;
pub mod htmlanchorelement;
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;

View file

@ -1,4 +1,6 @@
<!DOCTYPE html>
<html> <html>
<!-- comment -->
<head> <head>
<script src="test_bindings.js"></script> <script src="test_bindings.js"></script>
</head> </head>

View file

@ -124,6 +124,8 @@ window.alert(document.title);
document.title = "foo"; document.title = "foo";
window.alert(document.title); window.alert(document.title);
window.alert(document.links[0]);
//TODO: Doesn't work until we throw proper exceptions instead of returning 0 on //TODO: Doesn't work until we throw proper exceptions instead of returning 0 on
// unwrap failure. // unwrap failure.
/*try { /*try {